From e19083fc130a711b5416f613ff6524b298b7debd Mon Sep 17 00:00:00 2001 From: Niklas Dusenlund Date: Tue, 15 Oct 2024 11:48:11 +0200 Subject: [PATCH] Vendor rust deps --- Dockerfile | 5 +- bitbox02-bt/.cargo/config.toml | 6 + bitbox02-bt/Cargo.lock | 284 - .../vendor/bare-metal/.cargo-checksum.json | 1 + bitbox02-bt/vendor/bare-metal/CHANGELOG.md | 77 + bitbox02-bt/vendor/bare-metal/Cargo.toml | 27 + bitbox02-bt/vendor/bare-metal/LICENSE-APACHE | 201 + bitbox02-bt/vendor/bare-metal/LICENSE-MIT | 25 + bitbox02-bt/vendor/bare-metal/README.md | 21 + bitbox02-bt/vendor/bare-metal/bors.toml | 3 + bitbox02-bt/vendor/bare-metal/build.rs | 9 + bitbox02-bt/vendor/bare-metal/ci/install.sh | 9 + bitbox02-bt/vendor/bare-metal/ci/script.sh | 11 + bitbox02-bt/vendor/bare-metal/src/lib.rs | 101 + .../vendor/bitfield/.cargo-checksum.json | 1 + bitbox02-bt/vendor/bitfield/CHANGELOG.md | 16 + bitbox02-bt/vendor/bitfield/Cargo.toml | 22 + bitbox02-bt/vendor/bitfield/LICENSE-APACHE | 202 + bitbox02-bt/vendor/bitfield/LICENSE-MIT | 19 + bitbox02-bt/vendor/bitfield/README.md | 57 + .../vendor/bitfield/examples/bits_position.rs | 75 + bitbox02-bt/vendor/bitfield/examples/ipv4.rs | 60 + bitbox02-bt/vendor/bitfield/multitest.toml | 22 + bitbox02-bt/vendor/bitfield/src/lib.rs | 668 ++ bitbox02-bt/vendor/bitfield/tests/lib.rs | 1105 +++ .../vendor/byteorder/.cargo-checksum.json | 1 + bitbox02-bt/vendor/byteorder/CHANGELOG.md | 143 + bitbox02-bt/vendor/byteorder/COPYING | 3 + bitbox02-bt/vendor/byteorder/Cargo.toml | 54 + bitbox02-bt/vendor/byteorder/LICENSE-MIT | 21 + bitbox02-bt/vendor/byteorder/README.md | 77 + bitbox02-bt/vendor/byteorder/UNLICENSE | 24 + bitbox02-bt/vendor/byteorder/benches/bench.rs | 326 + bitbox02-bt/vendor/byteorder/rustfmt.toml | 2 + bitbox02-bt/vendor/byteorder/src/io.rs | 1592 ++++ bitbox02-bt/vendor/byteorder/src/lib.rs | 3975 ++++++++++ bitbox02-bt/vendor/cc/.cargo-checksum.json | 1 + bitbox02-bt/vendor/cc/CHANGELOG.md | 238 + bitbox02-bt/vendor/cc/Cargo.toml | 66 + bitbox02-bt/vendor/cc/LICENSE-APACHE | 201 + bitbox02-bt/vendor/cc/LICENSE-MIT | 25 + bitbox02-bt/vendor/cc/README.md | 27 + bitbox02-bt/vendor/cc/clippy.toml | 5 + bitbox02-bt/vendor/cc/src/command_helpers.rs | 491 ++ .../vendor/cc/src/detect_compiler_family.c | 15 + bitbox02-bt/vendor/cc/src/lib.rs | 4346 +++++++++++ .../vendor/cc/src/parallel/async_executor.rs | 118 + .../vendor/cc/src/parallel/job_token.rs | 273 + bitbox02-bt/vendor/cc/src/parallel/mod.rs | 4 + .../vendor/cc/src/parallel/once_lock.rs | 47 + bitbox02-bt/vendor/cc/src/parallel/stderr.rs | 91 + bitbox02-bt/vendor/cc/src/target_info.rs | 29 + bitbox02-bt/vendor/cc/src/tempfile.rs | 86 + bitbox02-bt/vendor/cc/src/tool.rs | 476 ++ bitbox02-bt/vendor/cc/src/utilities.rs | 45 + bitbox02-bt/vendor/cc/src/windows/com.rs | 110 + .../vendor/cc/src/windows/find_tools.rs | 1191 +++ bitbox02-bt/vendor/cc/src/windows/mod.rs | 22 + bitbox02-bt/vendor/cc/src/windows/registry.rs | 191 + .../vendor/cc/src/windows/setup_config.rs | 283 + .../vendor/cc/src/windows/vs_instances.rs | 199 + bitbox02-bt/vendor/cc/src/windows/winapi.rs | 146 + .../vendor/cc/src/windows/windows_sys.rs | 121 + .../vendor/cc/src/windows/windows_targets.rs | 19 + .../vendor/cortex-m/.cargo-checksum.json | 1 + bitbox02-bt/vendor/cortex-m/CHANGELOG.md | 807 ++ .../vendor/cortex-m/CODE_OF_CONDUCT.md | 37 + bitbox02-bt/vendor/cortex-m/Cargo.toml | 77 + bitbox02-bt/vendor/cortex-m/LICENSE-APACHE | 201 + bitbox02-bt/vendor/cortex-m/LICENSE-MIT | 25 + bitbox02-bt/vendor/cortex-m/README.md | 39 + bitbox02-bt/vendor/cortex-m/asm-toolchain | 1 + bitbox02-bt/vendor/cortex-m/asm/inline.rs | 448 ++ bitbox02-bt/vendor/cortex-m/asm/lib.rs | 143 + .../cortex-m/bin/thumbv6m-none-eabi-lto.a | Bin 0 -> 11196 bytes .../vendor/cortex-m/bin/thumbv6m-none-eabi.a | Bin 0 -> 14576 bytes .../cortex-m/bin/thumbv7em-none-eabi-lto.a | Bin 0 -> 15280 bytes .../vendor/cortex-m/bin/thumbv7em-none-eabi.a | Bin 0 -> 19336 bytes .../cortex-m/bin/thumbv7em-none-eabihf-lto.a | Bin 0 -> 16104 bytes .../cortex-m/bin/thumbv7em-none-eabihf.a | Bin 0 -> 20480 bytes .../cortex-m/bin/thumbv7m-none-eabi-lto.a | Bin 0 -> 14244 bytes .../vendor/cortex-m/bin/thumbv7m-none-eabi.a | Bin 0 -> 18068 bytes .../bin/thumbv8m.base-none-eabi-lto.a | Bin 0 -> 14280 bytes .../cortex-m/bin/thumbv8m.base-none-eabi.a | Bin 0 -> 18680 bytes .../bin/thumbv8m.main-none-eabi-lto.a | Bin 0 -> 18672 bytes .../cortex-m/bin/thumbv8m.main-none-eabi.a | Bin 0 -> 24408 bytes .../bin/thumbv8m.main-none-eabihf-lto.a | Bin 0 -> 19508 bytes .../cortex-m/bin/thumbv8m.main-none-eabihf.a | Bin 0 -> 25524 bytes bitbox02-bt/vendor/cortex-m/build.rs | 54 + bitbox02-bt/vendor/cortex-m/src/asm.rs | 209 + bitbox02-bt/vendor/cortex-m/src/call_asm.rs | 24 + bitbox02-bt/vendor/cortex-m/src/cmse.rs | 238 + .../vendor/cortex-m/src/critical_section.rs | 25 + bitbox02-bt/vendor/cortex-m/src/delay.rs | 136 + bitbox02-bt/vendor/cortex-m/src/interrupt.rs | 73 + bitbox02-bt/vendor/cortex-m/src/itm.rs | 158 + bitbox02-bt/vendor/cortex-m/src/lib.rs | 112 + bitbox02-bt/vendor/cortex-m/src/macros.rs | 114 + .../vendor/cortex-m/src/peripheral/ac.rs | 93 + .../vendor/cortex-m/src/peripheral/cbp.rs | 138 + .../vendor/cortex-m/src/peripheral/cpuid.rs | 140 + .../vendor/cortex-m/src/peripheral/dcb.rs | 60 + .../vendor/cortex-m/src/peripheral/dwt.rs | 268 + .../vendor/cortex-m/src/peripheral/fpb.rs | 21 + .../vendor/cortex-m/src/peripheral/fpu.rs | 19 + .../vendor/cortex-m/src/peripheral/icb.rs | 32 + .../vendor/cortex-m/src/peripheral/itm.rs | 71 + .../vendor/cortex-m/src/peripheral/mod.rs | 685 ++ .../vendor/cortex-m/src/peripheral/mpu.rs | 65 + .../vendor/cortex-m/src/peripheral/nvic.rs | 265 + .../vendor/cortex-m/src/peripheral/sau.rs | 243 + .../vendor/cortex-m/src/peripheral/scb.rs | 1109 +++ .../vendor/cortex-m/src/peripheral/syst.rs | 185 + .../vendor/cortex-m/src/peripheral/test.rs | 170 + .../vendor/cortex-m/src/peripheral/tpiu.rs | 31 + bitbox02-bt/vendor/cortex-m/src/prelude.rs | 3 + .../vendor/cortex-m/src/register/apsr.rs | 54 + .../vendor/cortex-m/src/register/basepri.rs | 24 + .../cortex-m/src/register/basepri_max.rs | 21 + .../vendor/cortex-m/src/register/control.rs | 164 + .../vendor/cortex-m/src/register/faultmask.rs | 35 + .../vendor/cortex-m/src/register/fpscr.rs | 305 + .../vendor/cortex-m/src/register/lr.rs | 17 + .../vendor/cortex-m/src/register/mod.rs | 68 + .../vendor/cortex-m/src/register/msp.rs | 32 + .../vendor/cortex-m/src/register/msplim.rs | 13 + .../vendor/cortex-m/src/register/pc.rs | 17 + .../vendor/cortex-m/src/register/primask.rs | 35 + .../vendor/cortex-m/src/register/psp.rs | 13 + .../vendor/cortex-m/src/register/psplim.rs | 13 + bitbox02-bt/vendor/cortex-m/triagebot.toml | 1 + .../critical-section/.cargo-checksum.json | 1 + .../vendor/critical-section/CHANGELOG.md | 142 + .../critical-section/CODE_OF_CONDUCT.md | 37 + .../vendor/critical-section/Cargo.toml | 43 + .../vendor/critical-section/LICENSE-APACHE | 201 + .../vendor/critical-section/LICENSE-MIT | 25 + bitbox02-bt/vendor/critical-section/README.md | 250 + .../vendor/critical-section/docs/msrv.md | 30 + .../vendor/critical-section/src/lib.rs | 299 + .../vendor/critical-section/src/mutex.rs | 200 + .../vendor/critical-section/src/std.rs | 80 + bitbox02-bt/vendor/cty/.cargo-checksum.json | 1 + bitbox02-bt/vendor/cty/CHANGELOG.md | 73 + bitbox02-bt/vendor/cty/Cargo.toml | 21 + bitbox02-bt/vendor/cty/LICENSE-APACHE | 201 + bitbox02-bt/vendor/cty/LICENSE-MIT | 25 + bitbox02-bt/vendor/cty/README.md | 22 + bitbox02-bt/vendor/cty/ci/install.sh | 7 + bitbox02-bt/vendor/cty/ci/script.sh | 10 + bitbox02-bt/vendor/cty/src/lib.rs | 136 + .../vendor/da14531/.cargo-checksum.json | 1 + bitbox02-bt/vendor/da14531/Cargo.toml | 49 + bitbox02-bt/vendor/da14531/README.md | 11 + bitbox02-bt/vendor/da14531/src/adplldig.rs | 214 + .../src/adplldig/adpll_acc_ctrl_reg.rs | 187 + .../src/adplldig/adpll_ana_ctrl_reg.rs | 637 ++ .../src/adplldig/adpll_anatst_ctrl_reg.rs | 140 + .../src/adplldig/adpll_anatst_rd_reg.rs | 86 + .../src/adplldig/adpll_attr_ctrl_reg.rs | 160 + .../da14531/src/adplldig/adpll_cn_ctrl_reg.rs | 234 + .../da14531/src/adplldig/adpll_dco_rd_reg.rs | 166 + .../src/adplldig/adpll_dcoamp_cal_ctrl_reg.rs | 382 + .../src/adplldig/adpll_div_ctrl_reg.rs | 281 + .../src/adplldig/adpll_fif_ctrl1_reg.rs | 103 + .../src/adplldig/adpll_fif_ctrl2_reg.rs | 140 + .../src/adplldig/adpll_freqmeas_rd_reg.rs | 186 + .../src/adplldig/adpll_fsm_ctrl_reg.rs | 325 + .../src/adplldig/adpll_init_ctrl_reg.rs | 214 + .../src/adplldig/adpll_kdco_cal_ctrl1_reg.rs | 140 + .../src/adplldig/adpll_kdco_cal_ctrl2_reg.rs | 355 + .../da14531/src/adplldig/adpll_kdco_rd_reg.rs | 146 + .../da14531/src/adplldig/adpll_kdtc_rd_reg.rs | 146 + .../adplldig/adpll_kdtctdc_cal_ctrl1_reg.rs | 261 + .../adplldig/adpll_kdtctdc_cal_ctrl2_reg.rs | 459 ++ .../src/adplldig/adpll_lf_ctrl1_reg.rs | 177 + .../src/adplldig/adpll_lf_ctrl2_reg.rs | 298 + .../src/adplldig/adpll_misc_ctrl_reg.rs | 308 + .../src/adplldig/adpll_mon_ctrl_reg.rs | 439 ++ .../src/adplldig/adpll_overrule_ctrl1_reg.rs | 892 +++ .../src/adplldig/adpll_overrule_ctrl2_reg.rs | 402 + .../src/adplldig/adpll_overrule_ctrl3_reg.rs | 442 ++ .../src/adplldig/adpll_pllfcwdt_rd_reg.rs | 86 + .../src/adplldig/adpll_rfpt_ctrl_reg.rs | 197 + .../src/adplldig/adpll_sdmod_ctrl_reg.rs | 140 + .../src/adplldig/adpll_tunestate_rd_reg.rs | 106 + .../src/adplldig/adpll_txmod_ctrl_reg.rs | 328 + bitbox02-bt/vendor/da14531/src/anamisc.rs | 28 + .../da14531/src/anamisc/clk_ref_cnt_reg.rs | 103 + .../da14531/src/anamisc/clk_ref_sel_reg.rs | 197 + .../da14531/src/anamisc/clk_ref_val_h_reg.rs | 86 + .../da14531/src/anamisc/clk_ref_val_l_reg.rs | 86 + bitbox02-bt/vendor/da14531/src/ble.rs | 364 + .../da14531/src/ble/ble_actscanstat_reg.rs | 106 + .../da14531/src/ble/ble_advchmap_reg.rs | 107 + .../vendor/da14531/src/ble/ble_advtim_reg.rs | 103 + .../vendor/da14531/src/ble/ble_aescntl_reg.rs | 140 + .../da14531/src/ble/ble_aeskey127_96_reg.rs | 103 + .../da14531/src/ble/ble_aeskey31_0_reg.rs | 103 + .../da14531/src/ble/ble_aeskey63_32_reg.rs | 103 + .../da14531/src/ble/ble_aeskey95_64_reg.rs | 103 + .../vendor/da14531/src/ble/ble_aesptr_reg.rs | 103 + .../da14531/src/ble/ble_basetimecnt_reg.rs | 86 + .../src/ble/ble_basetimecntcorr_reg.rs | 103 + .../vendor/da14531/src/ble/ble_bdaddrl_reg.rs | 103 + .../vendor/da14531/src/ble/ble_bdaddru_reg.rs | 150 + .../da14531/src/ble/ble_blemprio0_reg.rs | 362 + .../da14531/src/ble/ble_blemprio1_reg.rs | 103 + .../vendor/da14531/src/ble/ble_cntl2_reg.rs | 675 ++ .../da14531/src/ble/ble_coexifcntl0_reg.rs | 308 + .../da14531/src/ble/ble_coexifcntl1_reg.rs | 222 + .../src/ble/ble_currentrxdescptr_reg.rs | 140 + .../da14531/src/ble/ble_debugaddmax_reg.rs | 140 + .../da14531/src/ble/ble_debugaddmin_reg.rs | 140 + .../da14531/src/ble/ble_deepslcntl_reg.rs | 271 + .../da14531/src/ble/ble_deepslstat_reg.rs | 86 + .../da14531/src/ble/ble_deepslwkup_reg.rs | 103 + .../da14531/src/ble/ble_diagcntl2_reg.rs | 402 + .../da14531/src/ble/ble_diagcntl3_reg.rs | 738 ++ .../da14531/src/ble/ble_diagcntl_reg.rs | 402 + .../da14531/src/ble/ble_diagstat_reg.rs | 154 + .../vendor/da14531/src/ble/ble_em_base_reg.rs | 103 + .../da14531/src/ble/ble_enbpreset_reg.rs | 201 + .../da14531/src/ble/ble_errortypestat_reg.rs | 426 ++ .../da14531/src/ble/ble_finecntcorr_reg.rs | 103 + .../da14531/src/ble/ble_finetimecnt_reg.rs | 86 + .../da14531/src/ble/ble_finetimtgt_reg.rs | 103 + .../da14531/src/ble/ble_grosstimtgt_reg.rs | 115 + .../vendor/da14531/src/ble/ble_intack_reg.rs | 334 + .../vendor/da14531/src/ble/ble_intcntl_reg.rs | 583 ++ .../da14531/src/ble/ble_intrawstat_reg.rs | 266 + .../vendor/da14531/src/ble/ble_intstat_reg.rs | 266 + .../da14531/src/ble/ble_radiocntl0_reg.rs | 64 + .../da14531/src/ble/ble_radiocntl1_reg.rs | 103 + .../da14531/src/ble/ble_radiocntl2_reg.rs | 64 + .../da14531/src/ble/ble_radiocntl3_reg.rs | 64 + .../da14531/src/ble/ble_radiopwrupdn_reg.rs | 214 + .../da14531/src/ble/ble_rftestcntl_reg.rs | 448 ++ .../da14531/src/ble/ble_rftestrxstat_reg.rs | 88 + .../da14531/src/ble/ble_rftesttxstat_reg.rs | 88 + .../da14531/src/ble/ble_rwblecntl_reg.rs | 772 ++ .../da14531/src/ble/ble_rwbleconf_reg.rs | 266 + .../da14531/src/ble/ble_rxmicval_reg.rs | 86 + .../da14531/src/ble/ble_sampleclk_reg.rs | 91 + .../da14531/src/ble/ble_swprofiling_reg.rs | 103 + .../da14531/src/ble/ble_timgencntl_reg.rs | 187 + .../da14531/src/ble/ble_txmicval_reg.rs | 86 + .../vendor/da14531/src/ble/ble_version_reg.rs | 146 + .../vendor/da14531/src/ble/ble_wlnbdev_reg.rs | 140 + .../da14531/src/ble/ble_wlprivaddptr_reg.rs | 103 + .../da14531/src/ble/ble_wlpubaddptr_reg.rs | 103 + .../vendor/da14531/src/chip_version.rs | 59 + .../da14531/src/chip_version/chip_id1_reg.rs | 86 + .../da14531/src/chip_version/chip_id2_reg.rs | 86 + .../da14531/src/chip_version/chip_id3_reg.rs | 86 + .../da14531/src/chip_version/chip_id4_reg.rs | 86 + .../src/chip_version/chip_revision_reg.rs | 86 + .../da14531/src/chip_version/chip_swc_reg.rs | 86 + .../src/chip_version/chip_test1_reg.rs | 86 + .../src/chip_version/chip_test2_reg.rs | 86 + bitbox02-bt/vendor/da14531/src/crg_aon.rs | 59 + .../vendor/da14531/src/crg_aon/gp_data_reg.rs | 187 + .../da14531/src/crg_aon/hibern_ctrl_reg.rs | 201 + .../da14531/src/crg_aon/hwr_ctrl_reg.rs | 113 + .../da14531/src/crg_aon/pad_latch_reg.rs | 113 + .../da14531/src/crg_aon/power_aon_ctrl_reg.rs | 506 ++ .../da14531/src/crg_aon/ram_lpmx_reg.rs | 107 + .../da14531/src/crg_aon/reset_stat_reg.rs | 258 + .../da14531/src/crg_aon/test_vdd_reg.rs | 160 + bitbox02-bt/vendor/da14531/src/crg_tim.rs | 11 + .../da14531/src/crg_tim/clk_rtcdiv_reg.rs | 281 + bitbox02-bt/vendor/da14531/src/crg_top.rs | 166 + .../da14531/src/crg_top/ana_status_reg.rs | 326 + .../vendor/da14531/src/crg_top/bandgap_reg.rs | 140 + .../da14531/src/crg_top/clk_amba_reg.rs | 187 + .../da14531/src/crg_top/clk_ctrl_reg.rs | 251 + .../da14531/src/crg_top/clk_freq_trim_reg.rs | 103 + .../vendor/da14531/src/crg_top/clk_per_reg.rs | 432 ++ .../da14531/src/crg_top/clk_radio_reg.rs | 244 + .../da14531/src/crg_top/clk_rc32k_reg.rs | 150 + .../da14531/src/crg_top/clk_rc32m_reg.rs | 224 + .../vendor/da14531/src/crg_top/clk_rcx_reg.rs | 281 + .../da14531/src/crg_top/clk_xtal32k_reg.rs | 285 + .../da14531/src/crg_top/pmu_ctrl_reg.rs | 295 + .../da14531/src/crg_top/pmu_sleep_reg.rs | 103 + .../vendor/da14531/src/crg_top/por_pin_reg.rs | 150 + .../da14531/src/crg_top/por_timer_reg.rs | 103 + .../da14531/src/crg_top/power_ctrl_reg.rs | 761 ++ .../da14531/src/crg_top/power_level_reg.rs | 298 + .../da14531/src/crg_top/ram_pwr_ctrl_reg.rs | 177 + .../da14531/src/crg_top/sys_ctrl_reg.rs | 363 + .../da14531/src/crg_top/sys_stat_reg.rs | 206 + .../da14531/src/crg_top/trim_ctrl_reg.rs | 193 + .../da14531/src/crg_top/xtal32m_ctrl0_reg.rs | 271 + .../da14531/src/crg_top/xtal32m_start_reg.rs | 140 + .../da14531/src/crg_top/xtal32m_trstat_reg.rs | 86 + .../da14531/src/crg_top/xtalrdy_ctrl_reg.rs | 103 + .../da14531/src/crg_top/xtalrdy_stat_reg.rs | 86 + bitbox02-bt/vendor/da14531/src/generic.rs | 260 + bitbox02-bt/vendor/da14531/src/gpadc.rs | 72 + .../da14531/src/gpadc/gp_adc_clear_int_reg.rs | 81 + .../da14531/src/gpadc/gp_adc_ctrl2_reg.rs | 345 + .../da14531/src/gpadc/gp_adc_ctrl3_reg.rs | 140 + .../da14531/src/gpadc/gp_adc_ctrl_reg.rs | 650 ++ .../da14531/src/gpadc/gp_adc_offn_reg.rs | 103 + .../da14531/src/gpadc/gp_adc_offp_reg.rs | 103 + .../da14531/src/gpadc/gp_adc_param_dif_reg.rs | 64 + .../da14531/src/gpadc/gp_adc_param_se_reg.rs | 64 + .../da14531/src/gpadc/gp_adc_result_reg.rs | 86 + .../da14531/src/gpadc/gp_adc_sel_reg.rs | 140 + .../da14531/src/gpadc/gp_adc_trim_reg.rs | 140 + bitbox02-bt/vendor/da14531/src/gpio.rs | 95 + .../vendor/da14531/src/gpio/bist_ctrl_reg.rs | 381 + .../vendor/da14531/src/gpio/p0_data_reg.rs | 103 + .../vendor/da14531/src/gpio/p0_mode_reg.rs | 145 + .../da14531/src/gpio/p0_reset_data_reg.rs | 85 + .../da14531/src/gpio/p0_set_data_reg.rs | 85 + .../da14531/src/gpio/pad_weak_ctrl_reg.rs | 103 + .../da14531/src/gpio/rombist_resulth_reg.rs | 86 + .../da14531/src/gpio/rombist_resultl_reg.rs | 86 + .../da14531/src/gpio/scan_observe_reg.rs | 86 + .../vendor/da14531/src/gpio/test_ctrl2_reg.rs | 187 + .../vendor/da14531/src/gpio/test_ctrl3_reg.rs | 234 + .../vendor/da14531/src/gpio/test_ctrl4_reg.rs | 187 + .../vendor/da14531/src/gpio/test_ctrl_reg.rs | 479 ++ .../da14531/src/gpio/xtal32m_testctrl0_reg.rs | 600 ++ .../da14531/src/gpio/xtal32m_testctrl1_reg.rs | 489 ++ bitbox02-bt/vendor/da14531/src/gpreg.rs | 46 + .../vendor/da14531/src/gpreg/ble_timer_reg.rs | 103 + .../vendor/da14531/src/gpreg/debug_reg.rs | 113 + .../da14531/src/gpreg/gp_control_reg.rs | 217 + .../vendor/da14531/src/gpreg/gp_status_reg.rs | 113 + .../vendor/da14531/src/gpreg/mem_ctrl_reg.rs | 314 + .../da14531/src/gpreg/reset_freeze_reg.rs | 301 + .../da14531/src/gpreg/set_freeze_reg.rs | 305 + bitbox02-bt/vendor/da14531/src/i2c.rs | 301 + .../src/i2c/i2c_ack_general_call_reg.rs | 113 + .../da14531/src/i2c/i2c_clr_activity_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_gen_call_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_intr_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_rd_req_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_rx_done_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_rx_over_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_rx_under_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_start_det_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_stop_det_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_tx_abrt_reg.rs | 86 + .../da14531/src/i2c/i2c_clr_tx_over_reg.rs | 86 + .../da14531/src/i2c/i2c_comp2_version.rs | 86 + .../da14531/src/i2c/i2c_comp_param1_reg.rs | 86 + .../da14531/src/i2c/i2c_comp_param2_reg.rs | 86 + .../da14531/src/i2c/i2c_comp_type2_reg.rs | 86 + .../da14531/src/i2c/i2c_comp_type_reg.rs | 86 + .../da14531/src/i2c/i2c_comp_version_reg.rs | 86 + .../vendor/da14531/src/i2c/i2c_con_reg.rs | 338 + .../da14531/src/i2c/i2c_data_cmd_reg.rs | 244 + .../vendor/da14531/src/i2c/i2c_dma_cr_reg.rs | 160 + .../da14531/src/i2c/i2c_dma_rdlr_reg.rs | 103 + .../da14531/src/i2c/i2c_dma_tdlr_reg.rs | 103 + .../vendor/da14531/src/i2c/i2c_enable_reg.rs | 160 + .../da14531/src/i2c/i2c_enable_status_reg.rs | 126 + .../da14531/src/i2c/i2c_fs_scl_hcnt_reg.rs | 103 + .../da14531/src/i2c/i2c_fs_scl_lcnt_reg.rs | 103 + .../da14531/src/i2c/i2c_ic_fs_spklen_reg.rs | 103 + .../da14531/src/i2c/i2c_intr_mask_reg.rs | 630 ++ .../da14531/src/i2c/i2c_intr_stat_reg.rs | 306 + .../da14531/src/i2c/i2c_raw_intr_stat_reg.rs | 306 + .../vendor/da14531/src/i2c/i2c_rx_tl_reg.rs | 103 + .../vendor/da14531/src/i2c/i2c_rxflr_reg.rs | 86 + .../vendor/da14531/src/i2c/i2c_sar_reg.rs | 107 + .../da14531/src/i2c/i2c_sda_hold_reg.rs | 103 + .../da14531/src/i2c/i2c_sda_setup_reg.rs | 107 + .../da14531/src/i2c/i2c_ss_scl_hcnt_reg.rs | 103 + .../da14531/src/i2c/i2c_ss_scl_lcnt_reg.rs | 103 + .../vendor/da14531/src/i2c/i2c_status_reg.rs | 206 + .../vendor/da14531/src/i2c/i2c_tar_reg.rs | 197 + .../da14531/src/i2c/i2c_tx_abrt_source_reg.rs | 392 + .../vendor/da14531/src/i2c/i2c_tx_tl_reg.rs | 103 + .../vendor/da14531/src/i2c/i2c_txflr_reg.rs | 86 + bitbox02-bt/vendor/da14531/src/kbrd.rs | 66 + .../da14531/src/kbrd/gpio_debounce_reg.rs | 385 + .../src/kbrd/gpio_int_level_ctrl_reg.rs | 536 ++ .../da14531/src/kbrd/gpio_irq0_in_sel_reg.rs | 151 + .../da14531/src/kbrd/gpio_irq1_in_sel_reg.rs | 103 + .../da14531/src/kbrd/gpio_irq2_in_sel_reg.rs | 103 + .../da14531/src/kbrd/gpio_irq3_in_sel_reg.rs | 103 + .../da14531/src/kbrd/gpio_irq4_in_sel_reg.rs | 103 + .../da14531/src/kbrd/gpio_reset_irq_reg.rs | 226 + .../vendor/da14531/src/kbrd/kbrd_ctrl_reg.rs | 197 + .../da14531/src/kbrd/kbrd_irq_in_sel0_reg.rs | 678 ++ bitbox02-bt/vendor/da14531/src/lib.rs | 1038 +++ .../vendor/da14531/src/mbist_sram12.rs | 30 + .../src/mbist_sram12/mbist_sram12_addr_reg.rs | 86 + .../mbist_sram12/mbist_sram12_rd_lsb_reg.rs | 86 + .../mbist_sram12/mbist_sram12_rd_msb_reg.rs | 86 + .../mbist_sram12/mbist_sram12_state_reg.rs | 86 + bitbox02-bt/vendor/da14531/src/mbist_sram3.rs | 28 + .../src/mbist_sram3/mbist_sram3_addr_reg.rs | 86 + .../src/mbist_sram3/mbist_sram3_rd_lsb_reg.rs | 86 + .../src/mbist_sram3/mbist_sram3_rd_msb_reg.rs | 86 + .../src/mbist_sram3/mbist_sram3_state_reg.rs | 86 + bitbox02-bt/vendor/da14531/src/otpc.rs | 58 + .../da14531/src/otpc/otpc_ahbadr_reg.rs | 107 + .../da14531/src/otpc/otpc_celadr_reg.rs | 103 + .../vendor/da14531/src/otpc/otpc_mode_reg.rs | 246 + .../da14531/src/otpc/otpc_nwords_reg.rs | 103 + .../vendor/da14531/src/otpc/otpc_paddr_reg.rs | 103 + .../vendor/da14531/src/otpc/otpc_pword_reg.rs | 107 + .../vendor/da14531/src/otpc/otpc_stat_reg.rs | 128 + .../vendor/da14531/src/otpc/otpc_tim1_reg.rs | 288 + .../vendor/da14531/src/otpc/otpc_tim2_reg.rs | 372 + bitbox02-bt/vendor/da14531/src/patch.rs | 175 + .../da14531/src/patch/patch_addr0_reg.rs | 150 + .../da14531/src/patch/patch_addr10_reg.rs | 150 + .../da14531/src/patch/patch_addr11_reg.rs | 150 + .../da14531/src/patch/patch_addr12_reg.rs | 150 + .../da14531/src/patch/patch_addr13_reg.rs | 150 + .../da14531/src/patch/patch_addr14_reg.rs | 150 + .../da14531/src/patch/patch_addr15_reg.rs | 150 + .../da14531/src/patch/patch_addr16_reg.rs | 150 + .../da14531/src/patch/patch_addr17_reg.rs | 150 + .../da14531/src/patch/patch_addr18_reg.rs | 150 + .../da14531/src/patch/patch_addr19_reg.rs | 150 + .../da14531/src/patch/patch_addr1_reg.rs | 150 + .../da14531/src/patch/patch_addr20_reg.rs | 150 + .../da14531/src/patch/patch_addr21_reg.rs | 150 + .../da14531/src/patch/patch_addr2_reg.rs | 150 + .../da14531/src/patch/patch_addr3_reg.rs | 150 + .../da14531/src/patch/patch_addr4_reg.rs | 150 + .../da14531/src/patch/patch_addr5_reg.rs | 150 + .../da14531/src/patch/patch_addr6_reg.rs | 150 + .../da14531/src/patch/patch_addr7_reg.rs | 150 + .../da14531/src/patch/patch_addr8_reg.rs | 150 + .../da14531/src/patch/patch_addr9_reg.rs | 150 + .../da14531/src/patch/patch_data20_reg.rs | 103 + .../da14531/src/patch/patch_data21_reg.rs | 103 + .../da14531/src/patch/patch_valid_reg.rs | 103 + bitbox02-bt/vendor/da14531/src/quadec.rs | 46 + .../da14531/src/quadec/qdec_clockdiv_reg.rs | 150 + .../da14531/src/quadec/qdec_ctrl2_reg.rs | 462 ++ .../da14531/src/quadec/qdec_ctrl_reg.rs | 244 + .../da14531/src/quadec/qdec_event_cnt_reg.rs | 86 + .../da14531/src/quadec/qdec_xcnt_reg.rs | 86 + .../da14531/src/quadec/qdec_ycnt_reg.rs | 86 + .../da14531/src/quadec/qdec_zcnt_reg.rs | 86 + bitbox02-bt/vendor/da14531/src/rfcu.rs | 193 + .../da14531/src/rfcu/rf_adc_ctrl1_reg.rs | 207 + .../da14531/src/rfcu/rf_adc_ctrl2_reg.rs | 140 + .../da14531/src/rfcu/rf_adc_ctrl3_reg.rs | 140 + .../da14531/src/rfcu/rf_adci_dc_offset_reg.rs | 106 + .../da14531/src/rfcu/rf_adcq_dc_offset_reg.rs | 106 + .../da14531/src/rfcu/rf_adplldig_ctrl_reg.rs | 197 + .../src/rfcu/rf_adplldig_rfmon_ctrl_reg.rs | 187 + .../da14531/src/rfcu/rf_agc_ext_lut_reg.rs | 103 + .../vendor/da14531/src/rfcu/rf_attr_reg.rs | 234 + .../da14531/src/rfcu/rf_cal_ctrl_reg.rs | 207 + .../da14531/src/rfcu/rf_calstate_reg.rs | 86 + .../da14531/src/rfcu/rf_diagirq_ctrl_reg.rs | 738 ++ .../da14531/src/rfcu/rf_diagirq_stat_reg.rs | 86 + .../da14531/src/rfcu/rf_iff_ctrl_reg.rs | 318 + .../vendor/da14531/src/rfcu/rf_io_ctrl_reg.rs | 140 + .../da14531/src/rfcu/rf_irq_ctrl_reg.rs | 91 + .../da14531/src/rfcu/rf_ldo_ctrl_reg.rs | 637 ++ .../da14531/src/rfcu/rf_ldo_status_reg.rs | 246 + .../da14531/src/rfcu/rf_ldo_vref_sel_reg.rs | 207 + .../da14531/src/rfcu/rf_lna_ctrl1_reg.rs | 251 + .../da14531/src/rfcu/rf_lna_ctrl2_reg.rs | 251 + .../da14531/src/rfcu/rf_lna_ctrl3_reg.rs | 325 + .../da14531/src/rfcu/rf_mixer_ctrl1_reg.rs | 140 + .../da14531/src/rfcu/rf_mixer_ctrl2_reg.rs | 187 + .../da14531/src/rfcu/rf_overrule_reg.rs | 140 + .../vendor/da14531/src/rfcu/rf_pa_ctrl_reg.rs | 177 + .../da14531/src/rfcu/rf_radio_init_reg.rs | 583 ++ .../da14531/src/rfcu/rf_rfcu_ctrl_reg.rs | 113 + .../da14531/src/rfcu/rf_scan_feedback_reg.rs | 64 + .../vendor/da14531/src/rfcu/rf_spare_reg.rs | 207 + bitbox02-bt/vendor/da14531/src/rfcu_power.rs | 498 ++ .../src/rfcu_power/rf_always_en1_reg.rs | 1570 ++++ .../src/rfcu_power/rf_always_en2_reg.rs | 771 ++ .../src/rfcu_power/rf_cntrl_timer_10_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_11_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_12_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_13_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_14_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_15_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_16_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_17_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_18_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_19_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_1_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_20_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_21_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_22_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_23_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_24_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_25_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_26_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_27_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_28_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_29_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_2_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_30_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_31_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_3_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_4_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_5_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_6_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_7_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_8_reg.rs | 140 + .../src/rfcu_power/rf_cntrl_timer_9_reg.rs | 140 + .../src/rfcu_power/rf_enable_config0_reg.rs | 140 + .../src/rfcu_power/rf_enable_config10_reg.rs | 140 + .../src/rfcu_power/rf_enable_config11_reg.rs | 140 + .../src/rfcu_power/rf_enable_config12_reg.rs | 140 + .../src/rfcu_power/rf_enable_config13_reg.rs | 140 + .../src/rfcu_power/rf_enable_config14_reg.rs | 140 + .../src/rfcu_power/rf_enable_config15_reg.rs | 140 + .../src/rfcu_power/rf_enable_config16_reg.rs | 140 + .../src/rfcu_power/rf_enable_config17_reg.rs | 140 + .../src/rfcu_power/rf_enable_config18_reg.rs | 140 + .../src/rfcu_power/rf_enable_config19_reg.rs | 140 + .../src/rfcu_power/rf_enable_config1_reg.rs | 140 + .../src/rfcu_power/rf_enable_config20_reg.rs | 140 + .../src/rfcu_power/rf_enable_config21_reg.rs | 140 + .../src/rfcu_power/rf_enable_config22_reg.rs | 140 + .../src/rfcu_power/rf_enable_config23_reg.rs | 140 + .../src/rfcu_power/rf_enable_config24_reg.rs | 140 + .../src/rfcu_power/rf_enable_config25_reg.rs | 140 + .../src/rfcu_power/rf_enable_config26_reg.rs | 140 + .../src/rfcu_power/rf_enable_config27_reg.rs | 140 + .../src/rfcu_power/rf_enable_config28_reg.rs | 140 + .../src/rfcu_power/rf_enable_config29_reg.rs | 140 + .../src/rfcu_power/rf_enable_config2_reg.rs | 140 + .../src/rfcu_power/rf_enable_config30_reg.rs | 140 + .../src/rfcu_power/rf_enable_config31_reg.rs | 140 + .../src/rfcu_power/rf_enable_config32_reg.rs | 140 + .../src/rfcu_power/rf_enable_config33_reg.rs | 140 + .../src/rfcu_power/rf_enable_config34_reg.rs | 140 + .../src/rfcu_power/rf_enable_config35_reg.rs | 140 + .../src/rfcu_power/rf_enable_config36_reg.rs | 140 + .../src/rfcu_power/rf_enable_config37_reg.rs | 140 + .../src/rfcu_power/rf_enable_config38_reg.rs | 140 + .../src/rfcu_power/rf_enable_config39_reg.rs | 140 + .../src/rfcu_power/rf_enable_config3_reg.rs | 140 + .../src/rfcu_power/rf_enable_config40_reg.rs | 140 + .../src/rfcu_power/rf_enable_config41_reg.rs | 140 + .../src/rfcu_power/rf_enable_config42_reg.rs | 140 + .../src/rfcu_power/rf_enable_config43_reg.rs | 140 + .../src/rfcu_power/rf_enable_config44_reg.rs | 140 + .../src/rfcu_power/rf_enable_config45_reg.rs | 140 + .../src/rfcu_power/rf_enable_config46_reg.rs | 140 + .../src/rfcu_power/rf_enable_config4_reg.rs | 140 + .../src/rfcu_power/rf_enable_config5_reg.rs | 140 + .../src/rfcu_power/rf_enable_config6_reg.rs | 140 + .../src/rfcu_power/rf_enable_config7_reg.rs | 140 + .../src/rfcu_power/rf_enable_config8_reg.rs | 140 + .../src/rfcu_power/rf_enable_config9_reg.rs | 140 + .../da14531/src/rfcu_power/rf_port_en_reg.rs | 536 ++ .../da14531/src/rfcu_power/rf_port_pol_reg.rs | 301 + bitbox02-bt/vendor/da14531/src/rfmon.rs | 45 + .../da14531/src/rfmon/rfmon_addr_reg.rs | 103 + .../da14531/src/rfmon/rfmon_crv_addr_reg.rs | 86 + .../da14531/src/rfmon/rfmon_crv_len_reg.rs | 86 + .../da14531/src/rfmon/rfmon_ctrl_reg.rs | 160 + .../vendor/da14531/src/rfmon/rfmon_len_reg.rs | 103 + .../da14531/src/rfmon/rfmon_stat_reg.rs | 133 + bitbox02-bt/vendor/da14531/src/rtc.rs | 86 + .../da14531/src/rtc/rtc_alarm_enable_reg.rs | 348 + .../da14531/src/rtc/rtc_calendar_alarm_reg.rs | 224 + .../da14531/src/rtc/rtc_calendar_reg.rs | 456 ++ .../vendor/da14531/src/rtc/rtc_control_reg.rs | 160 + .../da14531/src/rtc/rtc_event_flags_reg.rs | 206 + .../da14531/src/rtc/rtc_hour_mode_reg.rs | 113 + .../src/rtc/rtc_interrupt_disable_reg.rs | 253 + .../src/rtc/rtc_interrupt_enable_reg.rs | 253 + .../da14531/src/rtc/rtc_interrupt_mask_reg.rs | 206 + .../da14531/src/rtc/rtc_keep_rtc_reg.rs | 113 + .../vendor/da14531/src/rtc/rtc_status_reg.rs | 146 + .../da14531/src/rtc/rtc_time_alarm_reg.rs | 409 ++ .../vendor/da14531/src/rtc/rtc_time_reg.rs | 456 ++ bitbox02-bt/vendor/da14531/src/spi.rs | 98 + .../vendor/da14531/src/spi/spi_clock_reg.rs | 150 + .../vendor/da14531/src/spi/spi_config_reg.rs | 187 + .../da14531/src/spi/spi_cs_config_reg.rs | 103 + .../vendor/da14531/src/spi/spi_ctrl_reg.rs | 442 ++ .../da14531/src/spi/spi_fifo_config_reg.rs | 140 + .../da14531/src/spi/spi_fifo_high_reg.rs | 103 + .../da14531/src/spi/spi_fifo_read_reg.rs | 86 + .../da14531/src/spi/spi_fifo_status_reg.rs | 186 + .../da14531/src/spi/spi_fifo_write_reg.rs | 81 + .../da14531/src/spi/spi_irq_mask_reg.rs | 160 + .../vendor/da14531/src/spi/spi_status_reg.rs | 106 + .../src/spi/spi_txbuffer_force_h_reg.rs | 81 + .../src/spi/spi_txbuffer_force_l_reg.rs | 81 + bitbox02-bt/vendor/da14531/src/sys_tick.rs | 28 + .../vendor/da14531/src/sys_tick/calib.rs | 95 + .../vendor/da14531/src/sys_tick/ctrl.rs | 254 + .../vendor/da14531/src/sys_tick/load.rs | 107 + .../vendor/da14531/src/sys_tick/val.rs | 107 + bitbox02-bt/vendor/da14531/src/sys_wdog.rs | 16 + .../da14531/src/sys_wdog/watchdog_ctrl_reg.rs | 113 + .../da14531/src/sys_wdog/watchdog_reg.rs | 175 + bitbox02-bt/vendor/da14531/src/timer0.rs | 112 + .../da14531/src/timer0/pwm2_end_cycle.rs | 103 + .../da14531/src/timer0/pwm2_start_cycle.rs | 103 + .../da14531/src/timer0/pwm3_end_cycle.rs | 103 + .../da14531/src/timer0/pwm3_start_cycle.rs | 103 + .../da14531/src/timer0/pwm4_end_cycle.rs | 103 + .../da14531/src/timer0/pwm4_start_cycle.rs | 103 + .../da14531/src/timer0/pwm5_end_cycle.rs | 103 + .../da14531/src/timer0/pwm5_start_cycle.rs | 103 + .../da14531/src/timer0/pwm6_end_cycle.rs | 103 + .../da14531/src/timer0/pwm6_start_cycle.rs | 103 + .../da14531/src/timer0/pwm7_end_cycle.rs | 103 + .../da14531/src/timer0/pwm7_start_cycle.rs | 103 + .../da14531/src/timer0/timer0_ctrl_reg.rs | 254 + .../da14531/src/timer0/timer0_on_reg.rs | 103 + .../da14531/src/timer0/timer0_reload_m_reg.rs | 103 + .../da14531/src/timer0/timer0_reload_n_reg.rs | 103 + .../da14531/src/timer0/triple_pwm_ctrl_reg.rs | 254 + .../src/timer0/triple_pwm_frequency.rs | 103 + bitbox02-bt/vendor/da14531/src/timer1.rs | 44 + .../src/timer1/timer1_capcnt1_value_reg.rs | 106 + .../src/timer1/timer1_capcnt2_value_reg.rs | 106 + .../da14531/src/timer1/timer1_capture_reg.rs | 590 ++ .../src/timer1/timer1_clr_event_reg.rs | 207 + .../da14531/src/timer1/timer1_ctrl_reg.rs | 385 + .../da14531/src/timer1/timer1_status_reg.rs | 186 + bitbox02-bt/vendor/da14531/src/uart.rs | 294 + .../da14531/src/uart/uart_ctr_high_reg.rs | 86 + .../vendor/da14531/src/uart/uart_ctr_reg.rs | 86 + .../vendor/da14531/src/uart/uart_dlf_reg.rs | 103 + .../vendor/da14531/src/uart/uart_dmasa_reg.rs | 91 + .../vendor/da14531/src/uart/uart_far_reg.rs | 86 + .../vendor/da14531/src/uart/uart_htx_reg.rs | 113 + .../da14531/src/uart/uart_ier_dlh_reg.rs | 338 + .../da14531/src/uart/uart_iir_fcr_reg.rs | 308 + .../vendor/da14531/src/uart/uart_lcr_reg.rs | 366 + .../vendor/da14531/src/uart/uart_lsr_reg.rs | 238 + .../vendor/da14531/src/uart/uart_mcr_reg.rs | 239 + .../vendor/da14531/src/uart/uart_msr_reg.rs | 90 + .../da14531/src/uart/uart_rbr_thr_dll_reg.rs | 119 + .../vendor/da14531/src/uart/uart_rfl_reg.rs | 86 + .../vendor/da14531/src/uart/uart_sbcr_reg.rs | 117 + .../vendor/da14531/src/uart/uart_scr_reg.rs | 103 + .../vendor/da14531/src/uart/uart_sdmam_reg.rs | 113 + .../vendor/da14531/src/uart/uart_sfe_reg.rs | 113 + .../da14531/src/uart/uart_srbr_sthr0_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr10_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr11_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr12_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr13_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr14_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr15_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr1_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr2_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr3_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr4_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr5_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr6_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr7_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr8_reg.rs | 119 + .../da14531/src/uart/uart_srbr_sthr9_reg.rs | 119 + .../vendor/da14531/src/uart/uart_srr_reg.rs | 145 + .../vendor/da14531/src/uart/uart_srt_reg.rs | 103 + .../vendor/da14531/src/uart/uart_srts_reg.rs | 133 + .../vendor/da14531/src/uart/uart_stet_reg.rs | 103 + .../vendor/da14531/src/uart/uart_tfl_reg.rs | 86 + .../da14531/src/uart/uart_ucv_high_reg.rs | 86 + .../vendor/da14531/src/uart/uart_ucv_reg.rs | 86 + .../vendor/da14531/src/uart/uart_usr_reg.rs | 166 + bitbox02-bt/vendor/da14531/src/uart2.rs | 280 + .../da14531/src/uart2/uart2_ctr_high_reg.rs | 86 + .../vendor/da14531/src/uart2/uart2_ctr_reg.rs | 86 + .../vendor/da14531/src/uart2/uart2_dlf_reg.rs | 103 + .../da14531/src/uart2/uart2_dmasa_reg.rs | 91 + .../vendor/da14531/src/uart2/uart2_far_reg.rs | 86 + .../vendor/da14531/src/uart2/uart2_htx_reg.rs | 113 + .../da14531/src/uart2/uart2_ier_dlh_reg.rs | 338 + .../da14531/src/uart2/uart2_iir_fcr_reg.rs | 308 + .../vendor/da14531/src/uart2/uart2_lcr_reg.rs | 366 + .../vendor/da14531/src/uart2/uart2_lsr_reg.rs | 238 + .../vendor/da14531/src/uart2/uart2_mcr_reg.rs | 121 + .../src/uart2/uart2_rbr_thr_dll_reg.rs | 119 + .../vendor/da14531/src/uart2/uart2_rfl_reg.rs | 86 + .../da14531/src/uart2/uart2_sbcr_reg.rs | 117 + .../vendor/da14531/src/uart2/uart2_scr_reg.rs | 103 + .../da14531/src/uart2/uart2_sdmam_reg.rs | 113 + .../vendor/da14531/src/uart2/uart2_sfe_reg.rs | 113 + .../da14531/src/uart2/uart2_srbr_sthr0_reg.rs | 119 + .../src/uart2/uart2_srbr_sthr10_reg.rs | 119 + .../src/uart2/uart2_srbr_sthr11_reg.rs | 119 + .../src/uart2/uart2_srbr_sthr12_reg.rs | 119 + .../src/uart2/uart2_srbr_sthr13_reg.rs | 119 + .../src/uart2/uart2_srbr_sthr14_reg.rs | 119 + .../src/uart2/uart2_srbr_sthr15_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr1_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr2_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr3_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr4_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr5_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr6_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr7_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr8_reg.rs | 119 + .../da14531/src/uart2/uart2_srbr_sthr9_reg.rs | 119 + .../vendor/da14531/src/uart2/uart2_srr_reg.rs | 145 + .../vendor/da14531/src/uart2/uart2_srt_reg.rs | 103 + .../da14531/src/uart2/uart2_stet_reg.rs | 103 + .../vendor/da14531/src/uart2/uart2_tfl_reg.rs | 86 + .../da14531/src/uart2/uart2_ucv_high_reg.rs | 86 + .../vendor/da14531/src/uart2/uart2_ucv_reg.rs | 86 + .../vendor/da14531/src/uart2/uart2_usr_reg.rs | 166 + bitbox02-bt/vendor/da14531/src/wkup.rs | 52 + .../da14531/src/wkup/wkup2_pol_gpio_reg.rs | 103 + .../da14531/src/wkup/wkup2_select_gpio_reg.rs | 103 + .../da14531/src/wkup/wkup_compare_reg.rs | 103 + .../da14531/src/wkup/wkup_counter_reg.rs | 106 + .../vendor/da14531/src/wkup/wkup_ctrl_reg.rs | 244 + .../da14531/src/wkup/wkup_irq_status_reg.rs | 214 + .../da14531/src/wkup/wkup_pol_gpio_reg.rs | 103 + .../da14531/src/wkup/wkup_select_gpio_reg.rs | 103 + bitbox02-bt/vendor/da14531/update.sh | 15 + .../vendor/embedded-hal/.cargo-checksum.json | 1 + bitbox02-bt/vendor/embedded-hal/CHANGELOG.md | 143 + .../vendor/embedded-hal/CODE_OF_CONDUCT.md | 37 + bitbox02-bt/vendor/embedded-hal/Cargo.toml | 38 + .../vendor/embedded-hal/LICENSE-APACHE | 201 + bitbox02-bt/vendor/embedded-hal/LICENSE-MIT | 25 + bitbox02-bt/vendor/embedded-hal/README.md | 86 + bitbox02-bt/vendor/embedded-hal/src/adc.rs | 98 + .../vendor/embedded-hal/src/blocking/can.rs | 17 + .../vendor/embedded-hal/src/blocking/delay.rs | 26 + .../vendor/embedded-hal/src/blocking/i2c.rs | 297 + .../vendor/embedded-hal/src/blocking/mod.rs | 12 + .../vendor/embedded-hal/src/blocking/rng.rs | 19 + .../embedded-hal/src/blocking/serial.rs | 54 + .../vendor/embedded-hal/src/blocking/spi.rs | 127 + bitbox02-bt/vendor/embedded-hal/src/can/id.rs | 160 + .../vendor/embedded-hal/src/can/mod.rs | 123 + bitbox02-bt/vendor/embedded-hal/src/can/nb.rs | 28 + .../vendor/embedded-hal/src/digital/mod.rs | 27 + .../vendor/embedded-hal/src/digital/v1.rs | 145 + .../embedded-hal/src/digital/v1_compat.rs | 298 + .../vendor/embedded-hal/src/digital/v2.rs | 216 + .../embedded-hal/src/digital/v2_compat.rs | 234 + bitbox02-bt/vendor/embedded-hal/src/fmt.rs | 18 + bitbox02-bt/vendor/embedded-hal/src/lib.rs | 999 +++ .../vendor/embedded-hal/src/prelude.rs | 44 + bitbox02-bt/vendor/embedded-hal/src/serial.rs | 27 + bitbox02-bt/vendor/embedded-hal/src/spi.rs | 78 + bitbox02-bt/vendor/embedded-hal/src/timer.rs | 95 + .../vendor/embedded-hal/src/watchdog.rs | 30 + .../vendor/envsubst/.cargo-checksum.json | 1 + bitbox02-bt/vendor/envsubst/COPYRIGHT | 7 + bitbox02-bt/vendor/envsubst/Cargo.toml | 36 + .../vendor/envsubst/LICENSE-APACHE-2.0 | 202 + bitbox02-bt/vendor/envsubst/LICENSE-MIT | 18 + bitbox02-bt/vendor/envsubst/README.md | 25 + bitbox02-bt/vendor/envsubst/src/lib.rs | 171 + .../vendor/equivalent/.cargo-checksum.json | 1 + bitbox02-bt/vendor/equivalent/Cargo.toml | 27 + bitbox02-bt/vendor/equivalent/LICENSE-APACHE | 201 + bitbox02-bt/vendor/equivalent/LICENSE-MIT | 25 + bitbox02-bt/vendor/equivalent/README.md | 25 + bitbox02-bt/vendor/equivalent/src/lib.rs | 113 + .../vendor/grounded/.cargo-checksum.json | 1 + bitbox02-bt/vendor/grounded/Cargo.toml | 37 + bitbox02-bt/vendor/grounded/LICENSE-APACHE | 201 + bitbox02-bt/vendor/grounded/LICENSE-MIT | 25 + bitbox02-bt/vendor/grounded/README.md | 23 + .../vendor/grounded/src/alloc_single.rs | 166 + bitbox02-bt/vendor/grounded/src/const_init.rs | 50 + bitbox02-bt/vendor/grounded/src/lib.rs | 8 + bitbox02-bt/vendor/grounded/src/uninit.rs | 317 + .../vendor/hashbrown/.cargo-checksum.json | 1 + bitbox02-bt/vendor/hashbrown/CHANGELOG.md | 571 ++ bitbox02-bt/vendor/hashbrown/Cargo.toml | 178 + bitbox02-bt/vendor/hashbrown/LICENSE-APACHE | 201 + bitbox02-bt/vendor/hashbrown/LICENSE-MIT | 25 + bitbox02-bt/vendor/hashbrown/README.md | 81 + bitbox02-bt/vendor/hashbrown/benches/bench.rs | 331 + .../benches/insert_unique_unchecked.rs | 34 + .../vendor/hashbrown/benches/set_ops.rs | 148 + bitbox02-bt/vendor/hashbrown/clippy.toml | 1 + .../external_trait_impls/borsh/hash_map.rs | 78 + .../src/external_trait_impls/borsh/mod.rs | 1 + .../hashbrown/src/external_trait_impls/mod.rs | 6 + .../src/external_trait_impls/rayon/helpers.rs | 27 + .../src/external_trait_impls/rayon/map.rs | 721 ++ .../src/external_trait_impls/rayon/mod.rs | 5 + .../src/external_trait_impls/rayon/raw.rs | 230 + .../src/external_trait_impls/rayon/set.rs | 659 ++ .../src/external_trait_impls/rayon/table.rs | 249 + .../src/external_trait_impls/serde.rs | 220 + bitbox02-bt/vendor/hashbrown/src/lib.rs | 177 + bitbox02-bt/vendor/hashbrown/src/macros.rs | 70 + bitbox02-bt/vendor/hashbrown/src/map.rs | 6510 +++++++++++++++++ bitbox02-bt/vendor/hashbrown/src/raw/alloc.rs | 86 + .../vendor/hashbrown/src/raw/bitmask.rs | 117 + .../vendor/hashbrown/src/raw/generic.rs | 157 + bitbox02-bt/vendor/hashbrown/src/raw/mod.rs | 4464 +++++++++++ bitbox02-bt/vendor/hashbrown/src/raw/neon.rs | 124 + bitbox02-bt/vendor/hashbrown/src/raw/sse2.rs | 149 + bitbox02-bt/vendor/hashbrown/src/raw_entry.rs | 1740 +++++ .../vendor/hashbrown/src/rustc_entry.rs | 567 ++ .../vendor/hashbrown/src/scopeguard.rs | 72 + bitbox02-bt/vendor/hashbrown/src/set.rs | 3106 ++++++++ bitbox02-bt/vendor/hashbrown/src/table.rs | 2383 ++++++ .../hashbrown/tests/equivalent_trait.rs | 53 + bitbox02-bt/vendor/hashbrown/tests/hasher.rs | 65 + bitbox02-bt/vendor/hashbrown/tests/rayon.rs | 535 ++ bitbox02-bt/vendor/hashbrown/tests/serde.rs | 65 + bitbox02-bt/vendor/hashbrown/tests/set.rs | 34 + .../vendor/indexmap/.cargo-checksum.json | 1 + bitbox02-bt/vendor/indexmap/Cargo.toml | 152 + bitbox02-bt/vendor/indexmap/LICENSE-APACHE | 201 + bitbox02-bt/vendor/indexmap/LICENSE-MIT | 25 + bitbox02-bt/vendor/indexmap/README.md | 59 + bitbox02-bt/vendor/indexmap/RELEASES.md | 531 ++ bitbox02-bt/vendor/indexmap/benches/bench.rs | 763 ++ .../vendor/indexmap/benches/faststring.rs | 185 + bitbox02-bt/vendor/indexmap/src/arbitrary.rs | 77 + bitbox02-bt/vendor/indexmap/src/borsh.rs | 122 + bitbox02-bt/vendor/indexmap/src/lib.rs | 274 + bitbox02-bt/vendor/indexmap/src/macros.rs | 178 + bitbox02-bt/vendor/indexmap/src/map.rs | 1578 ++++ bitbox02-bt/vendor/indexmap/src/map/core.rs | 718 ++ .../vendor/indexmap/src/map/core/entry.rs | 535 ++ .../indexmap/src/map/core/raw_entry_v1.rs | 666 ++ bitbox02-bt/vendor/indexmap/src/map/iter.rs | 775 ++ .../vendor/indexmap/src/map/mutable.rs | 166 + .../vendor/indexmap/src/map/serde_seq.rs | 138 + bitbox02-bt/vendor/indexmap/src/map/slice.rs | 539 ++ bitbox02-bt/vendor/indexmap/src/map/tests.rs | 830 +++ bitbox02-bt/vendor/indexmap/src/rayon/map.rs | 663 ++ bitbox02-bt/vendor/indexmap/src/rayon/mod.rs | 29 + bitbox02-bt/vendor/indexmap/src/rayon/set.rs | 756 ++ bitbox02-bt/vendor/indexmap/src/rustc.rs | 158 + bitbox02-bt/vendor/indexmap/src/serde.rs | 166 + bitbox02-bt/vendor/indexmap/src/set.rs | 1290 ++++ bitbox02-bt/vendor/indexmap/src/set/iter.rs | 627 ++ .../vendor/indexmap/src/set/mutable.rs | 86 + bitbox02-bt/vendor/indexmap/src/set/slice.rs | 340 + bitbox02-bt/vendor/indexmap/src/set/tests.rs | 723 ++ bitbox02-bt/vendor/indexmap/src/util.rs | 53 + .../vendor/indexmap/tests/equivalent_trait.rs | 53 + .../vendor/indexmap/tests/macros_full_path.rs | 19 + bitbox02-bt/vendor/indexmap/tests/quick.rs | 759 ++ bitbox02-bt/vendor/indexmap/tests/tests.rs | 28 + bitbox02-bt/vendor/itoa/.cargo-checksum.json | 1 + bitbox02-bt/vendor/itoa/Cargo.toml | 43 + bitbox02-bt/vendor/itoa/LICENSE-APACHE | 176 + bitbox02-bt/vendor/itoa/LICENSE-MIT | 23 + bitbox02-bt/vendor/itoa/README.md | 59 + bitbox02-bt/vendor/itoa/benches/bench.rs | 55 + bitbox02-bt/vendor/itoa/src/lib.rs | 309 + bitbox02-bt/vendor/itoa/src/udiv128.rs | 48 + bitbox02-bt/vendor/itoa/tests/test.rs | 30 + .../vendor/nb-0.1.3/.cargo-checksum.json | 1 + bitbox02-bt/vendor/nb-0.1.3/CHANGELOG.md | 37 + bitbox02-bt/vendor/nb-0.1.3/Cargo.toml | 34 + bitbox02-bt/vendor/nb-0.1.3/LICENSE-APACHE | 201 + bitbox02-bt/vendor/nb-0.1.3/LICENSE-MIT | 25 + bitbox02-bt/vendor/nb-0.1.3/README.md | 25 + bitbox02-bt/vendor/nb-0.1.3/bors.toml | 3 + bitbox02-bt/vendor/nb-0.1.3/src/lib.rs | 438 ++ bitbox02-bt/vendor/nb/.cargo-checksum.json | 1 + bitbox02-bt/vendor/nb/CHANGELOG.md | 46 + bitbox02-bt/vendor/nb/CODE_OF_CONDUCT.md | 37 + bitbox02-bt/vendor/nb/Cargo.toml | 40 + bitbox02-bt/vendor/nb/LICENSE-APACHE | 201 + bitbox02-bt/vendor/nb/LICENSE-MIT | 25 + bitbox02-bt/vendor/nb/README.md | 37 + bitbox02-bt/vendor/nb/src/lib.rs | 283 + bitbox02-bt/vendor/nb/triagebot.toml | 1 + .../vendor/panic-abort/.cargo-checksum.json | 1 + bitbox02-bt/vendor/panic-abort/CHANGELOG.md | 48 + bitbox02-bt/vendor/panic-abort/Cargo.toml | 22 + bitbox02-bt/vendor/panic-abort/LICENSE-APACHE | 201 + bitbox02-bt/vendor/panic-abort/LICENSE-MIT | 25 + bitbox02-bt/vendor/panic-abort/README.md | 19 + .../vendor/panic-abort/ci/after-success.sh | 20 + bitbox02-bt/vendor/panic-abort/ci/install.sh | 9 + bitbox02-bt/vendor/panic-abort/ci/script.sh | 7 + bitbox02-bt/vendor/panic-abort/src/lib.rs | 50 + bitbox02-bt/vendor/paste/.cargo-checksum.json | 1 + bitbox02-bt/vendor/paste/Cargo.toml | 72 + bitbox02-bt/vendor/paste/LICENSE-APACHE | 176 + bitbox02-bt/vendor/paste/LICENSE-MIT | 23 + bitbox02-bt/vendor/paste/README.md | 157 + bitbox02-bt/vendor/paste/build.rs | 38 + bitbox02-bt/vendor/paste/src/attr.rs | 164 + bitbox02-bt/vendor/paste/src/error.rs | 47 + bitbox02-bt/vendor/paste/src/lib.rs | 454 ++ bitbox02-bt/vendor/paste/src/segment.rs | 233 + bitbox02-bt/vendor/paste/tests/compiletest.rs | 7 + bitbox02-bt/vendor/paste/tests/test_attr.rs | 62 + bitbox02-bt/vendor/paste/tests/test_doc.rs | 79 + bitbox02-bt/vendor/paste/tests/test_expr.rs | 285 + bitbox02-bt/vendor/paste/tests/test_item.rs | 271 + .../vendor/paste/tests/ui/case-warning.rs | 15 + .../vendor/paste/tests/ui/case-warning.stderr | 16 + .../vendor/paste/tests/ui/env-empty.rs | 7 + .../vendor/paste/tests/ui/env-empty.stderr | 5 + .../vendor/paste/tests/ui/env-non-string.rs | 7 + .../paste/tests/ui/env-non-string.stderr | 5 + .../vendor/paste/tests/ui/env-suffix.rs | 7 + .../vendor/paste/tests/ui/env-suffix.stderr | 5 + .../vendor/paste/tests/ui/env-unexpected.rs | 7 + .../paste/tests/ui/env-unexpected.stderr | 5 + .../vendor/paste/tests/ui/invalid-ident.rs | 15 + .../paste/tests/ui/invalid-ident.stderr | 26 + .../paste/tests/ui/missing-paren-on-env.rs | 7 + .../tests/ui/missing-paren-on-env.stderr | 5 + .../vendor/paste/tests/ui/no-env-var.rs | 7 + .../vendor/paste/tests/ui/no-env-var.stderr | 5 + .../paste/tests/ui/no-ident-after-colon.rs | 7 + .../tests/ui/no-ident-after-colon.stderr | 5 + .../vendor/paste/tests/ui/unexpected-group.rs | 7 + .../paste/tests/ui/unexpected-group.stderr | 5 + .../paste/tests/ui/unexpected-modifier.rs | 7 + .../paste/tests/ui/unexpected-modifier.stderr | 5 + .../vendor/paste/tests/ui/unexpected-punct.rs | 7 + .../paste/tests/ui/unexpected-punct.stderr | 5 + .../paste/tests/ui/unsupported-literal.rs | 21 + .../paste/tests/ui/unsupported-literal.stderr | 23 + .../paste/tests/ui/unsupported-modifier.rs | 7 + .../tests/ui/unsupported-modifier.stderr | 5 + .../portable-atomic/.cargo-checksum.json | 1 + .../vendor/portable-atomic/CHANGELOG.md | 531 ++ bitbox02-bt/vendor/portable-atomic/Cargo.toml | 224 + .../vendor/portable-atomic/LICENSE-APACHE | 177 + .../vendor/portable-atomic/LICENSE-MIT | 23 + bitbox02-bt/vendor/portable-atomic/README.md | 202 + bitbox02-bt/vendor/portable-atomic/build.rs | 514 ++ .../vendor/portable-atomic/no_atomic.rs | 76 + .../vendor/portable-atomic/src/cfgs.rs | 633 ++ .../vendor/portable-atomic/src/gen/utils.rs | 149 + .../src/imp/atomic128/README.md | 36 + .../src/imp/atomic128/aarch64.rs | 2264 ++++++ .../src/imp/atomic128/intrinsics.rs | 515 ++ .../src/imp/atomic128/macros.rs | 356 + .../portable-atomic/src/imp/atomic128/mod.rs | 103 + .../src/imp/atomic128/powerpc64.rs | 945 +++ .../src/imp/atomic128/riscv64.rs | 651 ++ .../src/imp/atomic128/s390x.rs | 466 ++ .../src/imp/atomic128/x86_64.rs | 879 +++ .../src/imp/atomic64/README.md | 20 + .../src/imp/atomic64/arm_linux.rs | 322 + .../src/imp/atomic64/macros.rs | 237 + .../portable-atomic/src/imp/atomic64/mod.rs | 42 + .../src/imp/atomic64/riscv32.rs | 653 ++ .../portable-atomic/src/imp/core_atomic.rs | 439 ++ .../portable-atomic/src/imp/detect/README.md | 33 + .../src/imp/detect/aarch64_aa64reg.rs | 586 ++ .../src/imp/detect/aarch64_apple.rs | 151 + .../src/imp/detect/aarch64_fuchsia.rs | 94 + .../src/imp/detect/aarch64_illumos.rs | 82 + .../src/imp/detect/aarch64_windows.rs | 84 + .../portable-atomic/src/imp/detect/auxv.rs | 853 +++ .../portable-atomic/src/imp/detect/common.rs | 350 + .../src/imp/detect/riscv_linux.rs | 186 + .../portable-atomic/src/imp/detect/x86_64.rs | 137 + .../portable-atomic/src/imp/fallback/mod.rs | 451 ++ .../src/imp/fallback/outline_atomics.rs | 185 + .../src/imp/fallback/seq_lock.rs | 147 + .../src/imp/fallback/seq_lock_wide.rs | 180 + .../portable-atomic/src/imp/fallback/utils.rs | 147 + .../vendor/portable-atomic/src/imp/float.rs | 213 + .../src/imp/interrupt/README.md | 35 + .../src/imp/interrupt/armv4t.rs | 147 + .../src/imp/interrupt/armv6m.rs | 50 + .../portable-atomic/src/imp/interrupt/avr.rs | 59 + .../portable-atomic/src/imp/interrupt/mod.rs | 922 +++ .../src/imp/interrupt/msp430.rs | 66 + .../src/imp/interrupt/riscv.rs | 85 + .../src/imp/interrupt/xtensa.rs | 49 + .../vendor/portable-atomic/src/imp/mod.rs | 477 ++ .../vendor/portable-atomic/src/imp/msp430.rs | 291 + .../vendor/portable-atomic/src/imp/riscv.rs | 919 +++ .../vendor/portable-atomic/src/imp/x86.rs | 236 + bitbox02-bt/vendor/portable-atomic/src/lib.rs | 4995 +++++++++++++ .../portable-atomic/src/tests/helper.rs | 2421 ++++++ .../vendor/portable-atomic/src/tests/mod.rs | 433 ++ .../vendor/portable-atomic/src/utils.rs | 470 ++ bitbox02-bt/vendor/portable-atomic/version.rs | 132 + .../.cargo-checksum.json | 1 + .../vendor/proc-macro-error-attr/Cargo.toml | 33 + .../proc-macro-error-attr/LICENSE-APACHE | 201 + .../vendor/proc-macro-error-attr/LICENSE-MIT | 21 + .../vendor/proc-macro-error-attr/build.rs | 5 + .../vendor/proc-macro-error-attr/src/lib.rs | 121 + .../vendor/proc-macro-error-attr/src/parse.rs | 89 + .../proc-macro-error-attr/src/settings.rs | 72 + .../proc-macro-error/.cargo-checksum.json | 1 + .../vendor/proc-macro-error/CHANGELOG.md | 162 + .../vendor/proc-macro-error/Cargo.toml | 56 + .../vendor/proc-macro-error/LICENSE-APACHE | 201 + .../vendor/proc-macro-error/LICENSE-MIT | 21 + bitbox02-bt/vendor/proc-macro-error/README.md | 258 + bitbox02-bt/vendor/proc-macro-error/build.rs | 11 + .../vendor/proc-macro-error/src/diagnostic.rs | 349 + .../vendor/proc-macro-error/src/dummy.rs | 150 + .../proc-macro-error/src/imp/delegate.rs | 69 + .../proc-macro-error/src/imp/fallback.rs | 30 + .../vendor/proc-macro-error/src/lib.rs | 560 ++ .../vendor/proc-macro-error/src/macros.rs | 288 + .../vendor/proc-macro-error/src/sealed.rs | 3 + .../proc-macro-error/tests/macro-errors.rs | 8 + .../vendor/proc-macro-error/tests/ok.rs | 10 + .../proc-macro-error/tests/runtime-errors.rs | 13 + .../vendor/proc-macro-error/tests/ui/abort.rs | 11 + .../proc-macro-error/tests/ui/abort.stderr | 48 + .../proc-macro-error/tests/ui/append_dummy.rs | 13 + .../tests/ui/append_dummy.stderr | 5 + .../tests/ui/children_messages.rs | 6 + .../tests/ui/children_messages.stderr | 23 + .../vendor/proc-macro-error/tests/ui/dummy.rs | 13 + .../proc-macro-error/tests/ui/dummy.stderr | 5 + .../vendor/proc-macro-error/tests/ui/emit.rs | 7 + .../proc-macro-error/tests/ui/emit.stderr | 48 + .../tests/ui/explicit_span_range.rs | 6 + .../tests/ui/explicit_span_range.stderr | 5 + .../proc-macro-error/tests/ui/misuse.rs | 11 + .../proc-macro-error/tests/ui/misuse.stderr | 13 + .../tests/ui/multiple_tokens.rs | 6 + .../tests/ui/multiple_tokens.stderr | 5 + .../tests/ui/not_proc_macro.rs | 4 + .../tests/ui/not_proc_macro.stderr | 10 + .../proc-macro-error/tests/ui/option_ext.rs | 6 + .../tests/ui/option_ext.stderr | 7 + .../tests/ui/proc_macro_hack.rs | 10 + .../tests/ui/proc_macro_hack.stderr | 26 + .../proc-macro-error/tests/ui/result_ext.rs | 7 + .../tests/ui/result_ext.stderr | 11 + .../tests/ui/to_tokens_span.rs | 6 + .../tests/ui/to_tokens_span.stderr | 11 + .../tests/ui/unknown_setting.rs | 4 + .../tests/ui/unknown_setting.stderr | 5 + .../tests/ui/unrelated_panic.rs | 6 + .../tests/ui/unrelated_panic.stderr | 7 + .../vendor/proc-macro2/.cargo-checksum.json | 1 + bitbox02-bt/vendor/proc-macro2/Cargo.toml | 105 + bitbox02-bt/vendor/proc-macro2/LICENSE-APACHE | 176 + bitbox02-bt/vendor/proc-macro2/LICENSE-MIT | 23 + bitbox02-bt/vendor/proc-macro2/README.md | 94 + bitbox02-bt/vendor/proc-macro2/build.rs | 213 + bitbox02-bt/vendor/proc-macro2/build/probe.rs | 25 + .../vendor/proc-macro2/rust-toolchain.toml | 2 + .../vendor/proc-macro2/src/detection.rs | 75 + bitbox02-bt/vendor/proc-macro2/src/extra.rs | 151 + .../vendor/proc-macro2/src/fallback.rs | 1226 ++++ bitbox02-bt/vendor/proc-macro2/src/lib.rs | 1377 ++++ .../vendor/proc-macro2/src/location.rs | 29 + bitbox02-bt/vendor/proc-macro2/src/marker.rs | 17 + bitbox02-bt/vendor/proc-macro2/src/parse.rs | 996 +++ bitbox02-bt/vendor/proc-macro2/src/rcvec.rs | 145 + bitbox02-bt/vendor/proc-macro2/src/wrapper.rs | 993 +++ .../vendor/proc-macro2/tests/comments.rs | 105 + .../vendor/proc-macro2/tests/features.rs | 8 + .../vendor/proc-macro2/tests/marker.rs | 100 + bitbox02-bt/vendor/proc-macro2/tests/test.rs | 905 +++ .../vendor/proc-macro2/tests/test_fmt.rs | 28 + .../vendor/proc-macro2/tests/test_size.rs | 81 + bitbox02-bt/vendor/quote/.cargo-checksum.json | 1 + bitbox02-bt/vendor/quote/Cargo.toml | 64 + bitbox02-bt/vendor/quote/LICENSE-APACHE | 176 + bitbox02-bt/vendor/quote/LICENSE-MIT | 23 + bitbox02-bt/vendor/quote/README.md | 271 + bitbox02-bt/vendor/quote/rust-toolchain.toml | 2 + bitbox02-bt/vendor/quote/src/ext.rs | 110 + bitbox02-bt/vendor/quote/src/format.rs | 168 + .../vendor/quote/src/ident_fragment.rs | 88 + bitbox02-bt/vendor/quote/src/lib.rs | 1464 ++++ bitbox02-bt/vendor/quote/src/runtime.rs | 530 ++ bitbox02-bt/vendor/quote/src/spanned.rs | 50 + bitbox02-bt/vendor/quote/src/to_tokens.rs | 275 + bitbox02-bt/vendor/quote/tests/compiletest.rs | 7 + bitbox02-bt/vendor/quote/tests/test.rs | 565 ++ .../ui/does-not-have-iter-interpolated-dup.rs | 9 + ...does-not-have-iter-interpolated-dup.stderr | 11 + .../ui/does-not-have-iter-interpolated.rs | 9 + .../ui/does-not-have-iter-interpolated.stderr | 11 + .../tests/ui/does-not-have-iter-separated.rs | 5 + .../ui/does-not-have-iter-separated.stderr | 10 + .../quote/tests/ui/does-not-have-iter.rs | 5 + .../quote/tests/ui/does-not-have-iter.stderr | 10 + .../vendor/quote/tests/ui/not-quotable.rs | 7 + .../vendor/quote/tests/ui/not-quotable.stderr | 20 + .../vendor/quote/tests/ui/not-repeatable.rs | 8 + .../quote/tests/ui/not-repeatable.stderr | 34 + .../vendor/quote/tests/ui/wrong-type-span.rs | 7 + .../quote/tests/ui/wrong-type-span.stderr | 10 + .../rtt-target-0.3.1/.cargo-checksum.json | 1 + .../vendor/rtt-target-0.3.1/Cargo.toml | 34 + .../vendor/rtt-target-0.3.1/src/init.rs | 206 + .../vendor/rtt-target-0.3.1/src/lib.rs | 355 + .../vendor/rtt-target-0.3.1/src/print.rs | 226 + .../vendor/rtt-target-0.3.1/src/rtt.rs | 289 + .../vendor/rtt-target/.cargo-checksum.json | 1 + bitbox02-bt/vendor/rtt-target/Cargo.toml | 33 + bitbox02-bt/vendor/rtt-target/LICENSE | 21 + bitbox02-bt/vendor/rtt-target/README.md | 32 + bitbox02-bt/vendor/rtt-target/src/debug.rs | 45 + bitbox02-bt/vendor/rtt-target/src/init.rs | 207 + bitbox02-bt/vendor/rtt-target/src/lib.rs | 404 + bitbox02-bt/vendor/rtt-target/src/print.rs | 169 + bitbox02-bt/vendor/rtt-target/src/rtt.rs | 282 + .../vendor/rustc_version/.cargo-checksum.json | 1 + bitbox02-bt/vendor/rustc_version/Cargo.toml | 26 + .../vendor/rustc_version/LICENSE-APACHE | 201 + bitbox02-bt/vendor/rustc_version/LICENSE-MIT | 25 + bitbox02-bt/vendor/rustc_version/README.md | 75 + .../vendor/rustc_version/src/errors.rs | 79 + bitbox02-bt/vendor/rustc_version/src/lib.rs | 347 + bitbox02-bt/vendor/ryu/.cargo-checksum.json | 1 + bitbox02-bt/vendor/ryu/Cargo.lock | 149 + bitbox02-bt/vendor/ryu/Cargo.toml | 103 + bitbox02-bt/vendor/ryu/LICENSE-APACHE | 176 + bitbox02-bt/vendor/ryu/LICENSE-BOOST | 23 + bitbox02-bt/vendor/ryu/README.md | 110 + bitbox02-bt/vendor/ryu/benches/bench.rs | 62 + .../vendor/ryu/examples/upstream_benchmark.rs | 85 + bitbox02-bt/vendor/ryu/src/buffer/mod.rs | 171 + bitbox02-bt/vendor/ryu/src/common.rs | 95 + bitbox02-bt/vendor/ryu/src/d2s.rs | 302 + bitbox02-bt/vendor/ryu/src/d2s_full_table.rs | 696 ++ bitbox02-bt/vendor/ryu/src/d2s_intrinsics.rs | 89 + bitbox02-bt/vendor/ryu/src/d2s_small_table.rs | 142 + bitbox02-bt/vendor/ryu/src/digit_table.rs | 28 + bitbox02-bt/vendor/ryu/src/f2s.rs | 178 + bitbox02-bt/vendor/ryu/src/f2s_intrinsics.rs | 113 + bitbox02-bt/vendor/ryu/src/lib.rs | 125 + bitbox02-bt/vendor/ryu/src/parse.rs | 19 + bitbox02-bt/vendor/ryu/src/pretty/exponent.rs | 48 + bitbox02-bt/vendor/ryu/src/pretty/mantissa.rs | 82 + bitbox02-bt/vendor/ryu/src/pretty/mod.rs | 224 + bitbox02-bt/vendor/ryu/src/s2d.rs | 217 + bitbox02-bt/vendor/ryu/src/s2f.rs | 229 + bitbox02-bt/vendor/ryu/tests/common_test.rs | 91 + .../vendor/ryu/tests/d2s_intrinsics_test.rs | 72 + .../vendor/ryu/tests/d2s_table_test.rs | 59 + bitbox02-bt/vendor/ryu/tests/d2s_test.rs | 331 + bitbox02-bt/vendor/ryu/tests/exhaustive.rs | 52 + bitbox02-bt/vendor/ryu/tests/f2s_test.rs | 181 + bitbox02-bt/vendor/ryu/tests/macros/mod.rs | 8 + bitbox02-bt/vendor/ryu/tests/s2d_test.rs | 167 + bitbox02-bt/vendor/ryu/tests/s2f_test.rs | 110 + .../vendor/semver-parser/.cargo-checksum.json | 1 + bitbox02-bt/vendor/semver-parser/Cargo.toml | 11 + .../vendor/semver-parser/LICENSE-APACHE | 201 + bitbox02-bt/vendor/semver-parser/LICENSE-MIT | 25 + .../vendor/semver-parser/src/common.rs | 66 + bitbox02-bt/vendor/semver-parser/src/lib.rs | 8 + bitbox02-bt/vendor/semver-parser/src/range.rs | 696 ++ .../vendor/semver-parser/src/recognize.rs | 154 + .../vendor/semver-parser/src/version.rs | 365 + .../vendor/semver/.cargo-checksum.json | 1 + bitbox02-bt/vendor/semver/Cargo.toml | 45 + bitbox02-bt/vendor/semver/LICENSE-APACHE | 201 + bitbox02-bt/vendor/semver/LICENSE-MIT | 25 + bitbox02-bt/vendor/semver/README.md | 103 + bitbox02-bt/vendor/semver/src/lib.rs | 182 + bitbox02-bt/vendor/semver/src/version.rs | 759 ++ bitbox02-bt/vendor/semver/src/version_req.rs | 895 +++ .../vendor/semver/tests/deprecation.rs | 22 + bitbox02-bt/vendor/semver/tests/regression.rs | 25 + bitbox02-bt/vendor/semver/tests/serde.rs | 90 + bitbox02-bt/vendor/serde/.cargo-checksum.json | 1 + bitbox02-bt/vendor/serde/Cargo.toml | 79 + bitbox02-bt/vendor/serde/LICENSE-APACHE | 176 + bitbox02-bt/vendor/serde/LICENSE-MIT | 23 + bitbox02-bt/vendor/serde/README.md | 114 + bitbox02-bt/vendor/serde/build.rs | 137 + bitbox02-bt/vendor/serde/crates-io.md | 65 + .../vendor/serde/src/de/ignored_any.rs | 238 + bitbox02-bt/vendor/serde/src/de/impls.rs | 3183 ++++++++ bitbox02-bt/vendor/serde/src/de/mod.rs | 2335 ++++++ bitbox02-bt/vendor/serde/src/de/seed.rs | 19 + bitbox02-bt/vendor/serde/src/de/size_hint.rs | 29 + bitbox02-bt/vendor/serde/src/de/value.rs | 1720 +++++ bitbox02-bt/vendor/serde/src/format.rs | 30 + bitbox02-bt/vendor/serde/src/integer128.rs | 9 + bitbox02-bt/vendor/serde/src/lib.rs | 347 + bitbox02-bt/vendor/serde/src/macros.rs | 231 + bitbox02-bt/vendor/serde/src/private/de.rs | 2795 +++++++ bitbox02-bt/vendor/serde/src/private/doc.rs | 162 + bitbox02-bt/vendor/serde/src/private/mod.rs | 48 + bitbox02-bt/vendor/serde/src/private/ser.rs | 1360 ++++ bitbox02-bt/vendor/serde/src/ser/fmt.rs | 170 + bitbox02-bt/vendor/serde/src/ser/impls.rs | 1096 +++ .../vendor/serde/src/ser/impossible.rs | 216 + bitbox02-bt/vendor/serde/src/ser/mod.rs | 1954 +++++ bitbox02-bt/vendor/serde/src/std_error.rs | 48 + .../vendor/serde_derive/.cargo-checksum.json | 1 + bitbox02-bt/vendor/serde_derive/Cargo.toml | 79 + .../vendor/serde_derive/LICENSE-APACHE | 176 + bitbox02-bt/vendor/serde_derive/LICENSE-MIT | 23 + bitbox02-bt/vendor/serde_derive/README.md | 114 + bitbox02-bt/vendor/serde_derive/crates-io.md | 65 + bitbox02-bt/vendor/serde_derive/src/bound.rs | 408 ++ bitbox02-bt/vendor/serde_derive/src/de.rs | 3172 ++++++++ bitbox02-bt/vendor/serde_derive/src/dummy.rs | 23 + .../vendor/serde_derive/src/fragment.rs | 74 + .../vendor/serde_derive/src/internals/ast.rs | 205 + .../vendor/serde_derive/src/internals/attr.rs | 1871 +++++ .../vendor/serde_derive/src/internals/case.rs | 200 + .../serde_derive/src/internals/check.rs | 477 ++ .../vendor/serde_derive/src/internals/ctxt.rs | 68 + .../vendor/serde_derive/src/internals/mod.rs | 27 + .../serde_derive/src/internals/receiver.rs | 292 + .../serde_derive/src/internals/respan.rs | 16 + .../serde_derive/src/internals/symbol.rs | 71 + bitbox02-bt/vendor/serde_derive/src/lib.rs | 102 + .../vendor/serde_derive/src/pretend.rs | 185 + bitbox02-bt/vendor/serde_derive/src/ser.rs | 1350 ++++ bitbox02-bt/vendor/serde_derive/src/this.rs | 32 + .../vendor/serde_yaml/.cargo-checksum.json | 1 + bitbox02-bt/vendor/serde_yaml/Cargo.toml | 62 + bitbox02-bt/vendor/serde_yaml/LICENSE-APACHE | 176 + bitbox02-bt/vendor/serde_yaml/LICENSE-MIT | 23 + bitbox02-bt/vendor/serde_yaml/README.md | 152 + bitbox02-bt/vendor/serde_yaml/src/de.rs | 1846 +++++ bitbox02-bt/vendor/serde_yaml/src/error.rs | 290 + bitbox02-bt/vendor/serde_yaml/src/lib.rs | 191 + .../vendor/serde_yaml/src/libyaml/cstr.rs | 127 + .../vendor/serde_yaml/src/libyaml/emitter.rs | 217 + .../vendor/serde_yaml/src/libyaml/error.rs | 162 + .../vendor/serde_yaml/src/libyaml/mod.rs | 8 + .../vendor/serde_yaml/src/libyaml/parser.rs | 201 + .../vendor/serde_yaml/src/libyaml/tag.rs | 38 + .../vendor/serde_yaml/src/libyaml/util.rs | 48 + bitbox02-bt/vendor/serde_yaml/src/loader.rs | 119 + bitbox02-bt/vendor/serde_yaml/src/mapping.rs | 851 +++ bitbox02-bt/vendor/serde_yaml/src/number.rs | 561 ++ bitbox02-bt/vendor/serde_yaml/src/path.rs | 34 + bitbox02-bt/vendor/serde_yaml/src/ser.rs | 714 ++ bitbox02-bt/vendor/serde_yaml/src/value/de.rs | 1242 ++++ .../vendor/serde_yaml/src/value/debug.rs | 57 + .../vendor/serde_yaml/src/value/from.rs | 178 + .../vendor/serde_yaml/src/value/index.rs | 279 + .../vendor/serde_yaml/src/value/mod.rs | 698 ++ .../vendor/serde_yaml/src/value/partial_eq.rs | 87 + .../vendor/serde_yaml/src/value/ser.rs | 840 +++ .../vendor/serde_yaml/src/value/tagged.rs | 474 ++ bitbox02-bt/vendor/serde_yaml/src/with.rs | 2124 ++++++ .../vendor/serde_yaml/tests/test_de.rs | 717 ++ .../vendor/serde_yaml/tests/test_error.rs | 500 ++ .../vendor/serde_yaml/tests/test_serde.rs | 578 ++ .../vendor/serde_yaml/tests/test_value.rs | 153 + bitbox02-bt/vendor/shlex/.cargo-checksum.json | 1 + bitbox02-bt/vendor/shlex/CHANGELOG.md | 21 + bitbox02-bt/vendor/shlex/Cargo.toml | 35 + bitbox02-bt/vendor/shlex/LICENSE-APACHE | 13 + bitbox02-bt/vendor/shlex/LICENSE-MIT | 21 + bitbox02-bt/vendor/shlex/README.md | 39 + bitbox02-bt/vendor/shlex/src/bytes.rs | 576 ++ bitbox02-bt/vendor/shlex/src/lib.rs | 358 + .../vendor/shlex/src/quoting_warning.md | 365 + .../vendor/syn-1.0.109/.cargo-checksum.json | 1 + bitbox02-bt/vendor/syn-1.0.109/Cargo.toml | 147 + bitbox02-bt/vendor/syn-1.0.109/LICENSE-APACHE | 201 + bitbox02-bt/vendor/syn-1.0.109/LICENSE-MIT | 23 + bitbox02-bt/vendor/syn-1.0.109/README.md | 285 + .../vendor/syn-1.0.109/benches/file.rs | 55 + .../vendor/syn-1.0.109/benches/rust.rs | 170 + bitbox02-bt/vendor/syn-1.0.109/build.rs | 51 + bitbox02-bt/vendor/syn-1.0.109/src/attr.rs | 662 ++ bitbox02-bt/vendor/syn-1.0.109/src/await.rs | 2 + bitbox02-bt/vendor/syn-1.0.109/src/bigint.rs | 66 + bitbox02-bt/vendor/syn-1.0.109/src/buffer.rs | 398 + .../vendor/syn-1.0.109/src/custom_keyword.rs | 253 + .../syn-1.0.109/src/custom_punctuation.rs | 300 + bitbox02-bt/vendor/syn-1.0.109/src/data.rs | 493 ++ bitbox02-bt/vendor/syn-1.0.109/src/derive.rs | 274 + .../vendor/syn-1.0.109/src/discouraged.rs | 194 + bitbox02-bt/vendor/syn-1.0.109/src/drops.rs | 58 + bitbox02-bt/vendor/syn-1.0.109/src/error.rs | 428 ++ bitbox02-bt/vendor/syn-1.0.109/src/export.rs | 39 + bitbox02-bt/vendor/syn-1.0.109/src/expr.rs | 3558 +++++++++ bitbox02-bt/vendor/syn-1.0.109/src/ext.rs | 139 + bitbox02-bt/vendor/syn-1.0.109/src/file.rs | 125 + .../vendor/syn-1.0.109/src/gen/clone.rs | 2241 ++++++ .../vendor/syn-1.0.109/src/gen/debug.rs | 3042 ++++++++ bitbox02-bt/vendor/syn-1.0.109/src/gen/eq.rs | 2195 ++++++ .../vendor/syn-1.0.109/src/gen/fold.rs | 3341 +++++++++ .../vendor/syn-1.0.109/src/gen/hash.rs | 2869 ++++++++ .../vendor/syn-1.0.109/src/gen/visit.rs | 3786 ++++++++++ .../vendor/syn-1.0.109/src/gen/visit_mut.rs | 3786 ++++++++++ .../vendor/syn-1.0.109/src/gen_helper.rs | 154 + .../vendor/syn-1.0.109/src/generics.rs | 1362 ++++ bitbox02-bt/vendor/syn-1.0.109/src/group.rs | 282 + bitbox02-bt/vendor/syn-1.0.109/src/ident.rs | 101 + bitbox02-bt/vendor/syn-1.0.109/src/item.rs | 3313 +++++++++ bitbox02-bt/vendor/syn-1.0.109/src/lib.rs | 984 +++ .../vendor/syn-1.0.109/src/lifetime.rs | 154 + bitbox02-bt/vendor/syn-1.0.109/src/lit.rs | 1599 ++++ .../vendor/syn-1.0.109/src/lookahead.rs | 169 + bitbox02-bt/vendor/syn-1.0.109/src/mac.rs | 219 + bitbox02-bt/vendor/syn-1.0.109/src/macros.rs | 177 + bitbox02-bt/vendor/syn-1.0.109/src/op.rs | 234 + bitbox02-bt/vendor/syn-1.0.109/src/parse.rs | 1314 ++++ .../syn-1.0.109/src/parse_macro_input.rs | 179 + .../vendor/syn-1.0.109/src/parse_quote.rs | 167 + bitbox02-bt/vendor/syn-1.0.109/src/pat.rs | 927 +++ bitbox02-bt/vendor/syn-1.0.109/src/path.rs | 854 +++ bitbox02-bt/vendor/syn-1.0.109/src/print.rs | 16 + .../vendor/syn-1.0.109/src/punctuated.rs | 1087 +++ .../vendor/syn-1.0.109/src/reserved.rs | 44 + bitbox02-bt/vendor/syn-1.0.109/src/sealed.rs | 4 + bitbox02-bt/vendor/syn-1.0.109/src/span.rs | 67 + bitbox02-bt/vendor/syn-1.0.109/src/spanned.rs | 114 + bitbox02-bt/vendor/syn-1.0.109/src/stmt.rs | 349 + bitbox02-bt/vendor/syn-1.0.109/src/thread.rs | 41 + bitbox02-bt/vendor/syn-1.0.109/src/token.rs | 1013 +++ bitbox02-bt/vendor/syn-1.0.109/src/tt.rs | 107 + bitbox02-bt/vendor/syn-1.0.109/src/ty.rs | 1304 ++++ .../vendor/syn-1.0.109/src/verbatim.rs | 33 + .../vendor/syn-1.0.109/src/whitespace.rs | 65 + .../vendor/syn-1.0.109/tests/common/eq.rs | 806 ++ .../vendor/syn-1.0.109/tests/common/mod.rs | 28 + .../vendor/syn-1.0.109/tests/common/parse.rs | 48 + .../vendor/syn-1.0.109/tests/debug/gen.rs | 5640 ++++++++++++++ .../vendor/syn-1.0.109/tests/debug/mod.rs | 125 + .../vendor/syn-1.0.109/tests/macros/mod.rs | 79 + .../vendor/syn-1.0.109/tests/regression.rs | 3 + .../syn-1.0.109/tests/regression/issue1108.rs | 5 + .../syn-1.0.109/tests/regression/issue1235.rs | 32 + .../vendor/syn-1.0.109/tests/repo/mod.rs | 215 + .../vendor/syn-1.0.109/tests/repo/progress.rs | 37 + .../syn-1.0.109/tests/test_asyncness.rs | 37 + .../syn-1.0.109/tests/test_attribute.rs | 336 + .../syn-1.0.109/tests/test_derive_input.rs | 894 +++ .../vendor/syn-1.0.109/tests/test_expr.rs | 306 + .../vendor/syn-1.0.109/tests/test_generics.rs | 285 + .../vendor/syn-1.0.109/tests/test_grouping.rs | 52 + .../vendor/syn-1.0.109/tests/test_ident.rs | 85 + .../vendor/syn-1.0.109/tests/test_item.rs | 336 + .../syn-1.0.109/tests/test_iterators.rs | 68 + .../vendor/syn-1.0.109/tests/test_lit.rs | 270 + .../vendor/syn-1.0.109/tests/test_meta.rs | 378 + .../syn-1.0.109/tests/test_parse_buffer.rs | 92 + .../syn-1.0.109/tests/test_parse_stream.rs | 12 + .../vendor/syn-1.0.109/tests/test_pat.rs | 67 + .../vendor/syn-1.0.109/tests/test_path.rs | 126 + .../syn-1.0.109/tests/test_precedence.rs | 460 ++ .../vendor/syn-1.0.109/tests/test_receiver.rs | 127 + .../syn-1.0.109/tests/test_round_trip.rs | 241 + .../vendor/syn-1.0.109/tests/test_shebang.rs | 59 + .../syn-1.0.109/tests/test_should_parse.rs | 45 + .../vendor/syn-1.0.109/tests/test_size.rs | 29 + .../vendor/syn-1.0.109/tests/test_stmt.rs | 93 + .../syn-1.0.109/tests/test_token_trees.rs | 30 + .../vendor/syn-1.0.109/tests/test_ty.rs | 352 + .../syn-1.0.109/tests/test_visibility.rs | 148 + .../vendor/syn-1.0.109/tests/zzz_stable.rs | 33 + bitbox02-bt/vendor/syn/.cargo-checksum.json | 1 + bitbox02-bt/vendor/syn/Cargo.toml | 264 + bitbox02-bt/vendor/syn/LICENSE-APACHE | 176 + bitbox02-bt/vendor/syn/LICENSE-MIT | 23 + bitbox02-bt/vendor/syn/README.md | 284 + bitbox02-bt/vendor/syn/benches/file.rs | 57 + bitbox02-bt/vendor/syn/benches/rust.rs | 190 + bitbox02-bt/vendor/syn/src/attr.rs | 824 +++ bitbox02-bt/vendor/syn/src/bigint.rs | 66 + bitbox02-bt/vendor/syn/src/buffer.rs | 431 ++ bitbox02-bt/vendor/syn/src/classify.rs | 389 + bitbox02-bt/vendor/syn/src/custom_keyword.rs | 260 + .../vendor/syn/src/custom_punctuation.rs | 304 + bitbox02-bt/vendor/syn/src/data.rs | 501 ++ bitbox02-bt/vendor/syn/src/derive.rs | 259 + bitbox02-bt/vendor/syn/src/discouraged.rs | 225 + bitbox02-bt/vendor/syn/src/drops.rs | 58 + bitbox02-bt/vendor/syn/src/error.rs | 467 ++ bitbox02-bt/vendor/syn/src/export.rs | 73 + bitbox02-bt/vendor/syn/src/expr.rs | 3932 ++++++++++ bitbox02-bt/vendor/syn/src/ext.rs | 136 + bitbox02-bt/vendor/syn/src/file.rs | 125 + bitbox02-bt/vendor/syn/src/fixup.rs | 347 + bitbox02-bt/vendor/syn/src/gen/clone.rs | 2208 ++++++ bitbox02-bt/vendor/syn/src/gen/debug.rs | 3159 ++++++++ bitbox02-bt/vendor/syn/src/gen/eq.rs | 2241 ++++++ bitbox02-bt/vendor/syn/src/gen/fold.rs | 3779 ++++++++++ bitbox02-bt/vendor/syn/src/gen/hash.rs | 2806 +++++++ bitbox02-bt/vendor/syn/src/gen/visit.rs | 3858 ++++++++++ bitbox02-bt/vendor/syn/src/gen/visit_mut.rs | 3855 ++++++++++ bitbox02-bt/vendor/syn/src/generics.rs | 1284 ++++ bitbox02-bt/vendor/syn/src/group.rs | 291 + bitbox02-bt/vendor/syn/src/ident.rs | 108 + bitbox02-bt/vendor/syn/src/item.rs | 3445 +++++++++ bitbox02-bt/vendor/syn/src/lib.rs | 1018 +++ bitbox02-bt/vendor/syn/src/lifetime.rs | 156 + bitbox02-bt/vendor/syn/src/lit.rs | 1869 +++++ bitbox02-bt/vendor/syn/src/lookahead.rs | 165 + bitbox02-bt/vendor/syn/src/mac.rs | 225 + bitbox02-bt/vendor/syn/src/macros.rs | 182 + bitbox02-bt/vendor/syn/src/meta.rs | 427 ++ bitbox02-bt/vendor/syn/src/op.rs | 219 + bitbox02-bt/vendor/syn/src/parse.rs | 1414 ++++ .../vendor/syn/src/parse_macro_input.rs | 128 + bitbox02-bt/vendor/syn/src/parse_quote.rs | 211 + bitbox02-bt/vendor/syn/src/pat.rs | 955 +++ bitbox02-bt/vendor/syn/src/path.rs | 956 +++ bitbox02-bt/vendor/syn/src/precedence.rs | 162 + bitbox02-bt/vendor/syn/src/print.rs | 16 + bitbox02-bt/vendor/syn/src/punctuated.rs | 1155 +++ bitbox02-bt/vendor/syn/src/restriction.rs | 178 + bitbox02-bt/vendor/syn/src/sealed.rs | 4 + bitbox02-bt/vendor/syn/src/span.rs | 63 + bitbox02-bt/vendor/syn/src/spanned.rs | 118 + bitbox02-bt/vendor/syn/src/stmt.rs | 481 ++ bitbox02-bt/vendor/syn/src/thread.rs | 60 + bitbox02-bt/vendor/syn/src/token.rs | 1092 +++ bitbox02-bt/vendor/syn/src/tt.rs | 107 + bitbox02-bt/vendor/syn/src/ty.rs | 1217 +++ bitbox02-bt/vendor/syn/src/verbatim.rs | 33 + bitbox02-bt/vendor/syn/src/whitespace.rs | 65 + bitbox02-bt/vendor/syn/tests/common/eq.rs | 914 +++ bitbox02-bt/vendor/syn/tests/common/mod.rs | 5 + bitbox02-bt/vendor/syn/tests/common/parse.rs | 46 + bitbox02-bt/vendor/syn/tests/debug/gen.rs | 5163 +++++++++++++ bitbox02-bt/vendor/syn/tests/debug/mod.rs | 147 + bitbox02-bt/vendor/syn/tests/macros/mod.rs | 93 + bitbox02-bt/vendor/syn/tests/regression.rs | 5 + .../vendor/syn/tests/regression/issue1108.rs | 5 + .../vendor/syn/tests/regression/issue1235.rs | 32 + bitbox02-bt/vendor/syn/tests/repo/mod.rs | 510 ++ bitbox02-bt/vendor/syn/tests/repo/progress.rs | 37 + .../vendor/syn/tests/test_asyncness.rs | 43 + .../vendor/syn/tests/test_attribute.rs | 225 + .../vendor/syn/tests/test_derive_input.rs | 781 ++ bitbox02-bt/vendor/syn/tests/test_expr.rs | 718 ++ bitbox02-bt/vendor/syn/tests/test_generics.rs | 282 + bitbox02-bt/vendor/syn/tests/test_grouping.rs | 53 + bitbox02-bt/vendor/syn/tests/test_ident.rs | 87 + bitbox02-bt/vendor/syn/tests/test_item.rs | 332 + .../vendor/syn/tests/test_iterators.rs | 89 + bitbox02-bt/vendor/syn/tests/test_lit.rs | 331 + bitbox02-bt/vendor/syn/tests/test_meta.rs | 154 + .../vendor/syn/tests/test_parse_buffer.rs | 103 + .../vendor/syn/tests/test_parse_quote.rs | 166 + .../vendor/syn/tests/test_parse_stream.rs | 187 + bitbox02-bt/vendor/syn/tests/test_pat.rs | 152 + bitbox02-bt/vendor/syn/tests/test_path.rs | 130 + .../vendor/syn/tests/test_precedence.rs | 532 ++ bitbox02-bt/vendor/syn/tests/test_receiver.rs | 321 + .../vendor/syn/tests/test_round_trip.rs | 256 + bitbox02-bt/vendor/syn/tests/test_shebang.rs | 67 + bitbox02-bt/vendor/syn/tests/test_size.rs | 54 + bitbox02-bt/vendor/syn/tests/test_stmt.rs | 322 + .../vendor/syn/tests/test_token_trees.rs | 32 + bitbox02-bt/vendor/syn/tests/test_ty.rs | 444 ++ .../vendor/syn/tests/test_unparenthesize.rs | 63 + .../vendor/syn/tests/test_visibility.rs | 185 + bitbox02-bt/vendor/syn/tests/zzz_stable.rs | 33 + .../thiserror-impl/.cargo-checksum.json | 1 + bitbox02-bt/vendor/thiserror-impl/Cargo.toml | 44 + .../vendor/thiserror-impl/LICENSE-APACHE | 176 + bitbox02-bt/vendor/thiserror-impl/LICENSE-MIT | 23 + bitbox02-bt/vendor/thiserror-impl/src/ast.rs | 161 + bitbox02-bt/vendor/thiserror-impl/src/attr.rs | 275 + .../vendor/thiserror-impl/src/expand.rs | 570 ++ bitbox02-bt/vendor/thiserror-impl/src/fmt.rs | 173 + .../vendor/thiserror-impl/src/generics.rs | 83 + bitbox02-bt/vendor/thiserror-impl/src/lib.rs | 36 + bitbox02-bt/vendor/thiserror-impl/src/prop.rs | 147 + bitbox02-bt/vendor/thiserror-impl/src/span.rs | 15 + .../vendor/thiserror-impl/src/valid.rs | 237 + .../vendor/thiserror/.cargo-checksum.json | 1 + bitbox02-bt/vendor/thiserror/Cargo.toml | 109 + bitbox02-bt/vendor/thiserror/LICENSE-APACHE | 176 + bitbox02-bt/vendor/thiserror/LICENSE-MIT | 23 + bitbox02-bt/vendor/thiserror/README.md | 238 + bitbox02-bt/vendor/thiserror/build.rs | 124 + bitbox02-bt/vendor/thiserror/build/probe.rs | 32 + .../vendor/thiserror/rust-toolchain.toml | 2 + bitbox02-bt/vendor/thiserror/src/aserror.rs | 50 + bitbox02-bt/vendor/thiserror/src/display.rs | 40 + bitbox02-bt/vendor/thiserror/src/lib.rs | 290 + bitbox02-bt/vendor/thiserror/src/provide.rs | 20 + .../vendor/thiserror/tests/compiletest.rs | 7 + .../vendor/thiserror/tests/test_backtrace.rs | 277 + .../vendor/thiserror/tests/test_deprecated.rs | 10 + .../vendor/thiserror/tests/test_display.rs | 370 + .../vendor/thiserror/tests/test_error.rs | 56 + .../vendor/thiserror/tests/test_expr.rs | 88 + .../vendor/thiserror/tests/test_from.rs | 64 + .../vendor/thiserror/tests/test_generics.rs | 161 + .../vendor/thiserror/tests/test_lints.rs | 20 + .../vendor/thiserror/tests/test_option.rs | 108 + .../vendor/thiserror/tests/test_path.rs | 37 + .../vendor/thiserror/tests/test_source.rs | 65 + .../thiserror/tests/test_transparent.rs | 78 + .../thiserror/tests/ui/bad-field-attr.rs | 7 + .../thiserror/tests/ui/bad-field-attr.stderr | 5 + .../thiserror/tests/ui/concat-display.rs | 15 + .../thiserror/tests/ui/concat-display.stderr | 10 + .../tests/ui/duplicate-enum-source.rs | 13 + .../tests/ui/duplicate-enum-source.stderr | 5 + .../thiserror/tests/ui/duplicate-fmt.rs | 8 + .../thiserror/tests/ui/duplicate-fmt.stderr | 5 + .../tests/ui/duplicate-struct-source.rs | 11 + .../tests/ui/duplicate-struct-source.stderr | 5 + .../tests/ui/duplicate-transparent.rs | 8 + .../tests/ui/duplicate-transparent.stderr | 5 + .../tests/ui/fallback-impl-with-display.rs | 14 + .../ui/fallback-impl-with-display.stderr | 16 + .../tests/ui/from-backtrace-backtrace.rs | 15 + .../tests/ui/from-backtrace-backtrace.stderr | 5 + .../thiserror/tests/ui/from-not-source.rs | 11 + .../thiserror/tests/ui/from-not-source.stderr | 5 + .../tests/ui/invalid-input-impl-anyway.rs | 11 + .../tests/ui/invalid-input-impl-anyway.stderr | 5 + .../vendor/thiserror/tests/ui/lifetime.rs | 24 + .../vendor/thiserror/tests/ui/lifetime.stderr | 11 + .../thiserror/tests/ui/missing-display.rs | 9 + .../thiserror/tests/ui/missing-display.stderr | 13 + .../vendor/thiserror/tests/ui/missing-fmt.rs | 10 + .../thiserror/tests/ui/missing-fmt.stderr | 5 + .../vendor/thiserror/tests/ui/no-display.rs | 12 + .../thiserror/tests/ui/no-display.stderr | 20 + .../tests/ui/source-enum-not-error.rs | 12 + .../tests/ui/source-enum-not-error.stderr | 22 + .../ui/source-enum-unnamed-field-not-error.rs | 12 + ...source-enum-unnamed-field-not-error.stderr | 22 + .../tests/ui/source-struct-not-error.rs | 12 + .../tests/ui/source-struct-not-error.stderr | 20 + .../source-struct-unnamed-field-not-error.rs | 10 + ...urce-struct-unnamed-field-not-error.stderr | 20 + .../thiserror/tests/ui/transparent-display.rs | 8 + .../tests/ui/transparent-display.stderr | 5 + .../tests/ui/transparent-enum-many.rs | 9 + .../tests/ui/transparent-enum-many.stderr | 6 + .../tests/ui/transparent-enum-not-error.rs | 9 + .../ui/transparent-enum-not-error.stderr | 20 + .../tests/ui/transparent-enum-source.rs | 9 + .../tests/ui/transparent-enum-source.stderr | 5 + ...ransparent-enum-unnamed-field-not-error.rs | 9 + ...parent-enum-unnamed-field-not-error.stderr | 20 + .../tests/ui/transparent-struct-many.rs | 10 + .../tests/ui/transparent-struct-many.stderr | 5 + .../tests/ui/transparent-struct-not-error.rs | 9 + .../ui/transparent-struct-not-error.stderr | 18 + .../tests/ui/transparent-struct-source.rs | 7 + .../tests/ui/transparent-struct-source.stderr | 5 + ...nsparent-struct-unnamed-field-not-error.rs | 7 + ...rent-struct-unnamed-field-not-error.stderr | 18 + .../tests/ui/unexpected-field-fmt.rs | 11 + .../tests/ui/unexpected-field-fmt.stderr | 5 + .../tests/ui/unexpected-struct-source.rs | 7 + .../tests/ui/unexpected-struct-source.stderr | 5 + .../vendor/thiserror/tests/ui/union.rs | 9 + .../vendor/thiserror/tests/ui/union.stderr | 8 + .../vendor/ufmt-write/.cargo-checksum.json | 1 + bitbox02-bt/vendor/ufmt-write/Cargo.toml | 25 + bitbox02-bt/vendor/ufmt-write/src/lib.rs | 48 + .../vendor/unicode-ident/.cargo-checksum.json | 1 + bitbox02-bt/vendor/unicode-ident/Cargo.toml | 79 + .../vendor/unicode-ident/LICENSE-APACHE | 176 + bitbox02-bt/vendor/unicode-ident/LICENSE-MIT | 23 + .../vendor/unicode-ident/LICENSE-UNICODE | 46 + bitbox02-bt/vendor/unicode-ident/README.md | 283 + .../vendor/unicode-ident/benches/xid.rs | 127 + bitbox02-bt/vendor/unicode-ident/src/lib.rs | 269 + .../vendor/unicode-ident/src/tables.rs | 671 ++ .../vendor/unicode-ident/tests/compare.rs | 71 + .../vendor/unicode-ident/tests/fst/mod.rs | 11 + .../unicode-ident/tests/fst/xid_continue.fst | Bin 0 -> 76404 bytes .../unicode-ident/tests/fst/xid_start.fst | Bin 0 -> 67736 bytes .../vendor/unicode-ident/tests/roaring/mod.rs | 21 + .../vendor/unicode-ident/tests/static_size.rs | 95 + .../vendor/unicode-ident/tests/tables/mod.rs | 7 + .../unicode-ident/tests/tables/tables.rs | 357 + .../vendor/unicode-ident/tests/trie/mod.rs | 7 + .../vendor/unicode-ident/tests/trie/trie.rs | 452 ++ .../unsafe-libyaml/.cargo-checksum.json | 1 + bitbox02-bt/vendor/unsafe-libyaml/Cargo.lock | 32 + bitbox02-bt/vendor/unsafe-libyaml/Cargo.toml | 38 + bitbox02-bt/vendor/unsafe-libyaml/LICENSE-MIT | 23 + bitbox02-bt/vendor/unsafe-libyaml/README.md | 24 + bitbox02-bt/vendor/unsafe-libyaml/src/api.rs | 1549 ++++ .../vendor/unsafe-libyaml/src/bin/cstr/mod.rs | 47 + .../src/bin/run-emitter-test-suite.rs | 307 + .../src/bin/run-parser-test-suite.rs | 222 + .../vendor/unsafe-libyaml/src/dumper.rs | 450 ++ .../vendor/unsafe-libyaml/src/emitter.rs | 2376 ++++++ bitbox02-bt/vendor/unsafe-libyaml/src/lib.rs | 324 + .../vendor/unsafe-libyaml/src/loader.rs | 579 ++ .../vendor/unsafe-libyaml/src/macros.rs | 514 ++ bitbox02-bt/vendor/unsafe-libyaml/src/ops.rs | 111 + .../vendor/unsafe-libyaml/src/parser.rs | 1352 ++++ .../vendor/unsafe-libyaml/src/reader.rs | 468 ++ .../vendor/unsafe-libyaml/src/scanner.rs | 2691 +++++++ .../vendor/unsafe-libyaml/src/success.rs | 25 + .../vendor/unsafe-libyaml/src/writer.rs | 149 + bitbox02-bt/vendor/unsafe-libyaml/src/yaml.rs | 1282 ++++ .../vendor/unsafe-libyaml/tests/bin/mod.rs | 48 + .../tests/ignorelist/libyaml-emitter | 72 + .../tests/ignorelist/libyaml-parser | 34 + .../tests/ignorelist/libyaml-parser-error | 10 + .../unsafe-libyaml/tests/test_emitter.rs | 37 + .../unsafe-libyaml/tests/test_parser.rs | 32 + .../unsafe-libyaml/tests/test_parser_error.rs | 31 + bitbox02-bt/vendor/vcell/.cargo-checksum.json | 1 + bitbox02-bt/vendor/vcell/CHANGELOG.md | 34 + bitbox02-bt/vendor/vcell/Cargo.toml | 24 + bitbox02-bt/vendor/vcell/LICENSE-APACHE | 201 + bitbox02-bt/vendor/vcell/LICENSE-MIT | 25 + bitbox02-bt/vendor/vcell/README.md | 27 + bitbox02-bt/vendor/vcell/src/lib.rs | 52 + .../vendor/version_check/.cargo-checksum.json | 1 + bitbox02-bt/vendor/version_check/Cargo.toml | 38 + .../vendor/version_check/LICENSE-APACHE | 201 + bitbox02-bt/vendor/version_check/LICENSE-MIT | 19 + bitbox02-bt/vendor/version_check/README.md | 80 + .../vendor/version_check/src/channel.rs | 195 + bitbox02-bt/vendor/version_check/src/date.rs | 203 + bitbox02-bt/vendor/version_check/src/lib.rs | 528 ++ .../vendor/version_check/src/version.rs | 316 + bitbox02-bt/vendor/void/.cargo-checksum.json | 1 + bitbox02-bt/vendor/void/Cargo.toml | 15 + bitbox02-bt/vendor/void/README.md | 39 + bitbox02-bt/vendor/void/src/lib.rs | 121 + .../volatile-register/.cargo-checksum.json | 1 + .../vendor/volatile-register/CHANGELOG.md | 57 + .../volatile-register/CODE_OF_CONDUCT.md | 37 + .../vendor/volatile-register/Cargo.toml | 47 + .../vendor/volatile-register/LICENSE-APACHE | 201 + .../vendor/volatile-register/LICENSE-MIT | 25 + .../vendor/volatile-register/README.md | 24 + .../vendor/volatile-register/src/lib.rs | 107 + da14531-sdk | 2 +- 1632 files changed, 410667 insertions(+), 286 deletions(-) create mode 100644 bitbox02-bt/vendor/bare-metal/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/bare-metal/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/bare-metal/Cargo.toml create mode 100644 bitbox02-bt/vendor/bare-metal/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/bare-metal/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/bare-metal/README.md create mode 100644 bitbox02-bt/vendor/bare-metal/bors.toml create mode 100644 bitbox02-bt/vendor/bare-metal/build.rs create mode 100644 bitbox02-bt/vendor/bare-metal/ci/install.sh create mode 100644 bitbox02-bt/vendor/bare-metal/ci/script.sh create mode 100644 bitbox02-bt/vendor/bare-metal/src/lib.rs create mode 100644 bitbox02-bt/vendor/bitfield/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/bitfield/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/bitfield/Cargo.toml create mode 100644 bitbox02-bt/vendor/bitfield/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/bitfield/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/bitfield/README.md create mode 100644 bitbox02-bt/vendor/bitfield/examples/bits_position.rs create mode 100644 bitbox02-bt/vendor/bitfield/examples/ipv4.rs create mode 100644 bitbox02-bt/vendor/bitfield/multitest.toml create mode 100644 bitbox02-bt/vendor/bitfield/src/lib.rs create mode 100644 bitbox02-bt/vendor/bitfield/tests/lib.rs create mode 100644 bitbox02-bt/vendor/byteorder/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/byteorder/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/byteorder/COPYING create mode 100644 bitbox02-bt/vendor/byteorder/Cargo.toml create mode 100644 bitbox02-bt/vendor/byteorder/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/byteorder/README.md create mode 100644 bitbox02-bt/vendor/byteorder/UNLICENSE create mode 100644 bitbox02-bt/vendor/byteorder/benches/bench.rs create mode 100644 bitbox02-bt/vendor/byteorder/rustfmt.toml create mode 100644 bitbox02-bt/vendor/byteorder/src/io.rs create mode 100644 bitbox02-bt/vendor/byteorder/src/lib.rs create mode 100644 bitbox02-bt/vendor/cc/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/cc/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/cc/Cargo.toml create mode 100644 bitbox02-bt/vendor/cc/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/cc/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/cc/README.md create mode 100644 bitbox02-bt/vendor/cc/clippy.toml create mode 100644 bitbox02-bt/vendor/cc/src/command_helpers.rs create mode 100644 bitbox02-bt/vendor/cc/src/detect_compiler_family.c create mode 100644 bitbox02-bt/vendor/cc/src/lib.rs create mode 100644 bitbox02-bt/vendor/cc/src/parallel/async_executor.rs create mode 100644 bitbox02-bt/vendor/cc/src/parallel/job_token.rs create mode 100644 bitbox02-bt/vendor/cc/src/parallel/mod.rs create mode 100644 bitbox02-bt/vendor/cc/src/parallel/once_lock.rs create mode 100644 bitbox02-bt/vendor/cc/src/parallel/stderr.rs create mode 100644 bitbox02-bt/vendor/cc/src/target_info.rs create mode 100644 bitbox02-bt/vendor/cc/src/tempfile.rs create mode 100644 bitbox02-bt/vendor/cc/src/tool.rs create mode 100644 bitbox02-bt/vendor/cc/src/utilities.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/com.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/find_tools.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/mod.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/registry.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/setup_config.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/vs_instances.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/winapi.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/windows_sys.rs create mode 100644 bitbox02-bt/vendor/cc/src/windows/windows_targets.rs create mode 100644 bitbox02-bt/vendor/cortex-m/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/cortex-m/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/cortex-m/CODE_OF_CONDUCT.md create mode 100644 bitbox02-bt/vendor/cortex-m/Cargo.toml create mode 100644 bitbox02-bt/vendor/cortex-m/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/cortex-m/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/cortex-m/README.md create mode 100644 bitbox02-bt/vendor/cortex-m/asm-toolchain create mode 100644 bitbox02-bt/vendor/cortex-m/asm/inline.rs create mode 100644 bitbox02-bt/vendor/cortex-m/asm/lib.rs create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv6m-none-eabi-lto.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv6m-none-eabi.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabi-lto.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabi.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabihf-lto.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabihf.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv7m-none-eabi-lto.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv7m-none-eabi.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv8m.base-none-eabi-lto.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv8m.base-none-eabi.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabi-lto.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabi.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabihf-lto.a create mode 100644 bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabihf.a create mode 100644 bitbox02-bt/vendor/cortex-m/build.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/asm.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/call_asm.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/cmse.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/critical_section.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/delay.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/interrupt.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/itm.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/lib.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/macros.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/ac.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/cbp.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/cpuid.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/dcb.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/dwt.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/fpb.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/fpu.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/icb.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/itm.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/mod.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/mpu.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/nvic.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/sau.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/scb.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/syst.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/test.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/peripheral/tpiu.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/prelude.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/apsr.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/basepri.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/basepri_max.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/control.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/faultmask.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/fpscr.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/lr.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/mod.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/msp.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/msplim.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/pc.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/primask.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/psp.rs create mode 100644 bitbox02-bt/vendor/cortex-m/src/register/psplim.rs create mode 100644 bitbox02-bt/vendor/cortex-m/triagebot.toml create mode 100644 bitbox02-bt/vendor/critical-section/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/critical-section/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/critical-section/CODE_OF_CONDUCT.md create mode 100644 bitbox02-bt/vendor/critical-section/Cargo.toml create mode 100644 bitbox02-bt/vendor/critical-section/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/critical-section/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/critical-section/README.md create mode 100644 bitbox02-bt/vendor/critical-section/docs/msrv.md create mode 100644 bitbox02-bt/vendor/critical-section/src/lib.rs create mode 100644 bitbox02-bt/vendor/critical-section/src/mutex.rs create mode 100644 bitbox02-bt/vendor/critical-section/src/std.rs create mode 100644 bitbox02-bt/vendor/cty/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/cty/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/cty/Cargo.toml create mode 100644 bitbox02-bt/vendor/cty/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/cty/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/cty/README.md create mode 100644 bitbox02-bt/vendor/cty/ci/install.sh create mode 100644 bitbox02-bt/vendor/cty/ci/script.sh create mode 100644 bitbox02-bt/vendor/cty/src/lib.rs create mode 100644 bitbox02-bt/vendor/da14531/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/da14531/Cargo.toml create mode 100644 bitbox02-bt/vendor/da14531/README.md create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_acc_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_ana_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_rd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_attr_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_cn_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_dco_rd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_dcoamp_cal_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_div_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_freqmeas_rd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_fsm_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_init_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_rd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtc_rd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_misc_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_mon_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_pllfcwdt_rd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_rfpt_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_sdmod_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_tunestate_rd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/adplldig/adpll_txmod_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/anamisc.rs create mode 100644 bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_cnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_h_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_l_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_actscanstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_advchmap_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_advtim_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_aescntl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_aeskey127_96_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_aeskey31_0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_aeskey63_32_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_aeskey95_64_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_aesptr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_basetimecnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_basetimecntcorr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_bdaddrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_bdaddru_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_blemprio0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_blemprio1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_cntl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_currentrxdescptr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmax_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmin_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_deepslcntl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_deepslstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_deepslwkup_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_diagstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_em_base_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_enbpreset_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_errortypestat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_finecntcorr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_finetimecnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_finetimtgt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_grosstimtgt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_intack_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_intcntl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_intrawstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_intstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_radiopwrupdn_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_rftestcntl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_rftestrxstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_rftesttxstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_rwblecntl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_rwbleconf_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_rxmicval_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_sampleclk_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_swprofiling_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_timgencntl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_txmicval_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_version_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_wlnbdev_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_wlprivaddptr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/ble/ble_wlpubaddptr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_id1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_id2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_id3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_id4_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_revision_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_swc_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_test1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/chip_version/chip_test2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/gp_data_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/hibern_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/hwr_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/pad_latch_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/power_aon_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/ram_lpmx_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/reset_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_aon/test_vdd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_tim.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_tim/clk_rtcdiv_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/ana_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/bandgap_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_amba_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_freq_trim_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_per_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_radio_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32k_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32m_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_rcx_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/clk_xtal32k_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/pmu_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/pmu_sleep_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/por_pin_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/por_timer_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/power_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/power_level_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/ram_pwr_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/sys_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/sys_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/trim_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_ctrl0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_start_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_trstat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/generic.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_clear_int_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offn_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offp_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_dif_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_se_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_result_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_trim_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/bist_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/p0_data_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/p0_mode_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/p0_reset_data_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/p0_set_data_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/pad_weak_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/rombist_resulth_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/rombist_resultl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/scan_observe_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/test_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/test_ctrl3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/test_ctrl4_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/test_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg/ble_timer_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg/debug_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg/gp_control_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg/gp_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg/mem_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg/reset_freeze_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/gpreg/set_freeze_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_ack_general_call_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_activity_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_gen_call_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_intr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rd_req_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_done_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_over_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_under_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_start_det_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_stop_det_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_abrt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_over_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_comp2_version.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_version_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_con_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_data_cmd_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_cr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_rdlr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_tdlr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_hcnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_lcnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_ic_fs_spklen_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_mask_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_raw_intr_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_rx_tl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_rxflr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_sar_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_hold_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_setup_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_hcnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_lcnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_tar_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_abrt_source_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_tl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/i2c/i2c_txflr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_debounce_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_int_level_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq0_in_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq1_in_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq2_in_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq3_in_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq4_in_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/gpio_reset_irq_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/kbrd_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/kbrd/kbrd_irq_in_sel0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/lib.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram12.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_addr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_lsb_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_msb_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_state_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram3.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_addr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_lsb_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_msb_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_state_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_ahbadr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_celadr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_mode_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_nwords_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_paddr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_pword_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_tim1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/otpc/otpc_tim2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr10_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr11_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr12_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr13_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr14_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr15_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr16_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr17_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr18_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr19_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr20_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr21_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr4_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr5_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr6_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr7_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr8_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_addr9_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_data20_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_data21_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/patch/patch_valid_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec/qdec_clockdiv_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec/qdec_event_cnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec/qdec_xcnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec/qdec_ycnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/quadec/qdec_zcnt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_adci_dc_offset_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_adcq_dc_offset_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_rfmon_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_agc_ext_lut_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_attr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_cal_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_calstate_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_iff_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_io_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_irq_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_vref_sel_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_overrule_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_pa_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_radio_init_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_rfcu_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_scan_feedback_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu/rf_spare_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_10_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_11_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_12_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_13_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_14_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_15_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_16_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_17_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_18_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_19_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_20_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_21_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_22_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_23_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_24_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_25_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_26_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_27_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_28_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_29_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_30_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_31_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_4_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_5_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_6_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_7_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_8_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_9_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config10_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config11_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config12_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config13_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config14_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config15_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config16_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config17_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config18_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config19_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config20_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config21_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config22_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config23_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config24_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config25_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config26_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config27_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config28_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config29_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config30_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config31_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config32_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config33_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config34_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config35_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config36_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config37_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config38_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config39_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config40_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config41_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config42_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config43_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config44_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config45_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config46_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config4_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config5_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config6_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config7_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config8_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config9_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_en_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_pol_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfmon.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfmon/rfmon_addr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_addr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_len_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfmon/rfmon_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfmon/rfmon_len_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rfmon/rfmon_stat_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_alarm_enable_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_alarm_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_control_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_event_flags_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_hour_mode_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_disable_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_enable_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_mask_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_keep_rtc_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_time_alarm_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/rtc/rtc_time_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_clock_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_config_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_cs_config_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_fifo_config_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_fifo_high_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_fifo_read_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_fifo_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_fifo_write_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_irq_mask_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_h_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_l_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_tick.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_tick/calib.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_tick/ctrl.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_tick/load.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_tick/val.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_wdog.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm2_end_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm2_start_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm3_end_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm3_start_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm4_end_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm4_start_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm5_end_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm5_start_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm6_end_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm6_start_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm7_end_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/pwm7_start_cycle.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/timer0_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/timer0_on_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_m_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_n_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_frequency.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer1.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt1_value_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt2_value_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer1/timer1_capture_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer1/timer1_clr_event_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer1/timer1_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/timer1/timer1_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_ctr_high_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_ctr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_dlf_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_dmasa_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_far_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_htx_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_ier_dlh_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_iir_fcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_lcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_lsr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_mcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_msr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_rbr_thr_dll_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_rfl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_sbcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_scr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_sdmam_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_sfe_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr10_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr11_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr12_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr13_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr14_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr15_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr4_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr5_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr6_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr7_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr8_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr9_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_srts_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_stet_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_tfl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_ucv_high_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_ucv_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart/uart_usr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_high_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_dlf_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_dmasa_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_far_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_htx_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_ier_dlh_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_iir_fcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_lcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_lsr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_mcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_rbr_thr_dll_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_rfl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_sbcr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_scr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_sdmam_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_sfe_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr0_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr10_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr11_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr12_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr13_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr14_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr15_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr1_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr2_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr3_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr4_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr5_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr6_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr7_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr8_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr9_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_srt_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_stet_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_tfl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_high_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/uart2/uart2_usr_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup2_pol_gpio_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup2_select_gpio_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup_compare_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup_counter_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup_ctrl_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup_irq_status_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup_pol_gpio_reg.rs create mode 100644 bitbox02-bt/vendor/da14531/src/wkup/wkup_select_gpio_reg.rs create mode 100755 bitbox02-bt/vendor/da14531/update.sh create mode 100644 bitbox02-bt/vendor/embedded-hal/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/embedded-hal/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/embedded-hal/CODE_OF_CONDUCT.md create mode 100644 bitbox02-bt/vendor/embedded-hal/Cargo.toml create mode 100644 bitbox02-bt/vendor/embedded-hal/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/embedded-hal/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/embedded-hal/README.md create mode 100644 bitbox02-bt/vendor/embedded-hal/src/adc.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/blocking/can.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/blocking/delay.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/blocking/i2c.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/blocking/mod.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/blocking/rng.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/blocking/serial.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/blocking/spi.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/can/id.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/can/mod.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/can/nb.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/digital/mod.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/digital/v1.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/digital/v1_compat.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/digital/v2.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/digital/v2_compat.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/fmt.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/lib.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/prelude.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/serial.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/spi.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/timer.rs create mode 100644 bitbox02-bt/vendor/embedded-hal/src/watchdog.rs create mode 100644 bitbox02-bt/vendor/envsubst/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/envsubst/COPYRIGHT create mode 100644 bitbox02-bt/vendor/envsubst/Cargo.toml create mode 100644 bitbox02-bt/vendor/envsubst/LICENSE-APACHE-2.0 create mode 100644 bitbox02-bt/vendor/envsubst/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/envsubst/README.md create mode 100644 bitbox02-bt/vendor/envsubst/src/lib.rs create mode 100644 bitbox02-bt/vendor/equivalent/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/equivalent/Cargo.toml create mode 100644 bitbox02-bt/vendor/equivalent/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/equivalent/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/equivalent/README.md create mode 100644 bitbox02-bt/vendor/equivalent/src/lib.rs create mode 100644 bitbox02-bt/vendor/grounded/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/grounded/Cargo.toml create mode 100644 bitbox02-bt/vendor/grounded/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/grounded/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/grounded/README.md create mode 100644 bitbox02-bt/vendor/grounded/src/alloc_single.rs create mode 100644 bitbox02-bt/vendor/grounded/src/const_init.rs create mode 100644 bitbox02-bt/vendor/grounded/src/lib.rs create mode 100644 bitbox02-bt/vendor/grounded/src/uninit.rs create mode 100644 bitbox02-bt/vendor/hashbrown/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/hashbrown/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/hashbrown/Cargo.toml create mode 100644 bitbox02-bt/vendor/hashbrown/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/hashbrown/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/hashbrown/README.md create mode 100644 bitbox02-bt/vendor/hashbrown/benches/bench.rs create mode 100644 bitbox02-bt/vendor/hashbrown/benches/insert_unique_unchecked.rs create mode 100644 bitbox02-bt/vendor/hashbrown/benches/set_ops.rs create mode 100644 bitbox02-bt/vendor/hashbrown/clippy.toml create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/hash_map.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/mod.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/mod.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/helpers.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/map.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/mod.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/raw.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/set.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/table.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/external_trait_impls/serde.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/lib.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/macros.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/map.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/raw/alloc.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/raw/bitmask.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/raw/generic.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/raw/mod.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/raw/neon.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/raw/sse2.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/raw_entry.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/rustc_entry.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/scopeguard.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/set.rs create mode 100644 bitbox02-bt/vendor/hashbrown/src/table.rs create mode 100644 bitbox02-bt/vendor/hashbrown/tests/equivalent_trait.rs create mode 100644 bitbox02-bt/vendor/hashbrown/tests/hasher.rs create mode 100644 bitbox02-bt/vendor/hashbrown/tests/rayon.rs create mode 100644 bitbox02-bt/vendor/hashbrown/tests/serde.rs create mode 100644 bitbox02-bt/vendor/hashbrown/tests/set.rs create mode 100644 bitbox02-bt/vendor/indexmap/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/indexmap/Cargo.toml create mode 100644 bitbox02-bt/vendor/indexmap/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/indexmap/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/indexmap/README.md create mode 100644 bitbox02-bt/vendor/indexmap/RELEASES.md create mode 100644 bitbox02-bt/vendor/indexmap/benches/bench.rs create mode 100644 bitbox02-bt/vendor/indexmap/benches/faststring.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/arbitrary.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/borsh.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/lib.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/macros.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/core.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/core/entry.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/core/raw_entry_v1.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/iter.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/mutable.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/serde_seq.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/slice.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/map/tests.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/rayon/map.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/rayon/mod.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/rayon/set.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/rustc.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/serde.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/set.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/set/iter.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/set/mutable.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/set/slice.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/set/tests.rs create mode 100644 bitbox02-bt/vendor/indexmap/src/util.rs create mode 100644 bitbox02-bt/vendor/indexmap/tests/equivalent_trait.rs create mode 100644 bitbox02-bt/vendor/indexmap/tests/macros_full_path.rs create mode 100644 bitbox02-bt/vendor/indexmap/tests/quick.rs create mode 100644 bitbox02-bt/vendor/indexmap/tests/tests.rs create mode 100644 bitbox02-bt/vendor/itoa/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/itoa/Cargo.toml create mode 100644 bitbox02-bt/vendor/itoa/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/itoa/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/itoa/README.md create mode 100644 bitbox02-bt/vendor/itoa/benches/bench.rs create mode 100644 bitbox02-bt/vendor/itoa/src/lib.rs create mode 100644 bitbox02-bt/vendor/itoa/src/udiv128.rs create mode 100644 bitbox02-bt/vendor/itoa/tests/test.rs create mode 100644 bitbox02-bt/vendor/nb-0.1.3/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/nb-0.1.3/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/nb-0.1.3/Cargo.toml create mode 100644 bitbox02-bt/vendor/nb-0.1.3/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/nb-0.1.3/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/nb-0.1.3/README.md create mode 100644 bitbox02-bt/vendor/nb-0.1.3/bors.toml create mode 100644 bitbox02-bt/vendor/nb-0.1.3/src/lib.rs create mode 100644 bitbox02-bt/vendor/nb/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/nb/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/nb/CODE_OF_CONDUCT.md create mode 100644 bitbox02-bt/vendor/nb/Cargo.toml create mode 100644 bitbox02-bt/vendor/nb/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/nb/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/nb/README.md create mode 100644 bitbox02-bt/vendor/nb/src/lib.rs create mode 100644 bitbox02-bt/vendor/nb/triagebot.toml create mode 100644 bitbox02-bt/vendor/panic-abort/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/panic-abort/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/panic-abort/Cargo.toml create mode 100644 bitbox02-bt/vendor/panic-abort/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/panic-abort/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/panic-abort/README.md create mode 100644 bitbox02-bt/vendor/panic-abort/ci/after-success.sh create mode 100644 bitbox02-bt/vendor/panic-abort/ci/install.sh create mode 100644 bitbox02-bt/vendor/panic-abort/ci/script.sh create mode 100644 bitbox02-bt/vendor/panic-abort/src/lib.rs create mode 100644 bitbox02-bt/vendor/paste/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/paste/Cargo.toml create mode 100644 bitbox02-bt/vendor/paste/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/paste/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/paste/README.md create mode 100644 bitbox02-bt/vendor/paste/build.rs create mode 100644 bitbox02-bt/vendor/paste/src/attr.rs create mode 100644 bitbox02-bt/vendor/paste/src/error.rs create mode 100644 bitbox02-bt/vendor/paste/src/lib.rs create mode 100644 bitbox02-bt/vendor/paste/src/segment.rs create mode 100644 bitbox02-bt/vendor/paste/tests/compiletest.rs create mode 100644 bitbox02-bt/vendor/paste/tests/test_attr.rs create mode 100644 bitbox02-bt/vendor/paste/tests/test_doc.rs create mode 100644 bitbox02-bt/vendor/paste/tests/test_expr.rs create mode 100644 bitbox02-bt/vendor/paste/tests/test_item.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/case-warning.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/case-warning.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-empty.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-empty.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-non-string.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-non-string.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-suffix.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-suffix.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-unexpected.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/env-unexpected.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/invalid-ident.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/invalid-ident.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/no-env-var.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/no-env-var.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unexpected-group.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unexpected-group.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.stderr create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.rs create mode 100644 bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.stderr create mode 100644 bitbox02-bt/vendor/portable-atomic/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/portable-atomic/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/portable-atomic/Cargo.toml create mode 100644 bitbox02-bt/vendor/portable-atomic/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/portable-atomic/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/portable-atomic/README.md create mode 100644 bitbox02-bt/vendor/portable-atomic/build.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/no_atomic.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/cfgs.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/gen/utils.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/README.md create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/aarch64.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/intrinsics.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/macros.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/mod.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/powerpc64.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/riscv64.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/s390x.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/x86_64.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/README.md create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/arm_linux.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/macros.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/mod.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/riscv32.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/core_atomic.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/README.md create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_aa64reg.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_apple.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_fuchsia.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_illumos.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_windows.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/auxv.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/common.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/riscv_linux.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/detect/x86_64.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/fallback/mod.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/fallback/outline_atomics.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock_wide.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/fallback/utils.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/float.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/README.md create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv4t.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv6m.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/avr.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/mod.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/msp430.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/riscv.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/xtensa.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/mod.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/msp430.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/riscv.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/imp/x86.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/lib.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/tests/helper.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/tests/mod.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/src/utils.rs create mode 100644 bitbox02-bt/vendor/portable-atomic/version.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/Cargo.toml create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/build.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/src/lib.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/src/parse.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error-attr/src/settings.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/proc-macro-error/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/proc-macro-error/Cargo.toml create mode 100644 bitbox02-bt/vendor/proc-macro-error/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/proc-macro-error/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/proc-macro-error/README.md create mode 100644 bitbox02-bt/vendor/proc-macro-error/build.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/src/diagnostic.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/src/dummy.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/src/imp/delegate.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/src/imp/fallback.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/src/lib.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/src/macros.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/src/sealed.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/macro-errors.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ok.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/runtime-errors.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.stderr create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.rs create mode 100644 bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.stderr create mode 100644 bitbox02-bt/vendor/proc-macro2/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/proc-macro2/Cargo.toml create mode 100644 bitbox02-bt/vendor/proc-macro2/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/proc-macro2/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/proc-macro2/README.md create mode 100644 bitbox02-bt/vendor/proc-macro2/build.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/build/probe.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/rust-toolchain.toml create mode 100644 bitbox02-bt/vendor/proc-macro2/src/detection.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/extra.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/fallback.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/lib.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/location.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/marker.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/parse.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/rcvec.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/src/wrapper.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/tests/comments.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/tests/features.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/tests/marker.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/tests/test.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/tests/test_fmt.rs create mode 100644 bitbox02-bt/vendor/proc-macro2/tests/test_size.rs create mode 100644 bitbox02-bt/vendor/quote/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/quote/Cargo.toml create mode 100644 bitbox02-bt/vendor/quote/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/quote/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/quote/README.md create mode 100644 bitbox02-bt/vendor/quote/rust-toolchain.toml create mode 100644 bitbox02-bt/vendor/quote/src/ext.rs create mode 100644 bitbox02-bt/vendor/quote/src/format.rs create mode 100644 bitbox02-bt/vendor/quote/src/ident_fragment.rs create mode 100644 bitbox02-bt/vendor/quote/src/lib.rs create mode 100644 bitbox02-bt/vendor/quote/src/runtime.rs create mode 100644 bitbox02-bt/vendor/quote/src/spanned.rs create mode 100644 bitbox02-bt/vendor/quote/src/to_tokens.rs create mode 100644 bitbox02-bt/vendor/quote/tests/compiletest.rs create mode 100644 bitbox02-bt/vendor/quote/tests/test.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.stderr create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.stderr create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.stderr create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.stderr create mode 100644 bitbox02-bt/vendor/quote/tests/ui/not-quotable.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/not-quotable.stderr create mode 100644 bitbox02-bt/vendor/quote/tests/ui/not-repeatable.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/not-repeatable.stderr create mode 100644 bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.rs create mode 100644 bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.stderr create mode 100644 bitbox02-bt/vendor/rtt-target-0.3.1/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/rtt-target-0.3.1/Cargo.toml create mode 100644 bitbox02-bt/vendor/rtt-target-0.3.1/src/init.rs create mode 100644 bitbox02-bt/vendor/rtt-target-0.3.1/src/lib.rs create mode 100644 bitbox02-bt/vendor/rtt-target-0.3.1/src/print.rs create mode 100644 bitbox02-bt/vendor/rtt-target-0.3.1/src/rtt.rs create mode 100644 bitbox02-bt/vendor/rtt-target/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/rtt-target/Cargo.toml create mode 100644 bitbox02-bt/vendor/rtt-target/LICENSE create mode 100644 bitbox02-bt/vendor/rtt-target/README.md create mode 100644 bitbox02-bt/vendor/rtt-target/src/debug.rs create mode 100644 bitbox02-bt/vendor/rtt-target/src/init.rs create mode 100644 bitbox02-bt/vendor/rtt-target/src/lib.rs create mode 100644 bitbox02-bt/vendor/rtt-target/src/print.rs create mode 100644 bitbox02-bt/vendor/rtt-target/src/rtt.rs create mode 100644 bitbox02-bt/vendor/rustc_version/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/rustc_version/Cargo.toml create mode 100644 bitbox02-bt/vendor/rustc_version/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/rustc_version/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/rustc_version/README.md create mode 100644 bitbox02-bt/vendor/rustc_version/src/errors.rs create mode 100644 bitbox02-bt/vendor/rustc_version/src/lib.rs create mode 100644 bitbox02-bt/vendor/ryu/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/ryu/Cargo.lock create mode 100644 bitbox02-bt/vendor/ryu/Cargo.toml create mode 100644 bitbox02-bt/vendor/ryu/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/ryu/LICENSE-BOOST create mode 100644 bitbox02-bt/vendor/ryu/README.md create mode 100644 bitbox02-bt/vendor/ryu/benches/bench.rs create mode 100644 bitbox02-bt/vendor/ryu/examples/upstream_benchmark.rs create mode 100644 bitbox02-bt/vendor/ryu/src/buffer/mod.rs create mode 100644 bitbox02-bt/vendor/ryu/src/common.rs create mode 100644 bitbox02-bt/vendor/ryu/src/d2s.rs create mode 100644 bitbox02-bt/vendor/ryu/src/d2s_full_table.rs create mode 100644 bitbox02-bt/vendor/ryu/src/d2s_intrinsics.rs create mode 100644 bitbox02-bt/vendor/ryu/src/d2s_small_table.rs create mode 100644 bitbox02-bt/vendor/ryu/src/digit_table.rs create mode 100644 bitbox02-bt/vendor/ryu/src/f2s.rs create mode 100644 bitbox02-bt/vendor/ryu/src/f2s_intrinsics.rs create mode 100644 bitbox02-bt/vendor/ryu/src/lib.rs create mode 100644 bitbox02-bt/vendor/ryu/src/parse.rs create mode 100644 bitbox02-bt/vendor/ryu/src/pretty/exponent.rs create mode 100644 bitbox02-bt/vendor/ryu/src/pretty/mantissa.rs create mode 100644 bitbox02-bt/vendor/ryu/src/pretty/mod.rs create mode 100644 bitbox02-bt/vendor/ryu/src/s2d.rs create mode 100644 bitbox02-bt/vendor/ryu/src/s2f.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/common_test.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/d2s_intrinsics_test.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/d2s_table_test.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/d2s_test.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/exhaustive.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/f2s_test.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/macros/mod.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/s2d_test.rs create mode 100644 bitbox02-bt/vendor/ryu/tests/s2f_test.rs create mode 100644 bitbox02-bt/vendor/semver-parser/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/semver-parser/Cargo.toml create mode 100644 bitbox02-bt/vendor/semver-parser/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/semver-parser/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/semver-parser/src/common.rs create mode 100644 bitbox02-bt/vendor/semver-parser/src/lib.rs create mode 100644 bitbox02-bt/vendor/semver-parser/src/range.rs create mode 100644 bitbox02-bt/vendor/semver-parser/src/recognize.rs create mode 100644 bitbox02-bt/vendor/semver-parser/src/version.rs create mode 100644 bitbox02-bt/vendor/semver/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/semver/Cargo.toml create mode 100644 bitbox02-bt/vendor/semver/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/semver/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/semver/README.md create mode 100644 bitbox02-bt/vendor/semver/src/lib.rs create mode 100644 bitbox02-bt/vendor/semver/src/version.rs create mode 100644 bitbox02-bt/vendor/semver/src/version_req.rs create mode 100644 bitbox02-bt/vendor/semver/tests/deprecation.rs create mode 100644 bitbox02-bt/vendor/semver/tests/regression.rs create mode 100644 bitbox02-bt/vendor/semver/tests/serde.rs create mode 100644 bitbox02-bt/vendor/serde/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/serde/Cargo.toml create mode 100644 bitbox02-bt/vendor/serde/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/serde/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/serde/README.md create mode 100644 bitbox02-bt/vendor/serde/build.rs create mode 100644 bitbox02-bt/vendor/serde/crates-io.md create mode 100644 bitbox02-bt/vendor/serde/src/de/ignored_any.rs create mode 100644 bitbox02-bt/vendor/serde/src/de/impls.rs create mode 100644 bitbox02-bt/vendor/serde/src/de/mod.rs create mode 100644 bitbox02-bt/vendor/serde/src/de/seed.rs create mode 100644 bitbox02-bt/vendor/serde/src/de/size_hint.rs create mode 100644 bitbox02-bt/vendor/serde/src/de/value.rs create mode 100644 bitbox02-bt/vendor/serde/src/format.rs create mode 100644 bitbox02-bt/vendor/serde/src/integer128.rs create mode 100644 bitbox02-bt/vendor/serde/src/lib.rs create mode 100644 bitbox02-bt/vendor/serde/src/macros.rs create mode 100644 bitbox02-bt/vendor/serde/src/private/de.rs create mode 100644 bitbox02-bt/vendor/serde/src/private/doc.rs create mode 100644 bitbox02-bt/vendor/serde/src/private/mod.rs create mode 100644 bitbox02-bt/vendor/serde/src/private/ser.rs create mode 100644 bitbox02-bt/vendor/serde/src/ser/fmt.rs create mode 100644 bitbox02-bt/vendor/serde/src/ser/impls.rs create mode 100644 bitbox02-bt/vendor/serde/src/ser/impossible.rs create mode 100644 bitbox02-bt/vendor/serde/src/ser/mod.rs create mode 100644 bitbox02-bt/vendor/serde/src/std_error.rs create mode 100644 bitbox02-bt/vendor/serde_derive/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/serde_derive/Cargo.toml create mode 100644 bitbox02-bt/vendor/serde_derive/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/serde_derive/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/serde_derive/README.md create mode 100644 bitbox02-bt/vendor/serde_derive/crates-io.md create mode 100644 bitbox02-bt/vendor/serde_derive/src/bound.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/de.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/dummy.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/fragment.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/ast.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/attr.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/case.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/check.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/ctxt.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/mod.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/receiver.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/respan.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/internals/symbol.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/lib.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/pretend.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/ser.rs create mode 100644 bitbox02-bt/vendor/serde_derive/src/this.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/serde_yaml/Cargo.toml create mode 100644 bitbox02-bt/vendor/serde_yaml/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/serde_yaml/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/serde_yaml/README.md create mode 100644 bitbox02-bt/vendor/serde_yaml/src/de.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/error.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/lib.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/libyaml/cstr.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/libyaml/emitter.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/libyaml/error.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/libyaml/mod.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/libyaml/parser.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/libyaml/tag.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/libyaml/util.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/loader.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/mapping.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/number.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/path.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/ser.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/de.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/debug.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/from.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/index.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/mod.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/partial_eq.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/ser.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/value/tagged.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/src/with.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/tests/test_de.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/tests/test_error.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/tests/test_serde.rs create mode 100644 bitbox02-bt/vendor/serde_yaml/tests/test_value.rs create mode 100644 bitbox02-bt/vendor/shlex/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/shlex/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/shlex/Cargo.toml create mode 100644 bitbox02-bt/vendor/shlex/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/shlex/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/shlex/README.md create mode 100644 bitbox02-bt/vendor/shlex/src/bytes.rs create mode 100644 bitbox02-bt/vendor/shlex/src/lib.rs create mode 100644 bitbox02-bt/vendor/shlex/src/quoting_warning.md create mode 100644 bitbox02-bt/vendor/syn-1.0.109/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/syn-1.0.109/Cargo.toml create mode 100644 bitbox02-bt/vendor/syn-1.0.109/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/syn-1.0.109/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/syn-1.0.109/README.md create mode 100644 bitbox02-bt/vendor/syn-1.0.109/benches/file.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/benches/rust.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/build.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/attr.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/await.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/bigint.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/buffer.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/custom_keyword.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/custom_punctuation.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/data.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/derive.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/discouraged.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/drops.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/error.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/export.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/expr.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/ext.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/file.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen/clone.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen/debug.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen/eq.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen/fold.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen/hash.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen/visit.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen/visit_mut.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/gen_helper.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/generics.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/group.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/ident.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/item.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/lib.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/lifetime.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/lit.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/lookahead.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/mac.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/macros.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/op.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/parse.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/parse_macro_input.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/parse_quote.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/pat.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/path.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/print.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/punctuated.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/reserved.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/sealed.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/span.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/spanned.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/stmt.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/thread.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/token.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/tt.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/ty.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/verbatim.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/src/whitespace.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/common/eq.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/common/mod.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/common/parse.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/debug/gen.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/debug/mod.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/macros/mod.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/regression.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/regression/issue1108.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/regression/issue1235.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/repo/mod.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/repo/progress.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_asyncness.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_attribute.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_derive_input.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_expr.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_generics.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_grouping.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_ident.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_item.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_iterators.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_lit.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_meta.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_parse_buffer.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_parse_stream.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_pat.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_path.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_precedence.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_receiver.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_round_trip.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_shebang.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_should_parse.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_size.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_stmt.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_token_trees.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_ty.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/test_visibility.rs create mode 100644 bitbox02-bt/vendor/syn-1.0.109/tests/zzz_stable.rs create mode 100644 bitbox02-bt/vendor/syn/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/syn/Cargo.toml create mode 100644 bitbox02-bt/vendor/syn/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/syn/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/syn/README.md create mode 100644 bitbox02-bt/vendor/syn/benches/file.rs create mode 100644 bitbox02-bt/vendor/syn/benches/rust.rs create mode 100644 bitbox02-bt/vendor/syn/src/attr.rs create mode 100644 bitbox02-bt/vendor/syn/src/bigint.rs create mode 100644 bitbox02-bt/vendor/syn/src/buffer.rs create mode 100644 bitbox02-bt/vendor/syn/src/classify.rs create mode 100644 bitbox02-bt/vendor/syn/src/custom_keyword.rs create mode 100644 bitbox02-bt/vendor/syn/src/custom_punctuation.rs create mode 100644 bitbox02-bt/vendor/syn/src/data.rs create mode 100644 bitbox02-bt/vendor/syn/src/derive.rs create mode 100644 bitbox02-bt/vendor/syn/src/discouraged.rs create mode 100644 bitbox02-bt/vendor/syn/src/drops.rs create mode 100644 bitbox02-bt/vendor/syn/src/error.rs create mode 100644 bitbox02-bt/vendor/syn/src/export.rs create mode 100644 bitbox02-bt/vendor/syn/src/expr.rs create mode 100644 bitbox02-bt/vendor/syn/src/ext.rs create mode 100644 bitbox02-bt/vendor/syn/src/file.rs create mode 100644 bitbox02-bt/vendor/syn/src/fixup.rs create mode 100644 bitbox02-bt/vendor/syn/src/gen/clone.rs create mode 100644 bitbox02-bt/vendor/syn/src/gen/debug.rs create mode 100644 bitbox02-bt/vendor/syn/src/gen/eq.rs create mode 100644 bitbox02-bt/vendor/syn/src/gen/fold.rs create mode 100644 bitbox02-bt/vendor/syn/src/gen/hash.rs create mode 100644 bitbox02-bt/vendor/syn/src/gen/visit.rs create mode 100644 bitbox02-bt/vendor/syn/src/gen/visit_mut.rs create mode 100644 bitbox02-bt/vendor/syn/src/generics.rs create mode 100644 bitbox02-bt/vendor/syn/src/group.rs create mode 100644 bitbox02-bt/vendor/syn/src/ident.rs create mode 100644 bitbox02-bt/vendor/syn/src/item.rs create mode 100644 bitbox02-bt/vendor/syn/src/lib.rs create mode 100644 bitbox02-bt/vendor/syn/src/lifetime.rs create mode 100644 bitbox02-bt/vendor/syn/src/lit.rs create mode 100644 bitbox02-bt/vendor/syn/src/lookahead.rs create mode 100644 bitbox02-bt/vendor/syn/src/mac.rs create mode 100644 bitbox02-bt/vendor/syn/src/macros.rs create mode 100644 bitbox02-bt/vendor/syn/src/meta.rs create mode 100644 bitbox02-bt/vendor/syn/src/op.rs create mode 100644 bitbox02-bt/vendor/syn/src/parse.rs create mode 100644 bitbox02-bt/vendor/syn/src/parse_macro_input.rs create mode 100644 bitbox02-bt/vendor/syn/src/parse_quote.rs create mode 100644 bitbox02-bt/vendor/syn/src/pat.rs create mode 100644 bitbox02-bt/vendor/syn/src/path.rs create mode 100644 bitbox02-bt/vendor/syn/src/precedence.rs create mode 100644 bitbox02-bt/vendor/syn/src/print.rs create mode 100644 bitbox02-bt/vendor/syn/src/punctuated.rs create mode 100644 bitbox02-bt/vendor/syn/src/restriction.rs create mode 100644 bitbox02-bt/vendor/syn/src/sealed.rs create mode 100644 bitbox02-bt/vendor/syn/src/span.rs create mode 100644 bitbox02-bt/vendor/syn/src/spanned.rs create mode 100644 bitbox02-bt/vendor/syn/src/stmt.rs create mode 100644 bitbox02-bt/vendor/syn/src/thread.rs create mode 100644 bitbox02-bt/vendor/syn/src/token.rs create mode 100644 bitbox02-bt/vendor/syn/src/tt.rs create mode 100644 bitbox02-bt/vendor/syn/src/ty.rs create mode 100644 bitbox02-bt/vendor/syn/src/verbatim.rs create mode 100644 bitbox02-bt/vendor/syn/src/whitespace.rs create mode 100644 bitbox02-bt/vendor/syn/tests/common/eq.rs create mode 100644 bitbox02-bt/vendor/syn/tests/common/mod.rs create mode 100644 bitbox02-bt/vendor/syn/tests/common/parse.rs create mode 100644 bitbox02-bt/vendor/syn/tests/debug/gen.rs create mode 100644 bitbox02-bt/vendor/syn/tests/debug/mod.rs create mode 100644 bitbox02-bt/vendor/syn/tests/macros/mod.rs create mode 100644 bitbox02-bt/vendor/syn/tests/regression.rs create mode 100644 bitbox02-bt/vendor/syn/tests/regression/issue1108.rs create mode 100644 bitbox02-bt/vendor/syn/tests/regression/issue1235.rs create mode 100644 bitbox02-bt/vendor/syn/tests/repo/mod.rs create mode 100644 bitbox02-bt/vendor/syn/tests/repo/progress.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_asyncness.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_attribute.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_derive_input.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_expr.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_generics.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_grouping.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_ident.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_item.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_iterators.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_lit.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_meta.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_parse_buffer.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_parse_quote.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_parse_stream.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_pat.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_path.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_precedence.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_receiver.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_round_trip.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_shebang.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_size.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_stmt.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_token_trees.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_ty.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_unparenthesize.rs create mode 100644 bitbox02-bt/vendor/syn/tests/test_visibility.rs create mode 100644 bitbox02-bt/vendor/syn/tests/zzz_stable.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/thiserror-impl/Cargo.toml create mode 100644 bitbox02-bt/vendor/thiserror-impl/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/thiserror-impl/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/ast.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/attr.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/expand.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/fmt.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/generics.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/lib.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/prop.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/span.rs create mode 100644 bitbox02-bt/vendor/thiserror-impl/src/valid.rs create mode 100644 bitbox02-bt/vendor/thiserror/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/thiserror/Cargo.toml create mode 100644 bitbox02-bt/vendor/thiserror/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/thiserror/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/thiserror/README.md create mode 100644 bitbox02-bt/vendor/thiserror/build.rs create mode 100644 bitbox02-bt/vendor/thiserror/build/probe.rs create mode 100644 bitbox02-bt/vendor/thiserror/rust-toolchain.toml create mode 100644 bitbox02-bt/vendor/thiserror/src/aserror.rs create mode 100644 bitbox02-bt/vendor/thiserror/src/display.rs create mode 100644 bitbox02-bt/vendor/thiserror/src/lib.rs create mode 100644 bitbox02-bt/vendor/thiserror/src/provide.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/compiletest.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_backtrace.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_deprecated.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_display.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_expr.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_from.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_generics.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_lints.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_option.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_path.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_source.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/test_transparent.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/bad-field-attr.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/bad-field-attr.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/concat-display.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/concat-display.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-enum-source.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-enum-source.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-fmt.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-fmt.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-struct-source.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-struct-source.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-transparent.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/duplicate-transparent.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/fallback-impl-with-display.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/fallback-impl-with-display.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/from-backtrace-backtrace.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/from-backtrace-backtrace.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/from-not-source.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/from-not-source.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/invalid-input-impl-anyway.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/invalid-input-impl-anyway.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/lifetime.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/lifetime.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/missing-display.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/missing-display.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/missing-fmt.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/missing-fmt.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/no-display.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/no-display.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-enum-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-enum-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-enum-unnamed-field-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-enum-unnamed-field-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-struct-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-struct-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-struct-unnamed-field-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/source-struct-unnamed-field-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-display.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-display.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-many.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-many.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-source.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-source.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-unnamed-field-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-enum-unnamed-field-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-many.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-many.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-source.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-source.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-unnamed-field-not-error.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/transparent-struct-unnamed-field-not-error.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/unexpected-field-fmt.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/unexpected-field-fmt.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/unexpected-struct-source.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/unexpected-struct-source.stderr create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/union.rs create mode 100644 bitbox02-bt/vendor/thiserror/tests/ui/union.stderr create mode 100644 bitbox02-bt/vendor/ufmt-write/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/ufmt-write/Cargo.toml create mode 100644 bitbox02-bt/vendor/ufmt-write/src/lib.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/unicode-ident/Cargo.toml create mode 100644 bitbox02-bt/vendor/unicode-ident/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/unicode-ident/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/unicode-ident/LICENSE-UNICODE create mode 100644 bitbox02-bt/vendor/unicode-ident/README.md create mode 100644 bitbox02-bt/vendor/unicode-ident/benches/xid.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/src/lib.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/src/tables.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/compare.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/fst/mod.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/fst/xid_continue.fst create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/fst/xid_start.fst create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/roaring/mod.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/static_size.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/tables/mod.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/tables/tables.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/trie/mod.rs create mode 100644 bitbox02-bt/vendor/unicode-ident/tests/trie/trie.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/Cargo.lock create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/Cargo.toml create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/README.md create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/api.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/bin/cstr/mod.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/bin/run-emitter-test-suite.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/bin/run-parser-test-suite.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/dumper.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/emitter.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/lib.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/loader.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/macros.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/ops.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/parser.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/reader.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/scanner.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/success.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/writer.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/src/yaml.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/tests/bin/mod.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/tests/ignorelist/libyaml-emitter create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/tests/ignorelist/libyaml-parser create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/tests/ignorelist/libyaml-parser-error create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/tests/test_emitter.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/tests/test_parser.rs create mode 100644 bitbox02-bt/vendor/unsafe-libyaml/tests/test_parser_error.rs create mode 100644 bitbox02-bt/vendor/vcell/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/vcell/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/vcell/Cargo.toml create mode 100644 bitbox02-bt/vendor/vcell/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/vcell/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/vcell/README.md create mode 100644 bitbox02-bt/vendor/vcell/src/lib.rs create mode 100644 bitbox02-bt/vendor/version_check/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/version_check/Cargo.toml create mode 100644 bitbox02-bt/vendor/version_check/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/version_check/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/version_check/README.md create mode 100644 bitbox02-bt/vendor/version_check/src/channel.rs create mode 100644 bitbox02-bt/vendor/version_check/src/date.rs create mode 100644 bitbox02-bt/vendor/version_check/src/lib.rs create mode 100644 bitbox02-bt/vendor/version_check/src/version.rs create mode 100644 bitbox02-bt/vendor/void/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/void/Cargo.toml create mode 100644 bitbox02-bt/vendor/void/README.md create mode 100644 bitbox02-bt/vendor/void/src/lib.rs create mode 100644 bitbox02-bt/vendor/volatile-register/.cargo-checksum.json create mode 100644 bitbox02-bt/vendor/volatile-register/CHANGELOG.md create mode 100644 bitbox02-bt/vendor/volatile-register/CODE_OF_CONDUCT.md create mode 100644 bitbox02-bt/vendor/volatile-register/Cargo.toml create mode 100644 bitbox02-bt/vendor/volatile-register/LICENSE-APACHE create mode 100644 bitbox02-bt/vendor/volatile-register/LICENSE-MIT create mode 100644 bitbox02-bt/vendor/volatile-register/README.md create mode 100644 bitbox02-bt/vendor/volatile-register/src/lib.rs diff --git a/Dockerfile b/Dockerfile index 86dec0a..65ecab8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -61,6 +61,7 @@ RUN --mount=source=.,target=/mnt \ for patch in `ls /mnt/da14531-sdk/patches`; do patch -p1 < /mnt/da14531-sdk/patches/$patch; done # Install rust compiler +ARG BINDGEN_VERSION=0.70.1 ENV PATH=/opt/cargo/bin:$PATH RUSTUP_HOME=/opt/rustup RUN --mount=source=rust-toolchain.toml,target=/mnt/rust-toolchain.toml \ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | CARGO_HOME=/opt/cargo sh -s -- --default-toolchain $(grep -oP '(?<=channel = ")[^"]+' /mnt/rust-toolchain.toml) -y && \ @@ -68,4 +69,6 @@ RUN --mount=source=rust-toolchain.toml,target=/mnt/rust-toolchain.toml \ rustup component add \ rustfmt \ clippy \ - rust-src + rust-src \ + && \ + CARGO_HOME=/opt/cargo cargo install bindgen-cli --version ${BINDGEN_VERSION} --locked diff --git a/bitbox02-bt/.cargo/config.toml b/bitbox02-bt/.cargo/config.toml index 550b86b..8aee7d2 100644 --- a/bitbox02-bt/.cargo/config.toml +++ b/bitbox02-bt/.cargo/config.toml @@ -1,6 +1,12 @@ [build] target = "thumbv6m-none-eabi" +[source.vendored-sources] +directory = "vendor" + +[source.crates-io] +replace-with = "vendored-sources" + [patch.crates-io] da14531-sdk-macros = {path="../da14531-sdk-macros"} diff --git a/bitbox02-bt/Cargo.lock b/bitbox02-bt/Cargo.lock index c2327e2..bc27879 100644 --- a/bitbox02-bt/Cargo.lock +++ b/bitbox02-bt/Cargo.lock @@ -2,25 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "aho-corasick" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" -dependencies = [ - "memchr", -] - -[[package]] -name = "annotate-snippets" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccaf7e9dfbb6ab22c82e473cd1a8a7bd313c19a5b7e40970f3d89ef5a5c9e81e" -dependencies = [ - "unicode-width", - "yansi-term", -] - [[package]] name = "bare-metal" version = "0.2.5" @@ -30,27 +11,6 @@ dependencies = [ "rustc_version", ] -[[package]] -name = "bindgen" -version = "0.70.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" -dependencies = [ - "annotate-snippets", - "bitflags", - "cexpr", - "clang-sys", - "itertools", - "log", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex", - "syn 2.0.79", -] - [[package]] name = "bitbox02-bt" version = "0.1.0" @@ -73,12 +33,6 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719" -[[package]] -name = "bitflags" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" - [[package]] name = "byteorder" version = "1.5.0" @@ -94,32 +48,6 @@ dependencies = [ "shlex", ] -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "clang-sys" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" -dependencies = [ - "glob", - "libc", - "libloading", -] - [[package]] name = "cortex-m" version = "0.7.7" @@ -170,7 +98,6 @@ dependencies = [ name = "da14531-sdk" version = "0.2.0" dependencies = [ - "bindgen", "cc", "cty", "da14531-sdk-macros", @@ -192,12 +119,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "either" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" - [[package]] name = "embedded-hal" version = "0.2.7" @@ -223,12 +144,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" -[[package]] -name = "glob" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" - [[package]] name = "grounded" version = "0.2.0" @@ -254,55 +169,12 @@ dependencies = [ "hashbrown", ] -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" -[[package]] -name = "libc" -version = "0.2.159" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5" - -[[package]] -name = "libloading" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" -dependencies = [ - "cfg-if", - "windows-targets", -] - -[[package]] -name = "log" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - [[package]] name = "nb" version = "0.1.3" @@ -318,16 +190,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d5439c4ad607c3c23abf66de8c8bf57ba8adcd1f129e699851a6e43935d339d" -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - [[package]] name = "panic-abort" version = "0.3.2" @@ -346,16 +208,6 @@ version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" -[[package]] -name = "prettyplease" -version = "0.2.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479cf940fbbb3426c32c5d5176f62ad57549a0bb84773423ba8be9d089f5faba" -dependencies = [ - "proc-macro2", - "syn 2.0.79", -] - [[package]] name = "proc-macro-error" version = "1.0.4" @@ -398,35 +250,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "regex" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38200e5ee88914975b69f657f0801b6f6dccafd44fd9326302a4aaeecfacb1d8" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" - [[package]] name = "rtt-target" version = "0.3.1" @@ -446,12 +269,6 @@ dependencies = [ "ufmt-write", ] -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - [[package]] name = "rustc_version" version = "0.2.3" @@ -582,12 +399,6 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -620,98 +431,3 @@ checksum = "de437e2a6208b014ab52972a27e59b33fa2920d3e00fe05026167a1c509d19cc" dependencies = [ "vcell", ] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -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 = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "yansi-term" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5c30ade05e61656247b2e334a031dfd0cc466fadef865bdcdea8d537951bf1" -dependencies = [ - "winapi", -] diff --git a/bitbox02-bt/vendor/bare-metal/.cargo-checksum.json b/bitbox02-bt/vendor/bare-metal/.cargo-checksum.json new file mode 100644 index 0000000..07d855e --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"cbe525fd84e5a7141bcee4fe5ae0c7ff9e1e50da7996277f902859a90600b8e4","Cargo.toml":"fb997fae9de7404a3b148f83ac3f03e84a19d16870843167dadd80e988ac098f","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"035e70219855119df4273b3c5b97543ae82e0dd60c520416e759107c602f651b","README.md":"afa5b1c70325ec18dbfcea11faa65a3d83368c2c907c158f7acb39736b3e0d94","bors.toml":"b96eaac6b3dc8487a2bcc6cb415e745a28d9a61937090df48186c62d2b614aeb","build.rs":"9485deb6c0ab46ed05b1fabfb62518fa6f9fbdcf7a207d4cb6844dc6df70f4d7","ci/install.sh":"e295d97db9e12ac6ee3e523e4597ad58fedcca2b8aa3a21302951ad2327b88a9","ci/script.sh":"e2c28462deea39c9ea792fa7069b9afdb6f561901aa1878ea27046c8ad058e43","src/lib.rs":"9197c65b0daec25ebb5e8c5587f82affaa35757b785a539ebb35ce91dae98b7d"},"package":"5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/bare-metal/CHANGELOG.md b/bitbox02-bt/vendor/bare-metal/CHANGELOG.md new file mode 100644 index 0000000..a06a869 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/CHANGELOG.md @@ -0,0 +1,77 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.2.5] - 2019-08-29 + +### Changed + +- The `const-fn` feature is now stable + +## [v0.2.4] - 2018-10-30 + +### Added + +- Note in the documentation that `Mutex` is not memory safe in multi-core systems. + +### Changed + +- The `const-fn` feature can now be used on 1.31-beta and will also work on stable 1.31. + +## [v0.2.3] - 2018-08-17 + +### Fixed + +- A compilation error when using a recent nightly while the "const-fn" feature was enabled. + +## [v0.2.2] - 2018-08-17 - YANKED + +### Fixed + +- A compilation error when using a recent nightly while the "const-fn" feature was enabled. + +## [v0.2.1] - 2018-08-03 + +### Fixed + +- Soundness issue where it was possible to borrow the contents of a Mutex for longer than the + lifetime of the Mutex. + +## [v0.2.0] - 2018-05-10 - YANKED + +YANKED due to a soundness issue: see v0.2.1 for details + +### Changed + +- [breaking-change] `const-fn` is no longer a default feature (i.e. a feature that's enabled by + default). The consequence is that this crate now compiles on 1.27 (beta) by default, and opting + into `const-fn` requires nightly. + +## [v0.1.2] - 2018-04-24 + +### Added + +- An opt-out "const-fn" Cargo feature. When this feature is disabled this crate compiles on stable. + +## [v0.1.1] - 2017-09-19 + +### Fixed + +- Added feature gate to make this work on recent nightlies + +## v0.1.0 - 2017-07-06 + +- Initial release + +[Unreleased]: https://github.com/japaric/bare-metal/compare/v0.2.5...HEAD +[v0.2.5]: https://github.com/japaric/bare-metal/compare/v0.2.4...v0.2.5 +[v0.2.4]: https://github.com/japaric/bare-metal/compare/v0.2.3...v0.2.4 +[v0.2.3]: https://github.com/japaric/bare-metal/compare/v0.2.2...v0.2.3 +[v0.2.2]: https://github.com/japaric/bare-metal/compare/v0.2.1...v0.2.2 +[v0.2.1]: https://github.com/japaric/bare-metal/compare/v0.2.0...v0.2.1 +[v0.2.0]: https://github.com/japaric/bare-metal/compare/v0.1.2...v0.2.0 +[v0.1.2]: https://github.com/japaric/bare-metal/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/japaric/bare-metal/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/bare-metal/Cargo.toml b/bitbox02-bt/vendor/bare-metal/Cargo.toml new file mode 100644 index 0000000..0c57fd9 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/Cargo.toml @@ -0,0 +1,27 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "bare-metal" +version = "0.2.5" +authors = ["Jorge Aparicio "] +description = "Abstractions common to bare metal systems" +documentation = "https://docs.rs/bare-metal" +keywords = ["bare-metal", "register", "peripheral", "interrupt"] +categories = ["embedded", "hardware-support", "no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/japaric/bare-metal" +[build-dependencies.rustc_version] +version = "0.2.3" + +[features] +const-fn = [] diff --git a/bitbox02-bt/vendor/bare-metal/LICENSE-APACHE b/bitbox02-bt/vendor/bare-metal/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/bare-metal/LICENSE-MIT b/bitbox02-bt/vendor/bare-metal/LICENSE-MIT new file mode 100644 index 0000000..a128ba4 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017 Jorge Aparicio + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/bare-metal/README.md b/bitbox02-bt/vendor/bare-metal/README.md new file mode 100644 index 0000000..b540f88 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/README.md @@ -0,0 +1,21 @@ +# `bare-metal` + +> Abstractions common to bare metal systems + +## [Change log](CHANGELOG.md) + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bitbox02-bt/vendor/bare-metal/bors.toml b/bitbox02-bt/vendor/bare-metal/bors.toml new file mode 100644 index 0000000..5ccee21 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/bors.toml @@ -0,0 +1,3 @@ +status = [ + "continuous-integration/travis-ci/push", +] \ No newline at end of file diff --git a/bitbox02-bt/vendor/bare-metal/build.rs b/bitbox02-bt/vendor/bare-metal/build.rs new file mode 100644 index 0000000..f197f20 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/build.rs @@ -0,0 +1,9 @@ +extern crate rustc_version; + +fn main() { + let vers = rustc_version::version().unwrap(); + + if vers.major == 1 && vers.minor < 31 { + println!("cargo:rustc-cfg=unstable_const_fn") + } +} diff --git a/bitbox02-bt/vendor/bare-metal/ci/install.sh b/bitbox02-bt/vendor/bare-metal/ci/install.sh new file mode 100644 index 0000000..3c41921 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/ci/install.sh @@ -0,0 +1,9 @@ +set -euxo pipefail + +main() { + if [ $TARGET != x86_64-unknown-linux-gnu ]; then + rustup target add $TARGET + fi +} + +main diff --git a/bitbox02-bt/vendor/bare-metal/ci/script.sh b/bitbox02-bt/vendor/bare-metal/ci/script.sh new file mode 100644 index 0000000..b0aec22 --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/ci/script.sh @@ -0,0 +1,11 @@ +set -euxo pipefail + +main() { + cargo check --target $TARGET + + if [ $TARGET = x86_64-unknown-linux-gnu ]; then + cargo test + fi +} + +main diff --git a/bitbox02-bt/vendor/bare-metal/src/lib.rs b/bitbox02-bt/vendor/bare-metal/src/lib.rs new file mode 100644 index 0000000..47a6b8e --- /dev/null +++ b/bitbox02-bt/vendor/bare-metal/src/lib.rs @@ -0,0 +1,101 @@ +//! Abstractions common to bare metal systems + +#![deny(missing_docs)] +#![deny(warnings)] +#![no_std] + +use core::cell::UnsafeCell; + +/// A peripheral +#[derive(Debug)] +pub struct Peripheral +where + T: 'static, +{ + address: *mut T, +} + +impl Peripheral { + /// Creates a new peripheral + /// + /// `address` is the base address of the register block + pub const unsafe fn new(address: usize) -> Self { + Peripheral { + address: address as *mut T, + } + } + + /// Borrows the peripheral for the duration of a critical section + pub fn borrow<'cs>(&self, _ctxt: &'cs CriticalSection) -> &'cs T { + unsafe { &*self.get() } + } + + /// Returns a pointer to the register block + pub fn get(&self) -> *mut T { + self.address as *mut T + } +} + +/// Critical section token +/// +/// Indicates that you are executing code within a critical section +pub struct CriticalSection { + _0: (), +} + +impl CriticalSection { + /// Creates a critical section token + /// + /// This method is meant to be used to create safe abstractions rather than + /// meant to be directly used in applications. + pub unsafe fn new() -> Self { + CriticalSection { _0: () } + } +} + +/// A "mutex" based on critical sections +/// +/// # Safety +/// +/// **This Mutex is only safe on single-core systems.** +/// +/// On multi-core systems, a `CriticalSection` **is not sufficient** to ensure exclusive access. +pub struct Mutex { + inner: UnsafeCell, +} + +impl Mutex { + /// Creates a new mutex + pub const fn new(value: T) -> Self { + Mutex { + inner: UnsafeCell::new(value), + } + } +} + +impl Mutex { + /// Borrows the data for the duration of the critical section + pub fn borrow<'cs>(&'cs self, _cs: &'cs CriticalSection) -> &'cs T { + unsafe { &*self.inner.get() } + } +} + +/// ``` compile_fail +/// fn bad(cs: &bare_metal::CriticalSection) -> &u32 { +/// let x = bare_metal::Mutex::new(42u32); +/// x.borrow(cs) +/// } +/// ``` +#[allow(dead_code)] +const GH_6: () = (); + +/// Interrupt number +pub unsafe trait Nr { + /// Returns the number associated with an interrupt + fn nr(&self) -> u8; +} + +// NOTE A `Mutex` can be used as a channel so the protected data must be `Send` +// to prevent sending non-Sendable stuff (e.g. access tokens) across different +// execution contexts (e.g. interrupts) +unsafe impl Sync for Mutex where T: Send {} diff --git a/bitbox02-bt/vendor/bitfield/.cargo-checksum.json b/bitbox02-bt/vendor/bitfield/.cargo-checksum.json new file mode 100644 index 0000000..d0313d9 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"c4945aec76bc2731a0497b605f863a7a11390cadd1d0ff59ae2b2fa2d03f0dda","Cargo.toml":"f36c4d7ba9d81f7105f178eaee447b032ba2f8710e05c6e43fca4fd85e50b549","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"af6b8d2c7ab89b819e3c2db77b572f145d14c8578dbd25015d739b30d4cc92f7","README.md":"0508f6529346eb36ac57497cc72c68e8e64e4f2aac7df2e9395582edfeead850","examples/bits_position.rs":"a00a3c79cb1d87e34e94372bb673a8a468e397ffca437acfbeda1228b2aa99e1","examples/ipv4.rs":"153d81430b512d2277c134c3b29e23924a23fb416c83a3eb010267e98ff0c30c","multitest.toml":"0ad084611444cc582d5421dfac4ef9e9893fd76a4a87d7132e80668f8531eafa","src/lib.rs":"4178acd8676440ac01dc406d23511ff77657d34231343528294d5c12dfa76290","tests/lib.rs":"8a1723a1e34287109cb807d3af318ab22869952d16cde633d6462faaa9e00886"},"package":"46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/bitfield/CHANGELOG.md b/bitbox02-bt/vendor/bitfield/CHANGELOG.md new file mode 100644 index 0000000..837f224 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.13.2] - 2019-05-28 + +### Added +- `from into` can be used in place of `from` to change the input type of the setter. Thanks to @roblabla + +[Unreleased]: https://github.com/dzamlo/rust-bitfield/compare/v0.13.1...HEAD +[0.13.2]: https://github.com/dzamlo/rust-bitfield/compare/v0.13.1...v0.13.2 + diff --git a/bitbox02-bt/vendor/bitfield/Cargo.toml b/bitbox02-bt/vendor/bitfield/Cargo.toml new file mode 100644 index 0000000..e2f4752 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/Cargo.toml @@ -0,0 +1,22 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "bitfield" +version = "0.13.2" +authors = ["Loïc Damien "] +description = "This crate provides macros to generate bitfield-like struct." +documentation = "https://docs.rs/bitfield" +license = "MIT OR Apache-2.0" +repository = "https://github.com/dzamlo/rust-bitfield" + +[dependencies] diff --git a/bitbox02-bt/vendor/bitfield/LICENSE-APACHE b/bitbox02-bt/vendor/bitfield/LICENSE-APACHE new file mode 100644 index 0000000..8f71f43 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/LICENSE-APACHE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/bitbox02-bt/vendor/bitfield/LICENSE-MIT b/bitbox02-bt/vendor/bitfield/LICENSE-MIT new file mode 100644 index 0000000..b964553 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright (c) 2017 Loïc Damien + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bitbox02-bt/vendor/bitfield/README.md b/bitbox02-bt/vendor/bitfield/README.md new file mode 100644 index 0000000..ac32705 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/README.md @@ -0,0 +1,57 @@ +rust-bitfield +============= + +This crate provides macros to generate bitfield-like struct. + +This a complete rewrite of the `bitfield` crate. +You can find the previous version in the [rust-bitfield-legacy](https://github.com/dzamlo/rust-bitfield-legacy) repository. This version works on the stable version of rustc and use a different syntax with different possibility. + + +## Example + +An IPv4 header could be described like that: + +```rust +bitfield!{ + struct IpV4Header(MSB0 [u8]); + u32; + get_version, _: 3, 0; + get_ihl, _: 7, 4; + get_dscp, _: 13, 8; + get_ecn, _: 15, 14; + get_total_length, _: 31, 16; + get_identification, _: 47, 31; + get_df, _: 49; + get_mf, _: 50; + get_fragment_offset, _: 63, 51; + get_time_to_live, _: 71, 64; + get_protocol, _: 79, 72; + get_header_checksum, _: 95, 79; + get_source_address, _: 127, 96; + get_destination_address, _: 159, 128; +} +``` + +In this example, all the fields are read-only, the _ as setter name signals to skip the setter method. +The range at the end (e.g. 3, 0) defines the bit range where the information is encoded. + +## Documentation + +The documentation of the released version is available on [doc.rs](https://docs.rs/bitfield). + + +## License + +Licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally +submitted for inclusion in the work by you, as defined in the Apache-2.0 +license, shall be dual licensed as above, without any additional terms or +conditions. diff --git a/bitbox02-bt/vendor/bitfield/examples/bits_position.rs b/bitbox02-bt/vendor/bitfield/examples/bits_position.rs new file mode 100644 index 0000000..0bcf360 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/examples/bits_position.rs @@ -0,0 +1,75 @@ +#[macro_use] +extern crate bitfield; + +use bitfield::Bit; +use bitfield::BitRange; + +bitfield! { + struct BitsLocations([u8]); +} + +bitfield! { + struct BitsLocationsMsb0(MSB0 [u8]); +} + +fn println_slice_bits(slice: &[u8]) { + if slice.is_empty() { + println!("[]"); + } else { + print!("[{:08b}", slice[0]); + + for byte in &slice[1..] { + print!(", {:08b}", byte); + } + + println!("]"); + } +} + +fn main() { + let mut bits_locations = BitsLocations([0; 3]); + let mut bits_locations_msb0 = BitsLocationsMsb0([0; 3]); + + println!("Default version:"); + for i in 0..(3 * 8) { + bits_locations.set_bit(i, true); + print!("{:2}: ", i); + println_slice_bits(&bits_locations.0); + bits_locations.set_bit(i, false); + } + + for i in 0..(3 * 8 - 3) { + let msb = i + 3; + let lsb = i; + for value in &[0b1111u8, 0b0001, 0b1000] { + bits_locations.set_bit_range(msb, lsb, *value); + print!("{:2} - {:2} ({:04b}): ", msb, lsb, value); + println_slice_bits(&bits_locations.0); + } + println!(); + bits_locations.set_bit_range(msb, lsb, 0u8); + } + + println!("MSB0 version:"); + + for i in 0..(3 * 8) { + bits_locations_msb0.set_bit(i, true); + print!("{:2}: ", i); + println_slice_bits(&bits_locations_msb0.0); + + bits_locations_msb0.set_bit(i, false); + } + + for i in 0..(3 * 8 - 3) { + let msb = i + 3; + let lsb = i; + for value in &[0b1111u8, 0b0001, 0b1000] { + bits_locations_msb0.set_bit_range(msb, lsb, *value); + print!("{:2} - {:2} ({:04b}): ", msb, lsb, value); + println_slice_bits(&bits_locations_msb0.0); + } + println!(); + + bits_locations_msb0.set_bit_range(msb, lsb, 0u8); + } +} diff --git a/bitbox02-bt/vendor/bitfield/examples/ipv4.rs b/bitbox02-bt/vendor/bitfield/examples/ipv4.rs new file mode 100644 index 0000000..93cedcd --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/examples/ipv4.rs @@ -0,0 +1,60 @@ +#![allow(dead_code)] + +#[macro_use] +extern crate bitfield; + +use std::net::Ipv4Addr; + +bitfield! { + struct IpV4Header(MSB0 [u8]); + impl Debug; + u32; + get_version, _: 3, 0; + get_ihl, _: 7, 4; + get_dscp, _: 13, 8; + get_ecn, _: 15, 14; + get_total_length, _: 31, 16; + get_identification, _: 47, 31; + get_df, _: 49; + get_mf, _: 50; + get_fragment_offset, _: 63, 51; + get_time_to_live, _: 71, 64; + get_protocol, _: 79, 72; + get_header_checksum, _: 95, 79; + u8, get_source_address, _: 103, 96, 4; + u32, into Ipv4Addr, get_destination_address, _: 159, 128; +} + +impl + AsMut<[u8]>> IpV4Header { + fn get_source_as_ip_addr(&self) -> Ipv4Addr { + let mut src = [0; 4]; + for (i, src) in src.iter_mut().enumerate() { + *src = self.get_source_address(i); + } + src.into() + } +} + +fn main() { + let data = [ + 0x45, 0x00, 0x00, 0x40, 0x69, 0x27, 0x40, 0x00, 0x40, 0x11, 0x4d, 0x0d, 0xc0, 0xa8, 0x01, + 0x2a, 0xc0, 0xa8, 0x01, 0xfe, + ]; + + let header = IpV4Header(data); + + assert_eq!(header.get_version(), 4); + assert_eq!(header.get_total_length(), 64); + assert_eq!(header.get_identification(), 0x6927); + assert!(header.get_df()); + assert!(!header.get_mf()); + assert_eq!(header.get_fragment_offset(), 0); + assert_eq!(header.get_protocol(), 0x11); + println!( + "from {} to {}", + header.get_source_as_ip_addr(), + header.get_destination_address() + ); + + println!("{:#?}", header); +} diff --git a/bitbox02-bt/vendor/bitfield/multitest.toml b/bitbox02-bt/vendor/bitfield/multitest.toml new file mode 100644 index 0000000..bb62f25 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/multitest.toml @@ -0,0 +1,22 @@ +[[tests]] +name = "cargo-test-{{toolchain}}" +command = ["cargo", "+{{toolchain}}", "test", "--all", "--frozen"] + +[[tests.env]] +name = "CARGO_TARGET_DIR" +value = "target/{{name}}" + +[tests.variables] +toolchain = ["stable", "beta", "nightly", "1.26.0"] + +[[tests]] +name = "cargo-clippy" +command = ["cargo", "+nightly", "clippy", "--all", "--frozen", "--all-targets", "--", "-D", "warnings"] + +[[tests.env]] +name = "CARGO_TARGET_DIR" +value = "target/cargo-test-nightly" + +[[tests]] +name = "cargo-fmt" +command = ["cargo", "fmt", "--all", "--", "--check"] diff --git a/bitbox02-bt/vendor/bitfield/src/lib.rs b/bitbox02-bt/vendor/bitfield/src/lib.rs new file mode 100644 index 0000000..749df77 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/src/lib.rs @@ -0,0 +1,668 @@ +#![no_std] +#![deny( + missing_docs, + unused_extern_crates, + unused_import_braces, + unused_qualifications +)] + +//! This crate provides macros to generate bitfield-like struct. +//! +//! See the documentation of the macros for how to use them. +//! +//! Examples and tests are also a great way to understand how to use these macros. + +/// Declares the fields of struct. +/// +/// This macro will generate the methods to access the fields of a bitfield. It must be called +/// from an `impl` block for a type that implements the `BitRange` and/or the `Bit` traits +/// (which traits are required depending on what type of fields are used). +/// +/// The syntax of this macro is composed of declarations ended by semicolons. There are two types +/// of declarations: default type, and fields. +/// +/// A default type is just a type followed by a semicolon. This will affect all the following field +/// declarations. +/// +/// A field declaration is composed of the following: +/// +/// * Optional attributes (`#[...]`), documentation comments (`///`) are attributes; +/// * An optional pub keyword to make the methods public +/// * An optional type followed by a comma +/// * Optionally, the word `into` followed by a type, followed by a comma +/// * The getter and setter idents, separated by a comma +/// * A colon +/// * One to three expressions of type `usize` +/// +/// The attributes and pub will be applied to the two methods generated. +/// +/// If the `into` part is used, the getter will convert the field after reading it. +/// +/// The getter and setter idents can be `_` to not generate one of the two. For example, if the +/// setter is `_`, the field will be read-only. +/// +/// The expressions at the end are the bit positions. Their meaning depends on the number of +/// expressions: +/// +/// * One expression: the field is a single bit. The type is ignored and `bool` is used. The trait +/// `Bit` is used. +/// * Two expressions: `msb, lsb`, the field is composed of the bits from `msb` to `lsb`, included. +/// * Three expressions: `msb, lsb, count`, the field is an array. The first element is composed of +/// the bits from `msb` to `lsb`. The following elements are consecutive bits range of the same +/// size. +/// +/// # Example +/// +/// ```rust +/// # #[macro_use] extern crate bitfield; +/// # fn main() {} +/// # struct FooBar(u64); +/// # bitfield_bitrange!{struct FooBar(u64)} +/// # impl From for FooBar{ fn from(_: u32) -> FooBar {unimplemented!()}} +/// # impl From for u32{ fn from(_: FooBar) -> u32 {unimplemented!()}} +/// # impl FooBar { +/// bitfield_fields!{ +/// // The default type will be `u64 +/// u64; +/// // filed1 is read-write, public, the methods are inline +/// #[inline] +/// pub field1, set_field1: 10, 0; +/// // `field2` is read-only, private, and of type bool. +/// field2, _ : 0; +/// // `field3` will be read as an `u32` and then converted to `FooBar`. +/// // The setter is not affected, it still need an `u32` value. +/// u32, into FooBar, field3, set_field3: 10, 0; +/// // `field4` will be read as an `u32` and then converted to `FooBar`. +/// // The setter will take a `FooBar`, and converted back to an `u32`. +/// u32, from into FooBar, field4, set_field4: 10, 0; +/// } +/// # } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! bitfield_fields { + (@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $from:ty, $into:ty, _, $setter:ident: $msb:expr, + $lsb:expr, $count:expr) => { + $(#[$attribute])* + #[allow(unknown_lints)] + #[allow(eq_op)] + $($vis)* fn $setter(&mut self, index: usize, value: $from) { + use $crate::BitRange; + __bitfield_debug_assert!(index < $count); + let width = $msb - $lsb + 1; + let lsb = $lsb + index*width; + let msb = lsb + width - 1; + self.set_bit_range(msb, lsb, $crate::Into::<$t>::into(value)); + } + }; + (@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $from:ty, $into:ty, _, $setter:ident: $msb:expr, + $lsb:expr) => { + $(#[$attribute])* + $($vis)* fn $setter(&mut self, value: $from) { + use $crate::BitRange; + self.set_bit_range($msb, $lsb, $crate::Into::<$t>::into(value)); + } + }; + (@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $from:ty, $into:ty, _, $setter:ident: $bit:expr) => { + $(#[$attribute])* + $($vis)* fn $setter(&mut self, value: bool) { + use $crate::Bit; + self.set_bit($bit, value); + } + }; + (@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $from:ty, $into:ty, $getter:ident, _: $msb:expr, + $lsb:expr, $count:expr) => { + $(#[$attribute])* + #[allow(unknown_lints)] + #[allow(eq_op)] + $($vis)* fn $getter(&self, index: usize) -> $into { + use $crate::BitRange; + __bitfield_debug_assert!(index < $count); + let width = $msb - $lsb + 1; + let lsb = $lsb + index*width; + let msb = lsb + width - 1; + let raw_value: $t = self.bit_range(msb, lsb); + $crate::Into::into(raw_value) + } + }; + (@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $from:ty, $into:ty, $getter:ident, _: $msb:expr, + $lsb:expr) => { + $(#[$attribute])* + $($vis)* fn $getter(&self) -> $into { + use $crate::BitRange; + let raw_value: $t = self.bit_range($msb, $lsb); + $crate::Into::into(raw_value) + } + }; + (@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $from:ty, $into:ty, $getter:ident, _: $bit:expr) => { + $(#[$attribute])* + $($vis)* fn $getter(&self) -> bool { + use $crate::Bit; + self.bit($bit) + } + }; + (@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $from:ty, $into:ty, $getter:ident, $setter:ident: + $($exprs:expr),*) => { + bitfield_fields!(@field $(#[$attribute])* ($($vis)*) $t, $from, $into, $getter, _: $($exprs),*); + bitfield_fields!(@field $(#[$attribute])* ($($vis)*) $t, $from, $into, _, $setter: $($exprs),*); + }; + + ($t:ty;) => {}; + ($default_ty:ty; pub $($rest:tt)*) => { + bitfield_fields!{$default_ty; () pub $($rest)*} + }; + ($default_ty:ty; #[$attribute:meta] $($rest:tt)*) => { + bitfield_fields!{$default_ty; (#[$attribute]) $($rest)*} + }; + ($default_ty:ty; ($(#[$attributes:meta])*) #[$attribute:meta] $($rest:tt)*) => { + bitfield_fields!{$default_ty; ($(#[$attributes])* #[$attribute]) $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, from into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* (pub) $t, $into, $into, $getter, $setter: $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* (pub) $t, $t, $into, $getter, $setter: $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, $getter:tt, $setter:tt: $($exprs:expr),*; + $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* (pub) $t, $t, $t, $getter, $setter: $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) pub from into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* (pub) $default_ty, $into, $into, $getter, $setter: + $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) pub into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* (pub) $default_ty, $default_ty, $into, $getter, $setter: + $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) pub $getter:tt, $setter:tt: $($exprs:expr),*; + $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* (pub) $default_ty, $default_ty, $default_ty, $getter, $setter: + $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + + ($default_ty:ty; ($(#[$attribute:meta])*) $t:ty, from into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* () $t, $into, $into, $getter, $setter: $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + + ($default_ty:ty; ($(#[$attribute:meta])*) $t:ty, into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* () $t, $t, $into, $getter, $setter: $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + + ($default_ty:ty; ($(#[$attribute:meta])*) $t:ty, $getter:tt, $setter:tt: $($exprs:expr),*; + $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* () $t, $t, $t, $getter, $setter: $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) from into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* () $default_ty, $into, $into, $getter, $setter: + $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) into $into:ty, $getter:tt, $setter:tt: + $($exprs:expr),*; $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* () $default_ty, $default_ty, $into, $getter, $setter: + $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; ($(#[$attribute:meta])*) $getter:tt, $setter:tt: $($exprs:expr),*; + $($rest:tt)*) => { + bitfield_fields!{@field $(#[$attribute])* () $default_ty, $default_ty, $default_ty, $getter, $setter: + $($exprs),*} + bitfield_fields!{$default_ty; $($rest)*} + }; + ($previous_default_ty:ty; $default_ty:ty; $($rest:tt)*) => { + bitfield_fields!{$default_ty; $($rest)*} + }; + ($default_ty:ty; $($rest:tt)*) => { + bitfield_fields!{$default_ty; () $($rest)*} + }; + ($($rest:tt)*) => { + bitfield_fields!{SET_A_DEFAULT_TYPE_OR_SPECIFY_THE_TYPE_FOR_EACH_FIELDS; $($rest)*} + } +} + +/// Generates a `fmt::Debug` implementation. +/// +/// This macros must be called from a `impl Debug for ...` block. It will generate the `fmt` method. +/// +/// In most of the case, you will not directly call this macros, but use `bitfield`. +/// +/// The syntax is `struct TheNameOfTheStruct` followed by the syntax of `bitfield_fields`. +/// +/// The write-only fields are ignored. +/// +/// # Example +/// +/// ```rust +/// # #[macro_use] extern crate bitfield; +/// struct FooBar(u32); +/// bitfield_bitrange!{struct FooBar(u32)} +/// impl FooBar{ +/// bitfield_fields!{ +/// u32; +/// field1, _: 7, 0; +/// field2, _: 31, 24; +/// } +/// } +/// +/// impl std::fmt::Debug for FooBar { +/// bitfield_debug!{ +/// struct FooBar; +/// field1, _: 7, 0; +/// field2, _: 31, 24; +/// } +/// } +/// +/// fn main() { +/// let foobar = FooBar(0x11223344); +/// println!("{:?}", foobar); + +/// } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! bitfield_debug { + (struct $name:ident; $($rest:tt)*) => { + fn fmt(&self, f: &mut $crate::fmt::Formatter) -> $crate::fmt::Result { + let mut debug_struct = f.debug_struct(__bitfield_stringify!($name)); + debug_struct.field(".0", &self.0); + bitfield_debug!{debug_struct, self, $($rest)*} + debug_struct.finish() + } + }; + ($debug_struct:ident, $self:ident, #[$attribute:meta] $($rest:tt)*) => { + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, pub $($rest:tt)*) => { + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, _, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, $type:ty; $($rest:tt)*) => { + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, $getter:ident, $setter:tt: $msb:expr, $lsb:expr, $count:expr; + $($rest:tt)*) => { + let mut array = [$self.$getter(0); $count]; + for (i, e) in (&mut array).into_iter().enumerate() { + *e = $self.$getter(i); + } + $debug_struct.field(__bitfield_stringify!($getter), &array); + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, $getter:ident, $setter:tt: $($exprs:expr),*; $($rest:tt)*) + => { + $debug_struct.field(__bitfield_stringify!($getter), &$self.$getter()); + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, from into $into:ty, $($rest:tt)*) => { + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, into $into:ty, $($rest:tt)*) => { + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, $type:ty, $($rest:tt)*) => { + bitfield_debug!{$debug_struct, $self, $($rest)*} + }; + ($debug_struct:ident, $self:ident, ) => {}; +} + +/// Implements `BitRange` for a tuple struct (or "newtype"). +/// +/// This macro will generate an implementation of the `BitRange` trait for an existing single +/// element tuple struct. +/// +/// The syntax is more or less the same as declaring a "newtype", **without** the attributes, +/// documentation comments and pub keyword. +/// +/// The difference with a normal "newtype" is the type in parentheses. If the type is `[t]` (where +/// `t` is any of the unsigned integer type), the "newtype" will be generic and implement +/// `BitRange` for `T: AsMut<[t]> + AsRef<[t]>` (for example a slice, an array or a `Vec`). You can +/// also use `MSB0 [t]`. The difference will be the positions of the bit. You can use the +/// `bits_positions` example to see where each bits is. If the type is neither of this two, the +/// "newtype" will wrap a value of the specified type and implements `BitRange` the same ways as +/// the wrapped type. +/// +/// # Examples +/// +/// ```rust +/// # #[macro_use] extern crate bitfield; +/// # fn main() {} +/// struct BitField1(u32); +/// bitfield_bitrange!{struct BitField1(u32)} +/// +/// struct BitField2(T); +/// bitfield_bitrange!{struct BitField2([u8])} +/// +/// struct BitField3(T); +/// bitfield_bitrange!{struct BitField3(MSB0 [u8])} +/// ``` +/// +#[macro_export(local_inner_macros)] +macro_rules! bitfield_bitrange { + (@impl_bitrange_slice $name:ident, $slice_ty:ty, $bitrange_ty:ty) => { + impl + AsRef<[$slice_ty]>> $crate::BitRange<$bitrange_ty> + for $name { + fn bit_range(&self, msb: usize, lsb: usize) -> $bitrange_ty { + let bit_len = $crate::size_of::<$slice_ty>()*8; + let value_bit_len = $crate::size_of::<$bitrange_ty>()*8; + let mut value = 0; + for i in (lsb..=msb).rev() { + value <<= 1; + value |= ((self.0.as_ref()[i/bit_len] >> (i%bit_len)) & 1) as $bitrange_ty; + } + value << (value_bit_len - (msb - lsb + 1)) >> (value_bit_len - (msb - lsb + 1)) + } + + fn set_bit_range(&mut self, msb: usize, lsb: usize, value: $bitrange_ty) { + let bit_len = $crate::size_of::<$slice_ty>()*8; + let mut value = value; + for i in lsb..=msb { + self.0.as_mut()[i/bit_len] &= !(1 << (i%bit_len)); + self.0.as_mut()[i/bit_len] |= (value & 1) as $slice_ty << (i%bit_len); + value >>= 1; + } + } + } + }; + (@impl_bitrange_slice_msb0 $name:ident, $slice_ty:ty, $bitrange_ty:ty) => { + impl + AsRef<[$slice_ty]>> $crate::BitRange<$bitrange_ty> + for $name { + fn bit_range(&self, msb: usize, lsb: usize) -> $bitrange_ty { + let bit_len = $crate::size_of::<$slice_ty>()*8; + let value_bit_len = $crate::size_of::<$bitrange_ty>()*8; + let mut value = 0; + for i in lsb..=msb { + value <<= 1; + value |= ((self.0.as_ref()[i/bit_len] >> (bit_len - i%bit_len - 1)) & 1) + as $bitrange_ty; + } + value << (value_bit_len - (msb - lsb + 1)) >> (value_bit_len - (msb - lsb + 1)) + } + + fn set_bit_range(&mut self, msb: usize, lsb: usize, value: $bitrange_ty) { + let bit_len = $crate::size_of::<$slice_ty>()*8; + let mut value = value; + for i in (lsb..=msb).rev() { + self.0.as_mut()[i/bit_len] &= !(1 << (bit_len - i%bit_len - 1)); + self.0.as_mut()[i/bit_len] |= (value & 1) as $slice_ty + << (bit_len - i%bit_len - 1); + value >>= 1; + } + } + } + }; + (struct $name:ident([$t:ty])) => { + bitfield_bitrange!(@impl_bitrange_slice $name, $t, u8); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, u16); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, u32); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, u64); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, u128); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, i8); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, i16); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, i32); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, i64); + bitfield_bitrange!(@impl_bitrange_slice $name, $t, i128); + }; + (struct $name:ident(MSB0 [$t:ty])) => { + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u8); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u16); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u32); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u64); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u128); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i8); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i16); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i32); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i64); + bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i128); + }; + (struct $name:ident($t:ty)) => { + impl $crate::BitRange for $name where $t: $crate::BitRange { + fn bit_range(&self, msb: usize, lsb: usize) -> T { + self.0.bit_range(msb, lsb) + } + fn set_bit_range(&mut self, msb: usize, lsb: usize, value: T) { + self.0.set_bit_range(msb, lsb, value); + } + } + }; +} + +/// Combines `bitfield_bitrange` and `bitfield_fields`. +/// +/// The syntax of this macro is the syntax of a tuple struct, including attributes and +/// documentation comments, followed by a semicolon, some optional elements, and finally the fields +/// as described in the `bitfield_fields` documentation. +/// +/// The first optional element is `no default BitRange;`. With that, no implementation of +/// `BitRange` will be generated. +/// +/// The second optional element is `impl Debug;`. This will generate an implementation of +/// `fmt::Debug` with the `bitfield_debug` macro. +/// +/// The difference with calling those macros separately is that `bitfield_fields` is called +/// from an appropriate `impl` block. If you use the non-slice form of `bitfield_bitrange`, the +/// default type for `bitfield_fields` will be set to the wrapped fields. +/// +/// See the documentation of these macros for more information on their respective syntax. +/// +/// # Example +/// +/// ```rust +/// # #[macro_use] extern crate bitfield; +/// # fn main() {} +/// bitfield!{ +/// pub struct BitField1(u16); +/// impl Debug; +/// // The fields default to u16 +/// field1, set_field1: 10, 0; +/// pub field2, _ : 12, 3; +/// } +/// ``` +/// +/// or with a custom `BitRange` implementation : +/// ```rust +/// # #[macro_use] extern crate bitfield; +/// # use bitfield::BitRange; +/// # fn main() {} +/// bitfield!{ +/// pub struct BitField1(u16); +/// no default BitRange; +/// impl Debug; +/// u8; +/// field1, set_field1: 10, 0; +/// pub field2, _ : 12, 3; +/// } +/// impl BitRange for BitField1 { +/// fn bit_range(&self, msb: usize, lsb: usize) -> u8 { +/// let width = msb - lsb + 1; +/// let mask = (1 << width) - 1; +/// ((self.0 >> lsb) & mask) as u8 +/// } +/// fn set_bit_range(&mut self, msb: usize, lsb: usize, value: u8) { +/// self.0 = (value as u16) << lsb; +/// } +/// } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! bitfield { + ($(#[$attribute:meta])* pub struct $($rest:tt)*) => { + bitfield!($(#[$attribute])* (pub) struct $($rest)*); + }; + ($(#[$attribute:meta])* struct $($rest:tt)*) => { + bitfield!($(#[$attribute])* () struct $($rest)*); + }; + // Force `impl Debug` to always be after `no default BitRange` it the two are present. + // This simplify the rest of the macro. + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident($($type:tt)*); impl Debug; no default BitRange; $($rest:tt)*) => { + bitfield!{$(#[$attribute])* ($($vis)*) struct $name($($type)*); no default BitRange; impl Debug; $($rest)*} + }; + + // If we have `impl Debug` without `no default BitRange`, we will still match, because when + // we call `bitfield_bitrange`, we add `no default BitRange`. + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident([$t:ty]); no default BitRange; impl Debug; $($rest:tt)*) => { + impl + AsRef<[$t]> + $crate::fmt::Debug> $crate::fmt::Debug for $name { + bitfield_debug!{struct $name; $($rest)*} + } + + bitfield!{$(#[$attribute])* ($($vis)*) struct $name([$t]); no default BitRange; $($rest)*} + }; + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident([$t:ty]); no default BitRange; $($rest:tt)*) => { + $(#[$attribute])* + $($vis)* struct $name(pub T); + + impl + AsRef<[$t]>> $name { + bitfield_fields!{$($rest)*} + } + }; + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident([$t:ty]); $($rest:tt)*) => { + bitfield_bitrange!(struct $name([$t])); + bitfield!{$(#[$attribute])* ($($vis)*) struct $name([$t]); no default BitRange; $($rest)*} + }; + + // The only difference between the MSB0 version anf the non-MSB0 version, is the BitRange + // implementation. We delegate everything else to the non-MSB0 version of the macro. + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident(MSB0 [$t:ty]); no default BitRange; $($rest:tt)*) => { + bitfield!{$(#[$attribute])* ($($vis)*) struct $name([$t]); no default BitRange; $($rest)*} + }; + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident(MSB0 [$t:ty]); $($rest:tt)*) => { + bitfield_bitrange!(struct $name(MSB0 [$t])); + bitfield!{$(#[$attribute])* ($($vis)*) struct $name([$t]); no default BitRange; $($rest)*} + }; + + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident($t:ty); no default BitRange; impl Debug; $($rest:tt)*) => { + impl $crate::fmt::Debug for $name { + bitfield_debug!{struct $name; $($rest)*} + } + + bitfield!{$(#[$attribute])* ($($vis)*) struct $name($t); no default BitRange; $($rest)*} + }; + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident($t:ty); no default BitRange; $($rest:tt)*) => { + $(#[$attribute])* + $($vis)* struct $name(pub $t); + + impl $name { + bitfield_fields!{$t; $($rest)*} + } + }; + ($(#[$attribute:meta])* ($($vis:tt)*) struct $name:ident($t:ty); $($rest:tt)*) => { + bitfield_bitrange!(struct $name($t)); + bitfield!{$(#[$attribute])* ($($vis)*) struct $name($t); no default BitRange; $($rest)*} + }; +} + +#[doc(hidden)] +pub use core::convert::Into; +#[doc(hidden)] +pub use core::fmt; +#[doc(hidden)] +pub use core::mem::size_of; + +/// A trait to get or set ranges of bits. +pub trait BitRange { + /// Get a range of bits. + fn bit_range(&self, msb: usize, lsb: usize) -> T; + /// Set a range of bits. + fn set_bit_range(&mut self, msb: usize, lsb: usize, value: T); +} + +/// A trait to get or set a single bit. +/// +/// This trait is implemented for all type that implement `BitRange`. +pub trait Bit { + /// Get a single bit. + fn bit(&self, bit: usize) -> bool; + + /// Set a single bit. + fn set_bit(&mut self, bit: usize, value: bool); +} + +impl> Bit for T { + fn bit(&self, bit: usize) -> bool { + self.bit_range(bit, bit) != 0 + } + fn set_bit(&mut self, bit: usize, value: bool) { + self.set_bit_range(bit, bit, value as u8); + } +} + +macro_rules! impl_bitrange_for_u { + ($t:ty, $bitrange_ty:ty) => { + impl BitRange<$bitrange_ty> for $t { + #[inline] + #[allow(unknown_lints)] + #[allow(cast_lossless)] + fn bit_range(&self, msb: usize, lsb: usize) -> $bitrange_ty { + let bit_len = size_of::<$t>()*8; + let result_bit_len = size_of::<$bitrange_ty>()*8; + let result = ((*self << (bit_len - msb - 1)) >> (bit_len - msb - 1 + lsb)) + as $bitrange_ty; + result << (result_bit_len - (msb - lsb + 1)) >> (result_bit_len - (msb - lsb + 1)) + } + + #[inline] + #[allow(unknown_lints)] + #[allow(cast_lossless)] + fn set_bit_range(&mut self, msb: usize, lsb: usize, value: $bitrange_ty) { + let bit_len = size_of::<$t>()*8; + let mask: $t = !(0 as $t) + << (bit_len - msb - 1) + >> (bit_len - msb - 1 + lsb) + << (lsb); + *self &= !mask; + *self |= (value as $t << lsb) & mask; + } + } + } +} + +macro_rules! impl_bitrange_for_u_combinations { +((),($($bitrange_ty:ty),*)) => { + +}; +(($t:ty),($($bitrange_ty:ty),*)) => { + $(impl_bitrange_for_u!{$t, $bitrange_ty})* +}; + (($t_head:ty, $($t_rest:ty),*),($($bitrange_ty:ty),*)) => { + impl_bitrange_for_u_combinations!{($t_head), ($($bitrange_ty),*)} + impl_bitrange_for_u_combinations!{($($t_rest),*), ($($bitrange_ty),*)} + }; +} + +impl_bitrange_for_u_combinations! {(u8, u16, u32, u64, u128), (u8, u16, u32, u64, u128)} +impl_bitrange_for_u_combinations! {(u8, u16, u32, u64, u128), (i8, i16, i32, i64, i128)} + +// Same as std::stringify but callable from local_inner_macros macros defined inside +// this crate. +#[macro_export] +#[doc(hidden)] +macro_rules! __bitfield_stringify { + ($s:ident) => { + stringify!($s) + }; +} + +// Same as std::debug_assert but callable from local_inner_macros macros defined inside +// this crate. +#[macro_export] +#[doc(hidden)] +macro_rules! __bitfield_debug_assert { + ($e:expr) => { + debug_assert!($e) + }; +} diff --git a/bitbox02-bt/vendor/bitfield/tests/lib.rs b/bitbox02-bt/vendor/bitfield/tests/lib.rs new file mode 100644 index 0000000..f762367 --- /dev/null +++ b/bitbox02-bt/vendor/bitfield/tests/lib.rs @@ -0,0 +1,1105 @@ +#![recursion_limit = "128"] + +#[macro_use] +extern crate bitfield; + +// We use a constant to make sure bits positions don't need to be literals but +// can also be constants or expressions. +const THREE: usize = 3; + +#[derive(Copy, Clone, Debug)] +pub struct Foo(u16); +impl From for Foo { + fn from(value: u8) -> Foo { + Foo(u16::from(value)) + } +} + +impl From for u8 { + fn from(value: Foo) -> u8 { + value.0 as u8 + } +} + +bitfield! { + #[derive(Copy, Clone)] + /// documentation comments also work! + struct FooBar(u32); + impl Debug; + foo1, set_foo1: 0, 0; + u8; + foo2, set_foo2: 31, 31; + foo3, set_foo3: THREE, 0; + // We make sure attributes are applied to fields. If attributes were not + // applied, the compilation would fail with a `duplicate definition` + // error. + #[cfg(not(test))] + foo3, set_foo3: 3, 0; + u16, foo4, set_foo4: 31, 28; + foo5, set_foo5: 0, 0, 32; + u32; + foo6, set_foo6: 5, THREE, THREE; + getter_only, _: 3, 1; + _, setter_only: 2*2, 2; + getter_only_array, _: 5, 3, 3; + _, setter_only_array: 2*THREE, 4, 3; + all_bits, set_all_bits: 31, 0; + single_bit, set_single_bit: 3; + u8, into Foo, into_foo1, set_into_foo1: 31, 31; + pub u8, into Foo, into_foo2, set_into_foo2: 31, 31; + u8, from into Foo, from_foo1, set_from_foo1: 31, 31; + u8, from into Foo, _, set_from_foo2: 31, 31; + u8; + into Foo, into_foo3, set_into_foo3: 31, 31; + pub into Foo, into_foo4, set_into_foo4: 31, 31; + into Foo, _, set_into_foo5: 31, 31; + into Foo, into_foo6, _: 29, 29, 3; + from into Foo, from_foo3, set_from_foo3: 31, 31; + from into Foo, _, set_from_foo4: 31, 31; + from into Foo, from_foo5, set_from_foo5: 29, 29, 3; + from into Foo, from_foo6, _: 31, 31; + i8; + signed_single_bit, set_signed_single_bit: 0, 0; + signed_two_bits, set_signed_two_bits: 1, 0; + signed_eight_bits, set_signed_eight_bits: 7, 0; + signed_eight_bits_unaligned, set_signed_eight_bits_unaligned: 8, 1; + u128, u128_getter, set_u128: 8, 1; + i128, i128_getter, set_i128: 8, 1; +} + +impl FooBar { + bitfield_fields! { + // Boolean field don't need a type + foo7, _: 1; + } + + bitfield_fields! { + // If all fields have a type, we don't need to specify a default type + u8, foo8,_: 1, 0; + u32, foo9, _: 2, 0; + } + + bitfield_fields! { + // We can still set a default type + u16; + foo10, _: 2, 0; + u32, foo11, _: 2, 0; + foo12, _: 2, 0; + } + + // Check if an empty bitfield_fields compiles without errors. + bitfield_fields! {} +} + +#[test] +fn test_single_bit() { + let mut fb = FooBar(0); + + fb.set_foo1(1); + assert_eq!(0x1, fb.0); + assert_eq!(0x1, fb.foo1()); + assert_eq!(0x0, fb.foo2()); + assert_eq!(false, fb.single_bit()); + assert_eq!(-1, fb.signed_single_bit()); + + fb.set_foo2(1); + assert_eq!(0x8000_0001, fb.0); + assert_eq!(0x1, fb.foo1()); + assert_eq!(0x1, fb.foo2()); + assert_eq!(false, fb.single_bit()); + assert_eq!(-1, fb.signed_single_bit()); + + fb.set_foo1(0); + assert_eq!(0x8000_0000, fb.0); + assert_eq!(0x0, fb.foo1()); + assert_eq!(0x1, fb.foo2()); + assert_eq!(false, fb.single_bit()); + assert_eq!(0, fb.signed_single_bit()); + + fb.set_single_bit(true); + assert_eq!(0x8000_0008, fb.0); + assert_eq!(0x0, fb.foo1()); + assert_eq!(0x1, fb.foo2()); + assert_eq!(true, fb.single_bit()); + assert_eq!(0, fb.signed_single_bit()); + + fb.set_signed_single_bit(-1); + assert_eq!(0x8000_0009, fb.0); + assert_eq!(0x1, fb.foo1()); + assert_eq!(0x1, fb.foo2()); + assert_eq!(true, fb.single_bit()); + assert_eq!(-1, fb.signed_single_bit()); +} + +#[test] +fn test_single_bit_plus_garbage() { + let mut fb = FooBar(0); + + fb.set_foo1(0b10); + assert_eq!(0x0, fb.0); + assert_eq!(0x0, fb.foo1()); + assert_eq!(0x0, fb.foo2()); + + fb.set_foo1(0b11); + assert_eq!(0x1, fb.0); + assert_eq!(0x1, fb.foo1()); + assert_eq!(0x0, fb.foo2()); +} + +#[test] +fn test_multiple_bit() { + let mut fb = FooBar(0); + + fb.set_foo3(0x0F); + assert_eq!(0xF, fb.0); + assert_eq!(0xF, fb.foo3()); + assert_eq!(0x0, fb.foo4()); + + fb.set_foo4(0x0F); + assert_eq!(0xF000_000F, fb.0); + assert_eq!(0xF, fb.foo3()); + assert_eq!(0xF, fb.foo4()); + + fb.set_foo3(0); + assert_eq!(0xF000_0000, fb.0); + assert_eq!(0x0, fb.foo3()); + assert_eq!(0xF, fb.foo4()); + + fb.set_foo3(0xA); + assert_eq!(0xF000_000A, fb.0); + assert_eq!(0xA, fb.foo3()); + assert_eq!(0xF, fb.foo4()); +} + +#[test] +fn test_getter_setter_only() { + let mut fb = FooBar(0); + fb.setter_only(0x7); + assert_eq!(0x1C, fb.0); + assert_eq!(0x6, fb.getter_only()); +} + +#[test] +fn test_array_field1() { + let mut fb = FooBar(0); + + fb.set_foo5(0, 1); + assert_eq!(0x1, fb.0); + assert_eq!(1, fb.foo5(0)); + + fb.set_foo5(0, 0); + assert_eq!(0x0, fb.0); + assert_eq!(0, fb.foo5(0)); + + fb.set_foo5(0, 1); + fb.set_foo5(6, 1); + fb.set_foo5(31, 1); + assert_eq!(0x8000_0041, fb.0); + assert_eq!(1, fb.foo5(0)); + assert_eq!(1, fb.foo5(6)); + assert_eq!(1, fb.foo5(31)); + assert_eq!(0, fb.foo5(1)); + assert_eq!(0, fb.foo5(5)); + assert_eq!(0, fb.foo5(7)); + assert_eq!(0, fb.foo5(30)); +} + +#[test] +fn test_array_field2() { + let mut fb = FooBar(0); + + fb.set_foo6(0, 1); + assert_eq!(0x8, fb.0); + assert_eq!(1, fb.foo6(0)); + assert_eq!(0, fb.foo6(1)); + assert_eq!(0, fb.foo6(2)); + + fb.set_foo6(0, 7); + assert_eq!(0x38, fb.0); + assert_eq!(7, fb.foo6(0)); + assert_eq!(0, fb.foo6(1)); + assert_eq!(0, fb.foo6(2)); + + fb.set_foo6(2, 7); + assert_eq!(0xE38, fb.0); + assert_eq!(7, fb.foo6(0)); + assert_eq!(0, fb.foo6(1)); + assert_eq!(7, fb.foo6(2)); + + fb.set_foo6(0, 0); + assert_eq!(0xE00, fb.0); + assert_eq!(0, fb.foo6(0)); + assert_eq!(0, fb.foo6(1)); + assert_eq!(7, fb.foo6(2)); +} + +#[allow(unknown_lints)] +#[allow(identity_op)] +#[allow(erasing_op)] +#[test] +fn test_setter_only_array() { + let mut fb = FooBar(0); + + fb.setter_only_array(0, 0); + assert_eq!(0x0, fb.0); + + fb.setter_only_array(0, 0b111); + assert_eq!(0b111 << (4 + 0 * 2), fb.0); + + fb.setter_only_array(0, 0); + fb.setter_only_array(1, 0b111); + assert_eq!(0b111 << (4 + 1 * 3), fb.0); + + fb.setter_only_array(1, 0); + fb.setter_only_array(2, 0b111); + assert_eq!(0b111 << (4 + 2 * 3), fb.0); +} + +#[test] +fn test_getter_only_array() { + let mut fb = FooBar(0); + + assert_eq!(0, fb.getter_only_array(0)); + assert_eq!(0, fb.getter_only_array(1)); + assert_eq!(0, fb.getter_only_array(2)); + + fb.0 = !(0x1FF << 3); + assert_eq!(0, fb.getter_only_array(0)); + assert_eq!(0, fb.getter_only_array(1)); + assert_eq!(0, fb.getter_only_array(2)); + + fb.0 = 0xF << 3; + assert_eq!(0b111, fb.getter_only_array(0)); + assert_eq!(0b001, fb.getter_only_array(1)); + assert_eq!(0, fb.getter_only_array(2)); + + fb.0 = 0xF << 6; + assert_eq!(0, fb.getter_only_array(0)); + assert_eq!(0b111, fb.getter_only_array(1)); + assert_eq!(0b001, fb.getter_only_array(2)); + + fb.0 = 0xF << 8; + assert_eq!(0, fb.getter_only_array(0)); + assert_eq!(0b100, fb.getter_only_array(1)); + assert_eq!(0b111, fb.getter_only_array(2)); + + fb.0 = 0b101_010_110 << 3; + assert_eq!(0b110, fb.getter_only_array(0)); + assert_eq!(0b010, fb.getter_only_array(1)); + assert_eq!(0b101, fb.getter_only_array(2)); +} + +#[test] +fn test_signed() { + let mut fb = FooBar(0); + + assert_eq!(0, fb.signed_two_bits()); + assert_eq!(0, fb.signed_eight_bits()); + assert_eq!(0, fb.signed_eight_bits_unaligned()); + + fb.set_signed_two_bits(-2); + assert_eq!(0b10, fb.0); + assert_eq!(-2, fb.signed_two_bits()); + assert_eq!(2, fb.signed_eight_bits()); + assert_eq!(1, fb.signed_eight_bits_unaligned()); + + fb.set_signed_two_bits(-1); + assert_eq!(0b11, fb.0); + assert_eq!(-1, fb.signed_two_bits()); + assert_eq!(3, fb.signed_eight_bits()); + assert_eq!(1, fb.signed_eight_bits_unaligned()); + + fb.set_signed_two_bits(0); + assert_eq!(0, fb.0); + assert_eq!(0, fb.signed_two_bits()); + assert_eq!(0, fb.signed_eight_bits()); + assert_eq!(0, fb.signed_eight_bits_unaligned()); + + fb.set_signed_two_bits(1); + assert_eq!(1, fb.0); + assert_eq!(1, fb.signed_two_bits()); + assert_eq!(1, fb.signed_eight_bits()); + assert_eq!(0, fb.signed_eight_bits_unaligned()); + + fb.set_signed_eight_bits(0); + assert_eq!(0, fb.0); + assert_eq!(0, fb.signed_two_bits()); + assert_eq!(0, fb.signed_eight_bits()); + assert_eq!(0, fb.signed_eight_bits_unaligned()); + + fb.set_signed_eight_bits(-1); + assert_eq!(0xFF, fb.0); + assert_eq!(-1, fb.signed_two_bits()); + assert_eq!(-1, fb.signed_eight_bits()); + assert_eq!(127, fb.signed_eight_bits_unaligned()); + + fb.set_signed_eight_bits(-128); + assert_eq!(0x80, fb.0); + assert_eq!(0, fb.signed_two_bits()); + assert_eq!(-128, fb.signed_eight_bits()); + assert_eq!(64, fb.signed_eight_bits_unaligned()); + + fb.set_signed_eight_bits(127); + assert_eq!(0x7F, fb.0); + assert_eq!(-1, fb.signed_two_bits()); + assert_eq!(127, fb.signed_eight_bits()); + assert_eq!(63, fb.signed_eight_bits_unaligned()); + + fb.set_signed_eight_bits_unaligned(0); + assert_eq!(1, fb.0); + assert_eq!(1, fb.signed_two_bits()); + assert_eq!(1, fb.signed_eight_bits()); + assert_eq!(0, fb.signed_eight_bits_unaligned()); + + fb.set_signed_eight_bits(0); + fb.set_signed_eight_bits_unaligned(-1); + assert_eq!(0x1FE, fb.0); + assert_eq!(-2, fb.signed_two_bits()); + assert_eq!(-2, fb.signed_eight_bits()); + assert_eq!(-1, fb.signed_eight_bits_unaligned()); + + fb.set_signed_eight_bits_unaligned(-128); + assert_eq!(0x100, fb.0); + assert_eq!(0, fb.signed_two_bits()); + assert_eq!(0, fb.signed_eight_bits()); + assert_eq!(-128, fb.signed_eight_bits_unaligned()); + fb.set_signed_eight_bits_unaligned(127); + assert_eq!(0xFE, fb.0); + assert_eq!(-2, fb.signed_two_bits()); + assert_eq!(-2, fb.signed_eight_bits()); + assert_eq!(127, fb.signed_eight_bits_unaligned()); +} + +#[test] +fn test_field_type() { + let fb = FooBar(0); + let _: u32 = fb.foo1(); + let _: u8 = fb.foo2(); + let _: u8 = fb.foo3(); + let _: u16 = fb.foo4(); + let _: u8 = fb.foo5(0); + let _: u32 = fb.foo6(0); + + let _: bool = fb.foo7(); + let _: u8 = fb.foo8(); + let _: u32 = fb.foo9(); + let _: u16 = fb.foo10(); + let _: u32 = fb.foo11(); + let _: u16 = fb.foo12(); + + let _: Foo = fb.into_foo1(); + let _: Foo = fb.into_foo2(); + let _: Foo = fb.into_foo3(); + let _: Foo = fb.into_foo4(); + let _: Foo = fb.into_foo6(0); + + let _: Foo = fb.from_foo1(); + let _: Foo = fb.from_foo3(); + let _: Foo = fb.from_foo5(0); + + let _: i8 = fb.signed_single_bit(); + let _: i8 = fb.signed_two_bits(); + let _: i8 = fb.signed_eight_bits(); + let _: i8 = fb.signed_eight_bits_unaligned(); + + let _: u128 = fb.u128_getter(); + let _: i128 = fb.i128_getter(); +} + +#[test] +fn test_into_setter() { + let mut fb = FooBar(0); + + // We just check that the parameter type is correct + fb.set_into_foo1(0u8); + fb.set_into_foo2(0u8); + fb.set_into_foo3(0u8); + fb.set_into_foo4(0u8); +} + +#[test] +fn test_from_setter() { + let mut fb = FooBar(0); + assert_eq!(0, fb.0); + + fb.set_from_foo1(Foo(1)); + assert_eq!(1 << 31, fb.0); + fb.set_from_foo1(Foo(0)); + assert_eq!(0, fb.0); + + fb.set_from_foo2(Foo(1)); + assert_eq!(1 << 31, fb.0); + fb.set_from_foo2(Foo(0)); + assert_eq!(0, fb.0); + + fb.set_from_foo3(Foo(1)); + assert_eq!(1 << 31, fb.0); + fb.set_from_foo3(Foo(0)); + assert_eq!(0, fb.0); + + fb.set_from_foo4(Foo(1)); + assert_eq!(1 << 31, fb.0); + fb.set_from_foo4(Foo(0)); + assert_eq!(0, fb.0); + + fb.set_from_foo5(1, Foo(1)); + assert_eq!(1 << 30, fb.0); +} + +#[test] +fn test_all_bits() { + let mut fb = FooBar(0); + + assert_eq!(0, fb.all_bits()); + + fb.set_all_bits(!0u32); + assert_eq!(!0u32, fb.0); + assert_eq!(!0u32, fb.all_bits()); + + fb.0 = 0x8000_0001; + assert_eq!(0x8000_0001, fb.all_bits()); +} + +#[test] +fn test_is_copy() { + let a = FooBar(0); + let _b = a; + let _c = a; +} + +#[test] +fn test_debug() { + let fb = FooBar(1_234_567_890); + let expected = "FooBar { .0: 1234567890, foo1: 0, foo2: 0, foo3: 2, foo3: 2, foo4: 4, foo5: [0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0], foo6: [2, 3, 1], getter_only: 1, getter_only_array: [2, 3, 1], all_bits: 1234567890, single_bit: false, into_foo1: Foo(0), into_foo2: Foo(0), from_foo1: Foo(0), into_foo3: Foo(0), into_foo4: Foo(0), into_foo6: [Foo(0), Foo(1), Foo(0)], from_foo3: Foo(0), from_foo5: [Foo(0), Foo(1), Foo(0)], from_foo6: Foo(0), signed_single_bit: 0, signed_two_bits: -2, signed_eight_bits: -46, signed_eight_bits_unaligned: 105, u128_getter: 105, i128_getter: 105 }"; + assert_eq!(expected, format!("{:?}", fb)) +} + +bitfield! { + struct ArrayBitfield([u8]); + u32; + foo1, set_foo1: 0, 0; + foo2, set_foo2: 7, 0; + foo3, set_foo3: 8, 1; + foo4, set_foo4: 19, 4; + i32; + signed_foo1, set_signed_foo1: 0, 0; + signed_foo2, set_signed_foo2: 7, 0; + signed_foo3, set_signed_foo3: 8, 1; + signed_foo4, set_signed_foo4: 19, 4; + u128, u128_getter, set_u128: 19, 4; +} + +#[test] +fn test_arraybitfield() { + let mut ab = ArrayBitfield([0; 3]); + + assert_eq!(0u32, ab.foo1()); + assert_eq!(0u32, ab.foo2()); + assert_eq!(0u32, ab.foo3()); + assert_eq!(0u32, ab.foo4()); + assert_eq!(0i32, ab.signed_foo1()); + assert_eq!(0i32, ab.signed_foo2()); + assert_eq!(0i32, ab.signed_foo3()); + assert_eq!(0i32, ab.signed_foo4()); + assert_eq!(0u128, ab.u128_getter()); + + ab.set_foo1(1); + assert_eq!([1, 0, 0], ab.0); + assert_eq!(1, ab.foo1()); + assert_eq!(1, ab.foo2()); + assert_eq!(0, ab.foo3()); + assert_eq!(0, ab.foo4()); + assert_eq!(-1, ab.signed_foo1()); + assert_eq!(1, ab.signed_foo2()); + assert_eq!(0, ab.signed_foo3()); + assert_eq!(0, ab.signed_foo4()); + assert_eq!(0, ab.u128_getter()); + + ab.set_foo1(0); + ab.set_foo2(0xFF); + assert_eq!([0xFF, 0, 0], ab.0); + assert_eq!(1, ab.foo1()); + assert_eq!(0xFF, ab.foo2()); + assert_eq!(0x7F, ab.foo3()); + assert_eq!(0x0F, ab.foo4()); + assert_eq!(-1, ab.signed_foo1()); + assert_eq!(-1, ab.signed_foo2()); + assert_eq!(127, ab.signed_foo3()); + assert_eq!(0x0F, ab.signed_foo4()); + assert_eq!(0x0F, ab.u128_getter()); + + ab.set_foo2(0); + ab.set_foo3(0xFF); + assert_eq!([0xFE, 0x01, 0], ab.0); + assert_eq!(0, ab.foo1()); + assert_eq!(0xFE, ab.foo2()); + assert_eq!(0xFF, ab.foo3()); + assert_eq!(0x1F, ab.foo4()); + assert_eq!(0, ab.signed_foo1()); + assert_eq!(-2, ab.signed_foo2()); + assert_eq!(-1, ab.signed_foo3()); + assert_eq!(0x1F, ab.signed_foo4()); + assert_eq!(0x1F, ab.u128_getter()); + + ab.set_foo3(0); + ab.set_foo4(0xFFFF); + assert_eq!([0xF0, 0xFF, 0x0F], ab.0); + assert_eq!(0, ab.foo1()); + assert_eq!(0xF0, ab.foo2()); + assert_eq!(0xF8, ab.foo3()); + assert_eq!(0xFFFF, ab.foo4()); + assert_eq!(0, ab.signed_foo1()); + assert_eq!(-16, ab.signed_foo2()); + assert_eq!(-8, ab.signed_foo3()); + assert_eq!(-1, ab.signed_foo4()); + assert_eq!(0xFFFF, ab.u128_getter()); + + ab.set_foo4(0x0); + ab.set_signed_foo1(0); + assert_eq!([0x00, 0x00, 0x00], ab.0); + + ab.set_signed_foo1(-1); + assert_eq!([0x01, 0x00, 0x00], ab.0); + + ab.set_signed_foo1(0); + ab.set_signed_foo2(127); + assert_eq!([0x7F, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(-128); + assert_eq!([0x80, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(1); + assert_eq!([0x01, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(-1); + assert_eq!([0xFF, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(0); + ab.set_signed_foo3(127); + assert_eq!([0xFE, 0x00, 0x00], ab.0); + + ab.set_signed_foo3(-1); + assert_eq!([0xFE, 0x01, 0x00], ab.0); + + ab.set_signed_foo3(0); + ab.set_signed_foo4(-1); + assert_eq!([0xF0, 0xFF, 0x0F], ab.0); + + ab.set_signed_foo4(0); + ab.set_u128(0xFFFF); + assert_eq!([0xF0, 0xFF, 0x0F], ab.0); +} + +#[test] +fn test_arraybitfield2() { + // Check that the macro can be called from a function. + bitfield! { + struct ArrayBitfield2([u16]); + impl Debug; + u32; + foo1, set_foo1: 0, 0; + foo2, set_foo2: 7, 0; + foo3, set_foo3: 8, 1; + foo4, set_foo4: 20, 4; + } + let mut ab = ArrayBitfield2([0; 2]); + + assert_eq!(0, ab.foo1()); + assert_eq!(0, ab.foo2()); + assert_eq!(0, ab.foo3()); + assert_eq!(0, ab.foo4()); + + ab.set_foo1(1); + assert_eq!([1, 0], ab.0); + assert_eq!(1, ab.foo1()); + assert_eq!(1, ab.foo2()); + assert_eq!(0, ab.foo3()); + assert_eq!(0, ab.foo4()); + + ab.set_foo1(0); + ab.set_foo2(0xFF); + assert_eq!([0xFF, 0], ab.0); + assert_eq!(1, ab.foo1()); + assert_eq!(0xFF, ab.foo2()); + assert_eq!(0x7F, ab.foo3()); + assert_eq!(0x0F, ab.foo4()); + + ab.set_foo2(0); + ab.set_foo3(0xFF); + assert_eq!([0x1FE, 0x0], ab.0); + assert_eq!(0, ab.foo1()); + assert_eq!(0xFE, ab.foo2()); + assert_eq!(0xFF, ab.foo3()); + assert_eq!(0x1F, ab.foo4()); + + ab.set_foo3(0); + ab.set_foo4(0xFFFF); + assert_eq!([0xFFF0, 0xF], ab.0); + assert_eq!(0, ab.foo1()); + assert_eq!(0xF0, ab.foo2()); + assert_eq!(0xF8, ab.foo3()); + assert_eq!(0xFFFF, ab.foo4()); +} + +bitfield! { + struct ArrayBitfieldMsb0(MSB0 [u8]); + impl Debug; + u32; + foo1, set_foo1: 0, 0; + foo2, set_foo2: 7, 0; + foo3, set_foo3: 8, 1; + foo4, set_foo4: 19, 4; + i32; + signed_foo1, set_signed_foo1: 0, 0; + signed_foo2, set_signed_foo2: 7, 0; + signed_foo3, set_signed_foo3: 8, 1; + signed_foo4, set_signed_foo4: 19, 4; +} + +#[test] +fn test_arraybitfield_msb0() { + let mut ab = ArrayBitfieldMsb0([0; 3]); + + assert_eq!(0, ab.foo1()); + assert_eq!(0, ab.foo2()); + assert_eq!(0, ab.foo3()); + assert_eq!(0, ab.foo4()); + assert_eq!(0, ab.signed_foo1()); + assert_eq!(0, ab.signed_foo2()); + assert_eq!(0, ab.signed_foo3()); + assert_eq!(0, ab.signed_foo4()); + + ab.set_foo1(1); + assert_eq!([0b1000_0000, 0, 0], ab.0); + assert_eq!(1, ab.foo1()); + assert_eq!(0b1000_0000, ab.foo2()); + assert_eq!(0, ab.foo3()); + assert_eq!(0, ab.foo4()); + assert_eq!(-1, ab.signed_foo1()); + assert_eq!(-128, ab.signed_foo2()); + assert_eq!(0, ab.signed_foo3()); + assert_eq!(0, ab.signed_foo4()); + + ab.set_foo1(0); + ab.set_foo2(0xFF); + assert_eq!([0b1111_1111, 0, 0], ab.0); + assert_eq!(1, ab.foo1()); + assert_eq!(0b1111_1111, ab.foo2()); + assert_eq!(0b1111_1110, ab.foo3()); + assert_eq!(0b1111_0000_0000_0000, ab.foo4()); + assert_eq!(-1, ab.signed_foo1()); + assert_eq!(-1, ab.signed_foo2()); + assert_eq!(-2, ab.signed_foo3()); + assert_eq!(-4096, ab.signed_foo4()); + + ab.set_foo2(0); + ab.set_foo3(0xFF); + assert_eq!([0b0111_1111, 0b1000_0000, 0], ab.0); + assert_eq!(0, ab.foo1()); + assert_eq!(0b0111_1111, ab.foo2()); + assert_eq!(0xFF, ab.foo3()); + assert_eq!(0b1111_1000_0000_0000, ab.foo4()); + assert_eq!(0, ab.signed_foo1()); + assert_eq!(127, ab.signed_foo2()); + assert_eq!(-1, ab.signed_foo3()); + assert_eq!(-2048, ab.signed_foo4()); + + ab.set_foo3(0); + ab.set_foo4(0xFFFF); + assert_eq!([0x0F, 0xFF, 0xF0], ab.0); + assert_eq!(0, ab.foo1()); + assert_eq!(0x0F, ab.foo2()); + assert_eq!(0b0001_1111, ab.foo3()); + assert_eq!(0xFFFF, ab.foo4()); + assert_eq!(0, ab.signed_foo1()); + assert_eq!(0x0F, ab.signed_foo2()); + assert_eq!(0b0001_1111, ab.signed_foo3()); + assert_eq!(-1, ab.signed_foo4()); + + ab.set_foo4(0x0); + ab.set_signed_foo1(0); + assert_eq!([0x00, 0x00, 0x00], ab.0); + + ab.set_signed_foo1(-1); + assert_eq!([0b1000_0000, 0x00, 0x00], ab.0); + + ab.set_signed_foo1(0); + ab.set_signed_foo2(127); + assert_eq!([0x7F, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(-128); + assert_eq!([0x80, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(1); + assert_eq!([0x01, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(-1); + assert_eq!([0xFF, 0x00, 0x00], ab.0); + + ab.set_signed_foo2(0); + ab.set_signed_foo3(127); + assert_eq!([0b0011_1111, 0b1000_0000, 0], ab.0); + + ab.set_signed_foo3(-1); + assert_eq!([0b0111_1111, 0b1000_0000, 0], ab.0); + + ab.set_signed_foo3(0); + ab.set_signed_foo4(-1); + assert_eq!([0x0F, 0xFF, 0xF0], ab.0); +} + +mod some_module { + bitfield! { + pub struct PubBitFieldInAModule(u32); + impl Debug; + /// Attribute works on pub fields + pub field1, set_field1: 1; + pub field2, _: 1; + pub _, set_field3: 1; + pub u16, field4, set_field4: 1; + /// Check if multiple attributes are applied + #[cfg(not(test))] + pub u16, field4, set_field4: 1; + pub u16, _, set_field5: 1; + pub u16, field6, _: 1; + pub field7, set_field7: 1; + pub field8, set_field8: 1, 1; + #[cfg(not(test))] + /// And make sure not only the last attributes is applied + pub field8, set_field8: 1, 1; + pub field9, set_field9: 1, 1, 1; + pub u32, field10, set_field10: 1; + pub u32, field11, set_field11: 1, 1; + pub u32, field12, set_field12: 1, 1, 1; + } + +} + +#[test] +fn struct_can_be_public() { + let _ = some_module::PubBitFieldInAModule(0); +} +#[test] +fn field_can_be_public() { + let mut a = some_module::PubBitFieldInAModule(0); + let _ = a.field1(); + a.set_field1(true); + let _ = a.field2(); + a.set_field3(true); + let _ = a.field4(); + a.set_field4(true); + a.set_field5(true); + let _ = a.field6(); + let _ = a.field7(); + a.set_field7(true); + let _ = a.field8(); + a.set_field8(0); + let _ = a.field9(0); + a.set_field9(0, 0); + let _ = a.field10(); + a.set_field10(true); + let _ = a.field11(); + a.set_field11(0); + let _ = a.field12(0); + a.set_field12(0, 0); +} + +// Everything in this module is to make sure that its possible to specify types +// in most of the possible ways. +#[allow(dead_code)] +mod test_types { + use bitfield::BitRange; + use std; + use std::sync::atomic::{self, AtomicUsize}; + + struct Foo; + + impl Foo { + bitfield_fields! { + std::sync::atomic::AtomicUsize, field1, set_field1: 0, 0; + std::sync::atomic::AtomicUsize; + field2, set_field2: 0, 0; + ::std::sync::atomic::AtomicUsize, field3, set_field3: 0, 0; + ::std::sync::atomic::AtomicUsize; + field4, set_field4: 0, 0; + atomic::AtomicUsize, field5, set_field5: 0, 0; + atomic::AtomicUsize; + field6, set_field6: 0, 0; + AtomicUsize, field7, set_field7: 0, 0; + AtomicUsize; + field8, set_field8: 0, 0; + Vec, field9, set_field9: 0, 0; + Vec; + field10, set_field10: 0, 0; + Vec<::std::sync::atomic::AtomicUsize>, field11, set_field11: 0, 0; + Vec<::std::sync::atomic::AtomicUsize>; + field12, set_field12: 0, 0; + Vec, field13, set_field13: 0, 0; + Vec; + field14, set_field14: 0, 0; + Vec, field15, set_field15: 0, 0; + Vec; + field16, set_field16: 0, 0; + &str, field17, set_field17: 0, 0; + &str; + field18, set_field18: 0, 0; + &'static str, field19, set_field19: 0, 0; + &'static str; + field20, set_field20: 0, 0; + } + } + + impl BitRange for Foo { + fn bit_range(&self, _msb: usize, _lsb: usize) -> AtomicUsize { + AtomicUsize::new(0) + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: AtomicUsize) {} + } + + impl BitRange> for Foo { + fn bit_range(&self, _msb: usize, _lsb: usize) -> Vec { + vec![AtomicUsize::new(0)] + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: Vec) {} + } + + impl<'a> BitRange<&'a str> for Foo { + fn bit_range(&self, _msb: usize, _lsb: usize) -> &'a str { + "" + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: &'a str) {} + } + + #[test] + fn test_field_type() { + let test = Foo; + let _: AtomicUsize = test.field1(); + let _: AtomicUsize = test.field2(); + let _: AtomicUsize = test.field3(); + let _: AtomicUsize = test.field4(); + let _: AtomicUsize = test.field5(); + let _: AtomicUsize = test.field6(); + let _: AtomicUsize = test.field7(); + let _: AtomicUsize = test.field8(); + let _: Vec = test.field9(); + let _: Vec = test.field10(); + let _: Vec = test.field11(); + let _: Vec = test.field12(); + let _: Vec = test.field13(); + let _: Vec = test.field14(); + let _: Vec = test.field15(); + let _: Vec = test.field16(); + let _: &str = test.field17(); + let _: &str = test.field18(); + let _: &'static str = test.field19(); + let _: &'static str = test.field20(); + } +} + +#[allow(dead_code)] +mod test_no_default_bitrange { + use bitfield::BitRange; + use std::fmt::Debug; + use std::fmt::Error; + use std::fmt::Formatter; + bitfield! { + #[derive(Eq, PartialEq)] + pub struct BitField1(u16); + no default BitRange; + impl Debug; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 2; + } + + impl BitRange for BitField1 { + fn bit_range(&self, msb: usize, lsb: usize) -> u8 { + (msb + lsb) as u8 + } + fn set_bit_range(&mut self, msb: usize, lsb: usize, value: u8) { + self.0 = msb as u16 + lsb as u16 + u16::from(value) + } + } + + #[allow(unknown_lints)] + #[allow(identity_op)] + #[test] + fn custom_bitrange_implementation_is_used() { + let mut bf = BitField1(0); + assert_eq!(bf.field1(), 10 + 0); + assert_eq!(bf.field2(), 12 + 3); + assert_eq!(bf.field3(), true); + bf.set_field1(42); + assert_eq!(bf, BitField1(10 + 0 + 42)); + } + + bitfield! { + pub struct BitField2(u16); + no default BitRange; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 0; + } + + impl BitRange for BitField2 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + // Make sure Debug wasn't implemented by implementing it. + impl Debug for BitField2 { + fn fmt(&self, _: &mut Formatter) -> Result<(), Error> { + unimplemented!() + } + } + + // Check that we can put `impl Debug` before `no default BitRange` + bitfield! { + pub struct BitField3(u16); + impl Debug; + no default BitRange; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 0; + } + + impl BitRange for BitField3 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + bitfield! { + #[derive(Eq, PartialEq)] + pub struct BitField4([u16]); + no default BitRange; + impl Debug; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 2; + } + + impl BitRange for BitField4 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + bitfield! { + pub struct BitField5([u16]); + no default BitRange; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 0; + } + + impl BitRange for BitField5 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + // Make sure Debug wasn't implemented by implementing it. + impl Debug for BitField5 { + fn fmt(&self, _: &mut Formatter) -> Result<(), Error> { + unimplemented!() + } + } + + // Check that we can put `impl Debug` before `no default BitRange` + bitfield! { + pub struct BitField6([u16]); + impl Debug; + no default BitRange; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 0; + } + + impl BitRange for BitField6 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + bitfield! { + #[derive(Eq, PartialEq)] + pub struct BitField7(MSB0 [u16]); + no default BitRange; + impl Debug; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 2; + } + + impl BitRange for BitField7 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + bitfield! { + pub struct BitField8(MSB0 [u16]); + no default BitRange; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 0; + } + + impl BitRange for BitField8 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + // Make sure Debug wasn't implemented by implementing it. + impl Debug for BitField8 { + fn fmt(&self, _: &mut Formatter) -> Result<(), Error> { + unimplemented!() + } + } + + // Check that we can put `impl Debug` before `no default BitRange` + bitfield! { + pub struct BitField9([u16]); + impl Debug; + no default BitRange; + u8; + field1, set_field1: 10, 0; + pub field2, _ : 12, 3; + field3, set_field3: 0; + } + + impl BitRange for BitField9 { + fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { + 0 + } + fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} + } + + #[test] + fn test_debug_is_implemented_with_no_default_bitrange() { + format!("{:?}", BitField1(0)); + format!("{:?}", BitField3(0)); + format!("{:?}", BitField4([0; 1])); + format!("{:?}", BitField6([0; 1])); + format!("{:?}", BitField7([0; 1])); + format!("{:?}", BitField9([0; 1])); + } +} diff --git a/bitbox02-bt/vendor/byteorder/.cargo-checksum.json b/bitbox02-bt/vendor/byteorder/.cargo-checksum.json new file mode 100644 index 0000000..bffae5d --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"c1cb69be6db5933c4bb4ebb6591e0fe3e7b97d491face3abcf947383c218bb31","COPYING":"01c266bced4a434da0051174d6bee16a4c82cf634e2679b6155d40d75012390f","Cargo.toml":"94ba374cb26f3c68fb83da2e5e7dce85920fc4fb827620b06b39d71a9d0e1e18","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","README.md":"2f2d64924c35b7203e3e3f3d136fcb714281762d145ca3513246da5547b1d014","UNLICENSE":"7e12e5df4bae12cb21581ba157ced20e1986a0508dd10d0e8a4ab9a4cf94e85c","benches/bench.rs":"8b114080042d3292ec8de425904e4114b7f532fe3add0d807521e6cc166a17ea","rustfmt.toml":"1ca600239a27401c4a43f363cf3f38183a212affc1f31bff3ae93234bbaec228","src/io.rs":"9612530634d0e7ce9887a23836b58c0d972c1f45b05d9ada8355961567075627","src/lib.rs":"ab3394c385b32457795931440cfb8dbca70ba5d9e1a428fcf651f7ccb2d6c34f"},"package":"1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/byteorder/CHANGELOG.md b/bitbox02-bt/vendor/byteorder/CHANGELOG.md new file mode 100644 index 0000000..9efb7ed --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/CHANGELOG.md @@ -0,0 +1,143 @@ +**WARNING:** This CHANGELOG is no longer updated. The activity for this project +is sparse enough that you should refer to the commit log instead. + + +1.3.4 +===== +This patch release squashes deprecation warnings for the `try!` macro, in +accordance with byteorder's minimum supported Rust version (currently at Rust +1.12.0). + + +1.3.3 +===== +This patch release adds `ByteOrder::write_i8_into()` as a simple, safe interface +for ordinarily unsafe or tedious code. + + +1.3.2 +===== +This patch release adds `ReadBytesExt::read_i8_into()` as a simple, safe interface +for ordinarily unsafe or tedious code. + + +1.3.1 +===== +This minor release performs mostly small internal changes. Going forward, these +are not going to be incorporated into the changelog. + + +1.3.0 +===== +This new minor release now enables `i128` support automatically on Rust +compilers that support 128-bit integers. The `i128` feature is now a no-op, but +continues to exist for backward compatibility purposes. The crate continues to +maintain compatibility with Rust 1.12.0. + +This release also deprecates the `ByteOrder` trait methods +`read_f32_into_unchecked` and `read_f64_into_unchecked` in favor of +`read_f32_into` and `read_f64_into`. This was an oversight from the 1.2 release +where the corresponding methods on `ReadBytesExt` were deprecated. + +`quickcheck` and `rand` were bumped to `0.8` and `0.6`, respectively. + +A few small documentation related bugs have been fixed. + + +1.2.7 +===== +This patch release excludes some CI files from the crate release and updates +the license field to use `OR` instead of `/`. + + +1.2.6 +===== +This patch release fixes some test compilation errors introduced by an +over-eager release of 1.2.5. + + +1.2.5 +===== +This patch release fixes some typos in the docs, adds doc tests to methods on +`WriteByteExt` and bumps the quickcheck dependency to `0.7`. + + +1.2.4 +===== +This patch release adds support for 48-bit integers by adding the following +methods to the `ByteOrder` trait: `read_u48`, `read_i48`, `write_u48` and +`write_i48`. Corresponding methods have been added to the `ReadBytesExt` and +`WriteBytesExt` traits as well. + + +1.2.3 +===== +This patch release removes the use of `feature(i128_type)` from byteorder, +since it has been stabilized. We leave byteorder's `i128` feature in place +in order to continue supporting compilation on older versions of Rust. + + +1.2.2 +===== +This patch release only consists of internal improvements and refactorings. +Notably, this removes all uses of `transmute` and instead uses pointer casts. + + +1.2.1 +===== +This patch release removes more unnecessary uses of `unsafe` that +were overlooked in the prior `1.2.0` release. In particular, the +`ReadBytesExt::read_{f32,f64}_into_checked` methods have been deprecated and +replaced by more appropriately named `read_{f32,f64}_into` methods. + + +1.2.0 +===== +The most prominent change in this release of `byteorder` is the removal of +unnecessary signaling NaN masking, and in turn, the `unsafe` annotations +associated with methods that didn't do masking. See +[#103](https://github.com/BurntSushi/byteorder/issues/103) +for more details. + +* [BUG #102](https://github.com/BurntSushi/byteorder/issues/102): + Fix big endian tests. +* [BUG #103](https://github.com/BurntSushi/byteorder/issues/103): + Remove sNaN masking. + + +1.1.0 +===== +This release of `byteorder` features a number of fixes and improvements, mostly +as a result of the +[Litz Blitz evaluation](https://public.etherpad-mozilla.org/p/rust-crate-eval-byteorder). + +Feature enhancements: + +* [FEATURE #63](https://github.com/BurntSushi/byteorder/issues/63): + Add methods for reading/writing slices of numbers for a specific + endianness. +* [FEATURE #65](https://github.com/BurntSushi/byteorder/issues/65): + Add support for `u128`/`i128` types. (Behind the nightly only `i128` + feature.) +* [FEATURE #72](https://github.com/BurntSushi/byteorder/issues/72): + Add "panics" and "errors" sections for each relevant public API item. +* [FEATURE #74](https://github.com/BurntSushi/byteorder/issues/74): + Add CI badges to Cargo.toml. +* [FEATURE #75](https://github.com/BurntSushi/byteorder/issues/75): + Add more examples to public API items. +* Add 24-bit read/write methods. +* Add `BE` and `LE` type aliases for `BigEndian` and `LittleEndian`, + respectively. + +Bug fixes: + +* [BUG #68](https://github.com/BurntSushi/byteorder/issues/68): + Panic in {BigEndian,LittleEndian}::default. +* [BUG #69](https://github.com/BurntSushi/byteorder/issues/69): + Seal the `ByteOrder` trait to prevent out-of-crate implementations. +* [BUG #71](https://github.com/BurntSushi/byteorder/issues/71): + Guarantee that the results of `read_f32`/`read_f64` are always defined. +* [BUG #73](https://github.com/BurntSushi/byteorder/issues/73): + Add crates.io categories. +* [BUG #77](https://github.com/BurntSushi/byteorder/issues/77): + Add `html_root` doc attribute. diff --git a/bitbox02-bt/vendor/byteorder/COPYING b/bitbox02-bt/vendor/byteorder/COPYING new file mode 100644 index 0000000..bb9c20a --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/COPYING @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff --git a/bitbox02-bt/vendor/byteorder/Cargo.toml b/bitbox02-bt/vendor/byteorder/Cargo.toml new file mode 100644 index 0000000..da515d9 --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/Cargo.toml @@ -0,0 +1,54 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.60" +name = "byteorder" +version = "1.5.0" +authors = ["Andrew Gallant "] +description = "Library for reading/writing numbers in big-endian and little-endian." +homepage = "https://github.com/BurntSushi/byteorder" +documentation = "https://docs.rs/byteorder" +readme = "README.md" +keywords = [ + "byte", + "endian", + "big-endian", + "little-endian", + "binary", +] +categories = [ + "encoding", + "parsing", + "no-std", +] +license = "Unlicense OR MIT" +repository = "https://github.com/BurntSushi/byteorder" + +[profile.bench] +opt-level = 3 + +[lib] +name = "byteorder" +bench = false + +[dev-dependencies.quickcheck] +version = "0.9.2" +default-features = false + +[dev-dependencies.rand] +version = "0.7" + +[features] +default = ["std"] +i128 = [] +std = [] diff --git a/bitbox02-bt/vendor/byteorder/LICENSE-MIT b/bitbox02-bt/vendor/byteorder/LICENSE-MIT new file mode 100644 index 0000000..3b0a5dc --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bitbox02-bt/vendor/byteorder/README.md b/bitbox02-bt/vendor/byteorder/README.md new file mode 100644 index 0000000..7c46019 --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/README.md @@ -0,0 +1,77 @@ +byteorder +========= +This crate provides convenience methods for encoding and decoding +numbers in either big-endian or little-endian order. + +[![Build status](https://github.com/BurntSushi/byteorder/workflows/ci/badge.svg)](https://github.com/BurntSushi/byteorder/actions) +[![crates.io](https://img.shields.io/crates/v/byteorder.svg)](https://crates.io/crates/byteorder) + +Dual-licensed under MIT or the [UNLICENSE](https://unlicense.org/). + + +### Documentation + +https://docs.rs/byteorder + + +### Installation + +This crate works with Cargo and is on +[crates.io](https://crates.io/crates/byteorder). Add it to your `Cargo.toml` +like so: + +```toml +[dependencies] +byteorder = "1" +``` + +If you want to augment existing `Read` and `Write` traits, then import the +extension methods like so: + +```rust +use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian}; +``` + +For example: + +```rust +use std::io::Cursor; +use byteorder::{BigEndian, ReadBytesExt}; + +let mut rdr = Cursor::new(vec![2, 5, 3, 0]); +// Note that we use type parameters to indicate which kind of byte order +// we want! +assert_eq!(517, rdr.read_u16::().unwrap()); +assert_eq!(768, rdr.read_u16::().unwrap()); +``` + +### `no_std` crates + +This crate has a feature, `std`, that is enabled by default. To use this crate +in a `no_std` context, add the following to your `Cargo.toml`: + +```toml +[dependencies] +byteorder = { version = "1", default-features = false } +``` + + +### Minimum Rust version policy + +This crate's minimum supported `rustc` version is `1.60.0`. + +The current policy is that the minimum Rust version required to use this crate +can be increased in minor version updates. For example, if `crate 1.0` requires +Rust 1.20.0, then `crate 1.0.z` for all values of `z` will also require Rust +1.20.0 or newer. However, `crate 1.y` for `y > 0` may require a newer minimum +version of Rust. + +In general, this crate will be conservative with respect to the minimum +supported version of Rust. + + +### Alternatives + +Note that as of Rust 1.32, the standard numeric types provide built-in methods +like `to_le_bytes` and `from_le_bytes`, which support some of the same use +cases. diff --git a/bitbox02-bt/vendor/byteorder/UNLICENSE b/bitbox02-bt/vendor/byteorder/UNLICENSE new file mode 100644 index 0000000..68a49da --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/bitbox02-bt/vendor/byteorder/benches/bench.rs b/bitbox02-bt/vendor/byteorder/benches/bench.rs new file mode 100644 index 0000000..963251c --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/benches/bench.rs @@ -0,0 +1,326 @@ +#![feature(test)] + +extern crate test; + +macro_rules! bench_num { + ($name:ident, $read:ident, $bytes:expr, $data:expr) => { + mod $name { + use byteorder::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + use test::black_box as bb; + use test::Bencher; + + const NITER: usize = 100_000; + + #[bench] + fn read_big_endian(b: &mut Bencher) { + let buf = $data; + b.iter(|| { + for _ in 0..NITER { + bb(BigEndian::$read(&buf, $bytes)); + } + }); + } + + #[bench] + fn read_little_endian(b: &mut Bencher) { + let buf = $data; + b.iter(|| { + for _ in 0..NITER { + bb(LittleEndian::$read(&buf, $bytes)); + } + }); + } + + #[bench] + fn read_native_endian(b: &mut Bencher) { + let buf = $data; + b.iter(|| { + for _ in 0..NITER { + bb(NativeEndian::$read(&buf, $bytes)); + } + }); + } + } + }; + ($ty:ident, $max:ident, + $read:ident, $write:ident, $size:expr, $data:expr) => { + mod $ty { + use byteorder::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + use std::$ty; + use test::black_box as bb; + use test::Bencher; + + const NITER: usize = 100_000; + + #[bench] + fn read_big_endian(b: &mut Bencher) { + let buf = $data; + b.iter(|| { + for _ in 0..NITER { + bb(BigEndian::$read(&buf)); + } + }); + } + + #[bench] + fn read_little_endian(b: &mut Bencher) { + let buf = $data; + b.iter(|| { + for _ in 0..NITER { + bb(LittleEndian::$read(&buf)); + } + }); + } + + #[bench] + fn read_native_endian(b: &mut Bencher) { + let buf = $data; + b.iter(|| { + for _ in 0..NITER { + bb(NativeEndian::$read(&buf)); + } + }); + } + + #[bench] + fn write_big_endian(b: &mut Bencher) { + let mut buf = $data; + let n = $ty::$max; + b.iter(|| { + for _ in 0..NITER { + bb(BigEndian::$write(&mut buf, n)); + } + }); + } + + #[bench] + fn write_little_endian(b: &mut Bencher) { + let mut buf = $data; + let n = $ty::$max; + b.iter(|| { + for _ in 0..NITER { + bb(LittleEndian::$write(&mut buf, n)); + } + }); + } + + #[bench] + fn write_native_endian(b: &mut Bencher) { + let mut buf = $data; + let n = $ty::$max; + b.iter(|| { + for _ in 0..NITER { + bb(NativeEndian::$write(&mut buf, n)); + } + }); + } + } + }; +} + +bench_num!(u16, MAX, read_u16, write_u16, 2, [1, 2]); +bench_num!(i16, MAX, read_i16, write_i16, 2, [1, 2]); +bench_num!(u32, MAX, read_u32, write_u32, 4, [1, 2, 3, 4]); +bench_num!(i32, MAX, read_i32, write_i32, 4, [1, 2, 3, 4]); +bench_num!(u64, MAX, read_u64, write_u64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); +bench_num!(i64, MAX, read_i64, write_i64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); +bench_num!(f32, MAX, read_f32, write_f32, 4, [1, 2, 3, 4]); +bench_num!(f64, MAX, read_f64, write_f64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); + +bench_num!(uint_1, read_uint, 1, [1]); +bench_num!(uint_2, read_uint, 2, [1, 2]); +bench_num!(uint_3, read_uint, 3, [1, 2, 3]); +bench_num!(uint_4, read_uint, 4, [1, 2, 3, 4]); +bench_num!(uint_5, read_uint, 5, [1, 2, 3, 4, 5]); +bench_num!(uint_6, read_uint, 6, [1, 2, 3, 4, 5, 6]); +bench_num!(uint_7, read_uint, 7, [1, 2, 3, 4, 5, 6, 7]); +bench_num!(uint_8, read_uint, 8, [1, 2, 3, 4, 5, 6, 7, 8]); + +bench_num!(int_1, read_int, 1, [1]); +bench_num!(int_2, read_int, 2, [1, 2]); +bench_num!(int_3, read_int, 3, [1, 2, 3]); +bench_num!(int_4, read_int, 4, [1, 2, 3, 4]); +bench_num!(int_5, read_int, 5, [1, 2, 3, 4, 5]); +bench_num!(int_6, read_int, 6, [1, 2, 3, 4, 5, 6]); +bench_num!(int_7, read_int, 7, [1, 2, 3, 4, 5, 6, 7]); +bench_num!(int_8, read_int, 8, [1, 2, 3, 4, 5, 6, 7, 8]); + +bench_num!( + u128, + MAX, + read_u128, + write_u128, + 16, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] +); +bench_num!( + i128, + MAX, + read_i128, + write_i128, + 16, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] +); + +bench_num!(uint128_1, read_uint128, 1, [1]); +bench_num!(uint128_2, read_uint128, 2, [1, 2]); +bench_num!(uint128_3, read_uint128, 3, [1, 2, 3]); +bench_num!(uint128_4, read_uint128, 4, [1, 2, 3, 4]); +bench_num!(uint128_5, read_uint128, 5, [1, 2, 3, 4, 5]); +bench_num!(uint128_6, read_uint128, 6, [1, 2, 3, 4, 5, 6]); +bench_num!(uint128_7, read_uint128, 7, [1, 2, 3, 4, 5, 6, 7]); +bench_num!(uint128_8, read_uint128, 8, [1, 2, 3, 4, 5, 6, 7, 8]); +bench_num!(uint128_9, read_uint128, 9, [1, 2, 3, 4, 5, 6, 7, 8, 9]); +bench_num!(uint128_10, read_uint128, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +bench_num!(uint128_11, read_uint128, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); +bench_num!( + uint128_12, + read_uint128, + 12, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] +); +bench_num!( + uint128_13, + read_uint128, + 13, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] +); +bench_num!( + uint128_14, + read_uint128, + 14, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] +); +bench_num!( + uint128_15, + read_uint128, + 15, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] +); +bench_num!( + uint128_16, + read_uint128, + 16, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] +); + +bench_num!(int128_1, read_int128, 1, [1]); +bench_num!(int128_2, read_int128, 2, [1, 2]); +bench_num!(int128_3, read_int128, 3, [1, 2, 3]); +bench_num!(int128_4, read_int128, 4, [1, 2, 3, 4]); +bench_num!(int128_5, read_int128, 5, [1, 2, 3, 4, 5]); +bench_num!(int128_6, read_int128, 6, [1, 2, 3, 4, 5, 6]); +bench_num!(int128_7, read_int128, 7, [1, 2, 3, 4, 5, 6, 7]); +bench_num!(int128_8, read_int128, 8, [1, 2, 3, 4, 5, 6, 7, 8]); +bench_num!(int128_9, read_int128, 9, [1, 2, 3, 4, 5, 6, 7, 8, 9]); +bench_num!(int128_10, read_int128, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +bench_num!(int128_11, read_int128, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); +bench_num!( + int128_12, + read_int128, + 12, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] +); +bench_num!( + int128_13, + read_int128, + 13, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] +); +bench_num!( + int128_14, + read_int128, + 14, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] +); +bench_num!( + int128_15, + read_int128, + 15, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] +); +bench_num!( + int128_16, + read_int128, + 16, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] +); + +macro_rules! bench_slice { + ($name:ident, $numty:ty, $read:ident, $write:ident) => { + mod $name { + use std::mem::size_of; + + use byteorder::{BigEndian, ByteOrder, LittleEndian}; + use rand::distributions; + use rand::{self, Rng}; + use test::Bencher; + + #[bench] + fn read_big_endian(b: &mut Bencher) { + let mut numbers: Vec<$numty> = rand::thread_rng() + .sample_iter(&distributions::Standard) + .take(100000) + .collect(); + let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; + BigEndian::$write(&numbers, &mut bytes); + + b.bytes = bytes.len() as u64; + b.iter(|| { + BigEndian::$read(&bytes, &mut numbers); + }); + } + + #[bench] + fn read_little_endian(b: &mut Bencher) { + let mut numbers: Vec<$numty> = rand::thread_rng() + .sample_iter(&distributions::Standard) + .take(100000) + .collect(); + let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; + LittleEndian::$write(&numbers, &mut bytes); + + b.bytes = bytes.len() as u64; + b.iter(|| { + LittleEndian::$read(&bytes, &mut numbers); + }); + } + + #[bench] + fn write_big_endian(b: &mut Bencher) { + let numbers: Vec<$numty> = rand::thread_rng() + .sample_iter(&distributions::Standard) + .take(100000) + .collect(); + let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; + + b.bytes = bytes.len() as u64; + b.iter(|| { + BigEndian::$write(&numbers, &mut bytes); + }); + } + + #[bench] + fn write_little_endian(b: &mut Bencher) { + let numbers: Vec<$numty> = rand::thread_rng() + .sample_iter(&distributions::Standard) + .take(100000) + .collect(); + let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; + + b.bytes = bytes.len() as u64; + b.iter(|| { + LittleEndian::$write(&numbers, &mut bytes); + }); + } + } + }; +} + +bench_slice!(slice_u16, u16, read_u16_into, write_u16_into); +bench_slice!(slice_u64, u64, read_u64_into, write_u64_into); +bench_slice!(slice_i64, i64, read_i64_into, write_i64_into); diff --git a/bitbox02-bt/vendor/byteorder/rustfmt.toml b/bitbox02-bt/vendor/byteorder/rustfmt.toml new file mode 100644 index 0000000..aa37a21 --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 79 +use_small_heuristics = "max" diff --git a/bitbox02-bt/vendor/byteorder/src/io.rs b/bitbox02-bt/vendor/byteorder/src/io.rs new file mode 100644 index 0000000..dfad2ca --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/src/io.rs @@ -0,0 +1,1592 @@ +use std::{ + io::{self, Result}, + slice, +}; + +use crate::ByteOrder; + +/// Extends [`Read`] with methods for reading numbers. (For `std::io`.) +/// +/// Most of the methods defined here have an unconstrained type parameter that +/// must be explicitly instantiated. Typically, it is instantiated with either +/// the [`BigEndian`] or [`LittleEndian`] types defined in this crate. +/// +/// # Examples +/// +/// Read unsigned 16 bit big-endian integers from a [`Read`]: +/// +/// ```rust +/// use std::io::Cursor; +/// use byteorder::{BigEndian, ReadBytesExt}; +/// +/// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); +/// assert_eq!(517, rdr.read_u16::().unwrap()); +/// assert_eq!(768, rdr.read_u16::().unwrap()); +/// ``` +/// +/// [`BigEndian`]: enum.BigEndian.html +/// [`LittleEndian`]: enum.LittleEndian.html +/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html +pub trait ReadBytesExt: io::Read { + /// Reads an unsigned 8 bit integer from the underlying reader. + /// + /// Note that since this reads a single byte, no byte order conversions + /// are used. It is included for completeness. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read unsigned 8 bit integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::ReadBytesExt; + /// + /// let mut rdr = Cursor::new(vec![2, 5]); + /// assert_eq!(2, rdr.read_u8().unwrap()); + /// assert_eq!(5, rdr.read_u8().unwrap()); + /// ``` + #[inline] + fn read_u8(&mut self) -> Result { + let mut buf = [0; 1]; + self.read_exact(&mut buf)?; + Ok(buf[0]) + } + + /// Reads a signed 8 bit integer from the underlying reader. + /// + /// Note that since this reads a single byte, no byte order conversions + /// are used. It is included for completeness. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read signed 8 bit integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::ReadBytesExt; + /// + /// let mut rdr = Cursor::new(vec![0x02, 0xfb]); + /// assert_eq!(2, rdr.read_i8().unwrap()); + /// assert_eq!(-5, rdr.read_i8().unwrap()); + /// ``` + #[inline] + fn read_i8(&mut self) -> Result { + let mut buf = [0; 1]; + self.read_exact(&mut buf)?; + Ok(buf[0] as i8) + } + + /// Reads an unsigned 16 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read unsigned 16 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); + /// assert_eq!(517, rdr.read_u16::().unwrap()); + /// assert_eq!(768, rdr.read_u16::().unwrap()); + /// ``` + #[inline] + fn read_u16(&mut self) -> Result { + let mut buf = [0; 2]; + self.read_exact(&mut buf)?; + Ok(T::read_u16(&buf)) + } + + /// Reads a signed 16 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read signed 16 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]); + /// assert_eq!(193, rdr.read_i16::().unwrap()); + /// assert_eq!(-132, rdr.read_i16::().unwrap()); + /// ``` + #[inline] + fn read_i16(&mut self) -> Result { + let mut buf = [0; 2]; + self.read_exact(&mut buf)?; + Ok(T::read_i16(&buf)) + } + + /// Reads an unsigned 24 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read unsigned 24 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x00, 0x01, 0x0b]); + /// assert_eq!(267, rdr.read_u24::().unwrap()); + /// ``` + #[inline] + fn read_u24(&mut self) -> Result { + let mut buf = [0; 3]; + self.read_exact(&mut buf)?; + Ok(T::read_u24(&buf)) + } + + /// Reads a signed 24 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read signed 24 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0xff, 0x7a, 0x33]); + /// assert_eq!(-34253, rdr.read_i24::().unwrap()); + /// ``` + #[inline] + fn read_i24(&mut self) -> Result { + let mut buf = [0; 3]; + self.read_exact(&mut buf)?; + Ok(T::read_i24(&buf)) + } + + /// Reads an unsigned 32 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read unsigned 32 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]); + /// assert_eq!(267, rdr.read_u32::().unwrap()); + /// ``` + #[inline] + fn read_u32(&mut self) -> Result { + let mut buf = [0; 4]; + self.read_exact(&mut buf)?; + Ok(T::read_u32(&buf)) + } + + /// Reads a signed 32 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read signed 32 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]); + /// assert_eq!(-34253, rdr.read_i32::().unwrap()); + /// ``` + #[inline] + fn read_i32(&mut self) -> Result { + let mut buf = [0; 4]; + self.read_exact(&mut buf)?; + Ok(T::read_i32(&buf)) + } + + /// Reads an unsigned 48 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read unsigned 48 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0xb6, 0x71, 0x6b, 0xdc, 0x2b, 0x31]); + /// assert_eq!(200598257150769, rdr.read_u48::().unwrap()); + /// ``` + #[inline] + fn read_u48(&mut self) -> Result { + let mut buf = [0; 6]; + self.read_exact(&mut buf)?; + Ok(T::read_u48(&buf)) + } + + /// Reads a signed 48 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read signed 48 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x9d, 0x71, 0xab, 0xe7, 0x97, 0x8f]); + /// assert_eq!(-108363435763825, rdr.read_i48::().unwrap()); + /// ``` + #[inline] + fn read_i48(&mut self) -> Result { + let mut buf = [0; 6]; + self.read_exact(&mut buf)?; + Ok(T::read_i48(&buf)) + } + + /// Reads an unsigned 64 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read an unsigned 64 bit big-endian integer from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83]); + /// assert_eq!(918733457491587, rdr.read_u64::().unwrap()); + /// ``` + #[inline] + fn read_u64(&mut self) -> Result { + let mut buf = [0; 8]; + self.read_exact(&mut buf)?; + Ok(T::read_u64(&buf)) + } + + /// Reads a signed 64 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a signed 64 bit big-endian integer from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]); + /// assert_eq!(i64::min_value(), rdr.read_i64::().unwrap()); + /// ``` + #[inline] + fn read_i64(&mut self) -> Result { + let mut buf = [0; 8]; + self.read_exact(&mut buf)?; + Ok(T::read_i64(&buf)) + } + + /// Reads an unsigned 128 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read an unsigned 128 bit big-endian integer from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 + /// ]); + /// assert_eq!(16947640962301618749969007319746179, rdr.read_u128::().unwrap()); + /// ``` + #[inline] + fn read_u128(&mut self) -> Result { + let mut buf = [0; 16]; + self.read_exact(&mut buf)?; + Ok(T::read_u128(&buf)) + } + + /// Reads a signed 128 bit integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a signed 128 bit big-endian integer from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + /// assert_eq!(i128::min_value(), rdr.read_i128::().unwrap()); + /// ``` + #[inline] + fn read_i128(&mut self) -> Result { + let mut buf = [0; 16]; + self.read_exact(&mut buf)?; + Ok(T::read_i128(&buf)) + } + + /// Reads an unsigned n-bytes integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read an unsigned n-byte big-endian integer from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0x80, 0x74, 0xfa]); + /// assert_eq!(8418554, rdr.read_uint::(3).unwrap()); + #[inline] + fn read_uint(&mut self, nbytes: usize) -> Result { + let mut buf = [0; 8]; + self.read_exact(&mut buf[..nbytes])?; + Ok(T::read_uint(&buf[..nbytes], nbytes)) + } + + /// Reads a signed n-bytes integer from the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read an unsigned n-byte big-endian integer from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0xc1, 0xff, 0x7c]); + /// assert_eq!(-4063364, rdr.read_int::(3).unwrap()); + #[inline] + fn read_int(&mut self, nbytes: usize) -> Result { + let mut buf = [0; 8]; + self.read_exact(&mut buf[..nbytes])?; + Ok(T::read_int(&buf[..nbytes], nbytes)) + } + + /// Reads an unsigned n-bytes integer from the underlying reader. + #[inline] + fn read_uint128(&mut self, nbytes: usize) -> Result { + let mut buf = [0; 16]; + self.read_exact(&mut buf[..nbytes])?; + Ok(T::read_uint128(&buf[..nbytes], nbytes)) + } + + /// Reads a signed n-bytes integer from the underlying reader. + #[inline] + fn read_int128(&mut self, nbytes: usize) -> Result { + let mut buf = [0; 16]; + self.read_exact(&mut buf[..nbytes])?; + Ok(T::read_int128(&buf[..nbytes], nbytes)) + } + + /// Reads a IEEE754 single-precision (4 bytes) floating point number from + /// the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a big-endian single-precision floating point number from a `Read`: + /// + /// ```rust + /// use std::f32; + /// use std::io::Cursor; + /// + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0x40, 0x49, 0x0f, 0xdb, + /// ]); + /// assert_eq!(f32::consts::PI, rdr.read_f32::().unwrap()); + /// ``` + #[inline] + fn read_f32(&mut self) -> Result { + let mut buf = [0; 4]; + self.read_exact(&mut buf)?; + Ok(T::read_f32(&buf)) + } + + /// Reads a IEEE754 double-precision (8 bytes) floating point number from + /// the underlying reader. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a big-endian double-precision floating point number from a `Read`: + /// + /// ```rust + /// use std::f64; + /// use std::io::Cursor; + /// + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, + /// ]); + /// assert_eq!(f64::consts::PI, rdr.read_f64::().unwrap()); + /// ``` + #[inline] + fn read_f64(&mut self) -> Result { + let mut buf = [0; 8]; + self.read_exact(&mut buf)?; + Ok(T::read_f64(&buf)) + } + + /// Reads a sequence of unsigned 16 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of unsigned 16 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); + /// let mut dst = [0; 2]; + /// rdr.read_u16_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_u16_into(&mut self, dst: &mut [u16]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_u16(dst); + Ok(()) + } + + /// Reads a sequence of unsigned 32 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of unsigned 32 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0, 0, 2, 5, 0, 0, 3, 0]); + /// let mut dst = [0; 2]; + /// rdr.read_u32_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_u32_into(&mut self, dst: &mut [u32]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_u32(dst); + Ok(()) + } + + /// Reads a sequence of unsigned 64 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of unsigned 64 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0, 0, 0, 0, 0, 0, 2, 5, + /// 0, 0, 0, 0, 0, 0, 3, 0, + /// ]); + /// let mut dst = [0; 2]; + /// rdr.read_u64_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_u64_into(&mut self, dst: &mut [u64]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_u64(dst); + Ok(()) + } + + /// Reads a sequence of unsigned 128 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of unsigned 128 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, + /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, + /// ]); + /// let mut dst = [0; 2]; + /// rdr.read_u128_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_u128_into( + &mut self, + dst: &mut [u128], + ) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_u128(dst); + Ok(()) + } + + /// Reads a sequence of signed 8 bit integers from the underlying reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// Note that since each `i8` is a single byte, no byte order conversions + /// are used. This method is included because it provides a safe, simple + /// way for the caller to read into a `&mut [i8]` buffer. (Without this + /// method, the caller would have to either use `unsafe` code or convert + /// each byte to `i8` individually.) + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of signed 8 bit integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![2, 251, 3]); + /// let mut dst = [0; 3]; + /// rdr.read_i8_into(&mut dst).unwrap(); + /// assert_eq!([2, -5, 3], dst); + /// ``` + #[inline] + fn read_i8_into(&mut self, dst: &mut [i8]) -> Result<()> { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf) + } + + /// Reads a sequence of signed 16 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of signed 16 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); + /// let mut dst = [0; 2]; + /// rdr.read_i16_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_i16_into(&mut self, dst: &mut [i16]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_i16(dst); + Ok(()) + } + + /// Reads a sequence of signed 32 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of signed 32 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![0, 0, 2, 5, 0, 0, 3, 0]); + /// let mut dst = [0; 2]; + /// rdr.read_i32_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_i32_into(&mut self, dst: &mut [i32]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_i32(dst); + Ok(()) + } + + /// Reads a sequence of signed 64 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of signed 64 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0, 0, 0, 0, 0, 0, 2, 5, + /// 0, 0, 0, 0, 0, 0, 3, 0, + /// ]); + /// let mut dst = [0; 2]; + /// rdr.read_i64_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_i64_into(&mut self, dst: &mut [i64]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_i64(dst); + Ok(()) + } + + /// Reads a sequence of signed 128 bit integers from the underlying + /// reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of signed 128 bit big-endian integers from a `Read`: + /// + /// ```rust + /// use std::io::Cursor; + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, + /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, + /// ]); + /// let mut dst = [0; 2]; + /// rdr.read_i128_into::(&mut dst).unwrap(); + /// assert_eq!([517, 768], dst); + /// ``` + #[inline] + fn read_i128_into( + &mut self, + dst: &mut [i128], + ) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_i128(dst); + Ok(()) + } + + /// Reads a sequence of IEEE754 single-precision (4 bytes) floating + /// point numbers from the underlying reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of big-endian single-precision floating point number + /// from a `Read`: + /// + /// ```rust + /// use std::f32; + /// use std::io::Cursor; + /// + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0x40, 0x49, 0x0f, 0xdb, + /// 0x3f, 0x80, 0x00, 0x00, + /// ]); + /// let mut dst = [0.0; 2]; + /// rdr.read_f32_into::(&mut dst).unwrap(); + /// assert_eq!([f32::consts::PI, 1.0], dst); + /// ``` + #[inline] + fn read_f32_into(&mut self, dst: &mut [f32]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_f32(dst); + Ok(()) + } + + /// **DEPRECATED**. + /// + /// This method is deprecated. Use `read_f32_into` instead. + /// + /// Reads a sequence of IEEE754 single-precision (4 bytes) floating + /// point numbers from the underlying reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of big-endian single-precision floating point number + /// from a `Read`: + /// + /// ```rust + /// use std::f32; + /// use std::io::Cursor; + /// + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0x40, 0x49, 0x0f, 0xdb, + /// 0x3f, 0x80, 0x00, 0x00, + /// ]); + /// let mut dst = [0.0; 2]; + /// rdr.read_f32_into_unchecked::(&mut dst).unwrap(); + /// assert_eq!([f32::consts::PI, 1.0], dst); + /// ``` + #[inline] + #[deprecated(since = "1.2.0", note = "please use `read_f32_into` instead")] + fn read_f32_into_unchecked( + &mut self, + dst: &mut [f32], + ) -> Result<()> { + self.read_f32_into::(dst) + } + + /// Reads a sequence of IEEE754 double-precision (8 bytes) floating + /// point numbers from the underlying reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of big-endian single-precision floating point number + /// from a `Read`: + /// + /// ```rust + /// use std::f64; + /// use std::io::Cursor; + /// + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, + /// 0x3f, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + /// ]); + /// let mut dst = [0.0; 2]; + /// rdr.read_f64_into::(&mut dst).unwrap(); + /// assert_eq!([f64::consts::PI, 1.0], dst); + /// ``` + #[inline] + fn read_f64_into(&mut self, dst: &mut [f64]) -> Result<()> { + { + let buf = unsafe { slice_to_u8_mut(dst) }; + self.read_exact(buf)?; + } + T::from_slice_f64(dst); + Ok(()) + } + + /// **DEPRECATED**. + /// + /// This method is deprecated. Use `read_f64_into` instead. + /// + /// Reads a sequence of IEEE754 double-precision (8 bytes) floating + /// point numbers from the underlying reader. + /// + /// The given buffer is either filled completely or an error is returned. + /// If an error is returned, the contents of `dst` are unspecified. + /// + /// # Safety + /// + /// This method is unsafe because there are no guarantees made about the + /// floating point values. In particular, this method does not check for + /// signaling NaNs, which may result in undefined behavior. + /// + /// # Errors + /// + /// This method returns the same errors as [`Read::read_exact`]. + /// + /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact + /// + /// # Examples + /// + /// Read a sequence of big-endian single-precision floating point number + /// from a `Read`: + /// + /// ```rust + /// use std::f64; + /// use std::io::Cursor; + /// + /// use byteorder::{BigEndian, ReadBytesExt}; + /// + /// let mut rdr = Cursor::new(vec![ + /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, + /// 0x3f, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + /// ]); + /// let mut dst = [0.0; 2]; + /// rdr.read_f64_into_unchecked::(&mut dst).unwrap(); + /// assert_eq!([f64::consts::PI, 1.0], dst); + /// ``` + #[inline] + #[deprecated(since = "1.2.0", note = "please use `read_f64_into` instead")] + fn read_f64_into_unchecked( + &mut self, + dst: &mut [f64], + ) -> Result<()> { + self.read_f64_into::(dst) + } +} + +/// All types that implement `Read` get methods defined in `ReadBytesExt` +/// for free. +impl ReadBytesExt for R {} + +/// Extends [`Write`] with methods for writing numbers. (For `std::io`.) +/// +/// Most of the methods defined here have an unconstrained type parameter that +/// must be explicitly instantiated. Typically, it is instantiated with either +/// the [`BigEndian`] or [`LittleEndian`] types defined in this crate. +/// +/// # Examples +/// +/// Write unsigned 16 bit big-endian integers to a [`Write`]: +/// +/// ```rust +/// use byteorder::{BigEndian, WriteBytesExt}; +/// +/// let mut wtr = vec![]; +/// wtr.write_u16::(517).unwrap(); +/// wtr.write_u16::(768).unwrap(); +/// assert_eq!(wtr, vec![2, 5, 3, 0]); +/// ``` +/// +/// [`BigEndian`]: enum.BigEndian.html +/// [`LittleEndian`]: enum.LittleEndian.html +/// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +pub trait WriteBytesExt: io::Write { + /// Writes an unsigned 8 bit integer to the underlying writer. + /// + /// Note that since this writes a single byte, no byte order conversions + /// are used. It is included for completeness. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write unsigned 8 bit integers to a `Write`: + /// + /// ```rust + /// use byteorder::WriteBytesExt; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_u8(2).unwrap(); + /// wtr.write_u8(5).unwrap(); + /// assert_eq!(wtr, b"\x02\x05"); + /// ``` + #[inline] + fn write_u8(&mut self, n: u8) -> Result<()> { + self.write_all(&[n]) + } + + /// Writes a signed 8 bit integer to the underlying writer. + /// + /// Note that since this writes a single byte, no byte order conversions + /// are used. It is included for completeness. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write signed 8 bit integers to a `Write`: + /// + /// ```rust + /// use byteorder::WriteBytesExt; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_i8(2).unwrap(); + /// wtr.write_i8(-5).unwrap(); + /// assert_eq!(wtr, b"\x02\xfb"); + /// ``` + #[inline] + fn write_i8(&mut self, n: i8) -> Result<()> { + self.write_all(&[n as u8]) + } + + /// Writes an unsigned 16 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write unsigned 16 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_u16::(517).unwrap(); + /// wtr.write_u16::(768).unwrap(); + /// assert_eq!(wtr, b"\x02\x05\x03\x00"); + /// ``` + #[inline] + fn write_u16(&mut self, n: u16) -> Result<()> { + let mut buf = [0; 2]; + T::write_u16(&mut buf, n); + self.write_all(&buf) + } + + /// Writes a signed 16 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write signed 16 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_i16::(193).unwrap(); + /// wtr.write_i16::(-132).unwrap(); + /// assert_eq!(wtr, b"\x00\xc1\xff\x7c"); + /// ``` + #[inline] + fn write_i16(&mut self, n: i16) -> Result<()> { + let mut buf = [0; 2]; + T::write_i16(&mut buf, n); + self.write_all(&buf) + } + + /// Writes an unsigned 24 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write unsigned 24 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_u24::(267).unwrap(); + /// wtr.write_u24::(120111).unwrap(); + /// assert_eq!(wtr, b"\x00\x01\x0b\x01\xd5\x2f"); + /// ``` + #[inline] + fn write_u24(&mut self, n: u32) -> Result<()> { + let mut buf = [0; 3]; + T::write_u24(&mut buf, n); + self.write_all(&buf) + } + + /// Writes a signed 24 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write signed 24 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_i24::(-34253).unwrap(); + /// wtr.write_i24::(120111).unwrap(); + /// assert_eq!(wtr, b"\xff\x7a\x33\x01\xd5\x2f"); + /// ``` + #[inline] + fn write_i24(&mut self, n: i32) -> Result<()> { + let mut buf = [0; 3]; + T::write_i24(&mut buf, n); + self.write_all(&buf) + } + + /// Writes an unsigned 32 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write unsigned 32 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_u32::(267).unwrap(); + /// wtr.write_u32::(1205419366).unwrap(); + /// assert_eq!(wtr, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66"); + /// ``` + #[inline] + fn write_u32(&mut self, n: u32) -> Result<()> { + let mut buf = [0; 4]; + T::write_u32(&mut buf, n); + self.write_all(&buf) + } + + /// Writes a signed 32 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write signed 32 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_i32::(-34253).unwrap(); + /// wtr.write_i32::(1205419366).unwrap(); + /// assert_eq!(wtr, b"\xff\xff\x7a\x33\x47\xd9\x3d\x66"); + /// ``` + #[inline] + fn write_i32(&mut self, n: i32) -> Result<()> { + let mut buf = [0; 4]; + T::write_i32(&mut buf, n); + self.write_all(&buf) + } + + /// Writes an unsigned 48 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write unsigned 48 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_u48::(52360336390828).unwrap(); + /// wtr.write_u48::(541).unwrap(); + /// assert_eq!(wtr, b"\x2f\x9f\x17\x40\x3a\xac\x00\x00\x00\x00\x02\x1d"); + /// ``` + #[inline] + fn write_u48(&mut self, n: u64) -> Result<()> { + let mut buf = [0; 6]; + T::write_u48(&mut buf, n); + self.write_all(&buf) + } + + /// Writes a signed 48 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write signed 48 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_i48::(-108363435763825).unwrap(); + /// wtr.write_i48::(77).unwrap(); + /// assert_eq!(wtr, b"\x9d\x71\xab\xe7\x97\x8f\x00\x00\x00\x00\x00\x4d"); + /// ``` + #[inline] + fn write_i48(&mut self, n: i64) -> Result<()> { + let mut buf = [0; 6]; + T::write_i48(&mut buf, n); + self.write_all(&buf) + } + + /// Writes an unsigned 64 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write unsigned 64 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_u64::(918733457491587).unwrap(); + /// wtr.write_u64::(143).unwrap(); + /// assert_eq!(wtr, b"\x00\x03\x43\x95\x4d\x60\x86\x83\x00\x00\x00\x00\x00\x00\x00\x8f"); + /// ``` + #[inline] + fn write_u64(&mut self, n: u64) -> Result<()> { + let mut buf = [0; 8]; + T::write_u64(&mut buf, n); + self.write_all(&buf) + } + + /// Writes a signed 64 bit integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write signed 64 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_i64::(i64::min_value()).unwrap(); + /// wtr.write_i64::(i64::max_value()).unwrap(); + /// assert_eq!(wtr, b"\x80\x00\x00\x00\x00\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff"); + /// ``` + #[inline] + fn write_i64(&mut self, n: i64) -> Result<()> { + let mut buf = [0; 8]; + T::write_i64(&mut buf, n); + self.write_all(&buf) + } + + /// Writes an unsigned 128 bit integer to the underlying writer. + #[inline] + fn write_u128(&mut self, n: u128) -> Result<()> { + let mut buf = [0; 16]; + T::write_u128(&mut buf, n); + self.write_all(&buf) + } + + /// Writes a signed 128 bit integer to the underlying writer. + #[inline] + fn write_i128(&mut self, n: i128) -> Result<()> { + let mut buf = [0; 16]; + T::write_i128(&mut buf, n); + self.write_all(&buf) + } + + /// Writes an unsigned n-bytes integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Panics + /// + /// If the given integer is not representable in the given number of bytes, + /// this method panics. If `nbytes > 8`, this method panics. + /// + /// # Examples + /// + /// Write unsigned 40 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_uint::(312550384361, 5).unwrap(); + /// wtr.write_uint::(43, 5).unwrap(); + /// assert_eq!(wtr, b"\x48\xc5\x74\x62\xe9\x00\x00\x00\x00\x2b"); + /// ``` + #[inline] + fn write_uint( + &mut self, + n: u64, + nbytes: usize, + ) -> Result<()> { + let mut buf = [0; 8]; + T::write_uint(&mut buf, n, nbytes); + self.write_all(&buf[0..nbytes]) + } + + /// Writes a signed n-bytes integer to the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Panics + /// + /// If the given integer is not representable in the given number of bytes, + /// this method panics. If `nbytes > 8`, this method panics. + /// + /// # Examples + /// + /// Write signed 56 bit big-endian integers to a `Write`: + /// + /// ```rust + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_int::(-3548172039376767, 7).unwrap(); + /// wtr.write_int::(43, 7).unwrap(); + /// assert_eq!(wtr, b"\xf3\x64\xf4\xd1\xfd\xb0\x81\x00\x00\x00\x00\x00\x00\x2b"); + /// ``` + #[inline] + fn write_int( + &mut self, + n: i64, + nbytes: usize, + ) -> Result<()> { + let mut buf = [0; 8]; + T::write_int(&mut buf, n, nbytes); + self.write_all(&buf[0..nbytes]) + } + + /// Writes an unsigned n-bytes integer to the underlying writer. + /// + /// If the given integer is not representable in the given number of bytes, + /// this method panics. If `nbytes > 16`, this method panics. + #[inline] + fn write_uint128( + &mut self, + n: u128, + nbytes: usize, + ) -> Result<()> { + let mut buf = [0; 16]; + T::write_uint128(&mut buf, n, nbytes); + self.write_all(&buf[0..nbytes]) + } + + /// Writes a signed n-bytes integer to the underlying writer. + /// + /// If the given integer is not representable in the given number of bytes, + /// this method panics. If `nbytes > 16`, this method panics. + #[inline] + fn write_int128( + &mut self, + n: i128, + nbytes: usize, + ) -> Result<()> { + let mut buf = [0; 16]; + T::write_int128(&mut buf, n, nbytes); + self.write_all(&buf[0..nbytes]) + } + + /// Writes a IEEE754 single-precision (4 bytes) floating point number to + /// the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write a big-endian single-precision floating point number to a `Write`: + /// + /// ```rust + /// use std::f32; + /// + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_f32::(f32::consts::PI).unwrap(); + /// assert_eq!(wtr, b"\x40\x49\x0f\xdb"); + /// ``` + #[inline] + fn write_f32(&mut self, n: f32) -> Result<()> { + let mut buf = [0; 4]; + T::write_f32(&mut buf, n); + self.write_all(&buf) + } + + /// Writes a IEEE754 double-precision (8 bytes) floating point number to + /// the underlying writer. + /// + /// # Errors + /// + /// This method returns the same errors as [`Write::write_all`]. + /// + /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all + /// + /// # Examples + /// + /// Write a big-endian double-precision floating point number to a `Write`: + /// + /// ```rust + /// use std::f64; + /// + /// use byteorder::{BigEndian, WriteBytesExt}; + /// + /// let mut wtr = Vec::new(); + /// wtr.write_f64::(f64::consts::PI).unwrap(); + /// assert_eq!(wtr, b"\x40\x09\x21\xfb\x54\x44\x2d\x18"); + /// ``` + #[inline] + fn write_f64(&mut self, n: f64) -> Result<()> { + let mut buf = [0; 8]; + T::write_f64(&mut buf, n); + self.write_all(&buf) + } +} + +/// All types that implement `Write` get methods defined in `WriteBytesExt` +/// for free. +impl WriteBytesExt for W {} + +/// Convert a slice of T (where T is plain old data) to its mutable binary +/// representation. +/// +/// This function is wildly unsafe because it permits arbitrary modification of +/// the binary representation of any `Copy` type. Use with care. It's intended +/// to be called only where `T` is a numeric type. +unsafe fn slice_to_u8_mut(slice: &mut [T]) -> &mut [u8] { + use std::mem::size_of; + + let len = size_of::() * slice.len(); + slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut u8, len) +} diff --git a/bitbox02-bt/vendor/byteorder/src/lib.rs b/bitbox02-bt/vendor/byteorder/src/lib.rs new file mode 100644 index 0000000..cfd53c3 --- /dev/null +++ b/bitbox02-bt/vendor/byteorder/src/lib.rs @@ -0,0 +1,3975 @@ +/*! +This crate provides convenience methods for encoding and decoding numbers in +either [big-endian or little-endian order]. + +The organization of the crate is pretty simple. A trait, [`ByteOrder`], specifies +byte conversion methods for each type of number in Rust (sans numbers that have +a platform dependent size like `usize` and `isize`). Two types, [`BigEndian`] +and [`LittleEndian`] implement these methods. Finally, [`ReadBytesExt`] and +[`WriteBytesExt`] provide convenience methods available to all types that +implement [`Read`] and [`Write`]. + +An alias, [`NetworkEndian`], for [`BigEndian`] is provided to help improve +code clarity. + +An additional alias, [`NativeEndian`], is provided for the endianness of the +local platform. This is convenient when serializing data for use and +conversions are not desired. + +# Examples + +Read unsigned 16 bit big-endian integers from a [`Read`] type: + +```rust +use std::io::Cursor; +use byteorder::{BigEndian, ReadBytesExt}; + +let mut rdr = Cursor::new(vec![2, 5, 3, 0]); +// Note that we use type parameters to indicate which kind of byte order +// we want! +assert_eq!(517, rdr.read_u16::().unwrap()); +assert_eq!(768, rdr.read_u16::().unwrap()); +``` + +Write unsigned 16 bit little-endian integers to a [`Write`] type: + +```rust +use byteorder::{LittleEndian, WriteBytesExt}; + +let mut wtr = vec![]; +wtr.write_u16::(517).unwrap(); +wtr.write_u16::(768).unwrap(); +assert_eq!(wtr, vec![5, 2, 0, 3]); +``` + +# Optional Features + +This crate optionally provides support for 128 bit values (`i128` and `u128`) +when built with the `i128` feature enabled. + +This crate can also be used without the standard library. + +# Alternatives + +Note that as of Rust 1.32, the standard numeric types provide built-in methods +like `to_le_bytes` and `from_le_bytes`, which support some of the same use +cases. + +[big-endian or little-endian order]: https://en.wikipedia.org/wiki/Endianness +[`ByteOrder`]: trait.ByteOrder.html +[`BigEndian`]: enum.BigEndian.html +[`LittleEndian`]: enum.LittleEndian.html +[`ReadBytesExt`]: trait.ReadBytesExt.html +[`WriteBytesExt`]: trait.WriteBytesExt.html +[`NetworkEndian`]: type.NetworkEndian.html +[`NativeEndian`]: type.NativeEndian.html +[`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html +[`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +*/ + +#![deny(missing_docs)] +#![cfg_attr(not(feature = "std"), no_std)] +// When testing under miri, we disable tests that take too long. But this +// provokes lots of dead code warnings. So we just squash them. +#![cfg_attr(miri, allow(dead_code, unused_macros))] + +use core::{ + convert::TryInto, fmt::Debug, hash::Hash, mem::align_of, + ptr::copy_nonoverlapping, slice, +}; + +#[cfg(feature = "std")] +pub use crate::io::{ReadBytesExt, WriteBytesExt}; + +#[cfg(feature = "std")] +mod io; + +#[inline] +fn extend_sign(val: u64, nbytes: usize) -> i64 { + let shift = (8 - nbytes) * 8; + (val << shift) as i64 >> shift +} + +#[inline] +fn extend_sign128(val: u128, nbytes: usize) -> i128 { + let shift = (16 - nbytes) * 8; + (val << shift) as i128 >> shift +} + +#[inline] +fn unextend_sign(val: i64, nbytes: usize) -> u64 { + let shift = (8 - nbytes) * 8; + (val << shift) as u64 >> shift +} + +#[inline] +fn unextend_sign128(val: i128, nbytes: usize) -> u128 { + let shift = (16 - nbytes) * 8; + (val << shift) as u128 >> shift +} + +#[inline] +fn pack_size(n: u64) -> usize { + if n < 1 << 8 { + 1 + } else if n < 1 << 16 { + 2 + } else if n < 1 << 24 { + 3 + } else if n < 1 << 32 { + 4 + } else if n < 1 << 40 { + 5 + } else if n < 1 << 48 { + 6 + } else if n < 1 << 56 { + 7 + } else { + 8 + } +} + +#[inline] +fn pack_size128(n: u128) -> usize { + if n < 1 << 8 { + 1 + } else if n < 1 << 16 { + 2 + } else if n < 1 << 24 { + 3 + } else if n < 1 << 32 { + 4 + } else if n < 1 << 40 { + 5 + } else if n < 1 << 48 { + 6 + } else if n < 1 << 56 { + 7 + } else if n < 1 << 64 { + 8 + } else if n < 1 << 72 { + 9 + } else if n < 1 << 80 { + 10 + } else if n < 1 << 88 { + 11 + } else if n < 1 << 96 { + 12 + } else if n < 1 << 104 { + 13 + } else if n < 1 << 112 { + 14 + } else if n < 1 << 120 { + 15 + } else { + 16 + } +} + +mod private { + /// Sealed stops crates other than byteorder from implementing any traits + /// that use it. + pub trait Sealed {} + impl Sealed for super::LittleEndian {} + impl Sealed for super::BigEndian {} +} + +/// `ByteOrder` describes types that can serialize integers as bytes. +/// +/// Note that `Self` does not appear anywhere in this trait's definition! +/// Therefore, in order to use it, you'll need to use syntax like +/// `T::read_u16(&[0, 1])` where `T` implements `ByteOrder`. +/// +/// This crate provides two types that implement `ByteOrder`: [`BigEndian`] +/// and [`LittleEndian`]. +/// This trait is sealed and cannot be implemented for callers to avoid +/// breaking backwards compatibility when adding new derived traits. +/// +/// # Examples +/// +/// Write and read `u32` numbers in little endian order: +/// +/// ```rust +/// use byteorder::{ByteOrder, LittleEndian}; +/// +/// let mut buf = [0; 4]; +/// LittleEndian::write_u32(&mut buf, 1_000_000); +/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); +/// ``` +/// +/// Write and read `i16` numbers in big endian order: +/// +/// ```rust +/// use byteorder::{ByteOrder, BigEndian}; +/// +/// let mut buf = [0; 2]; +/// BigEndian::write_i16(&mut buf, -5_000); +/// assert_eq!(-5_000, BigEndian::read_i16(&buf)); +/// ``` +/// +/// [`BigEndian`]: enum.BigEndian.html +/// [`LittleEndian`]: enum.LittleEndian.html +pub trait ByteOrder: + Clone + + Copy + + Debug + + Default + + Eq + + Hash + + Ord + + PartialEq + + PartialOrd + + private::Sealed +{ + /// Reads an unsigned 16 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 2`. + fn read_u16(buf: &[u8]) -> u16; + + /// Reads an unsigned 24 bit integer from `buf`, stored in u32. + /// + /// # Panics + /// + /// Panics when `buf.len() < 3`. + /// + /// # Examples + /// + /// Write and read 24 bit `u32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_u24(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf)); + /// ``` + fn read_u24(buf: &[u8]) -> u32 { + Self::read_uint(buf, 3) as u32 + } + + /// Reads an unsigned 32 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 4`. + /// + /// # Examples + /// + /// Write and read `u32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 4]; + /// LittleEndian::write_u32(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); + /// ``` + fn read_u32(buf: &[u8]) -> u32; + + /// Reads an unsigned 48 bit integer from `buf`, stored in u64. + /// + /// # Panics + /// + /// Panics when `buf.len() < 6`. + /// + /// # Examples + /// + /// Write and read 48 bit `u64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 6]; + /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000); + /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf)); + /// ``` + fn read_u48(buf: &[u8]) -> u64 { + Self::read_uint(buf, 6) as u64 + } + + /// Reads an unsigned 64 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 8`. + /// + /// # Examples + /// + /// Write and read `u64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 8]; + /// LittleEndian::write_u64(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf)); + /// ``` + fn read_u64(buf: &[u8]) -> u64; + + /// Reads an unsigned 128 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 16`. + /// + /// # Examples + /// + /// Write and read `u128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 16]; + /// LittleEndian::write_u128(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf)); + /// ``` + fn read_u128(buf: &[u8]) -> u128; + + /// Reads an unsigned n-bytes integer from `buf`. + /// + /// # Panics + /// + /// Panics when `nbytes < 1` or `nbytes > 8` or + /// `buf.len() < nbytes` + /// + /// # Examples + /// + /// Write and read an n-byte number in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_uint(&mut buf, 1_000_000, 3); + /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3)); + /// ``` + fn read_uint(buf: &[u8], nbytes: usize) -> u64; + + /// Reads an unsigned n-bytes integer from `buf`. + /// + /// # Panics + /// + /// Panics when `nbytes < 1` or `nbytes > 16` or + /// `buf.len() < nbytes` + /// + /// # Examples + /// + /// Write and read an n-byte number in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3); + /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3)); + /// ``` + fn read_uint128(buf: &[u8], nbytes: usize) -> u128; + + /// Writes an unsigned 16 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 2`. + /// + /// # Examples + /// + /// Write and read `u16` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 2]; + /// LittleEndian::write_u16(&mut buf, 1_000); + /// assert_eq!(1_000, LittleEndian::read_u16(&buf)); + /// ``` + fn write_u16(buf: &mut [u8], n: u16); + + /// Writes an unsigned 24 bit integer `n` to `buf`, stored in u32. + /// + /// # Panics + /// + /// Panics when `buf.len() < 3`. + /// + /// # Examples + /// + /// Write and read 24 bit `u32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_u24(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf)); + /// ``` + fn write_u24(buf: &mut [u8], n: u32) { + Self::write_uint(buf, n as u64, 3) + } + + /// Writes an unsigned 32 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 4`. + /// + /// # Examples + /// + /// Write and read `u32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 4]; + /// LittleEndian::write_u32(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); + /// ``` + fn write_u32(buf: &mut [u8], n: u32); + + /// Writes an unsigned 48 bit integer `n` to `buf`, stored in u64. + /// + /// # Panics + /// + /// Panics when `buf.len() < 6`. + /// + /// # Examples + /// + /// Write and read 48 bit `u64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 6]; + /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000); + /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf)); + /// ``` + fn write_u48(buf: &mut [u8], n: u64) { + Self::write_uint(buf, n as u64, 6) + } + + /// Writes an unsigned 64 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 8`. + /// + /// # Examples + /// + /// Write and read `u64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 8]; + /// LittleEndian::write_u64(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf)); + /// ``` + fn write_u64(buf: &mut [u8], n: u64); + + /// Writes an unsigned 128 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 16`. + /// + /// # Examples + /// + /// Write and read `u128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 16]; + /// LittleEndian::write_u128(&mut buf, 1_000_000); + /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf)); + /// ``` + fn write_u128(buf: &mut [u8], n: u128); + + /// Writes an unsigned integer `n` to `buf` using only `nbytes`. + /// + /// # Panics + /// + /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then + /// this method panics. + /// + /// # Examples + /// + /// Write and read an n-byte number in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_uint(&mut buf, 1_000_000, 3); + /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3)); + /// ``` + fn write_uint(buf: &mut [u8], n: u64, nbytes: usize); + + /// Writes an unsigned integer `n` to `buf` using only `nbytes`. + /// + /// # Panics + /// + /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then + /// this method panics. + /// + /// # Examples + /// + /// Write and read an n-byte number in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3); + /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3)); + /// ``` + fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize); + + /// Reads a signed 16 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 2`. + /// + /// # Examples + /// + /// Write and read `i16` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 2]; + /// LittleEndian::write_i16(&mut buf, -1_000); + /// assert_eq!(-1_000, LittleEndian::read_i16(&buf)); + /// ``` + #[inline] + fn read_i16(buf: &[u8]) -> i16 { + Self::read_u16(buf) as i16 + } + + /// Reads a signed 24 bit integer from `buf`, stored in i32. + /// + /// # Panics + /// + /// Panics when `buf.len() < 3`. + /// + /// # Examples + /// + /// Write and read 24 bit `i32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_i24(&mut buf, -1_000_000); + /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf)); + /// ``` + #[inline] + fn read_i24(buf: &[u8]) -> i32 { + Self::read_int(buf, 3) as i32 + } + + /// Reads a signed 32 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 4`. + /// + /// # Examples + /// + /// Write and read `i32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 4]; + /// LittleEndian::write_i32(&mut buf, -1_000_000); + /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf)); + /// ``` + #[inline] + fn read_i32(buf: &[u8]) -> i32 { + Self::read_u32(buf) as i32 + } + + /// Reads a signed 48 bit integer from `buf`, stored in i64. + /// + /// # Panics + /// + /// Panics when `buf.len() < 6`. + /// + /// # Examples + /// + /// Write and read 48 bit `i64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 6]; + /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000); + /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf)); + /// ``` + #[inline] + fn read_i48(buf: &[u8]) -> i64 { + Self::read_int(buf, 6) as i64 + } + + /// Reads a signed 64 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 8`. + /// + /// # Examples + /// + /// Write and read `i64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 8]; + /// LittleEndian::write_i64(&mut buf, -1_000_000_000); + /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf)); + /// ``` + #[inline] + fn read_i64(buf: &[u8]) -> i64 { + Self::read_u64(buf) as i64 + } + + /// Reads a signed 128 bit integer from `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 16`. + /// + /// # Examples + /// + /// Write and read `i128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 16]; + /// LittleEndian::write_i128(&mut buf, -1_000_000_000); + /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf)); + /// ``` + #[inline] + fn read_i128(buf: &[u8]) -> i128 { + Self::read_u128(buf) as i128 + } + + /// Reads a signed n-bytes integer from `buf`. + /// + /// # Panics + /// + /// Panics when `nbytes < 1` or `nbytes > 8` or + /// `buf.len() < nbytes` + /// + /// # Examples + /// + /// Write and read n-length signed numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_int(&mut buf, -1_000, 3); + /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3)); + /// ``` + #[inline] + fn read_int(buf: &[u8], nbytes: usize) -> i64 { + extend_sign(Self::read_uint(buf, nbytes), nbytes) + } + + /// Reads a signed n-bytes integer from `buf`. + /// + /// # Panics + /// + /// Panics when `nbytes < 1` or `nbytes > 16` or + /// `buf.len() < nbytes` + /// + /// # Examples + /// + /// Write and read n-length signed numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_int128(&mut buf, -1_000, 3); + /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3)); + /// ``` + #[inline] + fn read_int128(buf: &[u8], nbytes: usize) -> i128 { + extend_sign128(Self::read_uint128(buf, nbytes), nbytes) + } + + /// Reads a IEEE754 single-precision (4 bytes) floating point number. + /// + /// # Panics + /// + /// Panics when `buf.len() < 4`. + /// + /// # Examples + /// + /// Write and read `f32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let e = 2.71828; + /// let mut buf = [0; 4]; + /// LittleEndian::write_f32(&mut buf, e); + /// assert_eq!(e, LittleEndian::read_f32(&buf)); + /// ``` + #[inline] + fn read_f32(buf: &[u8]) -> f32 { + f32::from_bits(Self::read_u32(buf)) + } + + /// Reads a IEEE754 double-precision (8 bytes) floating point number. + /// + /// # Panics + /// + /// Panics when `buf.len() < 8`. + /// + /// # Examples + /// + /// Write and read `f64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let phi = 1.6180339887; + /// let mut buf = [0; 8]; + /// LittleEndian::write_f64(&mut buf, phi); + /// assert_eq!(phi, LittleEndian::read_f64(&buf)); + /// ``` + #[inline] + fn read_f64(buf: &[u8]) -> f64 { + f64::from_bits(Self::read_u64(buf)) + } + + /// Writes a signed 16 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 2`. + /// + /// # Examples + /// + /// Write and read `i16` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 2]; + /// LittleEndian::write_i16(&mut buf, -1_000); + /// assert_eq!(-1_000, LittleEndian::read_i16(&buf)); + /// ``` + #[inline] + fn write_i16(buf: &mut [u8], n: i16) { + Self::write_u16(buf, n as u16) + } + + /// Writes a signed 24 bit integer `n` to `buf`, stored in i32. + /// + /// # Panics + /// + /// Panics when `buf.len() < 3`. + /// + /// # Examples + /// + /// Write and read 24 bit `i32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_i24(&mut buf, -1_000_000); + /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf)); + /// ``` + #[inline] + fn write_i24(buf: &mut [u8], n: i32) { + Self::write_int(buf, n as i64, 3) + } + + /// Writes a signed 32 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 4`. + /// + /// # Examples + /// + /// Write and read `i32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 4]; + /// LittleEndian::write_i32(&mut buf, -1_000_000); + /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf)); + /// ``` + #[inline] + fn write_i32(buf: &mut [u8], n: i32) { + Self::write_u32(buf, n as u32) + } + + /// Writes a signed 48 bit integer `n` to `buf`, stored in i64. + /// + /// # Panics + /// + /// Panics when `buf.len() < 6`. + /// + /// # Examples + /// + /// Write and read 48 bit `i64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 6]; + /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000); + /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf)); + /// ``` + #[inline] + fn write_i48(buf: &mut [u8], n: i64) { + Self::write_int(buf, n as i64, 6) + } + + /// Writes a signed 64 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 8`. + /// + /// # Examples + /// + /// Write and read `i64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 8]; + /// LittleEndian::write_i64(&mut buf, -1_000_000_000); + /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf)); + /// ``` + #[inline] + fn write_i64(buf: &mut [u8], n: i64) { + Self::write_u64(buf, n as u64) + } + + /// Writes a signed 128 bit integer `n` to `buf`. + /// + /// # Panics + /// + /// Panics when `buf.len() < 16`. + /// + /// # Examples + /// + /// Write and read n-byte `i128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 16]; + /// LittleEndian::write_i128(&mut buf, -1_000_000_000); + /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf)); + /// ``` + #[inline] + fn write_i128(buf: &mut [u8], n: i128) { + Self::write_u128(buf, n as u128) + } + + /// Writes a signed integer `n` to `buf` using only `nbytes`. + /// + /// # Panics + /// + /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then + /// this method panics. + /// + /// # Examples + /// + /// Write and read an n-byte number in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_int(&mut buf, -1_000, 3); + /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3)); + /// ``` + #[inline] + fn write_int(buf: &mut [u8], n: i64, nbytes: usize) { + Self::write_uint(buf, unextend_sign(n, nbytes), nbytes) + } + + /// Writes a signed integer `n` to `buf` using only `nbytes`. + /// + /// # Panics + /// + /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then + /// this method panics. + /// + /// # Examples + /// + /// Write and read n-length signed numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut buf = [0; 3]; + /// LittleEndian::write_int128(&mut buf, -1_000, 3); + /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3)); + /// ``` + #[inline] + fn write_int128(buf: &mut [u8], n: i128, nbytes: usize) { + Self::write_uint128(buf, unextend_sign128(n, nbytes), nbytes) + } + + /// Writes a IEEE754 single-precision (4 bytes) floating point number. + /// + /// # Panics + /// + /// Panics when `buf.len() < 4`. + /// + /// # Examples + /// + /// Write and read `f32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let e = 2.71828; + /// let mut buf = [0; 4]; + /// LittleEndian::write_f32(&mut buf, e); + /// assert_eq!(e, LittleEndian::read_f32(&buf)); + /// ``` + #[inline] + fn write_f32(buf: &mut [u8], n: f32) { + Self::write_u32(buf, n.to_bits()) + } + + /// Writes a IEEE754 double-precision (8 bytes) floating point number. + /// + /// # Panics + /// + /// Panics when `buf.len() < 8`. + /// + /// # Examples + /// + /// Write and read `f64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let phi = 1.6180339887; + /// let mut buf = [0; 8]; + /// LittleEndian::write_f64(&mut buf, phi); + /// assert_eq!(phi, LittleEndian::read_f64(&buf)); + /// ``` + #[inline] + fn write_f64(buf: &mut [u8], n: f64) { + Self::write_u64(buf, n.to_bits()) + } + + /// Reads unsigned 16 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 2*dst.len()`. + /// + /// # Examples + /// + /// Write and read `u16` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 8]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u16_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u16_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn read_u16_into(src: &[u8], dst: &mut [u16]); + + /// Reads unsigned 32 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 4*dst.len()`. + /// + /// # Examples + /// + /// Write and read `u32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 16]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u32_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u32_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn read_u32_into(src: &[u8], dst: &mut [u32]); + + /// Reads unsigned 64 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 8*dst.len()`. + /// + /// # Examples + /// + /// Write and read `u64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 32]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u64_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u64_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn read_u64_into(src: &[u8], dst: &mut [u64]); + + /// Reads unsigned 128 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 16*dst.len()`. + /// + /// # Examples + /// + /// Write and read `u128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 64]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u128_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u128_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn read_u128_into(src: &[u8], dst: &mut [u128]); + + /// Reads signed 16 bit integers from `src` to `dst`. + /// + /// # Panics + /// + /// Panics when `buf.len() != 2*dst.len()`. + /// + /// # Examples + /// + /// Write and read `i16` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 8]; + /// let numbers_given = [1, 2, 0x0f, 0xee]; + /// LittleEndian::write_i16_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i16_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + fn read_i16_into(src: &[u8], dst: &mut [i16]) { + let dst = unsafe { + slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u16, dst.len()) + }; + Self::read_u16_into(src, dst) + } + + /// Reads signed 32 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 4*dst.len()`. + /// + /// # Examples + /// + /// Write and read `i32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 16]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_i32_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i32_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + fn read_i32_into(src: &[u8], dst: &mut [i32]) { + let dst = unsafe { + slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len()) + }; + Self::read_u32_into(src, dst); + } + + /// Reads signed 64 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 8*dst.len()`. + /// + /// # Examples + /// + /// Write and read `i64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 32]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_i64_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i64_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + fn read_i64_into(src: &[u8], dst: &mut [i64]) { + let dst = unsafe { + slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len()) + }; + Self::read_u64_into(src, dst); + } + + /// Reads signed 128 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 16*dst.len()`. + /// + /// # Examples + /// + /// Write and read `i128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 64]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_i128_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i128_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + fn read_i128_into(src: &[u8], dst: &mut [i128]) { + let dst = unsafe { + slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u128, dst.len()) + }; + Self::read_u128_into(src, dst); + } + + /// Reads IEEE754 single-precision (4 bytes) floating point numbers from + /// `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 4*dst.len()`. + /// + /// # Examples + /// + /// Write and read `f32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 16]; + /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; + /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0.0; 4]; + /// LittleEndian::read_f32_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + fn read_f32_into(src: &[u8], dst: &mut [f32]) { + let dst = unsafe { + const _: () = assert!(align_of::() <= align_of::()); + slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len()) + }; + Self::read_u32_into(src, dst); + } + + /// **DEPRECATED**. + /// + /// This method is deprecated. Use `read_f32_into` instead. + /// Reads IEEE754 single-precision (4 bytes) floating point numbers from + /// `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 4*dst.len()`. + /// + /// # Examples + /// + /// Write and read `f32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 16]; + /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; + /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0.0; 4]; + /// LittleEndian::read_f32_into_unchecked(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + #[deprecated(since = "1.3.0", note = "please use `read_f32_into` instead")] + fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32]) { + Self::read_f32_into(src, dst); + } + + /// Reads IEEE754 single-precision (4 bytes) floating point numbers from + /// `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 8*dst.len()`. + /// + /// # Examples + /// + /// Write and read `f64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 32]; + /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; + /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0.0; 4]; + /// LittleEndian::read_f64_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + fn read_f64_into(src: &[u8], dst: &mut [f64]) { + let dst = unsafe { + const _: () = assert!(align_of::() <= align_of::()); + slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len()) + }; + Self::read_u64_into(src, dst); + } + + /// **DEPRECATED**. + /// + /// This method is deprecated. Use `read_f64_into` instead. + /// + /// Reads IEEE754 single-precision (4 bytes) floating point numbers from + /// `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 8*dst.len()`. + /// + /// # Examples + /// + /// Write and read `f64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 32]; + /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; + /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0.0; 4]; + /// LittleEndian::read_f64_into_unchecked(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + #[inline] + #[deprecated(since = "1.3.0", note = "please use `read_f64_into` instead")] + fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64]) { + Self::read_f64_into(src, dst); + } + + /// Writes unsigned 16 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `dst.len() != 2*src.len()`. + /// + /// # Examples + /// + /// Write and read `u16` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 8]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u16_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u16_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_u16_into(src: &[u16], dst: &mut [u8]); + + /// Writes unsigned 32 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `dst.len() != 4*src.len()`. + /// + /// # Examples + /// + /// Write and read `u32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 16]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u32_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u32_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_u32_into(src: &[u32], dst: &mut [u8]); + + /// Writes unsigned 64 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `dst.len() != 8*src.len()`. + /// + /// # Examples + /// + /// Write and read `u64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 32]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u64_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u64_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_u64_into(src: &[u64], dst: &mut [u8]); + + /// Writes unsigned 128 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `dst.len() != 16*src.len()`. + /// + /// # Examples + /// + /// Write and read `u128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 64]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_u128_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_u128_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_u128_into(src: &[u128], dst: &mut [u8]); + + /// Writes signed 8 bit integers from `src` into `dst`. + /// + /// Note that since each `i8` is a single byte, no byte order conversions + /// are used. This method is included because it provides a safe, simple + /// way for the caller to write from a `&[i8]` buffer. (Without this + /// method, the caller would have to either use `unsafe` code or convert + /// each byte to `u8` individually.) + /// + /// # Panics + /// + /// Panics when `buf.len() != src.len()`. + /// + /// # Examples + /// + /// Write and read `i8` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; + /// + /// let mut bytes = [0; 4]; + /// let numbers_given = [1, 2, 0xf, 0xe]; + /// LittleEndian::write_i8_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// bytes.as_ref().read_i8_into(&mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_i8_into(src: &[i8], dst: &mut [u8]) { + let src = unsafe { + slice::from_raw_parts(src.as_ptr() as *const u8, src.len()) + }; + dst.copy_from_slice(src); + } + + /// Writes signed 16 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `buf.len() != 2*src.len()`. + /// + /// # Examples + /// + /// Write and read `i16` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 8]; + /// let numbers_given = [1, 2, 0x0f, 0xee]; + /// LittleEndian::write_i16_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i16_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_i16_into(src: &[i16], dst: &mut [u8]) { + let src = unsafe { + slice::from_raw_parts(src.as_ptr() as *const u16, src.len()) + }; + Self::write_u16_into(src, dst); + } + + /// Writes signed 32 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `dst.len() != 4*src.len()`. + /// + /// # Examples + /// + /// Write and read `i32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 16]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_i32_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i32_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_i32_into(src: &[i32], dst: &mut [u8]) { + let src = unsafe { + slice::from_raw_parts(src.as_ptr() as *const u32, src.len()) + }; + Self::write_u32_into(src, dst); + } + + /// Writes signed 64 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `dst.len() != 8*src.len()`. + /// + /// # Examples + /// + /// Write and read `i64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 32]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_i64_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i64_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_i64_into(src: &[i64], dst: &mut [u8]) { + let src = unsafe { + slice::from_raw_parts(src.as_ptr() as *const u64, src.len()) + }; + Self::write_u64_into(src, dst); + } + + /// Writes signed 128 bit integers from `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `dst.len() != 16*src.len()`. + /// + /// # Examples + /// + /// Write and read `i128` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 64]; + /// let numbers_given = [1, 2, 0xf00f, 0xffee]; + /// LittleEndian::write_i128_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0; 4]; + /// LittleEndian::read_i128_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_i128_into(src: &[i128], dst: &mut [u8]) { + let src = unsafe { + slice::from_raw_parts(src.as_ptr() as *const u128, src.len()) + }; + Self::write_u128_into(src, dst); + } + + /// Writes IEEE754 single-precision (4 bytes) floating point numbers from + /// `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 4*dst.len()`. + /// + /// # Examples + /// + /// Write and read `f32` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 16]; + /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; + /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0.0; 4]; + /// LittleEndian::read_f32_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_f32_into(src: &[f32], dst: &mut [u8]) { + let src = unsafe { + slice::from_raw_parts(src.as_ptr() as *const u32, src.len()) + }; + Self::write_u32_into(src, dst); + } + + /// Writes IEEE754 double-precision (8 bytes) floating point numbers from + /// `src` into `dst`. + /// + /// # Panics + /// + /// Panics when `src.len() != 8*dst.len()`. + /// + /// # Examples + /// + /// Write and read `f64` numbers in little endian order: + /// + /// ```rust + /// use byteorder::{ByteOrder, LittleEndian}; + /// + /// let mut bytes = [0; 32]; + /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; + /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); + /// + /// let mut numbers_got = [0.0; 4]; + /// LittleEndian::read_f64_into(&bytes, &mut numbers_got); + /// assert_eq!(numbers_given, numbers_got); + /// ``` + fn write_f64_into(src: &[f64], dst: &mut [u8]) { + let src = unsafe { + slice::from_raw_parts(src.as_ptr() as *const u64, src.len()) + }; + Self::write_u64_into(src, dst); + } + + /// Converts the given slice of unsigned 16 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 65000]; + /// BigEndian::from_slice_u16(&mut numbers); + /// assert_eq!(numbers, [5u16.to_be(), 65000u16.to_be()]); + /// ``` + fn from_slice_u16(numbers: &mut [u16]); + + /// Converts the given slice of unsigned 32 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 65000]; + /// BigEndian::from_slice_u32(&mut numbers); + /// assert_eq!(numbers, [5u32.to_be(), 65000u32.to_be()]); + /// ``` + fn from_slice_u32(numbers: &mut [u32]); + + /// Converts the given slice of unsigned 64 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 65000]; + /// BigEndian::from_slice_u64(&mut numbers); + /// assert_eq!(numbers, [5u64.to_be(), 65000u64.to_be()]); + /// ``` + fn from_slice_u64(numbers: &mut [u64]); + + /// Converts the given slice of unsigned 128 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 65000]; + /// BigEndian::from_slice_u128(&mut numbers); + /// assert_eq!(numbers, [5u128.to_be(), 65000u128.to_be()]); + /// ``` + fn from_slice_u128(numbers: &mut [u128]); + + /// Converts the given slice of signed 16 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 6500]; + /// BigEndian::from_slice_i16(&mut numbers); + /// assert_eq!(numbers, [5i16.to_be(), 6500i16.to_be()]); + /// ``` + #[inline] + fn from_slice_i16(src: &mut [i16]) { + let src = unsafe { + slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u16, src.len()) + }; + Self::from_slice_u16(src); + } + + /// Converts the given slice of signed 32 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 65000]; + /// BigEndian::from_slice_i32(&mut numbers); + /// assert_eq!(numbers, [5i32.to_be(), 65000i32.to_be()]); + /// ``` + #[inline] + fn from_slice_i32(src: &mut [i32]) { + let src = unsafe { + slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u32, src.len()) + }; + Self::from_slice_u32(src); + } + + /// Converts the given slice of signed 64 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 65000]; + /// BigEndian::from_slice_i64(&mut numbers); + /// assert_eq!(numbers, [5i64.to_be(), 65000i64.to_be()]); + /// ``` + #[inline] + fn from_slice_i64(src: &mut [i64]) { + let src = unsafe { + slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u64, src.len()) + }; + Self::from_slice_u64(src); + } + + /// Converts the given slice of signed 128 bit integers to a particular + /// endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + /// + /// # Examples + /// + /// Convert the host platform's endianness to big-endian: + /// + /// ```rust + /// use byteorder::{ByteOrder, BigEndian}; + /// + /// let mut numbers = [5, 65000]; + /// BigEndian::from_slice_i128(&mut numbers); + /// assert_eq!(numbers, [5i128.to_be(), 65000i128.to_be()]); + /// ``` + #[inline] + fn from_slice_i128(src: &mut [i128]) { + let src = unsafe { + slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u128, src.len()) + }; + Self::from_slice_u128(src); + } + + /// Converts the given slice of IEEE754 single-precision (4 bytes) floating + /// point numbers to a particular endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + fn from_slice_f32(numbers: &mut [f32]); + + /// Converts the given slice of IEEE754 double-precision (8 bytes) floating + /// point numbers to a particular endianness. + /// + /// If the endianness matches the endianness of the host platform, then + /// this is a no-op. + fn from_slice_f64(numbers: &mut [f64]); +} + +/// Defines big-endian serialization. +/// +/// Note that this type has no value constructor. It is used purely at the +/// type level. +/// +/// # Examples +/// +/// Write and read `u32` numbers in big endian order: +/// +/// ```rust +/// use byteorder::{ByteOrder, BigEndian}; +/// +/// let mut buf = [0; 4]; +/// BigEndian::write_u32(&mut buf, 1_000_000); +/// assert_eq!(1_000_000, BigEndian::read_u32(&buf)); +/// ``` +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub enum BigEndian {} + +impl Default for BigEndian { + fn default() -> BigEndian { + panic!("BigEndian default") + } +} + +/// A type alias for [`BigEndian`]. +/// +/// [`BigEndian`]: enum.BigEndian.html +pub type BE = BigEndian; + +/// Defines little-endian serialization. +/// +/// Note that this type has no value constructor. It is used purely at the +/// type level. +/// +/// # Examples +/// +/// Write and read `u32` numbers in little endian order: +/// +/// ```rust +/// use byteorder::{ByteOrder, LittleEndian}; +/// +/// let mut buf = [0; 4]; +/// LittleEndian::write_u32(&mut buf, 1_000_000); +/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); +/// ``` +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub enum LittleEndian {} + +impl Default for LittleEndian { + fn default() -> LittleEndian { + panic!("LittleEndian default") + } +} + +/// A type alias for [`LittleEndian`]. +/// +/// [`LittleEndian`]: enum.LittleEndian.html +pub type LE = LittleEndian; + +/// Defines network byte order serialization. +/// +/// Network byte order is defined by [RFC 1700][1] to be big-endian, and is +/// referred to in several protocol specifications. This type is an alias of +/// [`BigEndian`]. +/// +/// [1]: https://tools.ietf.org/html/rfc1700 +/// +/// Note that this type has no value constructor. It is used purely at the +/// type level. +/// +/// # Examples +/// +/// Write and read `i16` numbers in big endian order: +/// +/// ```rust +/// use byteorder::{ByteOrder, NetworkEndian, BigEndian}; +/// +/// let mut buf = [0; 2]; +/// BigEndian::write_i16(&mut buf, -5_000); +/// assert_eq!(-5_000, NetworkEndian::read_i16(&buf)); +/// ``` +/// +/// [`BigEndian`]: enum.BigEndian.html +pub type NetworkEndian = BigEndian; + +/// Defines system native-endian serialization. +/// +/// Note that this type has no value constructor. It is used purely at the +/// type level. +/// +/// On this platform, this is an alias for [`LittleEndian`]. +/// +/// [`LittleEndian`]: enum.LittleEndian.html +#[cfg(target_endian = "little")] +pub type NativeEndian = LittleEndian; + +/// Defines system native-endian serialization. +/// +/// Note that this type has no value constructor. It is used purely at the +/// type level. +/// +/// On this platform, this is an alias for [`BigEndian`]. +/// +/// [`BigEndian`]: enum.BigEndian.html +#[cfg(target_endian = "big")] +pub type NativeEndian = BigEndian; + +/// Copies a &[u8] $src into a &mut [$ty] $dst for the endianness given by +/// $from_bytes (must be either from_be_bytes or from_le_bytes). +/// +/// Panics if $src.len() != $dst.len() * size_of::<$ty>(). +macro_rules! read_slice { + ($src:expr, $dst:expr, $ty:ty, $from_bytes:ident) => {{ + const SIZE: usize = core::mem::size_of::<$ty>(); + // Check types: + let src: &[u8] = $src; + let dst: &mut [$ty] = $dst; + assert_eq!(src.len(), dst.len() * SIZE); + for (src, dst) in src.chunks_exact(SIZE).zip(dst.iter_mut()) { + *dst = <$ty>::$from_bytes(src.try_into().unwrap()); + } + }}; +} + +/// Copies a &[$ty] $src into a &mut [u8] $dst for the endianness given by +/// $from_bytes (must be either from_be_bytes or from_le_bytes). +/// +/// Panics if $src.len() * size_of::<$ty>() != $dst.len(). +macro_rules! write_slice { + ($src:expr, $dst:expr, $ty:ty, $to_bytes:ident) => {{ + const SIZE: usize = core::mem::size_of::<$ty>(); + // Check types: + let src: &[$ty] = $src; + let dst: &mut [u8] = $dst; + assert_eq!(src.len() * SIZE, dst.len()); + for (src, dst) in src.iter().zip(dst.chunks_exact_mut(SIZE)) { + dst.copy_from_slice(&src.$to_bytes()); + } + }}; +} + +impl ByteOrder for BigEndian { + #[inline] + fn read_u16(buf: &[u8]) -> u16 { + u16::from_be_bytes(buf[..2].try_into().unwrap()) + } + + #[inline] + fn read_u32(buf: &[u8]) -> u32 { + u32::from_be_bytes(buf[..4].try_into().unwrap()) + } + + #[inline] + fn read_u64(buf: &[u8]) -> u64 { + u64::from_be_bytes(buf[..8].try_into().unwrap()) + } + + #[inline] + fn read_u128(buf: &[u8]) -> u128 { + u128::from_be_bytes(buf[..16].try_into().unwrap()) + } + + #[inline] + fn read_uint(buf: &[u8], nbytes: usize) -> u64 { + let mut out = [0; 8]; + assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); + let start = out.len() - nbytes; + out[start..].copy_from_slice(&buf[..nbytes]); + u64::from_be_bytes(out) + } + + #[inline] + fn read_uint128(buf: &[u8], nbytes: usize) -> u128 { + let mut out = [0; 16]; + assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); + let start = out.len() - nbytes; + out[start..].copy_from_slice(&buf[..nbytes]); + u128::from_be_bytes(out) + } + + #[inline] + fn write_u16(buf: &mut [u8], n: u16) { + buf[..2].copy_from_slice(&n.to_be_bytes()); + } + + #[inline] + fn write_u32(buf: &mut [u8], n: u32) { + buf[..4].copy_from_slice(&n.to_be_bytes()); + } + + #[inline] + fn write_u64(buf: &mut [u8], n: u64) { + buf[..8].copy_from_slice(&n.to_be_bytes()); + } + + #[inline] + fn write_u128(buf: &mut [u8], n: u128) { + buf[..16].copy_from_slice(&n.to_be_bytes()); + } + + #[inline] + fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) { + assert!(pack_size(n) <= nbytes && nbytes <= 8); + assert!(nbytes <= buf.len()); + unsafe { + let bytes = *(&n.to_be() as *const u64 as *const [u8; 8]); + copy_nonoverlapping( + bytes.as_ptr().offset((8 - nbytes) as isize), + buf.as_mut_ptr(), + nbytes, + ); + } + } + + #[inline] + fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) { + assert!(pack_size128(n) <= nbytes && nbytes <= 16); + assert!(nbytes <= buf.len()); + unsafe { + let bytes = *(&n.to_be() as *const u128 as *const [u8; 16]); + copy_nonoverlapping( + bytes.as_ptr().offset((16 - nbytes) as isize), + buf.as_mut_ptr(), + nbytes, + ); + } + } + + #[inline] + fn read_u16_into(src: &[u8], dst: &mut [u16]) { + read_slice!(src, dst, u16, from_be_bytes); + } + + #[inline] + fn read_u32_into(src: &[u8], dst: &mut [u32]) { + read_slice!(src, dst, u32, from_be_bytes); + } + + #[inline] + fn read_u64_into(src: &[u8], dst: &mut [u64]) { + read_slice!(src, dst, u64, from_be_bytes); + } + + #[inline] + fn read_u128_into(src: &[u8], dst: &mut [u128]) { + read_slice!(src, dst, u128, from_be_bytes); + } + + #[inline] + fn write_u16_into(src: &[u16], dst: &mut [u8]) { + write_slice!(src, dst, u16, to_be_bytes); + } + + #[inline] + fn write_u32_into(src: &[u32], dst: &mut [u8]) { + write_slice!(src, dst, u32, to_be_bytes); + } + + #[inline] + fn write_u64_into(src: &[u64], dst: &mut [u8]) { + write_slice!(src, dst, u64, to_be_bytes); + } + + #[inline] + fn write_u128_into(src: &[u128], dst: &mut [u8]) { + write_slice!(src, dst, u128, to_be_bytes); + } + + #[inline] + fn from_slice_u16(numbers: &mut [u16]) { + if cfg!(target_endian = "little") { + for n in numbers { + *n = n.to_be(); + } + } + } + + #[inline] + fn from_slice_u32(numbers: &mut [u32]) { + if cfg!(target_endian = "little") { + for n in numbers { + *n = n.to_be(); + } + } + } + + #[inline] + fn from_slice_u64(numbers: &mut [u64]) { + if cfg!(target_endian = "little") { + for n in numbers { + *n = n.to_be(); + } + } + } + + #[inline] + fn from_slice_u128(numbers: &mut [u128]) { + if cfg!(target_endian = "little") { + for n in numbers { + *n = n.to_be(); + } + } + } + + #[inline] + fn from_slice_f32(numbers: &mut [f32]) { + if cfg!(target_endian = "little") { + for n in numbers { + unsafe { + let int = *(n as *const f32 as *const u32); + *n = *(&int.to_be() as *const u32 as *const f32); + } + } + } + } + + #[inline] + fn from_slice_f64(numbers: &mut [f64]) { + if cfg!(target_endian = "little") { + for n in numbers { + unsafe { + let int = *(n as *const f64 as *const u64); + *n = *(&int.to_be() as *const u64 as *const f64); + } + } + } + } +} + +impl ByteOrder for LittleEndian { + #[inline] + fn read_u16(buf: &[u8]) -> u16 { + u16::from_le_bytes(buf[..2].try_into().unwrap()) + } + + #[inline] + fn read_u32(buf: &[u8]) -> u32 { + u32::from_le_bytes(buf[..4].try_into().unwrap()) + } + + #[inline] + fn read_u64(buf: &[u8]) -> u64 { + u64::from_le_bytes(buf[..8].try_into().unwrap()) + } + + #[inline] + fn read_u128(buf: &[u8]) -> u128 { + u128::from_le_bytes(buf[..16].try_into().unwrap()) + } + + #[inline] + fn read_uint(buf: &[u8], nbytes: usize) -> u64 { + let mut out = [0; 8]; + assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); + out[..nbytes].copy_from_slice(&buf[..nbytes]); + u64::from_le_bytes(out) + } + + #[inline] + fn read_uint128(buf: &[u8], nbytes: usize) -> u128 { + let mut out = [0; 16]; + assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); + out[..nbytes].copy_from_slice(&buf[..nbytes]); + u128::from_le_bytes(out) + } + + #[inline] + fn write_u16(buf: &mut [u8], n: u16) { + buf[..2].copy_from_slice(&n.to_le_bytes()); + } + + #[inline] + fn write_u32(buf: &mut [u8], n: u32) { + buf[..4].copy_from_slice(&n.to_le_bytes()); + } + + #[inline] + fn write_u64(buf: &mut [u8], n: u64) { + buf[..8].copy_from_slice(&n.to_le_bytes()); + } + + #[inline] + fn write_u128(buf: &mut [u8], n: u128) { + buf[..16].copy_from_slice(&n.to_le_bytes()); + } + + #[inline] + fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) { + assert!(pack_size(n as u64) <= nbytes && nbytes <= 8); + assert!(nbytes <= buf.len()); + unsafe { + let bytes = *(&n.to_le() as *const u64 as *const [u8; 8]); + copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes); + } + } + + #[inline] + fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) { + assert!(pack_size128(n as u128) <= nbytes && nbytes <= 16); + assert!(nbytes <= buf.len()); + unsafe { + let bytes = *(&n.to_le() as *const u128 as *const [u8; 16]); + copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes); + } + } + + #[inline] + fn read_u16_into(src: &[u8], dst: &mut [u16]) { + read_slice!(src, dst, u16, from_le_bytes); + } + + #[inline] + fn read_u32_into(src: &[u8], dst: &mut [u32]) { + read_slice!(src, dst, u32, from_le_bytes); + } + + #[inline] + fn read_u64_into(src: &[u8], dst: &mut [u64]) { + read_slice!(src, dst, u64, from_le_bytes); + } + + #[inline] + fn read_u128_into(src: &[u8], dst: &mut [u128]) { + read_slice!(src, dst, u128, from_le_bytes); + } + + #[inline] + fn write_u16_into(src: &[u16], dst: &mut [u8]) { + write_slice!(src, dst, u16, to_le_bytes); + } + + #[inline] + fn write_u32_into(src: &[u32], dst: &mut [u8]) { + write_slice!(src, dst, u32, to_le_bytes); + } + + #[inline] + fn write_u64_into(src: &[u64], dst: &mut [u8]) { + write_slice!(src, dst, u64, to_le_bytes); + } + + #[inline] + fn write_u128_into(src: &[u128], dst: &mut [u8]) { + write_slice!(src, dst, u128, to_le_bytes); + } + + #[inline] + fn from_slice_u16(numbers: &mut [u16]) { + if cfg!(target_endian = "big") { + for n in numbers { + *n = n.to_le(); + } + } + } + + #[inline] + fn from_slice_u32(numbers: &mut [u32]) { + if cfg!(target_endian = "big") { + for n in numbers { + *n = n.to_le(); + } + } + } + + #[inline] + fn from_slice_u64(numbers: &mut [u64]) { + if cfg!(target_endian = "big") { + for n in numbers { + *n = n.to_le(); + } + } + } + + #[inline] + fn from_slice_u128(numbers: &mut [u128]) { + if cfg!(target_endian = "big") { + for n in numbers { + *n = n.to_le(); + } + } + } + + #[inline] + fn from_slice_f32(numbers: &mut [f32]) { + if cfg!(target_endian = "big") { + for n in numbers { + unsafe { + let int = *(n as *const f32 as *const u32); + *n = *(&int.to_le() as *const u32 as *const f32); + } + } + } + } + + #[inline] + fn from_slice_f64(numbers: &mut [f64]) { + if cfg!(target_endian = "big") { + for n in numbers { + unsafe { + let int = *(n as *const f64 as *const u64); + *n = *(&int.to_le() as *const u64 as *const f64); + } + } + } + } +} + +#[cfg(test)] +mod test { + use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen, Testable}; + use rand::{thread_rng, Rng}; + + pub const U24_MAX: u32 = 16_777_215; + pub const I24_MAX: i32 = 8_388_607; + pub const U48_MAX: u64 = 281_474_976_710_655; + pub const I48_MAX: i64 = 140_737_488_355_327; + + pub const U64_MAX: u64 = ::core::u64::MAX; + pub const I64_MAX: u64 = ::core::i64::MAX as u64; + + macro_rules! calc_max { + ($max:expr, $bytes:expr) => { + calc_max!($max, $bytes, 8) + }; + ($max:expr, $bytes:expr, $maxbytes:expr) => { + ($max - 1) >> (8 * ($maxbytes - $bytes)) + }; + } + + #[derive(Clone, Debug)] + pub struct Wi128(pub T); + + impl Wi128 { + pub fn clone(&self) -> T { + self.0.clone() + } + } + + impl PartialEq for Wi128 { + fn eq(&self, other: &T) -> bool { + self.0.eq(other) + } + } + + impl Arbitrary for Wi128 { + fn arbitrary(gen: &mut G) -> Wi128 { + let max = calc_max!(::core::u128::MAX, gen.size(), 16); + let output = (gen.gen::() as u128) + | ((gen.gen::() as u128) << 64); + Wi128(output & (max - 1)) + } + } + + impl Arbitrary for Wi128 { + fn arbitrary(gen: &mut G) -> Wi128 { + let max = calc_max!(::core::i128::MAX, gen.size(), 16); + let output = (gen.gen::() as i128) + | ((gen.gen::() as i128) << 64); + Wi128(output & (max - 1)) + } + } + + pub fn qc_sized(f: A, size: u64) { + QuickCheck::new() + .gen(StdGen::new(thread_rng(), size as usize)) + .tests(1_00) + .max_tests(10_000) + .quickcheck(f); + } + + macro_rules! qc_byte_order { + ($name:ident, $ty_int:ty, $max:expr, + $bytes:expr, $read:ident, $write:ident) => { + #[cfg(not(miri))] + mod $name { + #[allow(unused_imports)] + use super::{qc_sized, Wi128}; + use crate::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + + #[test] + fn big_endian() { + fn prop(n: $ty_int) -> bool { + let mut buf = [0; 16]; + BigEndian::$write(&mut buf, n.clone(), $bytes); + n == BigEndian::$read(&buf[..$bytes], $bytes) + } + qc_sized(prop as fn($ty_int) -> bool, $max); + } + + #[test] + fn little_endian() { + fn prop(n: $ty_int) -> bool { + let mut buf = [0; 16]; + LittleEndian::$write(&mut buf, n.clone(), $bytes); + n == LittleEndian::$read(&buf[..$bytes], $bytes) + } + qc_sized(prop as fn($ty_int) -> bool, $max); + } + + #[test] + fn native_endian() { + fn prop(n: $ty_int) -> bool { + let mut buf = [0; 16]; + NativeEndian::$write(&mut buf, n.clone(), $bytes); + n == NativeEndian::$read(&buf[..$bytes], $bytes) + } + qc_sized(prop as fn($ty_int) -> bool, $max); + } + } + }; + ($name:ident, $ty_int:ty, $max:expr, + $read:ident, $write:ident) => { + #[cfg(not(miri))] + mod $name { + #[allow(unused_imports)] + use super::{qc_sized, Wi128}; + use crate::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + use core::mem::size_of; + + #[test] + fn big_endian() { + fn prop(n: $ty_int) -> bool { + let bytes = size_of::<$ty_int>(); + let mut buf = [0; 16]; + BigEndian::$write(&mut buf[16 - bytes..], n.clone()); + n == BigEndian::$read(&buf[16 - bytes..]) + } + qc_sized(prop as fn($ty_int) -> bool, $max - 1); + } + + #[test] + fn little_endian() { + fn prop(n: $ty_int) -> bool { + let bytes = size_of::<$ty_int>(); + let mut buf = [0; 16]; + LittleEndian::$write(&mut buf[..bytes], n.clone()); + n == LittleEndian::$read(&buf[..bytes]) + } + qc_sized(prop as fn($ty_int) -> bool, $max - 1); + } + + #[test] + fn native_endian() { + fn prop(n: $ty_int) -> bool { + let bytes = size_of::<$ty_int>(); + let mut buf = [0; 16]; + NativeEndian::$write(&mut buf[..bytes], n.clone()); + n == NativeEndian::$read(&buf[..bytes]) + } + qc_sized(prop as fn($ty_int) -> bool, $max - 1); + } + } + }; + } + + qc_byte_order!( + prop_u16, + u16, + ::core::u16::MAX as u64, + read_u16, + write_u16 + ); + qc_byte_order!( + prop_i16, + i16, + ::core::i16::MAX as u64, + read_i16, + write_i16 + ); + qc_byte_order!( + prop_u24, + u32, + crate::test::U24_MAX as u64, + read_u24, + write_u24 + ); + qc_byte_order!( + prop_i24, + i32, + crate::test::I24_MAX as u64, + read_i24, + write_i24 + ); + qc_byte_order!( + prop_u32, + u32, + ::core::u32::MAX as u64, + read_u32, + write_u32 + ); + qc_byte_order!( + prop_i32, + i32, + ::core::i32::MAX as u64, + read_i32, + write_i32 + ); + qc_byte_order!( + prop_u48, + u64, + crate::test::U48_MAX as u64, + read_u48, + write_u48 + ); + qc_byte_order!( + prop_i48, + i64, + crate::test::I48_MAX as u64, + read_i48, + write_i48 + ); + qc_byte_order!( + prop_u64, + u64, + ::core::u64::MAX as u64, + read_u64, + write_u64 + ); + qc_byte_order!( + prop_i64, + i64, + ::core::i64::MAX as u64, + read_i64, + write_i64 + ); + qc_byte_order!( + prop_f32, + f32, + ::core::u64::MAX as u64, + read_f32, + write_f32 + ); + qc_byte_order!( + prop_f64, + f64, + ::core::i64::MAX as u64, + read_f64, + write_f64 + ); + + qc_byte_order!(prop_u128, Wi128, 16 + 1, read_u128, write_u128); + qc_byte_order!(prop_i128, Wi128, 16 + 1, read_i128, write_i128); + + qc_byte_order!( + prop_uint_1, + u64, + calc_max!(super::U64_MAX, 1), + 1, + read_uint, + write_uint + ); + qc_byte_order!( + prop_uint_2, + u64, + calc_max!(super::U64_MAX, 2), + 2, + read_uint, + write_uint + ); + qc_byte_order!( + prop_uint_3, + u64, + calc_max!(super::U64_MAX, 3), + 3, + read_uint, + write_uint + ); + qc_byte_order!( + prop_uint_4, + u64, + calc_max!(super::U64_MAX, 4), + 4, + read_uint, + write_uint + ); + qc_byte_order!( + prop_uint_5, + u64, + calc_max!(super::U64_MAX, 5), + 5, + read_uint, + write_uint + ); + qc_byte_order!( + prop_uint_6, + u64, + calc_max!(super::U64_MAX, 6), + 6, + read_uint, + write_uint + ); + qc_byte_order!( + prop_uint_7, + u64, + calc_max!(super::U64_MAX, 7), + 7, + read_uint, + write_uint + ); + qc_byte_order!( + prop_uint_8, + u64, + calc_max!(super::U64_MAX, 8), + 8, + read_uint, + write_uint + ); + + qc_byte_order!( + prop_uint128_1, + Wi128, + 1, + 1, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_2, + Wi128, + 2, + 2, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_3, + Wi128, + 3, + 3, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_4, + Wi128, + 4, + 4, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_5, + Wi128, + 5, + 5, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_6, + Wi128, + 6, + 6, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_7, + Wi128, + 7, + 7, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_8, + Wi128, + 8, + 8, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_9, + Wi128, + 9, + 9, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_10, + Wi128, + 10, + 10, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_11, + Wi128, + 11, + 11, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_12, + Wi128, + 12, + 12, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_13, + Wi128, + 13, + 13, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_14, + Wi128, + 14, + 14, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_15, + Wi128, + 15, + 15, + read_uint128, + write_uint128 + ); + qc_byte_order!( + prop_uint128_16, + Wi128, + 16, + 16, + read_uint128, + write_uint128 + ); + + qc_byte_order!( + prop_int_1, + i64, + calc_max!(super::I64_MAX, 1), + 1, + read_int, + write_int + ); + qc_byte_order!( + prop_int_2, + i64, + calc_max!(super::I64_MAX, 2), + 2, + read_int, + write_int + ); + qc_byte_order!( + prop_int_3, + i64, + calc_max!(super::I64_MAX, 3), + 3, + read_int, + write_int + ); + qc_byte_order!( + prop_int_4, + i64, + calc_max!(super::I64_MAX, 4), + 4, + read_int, + write_int + ); + qc_byte_order!( + prop_int_5, + i64, + calc_max!(super::I64_MAX, 5), + 5, + read_int, + write_int + ); + qc_byte_order!( + prop_int_6, + i64, + calc_max!(super::I64_MAX, 6), + 6, + read_int, + write_int + ); + qc_byte_order!( + prop_int_7, + i64, + calc_max!(super::I64_MAX, 7), + 7, + read_int, + write_int + ); + qc_byte_order!( + prop_int_8, + i64, + calc_max!(super::I64_MAX, 8), + 8, + read_int, + write_int + ); + + qc_byte_order!( + prop_int128_1, + Wi128, + 1, + 1, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_2, + Wi128, + 2, + 2, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_3, + Wi128, + 3, + 3, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_4, + Wi128, + 4, + 4, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_5, + Wi128, + 5, + 5, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_6, + Wi128, + 6, + 6, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_7, + Wi128, + 7, + 7, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_8, + Wi128, + 8, + 8, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_9, + Wi128, + 9, + 9, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_10, + Wi128, + 10, + 10, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_11, + Wi128, + 11, + 11, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_12, + Wi128, + 12, + 12, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_13, + Wi128, + 13, + 13, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_14, + Wi128, + 14, + 14, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_15, + Wi128, + 15, + 15, + read_int128, + write_int128 + ); + qc_byte_order!( + prop_int128_16, + Wi128, + 16, + 16, + read_int128, + write_int128 + ); + + // Test that all of the byte conversion functions panic when given a + // buffer that is too small. + // + // These tests are critical to ensure safety, otherwise we might end up + // with a buffer overflow. + macro_rules! too_small { + ($name:ident, $maximally_small:expr, $zero:expr, + $read:ident, $write:ident) => { + mod $name { + use crate::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + + #[test] + #[should_panic] + fn read_big_endian() { + let buf = [0; $maximally_small]; + BigEndian::$read(&buf); + } + + #[test] + #[should_panic] + fn read_little_endian() { + let buf = [0; $maximally_small]; + LittleEndian::$read(&buf); + } + + #[test] + #[should_panic] + fn read_native_endian() { + let buf = [0; $maximally_small]; + NativeEndian::$read(&buf); + } + + #[test] + #[should_panic] + fn write_big_endian() { + let mut buf = [0; $maximally_small]; + BigEndian::$write(&mut buf, $zero); + } + + #[test] + #[should_panic] + fn write_little_endian() { + let mut buf = [0; $maximally_small]; + LittleEndian::$write(&mut buf, $zero); + } + + #[test] + #[should_panic] + fn write_native_endian() { + let mut buf = [0; $maximally_small]; + NativeEndian::$write(&mut buf, $zero); + } + } + }; + ($name:ident, $maximally_small:expr, $read:ident) => { + mod $name { + use crate::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + + #[test] + #[should_panic] + fn read_big_endian() { + let buf = [0; $maximally_small]; + BigEndian::$read(&buf, $maximally_small + 1); + } + + #[test] + #[should_panic] + fn read_little_endian() { + let buf = [0; $maximally_small]; + LittleEndian::$read(&buf, $maximally_small + 1); + } + + #[test] + #[should_panic] + fn read_native_endian() { + let buf = [0; $maximally_small]; + NativeEndian::$read(&buf, $maximally_small + 1); + } + } + }; + } + + too_small!(small_u16, 1, 0, read_u16, write_u16); + too_small!(small_i16, 1, 0, read_i16, write_i16); + too_small!(small_u32, 3, 0, read_u32, write_u32); + too_small!(small_i32, 3, 0, read_i32, write_i32); + too_small!(small_u64, 7, 0, read_u64, write_u64); + too_small!(small_i64, 7, 0, read_i64, write_i64); + too_small!(small_f32, 3, 0.0, read_f32, write_f32); + too_small!(small_f64, 7, 0.0, read_f64, write_f64); + too_small!(small_u128, 15, 0, read_u128, write_u128); + too_small!(small_i128, 15, 0, read_i128, write_i128); + + too_small!(small_uint_1, 1, read_uint); + too_small!(small_uint_2, 2, read_uint); + too_small!(small_uint_3, 3, read_uint); + too_small!(small_uint_4, 4, read_uint); + too_small!(small_uint_5, 5, read_uint); + too_small!(small_uint_6, 6, read_uint); + too_small!(small_uint_7, 7, read_uint); + + too_small!(small_uint128_1, 1, read_uint128); + too_small!(small_uint128_2, 2, read_uint128); + too_small!(small_uint128_3, 3, read_uint128); + too_small!(small_uint128_4, 4, read_uint128); + too_small!(small_uint128_5, 5, read_uint128); + too_small!(small_uint128_6, 6, read_uint128); + too_small!(small_uint128_7, 7, read_uint128); + too_small!(small_uint128_8, 8, read_uint128); + too_small!(small_uint128_9, 9, read_uint128); + too_small!(small_uint128_10, 10, read_uint128); + too_small!(small_uint128_11, 11, read_uint128); + too_small!(small_uint128_12, 12, read_uint128); + too_small!(small_uint128_13, 13, read_uint128); + too_small!(small_uint128_14, 14, read_uint128); + too_small!(small_uint128_15, 15, read_uint128); + + too_small!(small_int_1, 1, read_int); + too_small!(small_int_2, 2, read_int); + too_small!(small_int_3, 3, read_int); + too_small!(small_int_4, 4, read_int); + too_small!(small_int_5, 5, read_int); + too_small!(small_int_6, 6, read_int); + too_small!(small_int_7, 7, read_int); + + too_small!(small_int128_1, 1, read_int128); + too_small!(small_int128_2, 2, read_int128); + too_small!(small_int128_3, 3, read_int128); + too_small!(small_int128_4, 4, read_int128); + too_small!(small_int128_5, 5, read_int128); + too_small!(small_int128_6, 6, read_int128); + too_small!(small_int128_7, 7, read_int128); + too_small!(small_int128_8, 8, read_int128); + too_small!(small_int128_9, 9, read_int128); + too_small!(small_int128_10, 10, read_int128); + too_small!(small_int128_11, 11, read_int128); + too_small!(small_int128_12, 12, read_int128); + too_small!(small_int128_13, 13, read_int128); + too_small!(small_int128_14, 14, read_int128); + too_small!(small_int128_15, 15, read_int128); + + // Test that reading/writing slices enforces the correct lengths. + macro_rules! slice_lengths { + ($name:ident, $read:ident, $write:ident, + $num_bytes:expr, $numbers:expr) => { + mod $name { + use crate::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + + #[test] + #[should_panic] + fn read_big_endian() { + let bytes = [0; $num_bytes]; + let mut numbers = $numbers; + BigEndian::$read(&bytes, &mut numbers); + } + + #[test] + #[should_panic] + fn read_little_endian() { + let bytes = [0; $num_bytes]; + let mut numbers = $numbers; + LittleEndian::$read(&bytes, &mut numbers); + } + + #[test] + #[should_panic] + fn read_native_endian() { + let bytes = [0; $num_bytes]; + let mut numbers = $numbers; + NativeEndian::$read(&bytes, &mut numbers); + } + + #[test] + #[should_panic] + fn write_big_endian() { + let mut bytes = [0; $num_bytes]; + let numbers = $numbers; + BigEndian::$write(&numbers, &mut bytes); + } + + #[test] + #[should_panic] + fn write_little_endian() { + let mut bytes = [0; $num_bytes]; + let numbers = $numbers; + LittleEndian::$write(&numbers, &mut bytes); + } + + #[test] + #[should_panic] + fn write_native_endian() { + let mut bytes = [0; $num_bytes]; + let numbers = $numbers; + NativeEndian::$write(&numbers, &mut bytes); + } + } + }; + } + + slice_lengths!( + slice_len_too_small_u16, + read_u16_into, + write_u16_into, + 3, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_u16, + read_u16_into, + write_u16_into, + 5, + [0, 0] + ); + slice_lengths!( + slice_len_too_small_i16, + read_i16_into, + write_i16_into, + 3, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_i16, + read_i16_into, + write_i16_into, + 5, + [0, 0] + ); + + slice_lengths!( + slice_len_too_small_u32, + read_u32_into, + write_u32_into, + 7, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_u32, + read_u32_into, + write_u32_into, + 9, + [0, 0] + ); + slice_lengths!( + slice_len_too_small_i32, + read_i32_into, + write_i32_into, + 7, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_i32, + read_i32_into, + write_i32_into, + 9, + [0, 0] + ); + + slice_lengths!( + slice_len_too_small_u64, + read_u64_into, + write_u64_into, + 15, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_u64, + read_u64_into, + write_u64_into, + 17, + [0, 0] + ); + slice_lengths!( + slice_len_too_small_i64, + read_i64_into, + write_i64_into, + 15, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_i64, + read_i64_into, + write_i64_into, + 17, + [0, 0] + ); + + slice_lengths!( + slice_len_too_small_u128, + read_u128_into, + write_u128_into, + 31, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_u128, + read_u128_into, + write_u128_into, + 33, + [0, 0] + ); + slice_lengths!( + slice_len_too_small_i128, + read_i128_into, + write_i128_into, + 31, + [0, 0] + ); + slice_lengths!( + slice_len_too_big_i128, + read_i128_into, + write_i128_into, + 33, + [0, 0] + ); + + #[test] + fn uint_bigger_buffer() { + use crate::{ByteOrder, LittleEndian}; + let n = LittleEndian::read_uint(&[1, 2, 3, 4, 5, 6, 7, 8], 5); + assert_eq!(n, 0x05_0403_0201); + } + + #[test] + fn regression173_array_impl() { + use crate::{BigEndian, ByteOrder, LittleEndian}; + + let xs = [0; 100]; + + let x = BigEndian::read_u16(&xs); + assert_eq!(x, 0); + let x = BigEndian::read_u32(&xs); + assert_eq!(x, 0); + let x = BigEndian::read_u64(&xs); + assert_eq!(x, 0); + let x = BigEndian::read_u128(&xs); + assert_eq!(x, 0); + let x = BigEndian::read_i16(&xs); + assert_eq!(x, 0); + let x = BigEndian::read_i32(&xs); + assert_eq!(x, 0); + let x = BigEndian::read_i64(&xs); + assert_eq!(x, 0); + let x = BigEndian::read_i128(&xs); + assert_eq!(x, 0); + + let x = LittleEndian::read_u16(&xs); + assert_eq!(x, 0); + let x = LittleEndian::read_u32(&xs); + assert_eq!(x, 0); + let x = LittleEndian::read_u64(&xs); + assert_eq!(x, 0); + let x = LittleEndian::read_u128(&xs); + assert_eq!(x, 0); + let x = LittleEndian::read_i16(&xs); + assert_eq!(x, 0); + let x = LittleEndian::read_i32(&xs); + assert_eq!(x, 0); + let x = LittleEndian::read_i64(&xs); + assert_eq!(x, 0); + let x = LittleEndian::read_i128(&xs); + assert_eq!(x, 0); + } +} + +#[cfg(test)] +#[cfg(feature = "std")] +mod stdtests { + extern crate quickcheck; + extern crate rand; + + use self::quickcheck::{QuickCheck, StdGen, Testable}; + use self::rand::thread_rng; + + fn qc_unsized(f: A) { + QuickCheck::new() + .gen(StdGen::new(thread_rng(), 16)) + .tests(1_00) + .max_tests(10_000) + .quickcheck(f); + } + + macro_rules! calc_max { + ($max:expr, $bytes:expr) => { + ($max - 1) >> (8 * (8 - $bytes)) + }; + } + + macro_rules! qc_bytes_ext { + ($name:ident, $ty_int:ty, $max:expr, + $bytes:expr, $read:ident, $write:ident) => { + #[cfg(not(miri))] + mod $name { + #[allow(unused_imports)] + use crate::test::{qc_sized, Wi128}; + use crate::{ + BigEndian, LittleEndian, NativeEndian, ReadBytesExt, + WriteBytesExt, + }; + use std::io::Cursor; + + #[test] + fn big_endian() { + fn prop(n: $ty_int) -> bool { + let mut wtr = vec![]; + wtr.$write::(n.clone()).unwrap(); + let offset = wtr.len() - $bytes; + let mut rdr = Cursor::new(&mut wtr[offset..]); + n == rdr.$read::($bytes).unwrap() + } + qc_sized(prop as fn($ty_int) -> bool, $max); + } + + #[test] + fn little_endian() { + fn prop(n: $ty_int) -> bool { + let mut wtr = vec![]; + wtr.$write::(n.clone()).unwrap(); + let mut rdr = Cursor::new(wtr); + n == rdr.$read::($bytes).unwrap() + } + qc_sized(prop as fn($ty_int) -> bool, $max); + } + + #[test] + fn native_endian() { + fn prop(n: $ty_int) -> bool { + let mut wtr = vec![]; + wtr.$write::(n.clone()).unwrap(); + let offset = if cfg!(target_endian = "big") { + wtr.len() - $bytes + } else { + 0 + }; + let mut rdr = Cursor::new(&mut wtr[offset..]); + n == rdr.$read::($bytes).unwrap() + } + qc_sized(prop as fn($ty_int) -> bool, $max); + } + } + }; + ($name:ident, $ty_int:ty, $max:expr, $read:ident, $write:ident) => { + #[cfg(not(miri))] + mod $name { + #[allow(unused_imports)] + use crate::test::{qc_sized, Wi128}; + use crate::{ + BigEndian, LittleEndian, NativeEndian, ReadBytesExt, + WriteBytesExt, + }; + use std::io::Cursor; + + #[test] + fn big_endian() { + fn prop(n: $ty_int) -> bool { + let mut wtr = vec![]; + wtr.$write::(n.clone()).unwrap(); + let mut rdr = Cursor::new(wtr); + n == rdr.$read::().unwrap() + } + qc_sized(prop as fn($ty_int) -> bool, $max - 1); + } + + #[test] + fn little_endian() { + fn prop(n: $ty_int) -> bool { + let mut wtr = vec![]; + wtr.$write::(n.clone()).unwrap(); + let mut rdr = Cursor::new(wtr); + n == rdr.$read::().unwrap() + } + qc_sized(prop as fn($ty_int) -> bool, $max - 1); + } + + #[test] + fn native_endian() { + fn prop(n: $ty_int) -> bool { + let mut wtr = vec![]; + wtr.$write::(n.clone()).unwrap(); + let mut rdr = Cursor::new(wtr); + n == rdr.$read::().unwrap() + } + qc_sized(prop as fn($ty_int) -> bool, $max - 1); + } + } + }; + } + + qc_bytes_ext!( + prop_ext_u16, + u16, + ::std::u16::MAX as u64, + read_u16, + write_u16 + ); + qc_bytes_ext!( + prop_ext_i16, + i16, + ::std::i16::MAX as u64, + read_i16, + write_i16 + ); + qc_bytes_ext!( + prop_ext_u32, + u32, + ::std::u32::MAX as u64, + read_u32, + write_u32 + ); + qc_bytes_ext!( + prop_ext_i32, + i32, + ::std::i32::MAX as u64, + read_i32, + write_i32 + ); + qc_bytes_ext!( + prop_ext_u64, + u64, + ::std::u64::MAX as u64, + read_u64, + write_u64 + ); + qc_bytes_ext!( + prop_ext_i64, + i64, + ::std::i64::MAX as u64, + read_i64, + write_i64 + ); + qc_bytes_ext!( + prop_ext_f32, + f32, + ::std::u64::MAX as u64, + read_f32, + write_f32 + ); + qc_bytes_ext!( + prop_ext_f64, + f64, + ::std::i64::MAX as u64, + read_f64, + write_f64 + ); + + qc_bytes_ext!(prop_ext_u128, Wi128, 16 + 1, read_u128, write_u128); + qc_bytes_ext!(prop_ext_i128, Wi128, 16 + 1, read_i128, write_i128); + + qc_bytes_ext!( + prop_ext_uint_1, + u64, + calc_max!(crate::test::U64_MAX, 1), + 1, + read_uint, + write_u64 + ); + qc_bytes_ext!( + prop_ext_uint_2, + u64, + calc_max!(crate::test::U64_MAX, 2), + 2, + read_uint, + write_u64 + ); + qc_bytes_ext!( + prop_ext_uint_3, + u64, + calc_max!(crate::test::U64_MAX, 3), + 3, + read_uint, + write_u64 + ); + qc_bytes_ext!( + prop_ext_uint_4, + u64, + calc_max!(crate::test::U64_MAX, 4), + 4, + read_uint, + write_u64 + ); + qc_bytes_ext!( + prop_ext_uint_5, + u64, + calc_max!(crate::test::U64_MAX, 5), + 5, + read_uint, + write_u64 + ); + qc_bytes_ext!( + prop_ext_uint_6, + u64, + calc_max!(crate::test::U64_MAX, 6), + 6, + read_uint, + write_u64 + ); + qc_bytes_ext!( + prop_ext_uint_7, + u64, + calc_max!(crate::test::U64_MAX, 7), + 7, + read_uint, + write_u64 + ); + qc_bytes_ext!( + prop_ext_uint_8, + u64, + calc_max!(crate::test::U64_MAX, 8), + 8, + read_uint, + write_u64 + ); + + qc_bytes_ext!( + prop_ext_uint128_1, + Wi128, + 1, + 1, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_2, + Wi128, + 2, + 2, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_3, + Wi128, + 3, + 3, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_4, + Wi128, + 4, + 4, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_5, + Wi128, + 5, + 5, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_6, + Wi128, + 6, + 6, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_7, + Wi128, + 7, + 7, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_8, + Wi128, + 8, + 8, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_9, + Wi128, + 9, + 9, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_10, + Wi128, + 10, + 10, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_11, + Wi128, + 11, + 11, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_12, + Wi128, + 12, + 12, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_13, + Wi128, + 13, + 13, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_14, + Wi128, + 14, + 14, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_15, + Wi128, + 15, + 15, + read_uint128, + write_u128 + ); + qc_bytes_ext!( + prop_ext_uint128_16, + Wi128, + 16, + 16, + read_uint128, + write_u128 + ); + + qc_bytes_ext!( + prop_ext_int_1, + i64, + calc_max!(crate::test::I64_MAX, 1), + 1, + read_int, + write_i64 + ); + qc_bytes_ext!( + prop_ext_int_2, + i64, + calc_max!(crate::test::I64_MAX, 2), + 2, + read_int, + write_i64 + ); + qc_bytes_ext!( + prop_ext_int_3, + i64, + calc_max!(crate::test::I64_MAX, 3), + 3, + read_int, + write_i64 + ); + qc_bytes_ext!( + prop_ext_int_4, + i64, + calc_max!(crate::test::I64_MAX, 4), + 4, + read_int, + write_i64 + ); + qc_bytes_ext!( + prop_ext_int_5, + i64, + calc_max!(crate::test::I64_MAX, 5), + 5, + read_int, + write_i64 + ); + qc_bytes_ext!( + prop_ext_int_6, + i64, + calc_max!(crate::test::I64_MAX, 6), + 6, + read_int, + write_i64 + ); + qc_bytes_ext!( + prop_ext_int_7, + i64, + calc_max!(crate::test::I64_MAX, 1), + 7, + read_int, + write_i64 + ); + qc_bytes_ext!( + prop_ext_int_8, + i64, + calc_max!(crate::test::I64_MAX, 8), + 8, + read_int, + write_i64 + ); + + qc_bytes_ext!( + prop_ext_int128_1, + Wi128, + 1, + 1, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_2, + Wi128, + 2, + 2, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_3, + Wi128, + 3, + 3, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_4, + Wi128, + 4, + 4, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_5, + Wi128, + 5, + 5, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_6, + Wi128, + 6, + 6, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_7, + Wi128, + 7, + 7, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_8, + Wi128, + 8, + 8, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_9, + Wi128, + 9, + 9, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_10, + Wi128, + 10, + 10, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_11, + Wi128, + 11, + 11, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_12, + Wi128, + 12, + 12, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_13, + Wi128, + 13, + 13, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_14, + Wi128, + 14, + 14, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_15, + Wi128, + 15, + 15, + read_int128, + write_i128 + ); + qc_bytes_ext!( + prop_ext_int128_16, + Wi128, + 16, + 16, + read_int128, + write_i128 + ); + + // Test slice serialization/deserialization. + macro_rules! qc_slice { + ($name:ident, $ty_int:ty, $read:ident, $write:ident, $zero:expr) => { + #[cfg(not(miri))] + mod $name { + use super::qc_unsized; + #[allow(unused_imports)] + use crate::test::Wi128; + use crate::{ + BigEndian, ByteOrder, LittleEndian, NativeEndian, + }; + use core::mem::size_of; + + #[test] + fn big_endian() { + #[allow(unused_unsafe)] + fn prop(numbers: Vec<$ty_int>) -> bool { + let numbers: Vec<_> = + numbers.into_iter().map(|x| x.clone()).collect(); + let num_bytes = size_of::<$ty_int>() * numbers.len(); + let mut bytes = vec![0; num_bytes]; + + BigEndian::$write(&numbers, &mut bytes); + + let mut got = vec![$zero; numbers.len()]; + unsafe { + BigEndian::$read(&bytes, &mut got); + } + + numbers == got + } + qc_unsized(prop as fn(_) -> bool); + } + + #[test] + fn little_endian() { + #[allow(unused_unsafe)] + fn prop(numbers: Vec<$ty_int>) -> bool { + let numbers: Vec<_> = + numbers.into_iter().map(|x| x.clone()).collect(); + let num_bytes = size_of::<$ty_int>() * numbers.len(); + let mut bytes = vec![0; num_bytes]; + + LittleEndian::$write(&numbers, &mut bytes); + + let mut got = vec![$zero; numbers.len()]; + unsafe { + LittleEndian::$read(&bytes, &mut got); + } + + numbers == got + } + qc_unsized(prop as fn(_) -> bool); + } + + #[test] + fn native_endian() { + #[allow(unused_unsafe)] + fn prop(numbers: Vec<$ty_int>) -> bool { + let numbers: Vec<_> = + numbers.into_iter().map(|x| x.clone()).collect(); + let num_bytes = size_of::<$ty_int>() * numbers.len(); + let mut bytes = vec![0; num_bytes]; + + NativeEndian::$write(&numbers, &mut bytes); + + let mut got = vec![$zero; numbers.len()]; + unsafe { + NativeEndian::$read(&bytes, &mut got); + } + + numbers == got + } + qc_unsized(prop as fn(_) -> bool); + } + } + }; + } + + qc_slice!(prop_slice_u16, u16, read_u16_into, write_u16_into, 0); + qc_slice!(prop_slice_i16, i16, read_i16_into, write_i16_into, 0); + qc_slice!(prop_slice_u32, u32, read_u32_into, write_u32_into, 0); + qc_slice!(prop_slice_i32, i32, read_i32_into, write_i32_into, 0); + qc_slice!(prop_slice_u64, u64, read_u64_into, write_u64_into, 0); + qc_slice!(prop_slice_i64, i64, read_i64_into, write_i64_into, 0); + qc_slice!( + prop_slice_u128, + Wi128, + read_u128_into, + write_u128_into, + 0 + ); + qc_slice!( + prop_slice_i128, + Wi128, + read_i128_into, + write_i128_into, + 0 + ); + + qc_slice!(prop_slice_f32, f32, read_f32_into, write_f32_into, 0.0); + qc_slice!(prop_slice_f64, f64, read_f64_into, write_f64_into, 0.0); +} diff --git a/bitbox02-bt/vendor/cc/.cargo-checksum.json b/bitbox02-bt/vendor/cc/.cargo-checksum.json new file mode 100644 index 0000000..75fb5fd --- /dev/null +++ b/bitbox02-bt/vendor/cc/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"15b6678ed98a5b8147503ba41ce151a8a0df7f0f3c2783a2ca40f7b88895d879","Cargo.toml":"2864ed366d73395a77ce7a0b4f9b4f2b89e4ee300dcd87c7a18351fbf95d6035","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"f1ddbede208a5b78333a25dac0a7598e678e9b601a7d99a791069bddaf180dfe","clippy.toml":"aa7850db4350883c8f373bd0d6b4d19bf3b75f13c1c238e24368c109cb52fb1d","src/command_helpers.rs":"63742844930bd693e029fa93b734d21c64453c1d9c58f792b3363b28a4c0e86d","src/detect_compiler_family.c":"97ca4b021495611e828becea6187add37414186a16dfedd26c2947cbce6e8b2f","src/lib.rs":"3a221d45e2e587e26f38b865dddb186194ae3f6e59a2bc49b48089655ba70b22","src/parallel/async_executor.rs":"4ce24435fff6b6555b43fee042c16bd65d4150d0346567f246b9190d85b45983","src/parallel/job_token.rs":"f4ed0a03d89a42bfd5527133d12b267af519b745f3f2b997ed293df15a2641b8","src/parallel/mod.rs":"55fb4c2d15e66677b2ed5ffa6d65ea161bcf1a1e1dc7910ee3bde06f2f67ab14","src/parallel/once_lock.rs":"d13e4cb82d6bca3297ca8671d83a40dd5affd7ac89191d733dd451867181bb02","src/parallel/stderr.rs":"74384d41198740a6fce0877f144262db09fb091225fa8fbfa771314bb11487c6","src/target_info.rs":"447d3083f24e10fe4c449925b349b3d14ab2ff103c0d9f942ea9b581873442e1","src/tempfile.rs":"ebafb5b0e5d08b0706916ed911d4245240e60c3e2d0c9a1630c520842988a2b3","src/tool.rs":"2e6550062e021f2b394388172bbb01e86fe6a94d2395bcb3c85a9e86690da1a9","src/utilities.rs":"a13bb0a351fcef72823485b1b5dc4f514c533fa4feac95deb66ed9e5fbfe7b53","src/windows/com.rs":"a2800ddb81215fff2bf618336f5c4ff8e8bdb746dd18b795873c7304b3f2a5e3","src/windows/find_tools.rs":"dd6b2450909cd8334a2aa2ce856bcc72a9654d92422267d6345d5fabfcbf57c5","src/windows/mod.rs":"34cfa201cfbcac7ccaa3ea5295d3e4200439af3cc5c6433baf81502596040a89","src/windows/registry.rs":"c521b72c825e8095843e73482ffa810ed066ad8bb9f86e6db0c5c143c171aba1","src/windows/setup_config.rs":"754439cbab492afd44c9755abcbec1a41c9b2c358131cee2df13c0e996dbbec8","src/windows/vs_instances.rs":"946527cf8fd32c3472f6a2884dcdec290763101097334c7478f9c24c3950db6b","src/windows/winapi.rs":"250d51c1826d1a2329e9889dd9f058cfce253dbf2a678b076147c6cdb5db046c","src/windows/windows_sys.rs":"e2714c8307bfa083b9745eb0e46cadd7f98d7b88abf45a7637172019324e34b8","src/windows/windows_targets.rs":"5b4648ebc22b028caca9f4b4bf8881fe2d094b7bec217264ba2e6e2c49d1ccee"},"package":"b16803a61b81d9eabb7eae2588776c4c1e584b738ede45fdbb4c972cec1e9945"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/cc/CHANGELOG.md b/bitbox02-bt/vendor/cc/CHANGELOG.md new file mode 100644 index 0000000..b31fee5 --- /dev/null +++ b/bitbox02-bt/vendor/cc/CHANGELOG.md @@ -0,0 +1,238 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [1.1.30](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.29...cc-v1.1.30) - 2024-10-11 + +### Other + +- Don't pass -fPIC by default on wasm ([#1245](https://github.com/rust-lang/cc-rs/pull/1245)) + +## [1.1.29](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.28...cc-v1.1.29) - 2024-10-11 + +### Other + +- Regenerate target info ([#1243](https://github.com/rust-lang/cc-rs/pull/1243)) + +## [1.1.28](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.27...cc-v1.1.28) - 2024-10-06 + +### Other + +- Environment variables: For one accepting boolean, treat "0", "false" and empty env as false ([#1238](https://github.com/rust-lang/cc-rs/pull/1238)) + +## [1.1.27](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.26...cc-v1.1.27) - 2024-10-06 + +### Other + +- Revert "Use debug version of MSVC runtime library on debug ([#1231](https://github.com/rust-lang/cc-rs/pull/1231))" ([#1237](https://github.com/rust-lang/cc-rs/pull/1237)) +- Disable `CC_ENABLE_DEBUG_OUTPUT` if it is set to "0" ([#1234](https://github.com/rust-lang/cc-rs/pull/1234)) + +## [1.1.26](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.25...cc-v1.1.26) - 2024-10-06 + +### Other + +- Use debug version of MSVC runtime library on debug ([#1231](https://github.com/rust-lang/cc-rs/pull/1231)) + +## [1.1.25](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.24...cc-v1.1.25) - 2024-10-05 + +### Other + +- Remove incorrect "lib" prefixes in CXXSTDLIB doc comments ([#1228](https://github.com/rust-lang/cc-rs/pull/1228)) + +## [1.1.24](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.23...cc-v1.1.24) - 2024-10-01 + +### Other + +- Fix wasm32-wasip1-threads: shared-memory disallowed due to not compiled with 'atomics' or 'bulk-memory' features ([#1221](https://github.com/rust-lang/cc-rs/pull/1221)) +- Reduce the need for the host target triple ([#1224](https://github.com/rust-lang/cc-rs/pull/1224)) +- Add auto cancellation for CI jobs ([#1222](https://github.com/rust-lang/cc-rs/pull/1222)) + +## [1.1.23](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.22...cc-v1.1.23) - 2024-09-30 + +### Other + +- Update doc for detecting changes/upgrades of compilers ([#1218](https://github.com/rust-lang/cc-rs/pull/1218)) + +## [1.1.22](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.21...cc-v1.1.22) - 2024-09-27 + +### Other + +- Don't rerun if PATH changes ([#1215](https://github.com/rust-lang/cc-rs/pull/1215)) + +## [1.1.21](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.20...cc-v1.1.21) - 2024-09-18 + +### Other + +- disable pic for targets that end in `-none` ([#1212](https://github.com/rust-lang/cc-rs/pull/1212)) + +## [1.1.20](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.19...cc-v1.1.20) - 2024-09-17 + +### Other + +- Add buildcache as known Rust and C/C++ compiler wrapper ([#1209](https://github.com/rust-lang/cc-rs/pull/1209)) + +## [1.1.19](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.18...cc-v1.1.19) - 2024-09-15 + +### Other + +- Add support arm64e-apple-darwin ([#1207](https://github.com/rust-lang/cc-rs/pull/1207)) + +## [1.1.18](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.17...cc-v1.1.18) - 2024-09-07 + +### Other +- Fixed unsoundness in `StderrForwarder::forward_available` ([#1203](https://github.com/rust-lang/cc-rs/pull/1203)) + +## [1.1.17](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.16...cc-v1.1.17) - 2024-09-06 + +### Fixed +- fix finding toolchains when invoked by msbuild ([#1201](https://github.com/rust-lang/cc-rs/pull/1201)) + +## [1.1.16](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.15...cc-v1.1.16) - 2024-09-04 + +### Other +- Treat VxWorks wr-cc as a Gnu compiler ([#1198](https://github.com/rust-lang/cc-rs/pull/1198)) + +## [1.1.15](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.14...cc-v1.1.15) - 2024-08-26 + +### Other +- Add -mfloat-abi=hard as a default argument when using any arm/thumb-none-eabihf target ([#1194](https://github.com/rust-lang/cc-rs/pull/1194)) + +## [1.1.14](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.13...cc-v1.1.14) - 2024-08-23 + +### Other +- allow finding tools from path if VisualStudioDir is set + +## [1.1.13](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.12...cc-v1.1.13) - 2024-08-16 + +### Other +- Fix detect family: should detect emscripten as clang, closes [#1185](https://github.com/rust-lang/cc-rs/pull/1185) ([#1186](https://github.com/rust-lang/cc-rs/pull/1186)) + +## [1.1.12](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.11...cc-v1.1.12) - 2024-08-15 + +### Other +- improve docs ([#1183](https://github.com/rust-lang/cc-rs/pull/1183)) + +## [1.1.11](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.10...cc-v1.1.11) - 2024-08-14 + +### Other +- Add support for parsing shell encoded `*FLAGS` ([#1181](https://github.com/rust-lang/cc-rs/pull/1181)) +- Replace vector of tuples with BTreeMap which already is sorted and free of duplicates ([#1177](https://github.com/rust-lang/cc-rs/pull/1177)) + +## [1.1.10](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.9...cc-v1.1.10) - 2024-08-11 + +### Other +- Remap Windows targets triples to their LLVM counterparts ([#1176](https://github.com/rust-lang/cc-rs/pull/1176)) + +## [1.1.9](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.8...cc-v1.1.9) - 2024-08-11 + +### Other +- Add custom CC wrapper to the wrapper whitelist ([#1175](https://github.com/rust-lang/cc-rs/pull/1175)) + +## [1.1.8](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.7...cc-v1.1.8) - 2024-08-06 + +### Other +- Fix broken link in docs.rs ([#1173](https://github.com/rust-lang/cc-rs/pull/1173)) + +## [1.1.7](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.6...cc-v1.1.7) - 2024-07-29 + +### Other +- add `.objects` ([#1166](https://github.com/rust-lang/cc-rs/pull/1166)) + +## [1.1.6](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.5...cc-v1.1.6) - 2024-07-19 + +### Other +- Clippy fixes ([#1163](https://github.com/rust-lang/cc-rs/pull/1163)) + +## [1.1.5](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.4...cc-v1.1.5) - 2024-07-15 + +### Other +- Fix cyclic compilation: Use vendored once_cell ([#1154](https://github.com/rust-lang/cc-rs/pull/1154)) + +## [1.1.4](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.3...cc-v1.1.4) - 2024-07-14 + +### Other +- Support compiling on wasm targets (Supersede [#1068](https://github.com/rust-lang/cc-rs/pull/1068)) ([#1160](https://github.com/rust-lang/cc-rs/pull/1160)) + +## [1.1.3](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.2...cc-v1.1.3) - 2024-07-14 + +### Other +- Reduce msrv to 1.63 ([#1158](https://github.com/rust-lang/cc-rs/pull/1158)) +- Revert "Use raw-dylib for windows-sys ([#1137](https://github.com/rust-lang/cc-rs/pull/1137))" ([#1157](https://github.com/rust-lang/cc-rs/pull/1157)) +- Fix typos ([#1152](https://github.com/rust-lang/cc-rs/pull/1152)) +- Fix `doc_lazy_continuation` lints ([#1153](https://github.com/rust-lang/cc-rs/pull/1153)) + +## [1.1.2](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.1...cc-v1.1.2) - 2024-07-12 + +### Other +- Add empty `jobserver` feature. ([#1150](https://github.com/rust-lang/cc-rs/pull/1150)) + +## [1.1.1](https://github.com/rust-lang/cc-rs/compare/cc-v1.1.0...cc-v1.1.1) - 2024-07-12 + +### Other +- Fix is_flag_supported not respecting emit_rerun_if_env_changed ([#1147](https://github.com/rust-lang/cc-rs/pull/1147)) ([#1148](https://github.com/rust-lang/cc-rs/pull/1148)) + +## [1.1.0](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.106...cc-v1.1.0) - 2024-07-08 + +### Added +- add cargo_output to eliminate last vestiges of stdout pollution ([#1141](https://github.com/rust-lang/cc-rs/pull/1141)) + +## [1.0.106](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.105...cc-v1.0.106) - 2024-07-08 + +### Other +- Drop support for Visual Studio 12 (2013) ([#1046](https://github.com/rust-lang/cc-rs/pull/1046)) +- Use raw-dylib for windows-sys ([#1137](https://github.com/rust-lang/cc-rs/pull/1137)) +- Bump msrv to 1.67 ([#1143](https://github.com/rust-lang/cc-rs/pull/1143)) +- Bump msrv to 1.65 ([#1140](https://github.com/rust-lang/cc-rs/pull/1140)) +- Fix clippy warnings ([#1138](https://github.com/rust-lang/cc-rs/pull/1138)) + +## [1.0.105](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.104...cc-v1.0.105) - 2024-07-07 + +### Other +- Regenerate windows sys bindings ([#1132](https://github.com/rust-lang/cc-rs/pull/1132)) +- Fix generate-windows-sys-bindings ([#1133](https://github.com/rust-lang/cc-rs/pull/1133)) +- Fix gen-windows-sys-binding ([#1130](https://github.com/rust-lang/cc-rs/pull/1130)) +- Fix gen-windows-sys-binding ([#1127](https://github.com/rust-lang/cc-rs/pull/1127)) +- Update windows-bindgen requirement from 0.57 to 0.58 ([#1123](https://github.com/rust-lang/cc-rs/pull/1123)) + +## [1.0.104](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.103...cc-v1.0.104) - 2024-07-01 + +### Other +- Fixed link break about compile-time-requirements ([#1118](https://github.com/rust-lang/cc-rs/pull/1118)) + +## [1.0.103](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.102...cc-v1.0.103) - 2024-06-30 + +### Other +- Fix compilation for wasm: env WASI_SYSROOT should be optional ([#1114](https://github.com/rust-lang/cc-rs/pull/1114)) + +## [1.0.102](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.101...cc-v1.0.102) - 2024-06-29 + +### Other +- Fix invalid wasi targets compatibility ([#1105](https://github.com/rust-lang/cc-rs/pull/1105)) +- Speedup regenerate-target-info and regenerate-windows-sys ([#1110](https://github.com/rust-lang/cc-rs/pull/1110)) + +## [1.0.101](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.100...cc-v1.0.101) - 2024-06-25 + +### Other +- Use `Build::getenv` instead of `env::var*` in anywhere that makes sense ([#1103](https://github.com/rust-lang/cc-rs/pull/1103)) + +## [1.0.100](https://github.com/rust-lang/cc-rs/compare/cc-v1.0.99...cc-v1.0.100) - 2024-06-23 + +### Other +- Update publish.yml to use release-plz ([#1101](https://github.com/rust-lang/cc-rs/pull/1101)) +- Accept `OsStr` instead of `str` for flags ([#1100](https://github.com/rust-lang/cc-rs/pull/1100)) +- Use `dep:` syntax to avoid implicit features. ([#1099](https://github.com/rust-lang/cc-rs/pull/1099)) +- Minor clippy fixes. ([#1098](https://github.com/rust-lang/cc-rs/pull/1098)) +- Fix WASI compilation for C++ ([#1083](https://github.com/rust-lang/cc-rs/pull/1083)) +- Regenerate windows sys bindings ([#1096](https://github.com/rust-lang/cc-rs/pull/1096)) +- Rename regenerate-windows-sys to regenerate-windows-sys.yml ([#1095](https://github.com/rust-lang/cc-rs/pull/1095)) +- Create regenerate-windows-sys.yml ([#1094](https://github.com/rust-lang/cc-rs/pull/1094)) +- Update windows-bindgen requirement from 0.56 to 0.57 ([#1091](https://github.com/rust-lang/cc-rs/pull/1091)) +- Eagerly close tempfile to fix [#1082](https://github.com/rust-lang/cc-rs/pull/1082) ([#1087](https://github.com/rust-lang/cc-rs/pull/1087)) +- Output msvc.exe in the output directory ([#1090](https://github.com/rust-lang/cc-rs/pull/1090)) +- Fix clippy warnings on Windows ([#1088](https://github.com/rust-lang/cc-rs/pull/1088)) +- Don't try to free DLL on drop ([#1089](https://github.com/rust-lang/cc-rs/pull/1089)) +- Fix panic safety issue in StderrForwarder ([#1079](https://github.com/rust-lang/cc-rs/pull/1079)) diff --git a/bitbox02-bt/vendor/cc/Cargo.toml b/bitbox02-bt/vendor/cc/Cargo.toml new file mode 100644 index 0000000..ae5f2d1 --- /dev/null +++ b/bitbox02-bt/vendor/cc/Cargo.toml @@ -0,0 +1,66 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.63" +name = "cc" +version = "1.1.30" +authors = ["Alex Crichton "] +build = false +exclude = [ + "/.github", + "tests", + "src/bin", +] +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = """ +A build-time dependency for Cargo build scripts to assist in invoking the native +C compiler to compile native C code into a static archive to be linked into Rust +code. +""" +homepage = "https://github.com/rust-lang/cc-rs" +documentation = "https://docs.rs/cc" +readme = "README.md" +keywords = ["build-dependencies"] +categories = ["development-tools::build-utils"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-lang/cc-rs" + +[lib] +name = "cc" +path = "src/lib.rs" + +[dependencies.jobserver] +version = "0.1.30" +optional = true +default-features = false + +[dependencies.shlex] +version = "1.3.0" + +[dev-dependencies.tempfile] +version = "3" + +[features] +jobserver = [] +parallel = [ + "dep:libc", + "dep:jobserver", +] + +[target."cfg(unix)".dependencies.libc] +version = "0.2.62" +optional = true +default-features = false diff --git a/bitbox02-bt/vendor/cc/LICENSE-APACHE b/bitbox02-bt/vendor/cc/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/cc/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/cc/LICENSE-MIT b/bitbox02-bt/vendor/cc/LICENSE-MIT new file mode 100644 index 0000000..39e0ed6 --- /dev/null +++ b/bitbox02-bt/vendor/cc/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/cc/README.md b/bitbox02-bt/vendor/cc/README.md new file mode 100644 index 0000000..33d4bb4 --- /dev/null +++ b/bitbox02-bt/vendor/cc/README.md @@ -0,0 +1,27 @@ +# cc-rs + +A library for [Cargo build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html) +to compile a set of C/C++/assembly/CUDA files into a static archive for Cargo +to link into the crate being built. This crate does not compile code itself; +it calls out to the default compiler for the platform. This crate will +automatically detect situations such as cross compilation and +various environment variables and will build code appropriately. + +Refer to the [documentation](https://docs.rs/cc) for detailed usage instructions. + +## License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + https://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + https://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in cc-rs by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bitbox02-bt/vendor/cc/clippy.toml b/bitbox02-bt/vendor/cc/clippy.toml new file mode 100644 index 0000000..39e6cc6 --- /dev/null +++ b/bitbox02-bt/vendor/cc/clippy.toml @@ -0,0 +1,5 @@ +disallowed-methods = [ + { path = "std::env::var_os", reason = "Please use Build::getenv" }, + { path = "std::env::var", reason = "Please use Build::getenv" }, +] +doc-valid-idents = ["AppleClang", "OpenBSD", ".."] diff --git a/bitbox02-bt/vendor/cc/src/command_helpers.rs b/bitbox02-bt/vendor/cc/src/command_helpers.rs new file mode 100644 index 0000000..9f83e38 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/command_helpers.rs @@ -0,0 +1,491 @@ +//! Miscellaneous helpers for running commands + +use std::{ + collections::hash_map, + ffi::OsString, + fmt::Display, + fs, + hash::Hasher, + io::{self, Read, Write}, + path::Path, + process::{Child, ChildStderr, Command, Stdio}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, +}; + +use crate::{Error, ErrorKind, Object}; + +#[derive(Clone, Debug)] +pub(crate) struct CargoOutput { + pub(crate) metadata: bool, + pub(crate) warnings: bool, + pub(crate) debug: bool, + pub(crate) output: OutputKind, + checked_dbg_var: Arc, +} + +/// Different strategies for handling compiler output (to stdout) +#[derive(Clone, Debug)] +pub(crate) enum OutputKind { + /// Forward the output to this process' stdout ([`Stdio::inherit()`]) + Forward, + /// Discard the output ([`Stdio::null()`]) + Discard, + /// Capture the result (`[Stdio::piped()`]) + Capture, +} + +impl CargoOutput { + pub(crate) fn new() -> Self { + #[allow(clippy::disallowed_methods)] + Self { + metadata: true, + warnings: true, + output: OutputKind::Forward, + debug: match std::env::var_os("CC_ENABLE_DEBUG_OUTPUT") { + Some(v) => v != "0" && v != "false" && v != "", + None => false, + }, + checked_dbg_var: Arc::new(AtomicBool::new(false)), + } + } + + pub(crate) fn print_metadata(&self, s: &dyn Display) { + if self.metadata { + println!("{}", s); + } + } + + pub(crate) fn print_warning(&self, arg: &dyn Display) { + if self.warnings { + println!("cargo:warning={}", arg); + } + } + + pub(crate) fn print_debug(&self, arg: &dyn Display) { + if self.metadata && !self.checked_dbg_var.load(Ordering::Relaxed) { + self.checked_dbg_var.store(true, Ordering::Relaxed); + println!("cargo:rerun-if-env-changed=CC_ENABLE_DEBUG_OUTPUT"); + } + if self.debug { + println!("{}", arg); + } + } + + fn stdio_for_warnings(&self) -> Stdio { + if self.warnings { + Stdio::piped() + } else { + Stdio::null() + } + } + + fn stdio_for_output(&self) -> Stdio { + match self.output { + OutputKind::Capture => Stdio::piped(), + OutputKind::Forward => Stdio::inherit(), + OutputKind::Discard => Stdio::null(), + } + } +} + +pub(crate) struct StderrForwarder { + inner: Option<(ChildStderr, Vec)>, + #[cfg(feature = "parallel")] + is_non_blocking: bool, + #[cfg(feature = "parallel")] + bytes_available_failed: bool, + /// number of bytes buffered in inner + bytes_buffered: usize, +} + +const MIN_BUFFER_CAPACITY: usize = 100; + +impl StderrForwarder { + pub(crate) fn new(child: &mut Child) -> Self { + Self { + inner: child + .stderr + .take() + .map(|stderr| (stderr, Vec::with_capacity(MIN_BUFFER_CAPACITY))), + bytes_buffered: 0, + #[cfg(feature = "parallel")] + is_non_blocking: false, + #[cfg(feature = "parallel")] + bytes_available_failed: false, + } + } + + fn forward_available(&mut self) -> bool { + if let Some((stderr, buffer)) = self.inner.as_mut() { + loop { + // For non-blocking we check to see if there is data available, so we should try to + // read at least that much. For blocking, always read at least the minimum amount. + #[cfg(not(feature = "parallel"))] + let to_reserve = MIN_BUFFER_CAPACITY; + #[cfg(feature = "parallel")] + let to_reserve = if self.is_non_blocking && !self.bytes_available_failed { + match crate::parallel::stderr::bytes_available(stderr) { + #[cfg(windows)] + Ok(0) => break false, + #[cfg(unix)] + Ok(0) => { + // On Unix, depending on the implementation, we may sometimes get 0 in a + // loop (either there is data available or the pipe is broken), so + // continue with the non-blocking read anyway. + MIN_BUFFER_CAPACITY + } + #[cfg(windows)] + Err(_) => { + // On Windows, if we get an error then the pipe is broken, so flush + // the buffer and bail. + if !buffer.is_empty() { + write_warning(&buffer[..]); + } + self.inner = None; + break true; + } + #[cfg(unix)] + Err(_) => { + // On Unix, depending on the implementation, we may get spurious + // errors so make a note not to use bytes_available again and try + // the non-blocking read anyway. + self.bytes_available_failed = true; + MIN_BUFFER_CAPACITY + } + #[cfg(target_family = "wasm")] + Err(_) => panic!("bytes_available should always succeed on wasm"), + Ok(bytes_available) => MIN_BUFFER_CAPACITY.max(bytes_available), + } + } else { + MIN_BUFFER_CAPACITY + }; + if self.bytes_buffered + to_reserve > buffer.len() { + buffer.resize(self.bytes_buffered + to_reserve, 0); + } + + match stderr.read(&mut buffer[self.bytes_buffered..]) { + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + // No data currently, yield back. + break false; + } + Err(err) if err.kind() == std::io::ErrorKind::Interrupted => { + // Interrupted, try again. + continue; + } + Ok(bytes_read) if bytes_read != 0 => { + self.bytes_buffered += bytes_read; + let mut consumed = 0; + for line in buffer[..self.bytes_buffered].split_inclusive(|&b| b == b'\n') { + // Only forward complete lines, leave the rest in the buffer. + if let Some((b'\n', line)) = line.split_last() { + consumed += line.len() + 1; + write_warning(line); + } + } + if consumed > 0 && consumed < self.bytes_buffered { + // Remove the consumed bytes from buffer + buffer.copy_within(consumed.., 0); + } + self.bytes_buffered -= consumed; + } + res => { + // End of stream: flush remaining data and bail. + if self.bytes_buffered > 0 { + write_warning(&buffer[..self.bytes_buffered]); + } + if let Err(err) = res { + write_warning( + format!("Failed to read from child stderr: {err}").as_bytes(), + ); + } + self.inner.take(); + break true; + } + } + } + } else { + true + } + } + + #[cfg(feature = "parallel")] + pub(crate) fn set_non_blocking(&mut self) -> Result<(), Error> { + assert!(!self.is_non_blocking); + + #[cfg(unix)] + if let Some((stderr, _)) = self.inner.as_ref() { + crate::parallel::stderr::set_non_blocking(stderr)?; + } + + self.is_non_blocking = true; + Ok(()) + } + + #[cfg(feature = "parallel")] + fn forward_all(&mut self) { + while !self.forward_available() {} + } + + #[cfg(not(feature = "parallel"))] + fn forward_all(&mut self) { + let forward_result = self.forward_available(); + assert!(forward_result, "Should have consumed all data"); + } +} + +fn write_warning(line: &[u8]) { + let stdout = io::stdout(); + let mut stdout = stdout.lock(); + stdout.write_all(b"cargo:warning=").unwrap(); + stdout.write_all(line).unwrap(); + stdout.write_all(b"\n").unwrap(); +} + +fn wait_on_child( + cmd: &Command, + program: &Path, + child: &mut Child, + cargo_output: &CargoOutput, +) -> Result<(), Error> { + StderrForwarder::new(child).forward_all(); + + let status = match child.wait() { + Ok(s) => s, + Err(e) => { + return Err(Error::new( + ErrorKind::ToolExecError, + format!( + "Failed to wait on spawned child process, command {:?} with args {}: {}.", + cmd, + program.display(), + e + ), + )); + } + }; + + cargo_output.print_debug(&status); + + if status.success() { + Ok(()) + } else { + Err(Error::new( + ErrorKind::ToolExecError, + format!( + "Command {:?} with args {} did not execute successfully (status code {}).", + cmd, + program.display(), + status + ), + )) + } +} + +/// Find the destination object path for each file in the input source files, +/// and store them in the output Object. +pub(crate) fn objects_from_files(files: &[Arc], dst: &Path) -> Result, Error> { + let mut objects = Vec::with_capacity(files.len()); + for file in files { + let basename = file + .file_name() + .ok_or_else(|| { + Error::new( + ErrorKind::InvalidArgument, + "No file_name for object file path!", + ) + })? + .to_string_lossy(); + let dirname = file + .parent() + .ok_or_else(|| { + Error::new( + ErrorKind::InvalidArgument, + "No parent for object file path!", + ) + })? + .to_string_lossy(); + + // Hash the dirname. This should prevent conflicts if we have multiple + // object files with the same filename in different subfolders. + let mut hasher = hash_map::DefaultHasher::new(); + hasher.write(dirname.to_string().as_bytes()); + let obj = dst + .join(format!("{:016x}-{}", hasher.finish(), basename)) + .with_extension("o"); + + match obj.parent() { + Some(s) => fs::create_dir_all(s)?, + None => { + return Err(Error::new( + ErrorKind::InvalidArgument, + "dst is an invalid path with no parent", + )); + } + }; + + objects.push(Object::new(file.to_path_buf(), obj)); + } + + Ok(objects) +} + +pub(crate) fn run( + cmd: &mut Command, + program: impl AsRef, + cargo_output: &CargoOutput, +) -> Result<(), Error> { + let program = program.as_ref(); + + let mut child = spawn(cmd, program, cargo_output)?; + wait_on_child(cmd, program, &mut child, cargo_output) +} + +pub(crate) fn run_output( + cmd: &mut Command, + program: impl AsRef, + cargo_output: &CargoOutput, +) -> Result, Error> { + let program = program.as_ref(); + + // We specifically need the output to be captured, so override default + let mut captured_cargo_output = cargo_output.clone(); + captured_cargo_output.output = OutputKind::Capture; + let mut child = spawn(cmd, program, &captured_cargo_output)?; + + let mut stdout = vec![]; + child + .stdout + .take() + .unwrap() + .read_to_end(&mut stdout) + .unwrap(); + + // Don't care about this output, use the normal settings + wait_on_child(cmd, program, &mut child, cargo_output)?; + + Ok(stdout) +} + +pub(crate) fn spawn( + cmd: &mut Command, + program: &Path, + cargo_output: &CargoOutput, +) -> Result { + struct ResetStderr<'cmd>(&'cmd mut Command); + + impl Drop for ResetStderr<'_> { + fn drop(&mut self) { + // Reset stderr to default to release pipe_writer so that print thread will + // not block forever. + self.0.stderr(Stdio::inherit()); + } + } + + cargo_output.print_debug(&format_args!("running: {:?}", cmd)); + + let cmd = ResetStderr(cmd); + let child = cmd + .0 + .stderr(cargo_output.stdio_for_warnings()) + .stdout(cargo_output.stdio_for_output()) + .spawn(); + match child { + Ok(child) => Ok(child), + Err(ref e) if e.kind() == io::ErrorKind::NotFound => { + let extra = if cfg!(windows) { + " (see https://docs.rs/cc/latest/cc/#compile-time-requirements \ +for help)" + } else { + "" + }; + Err(Error::new( + ErrorKind::ToolNotFound, + format!( + "Failed to find tool. Is `{}` installed?{}", + program.display(), + extra + ), + )) + } + Err(e) => Err(Error::new( + ErrorKind::ToolExecError, + format!( + "Command {:?} with args {} failed to start: {:?}", + cmd.0, + program.display(), + e + ), + )), + } +} + +pub(crate) struct CmdAddOutputFileArgs { + pub(crate) cuda: bool, + pub(crate) is_assembler_msvc: bool, + pub(crate) msvc: bool, + pub(crate) clang: bool, + pub(crate) gnu: bool, + pub(crate) is_asm: bool, + pub(crate) is_arm: bool, +} + +pub(crate) fn command_add_output_file(cmd: &mut Command, dst: &Path, args: CmdAddOutputFileArgs) { + if args.is_assembler_msvc + || !(!args.msvc || args.clang || args.gnu || args.cuda || (args.is_asm && args.is_arm)) + { + let mut s = OsString::from("-Fo"); + s.push(dst); + cmd.arg(s); + } else { + cmd.arg("-o").arg(dst); + } +} + +#[cfg(feature = "parallel")] +pub(crate) fn try_wait_on_child( + cmd: &Command, + program: &Path, + child: &mut Child, + stdout: &mut dyn io::Write, + stderr_forwarder: &mut StderrForwarder, +) -> Result, Error> { + stderr_forwarder.forward_available(); + + match child.try_wait() { + Ok(Some(status)) => { + stderr_forwarder.forward_all(); + + let _ = writeln!(stdout, "{}", status); + + if status.success() { + Ok(Some(())) + } else { + Err(Error::new( + ErrorKind::ToolExecError, + format!( + "Command {:?} with args {} did not execute successfully (status code {}).", + cmd, + program.display(), + status + ), + )) + } + } + Ok(None) => Ok(None), + Err(e) => { + stderr_forwarder.forward_all(); + Err(Error::new( + ErrorKind::ToolExecError, + format!( + "Failed to wait on spawned child process, command {:?} with args {}: {}.", + cmd, + program.display(), + e + ), + )) + } + } +} diff --git a/bitbox02-bt/vendor/cc/src/detect_compiler_family.c b/bitbox02-bt/vendor/cc/src/detect_compiler_family.c new file mode 100644 index 0000000..601cee6 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/detect_compiler_family.c @@ -0,0 +1,15 @@ +#ifdef __clang__ +#pragma message "clang" +#endif + +#ifdef __GNUC__ +#pragma message "gcc" +#endif + +#ifdef __EMSCRIPTEN__ +#pragma message "emscripten" +#endif + +#ifdef __VXWORKS__ +#pragma message "VxWorks" +#endif diff --git a/bitbox02-bt/vendor/cc/src/lib.rs b/bitbox02-bt/vendor/cc/src/lib.rs new file mode 100644 index 0000000..dee607c --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/lib.rs @@ -0,0 +1,4346 @@ +//! A library for [Cargo build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html) +//! to compile a set of C/C++/assembly/CUDA files into a static archive for Cargo +//! to link into the crate being built. This crate does not compile code itself; +//! it calls out to the default compiler for the platform. This crate will +//! automatically detect situations such as cross compilation and +//! [various environment variables](#external-configuration-via-environment-variables) and will build code appropriately. +//! +//! # Example +//! +//! First, you'll want to both add a build script for your crate (`build.rs`) and +//! also add this crate to your `Cargo.toml` via: +//! +//! ```toml +//! [build-dependencies] +//! cc = "1.0" +//! ``` +//! +//! Next up, you'll want to write a build script like so: +//! +//! ```rust,no_run +//! // build.rs +//! cc::Build::new() +//! .file("foo.c") +//! .file("bar.c") +//! .compile("foo"); +//! ``` +//! +//! And that's it! Running `cargo build` should take care of the rest and your Rust +//! application will now have the C files `foo.c` and `bar.c` compiled into a file +//! named `libfoo.a`. If the C files contain +//! +//! ```c +//! void foo_function(void) { ... } +//! ``` +//! +//! and +//! +//! ```c +//! int32_t bar_function(int32_t x) { ... } +//! ``` +//! +//! you can call them from Rust by declaring them in +//! your Rust code like so: +//! +//! ```rust,no_run +//! extern "C" { +//! fn foo_function(); +//! fn bar_function(x: i32) -> i32; +//! } +//! +//! pub fn call() { +//! unsafe { +//! foo_function(); +//! bar_function(42); +//! } +//! } +//! +//! fn main() { +//! call(); +//! } +//! ``` +//! +//! See [the Rustonomicon](https://doc.rust-lang.org/nomicon/ffi.html) for more details. +//! +//! # External configuration via environment variables +//! +//! To control the programs and flags used for building, the builder can set a +//! number of different environment variables. +//! +//! * `CFLAGS` - a series of space separated flags passed to compilers. Note that +//! individual flags cannot currently contain spaces, so doing +//! something like: `-L=foo\ bar` is not possible. +//! * `CC` - the actual C compiler used. Note that this is used as an exact +//! executable name, so (for example) no extra flags can be passed inside +//! this variable, and the builder must ensure that there aren't any +//! trailing spaces. This compiler must understand the `-c` flag. For +//! certain `TARGET`s, it also is assumed to know about other flags (most +//! common is `-fPIC`). +//! * `AR` - the `ar` (archiver) executable to use to build the static library. +//! * `CRATE_CC_NO_DEFAULTS` - the default compiler flags may cause conflicts in +//! some cross compiling scenarios. Setting this variable +//! will disable the generation of default compiler +//! flags. +//! * `CC_ENABLE_DEBUG_OUTPUT` - if set, compiler command invocations and exit codes will +//! be logged to stdout. This is useful for debugging build script issues, but can be +//! overly verbose for normal use. +//! * `CC_SHELL_ESCAPED_FLAGS` - if set, `*FLAGS` will be parsed as if they were shell +//! arguments (similar to `make` and `cmake`) rather than splitting them on each space. +//! For example, with `CFLAGS='a "b c"'`, the compiler will be invoked with 2 arguments - +//! `a` and `b c` - rather than 3: `a`, `"b` and `c"`. +//! * `CXX...` - see [C++ Support](#c-support). +//! +//! Furthermore, projects using this crate may specify custom environment variables +//! to be inspected, for example via the `Build::try_flags_from_environment` +//! function. Consult the project’s own documentation or its use of the `cc` crate +//! for any additional variables it may use. +//! +//! Each of these variables can also be supplied with certain prefixes and suffixes, +//! in the following prioritized order: +//! +//! 1. `_` - for example, `CC_x86_64-unknown-linux-gnu` +//! 2. `_` - for example, `CC_x86_64_unknown_linux_gnu` +//! 3. `_` - for example, `HOST_CC` or `TARGET_CFLAGS` +//! 4. `` - a plain `CC`, `AR` as above. +//! +//! If none of these variables exist, cc-rs uses built-in defaults. +//! +//! In addition to the above optional environment variables, `cc-rs` has some +//! functions with hard requirements on some variables supplied by [cargo's +//! build-script driver][cargo] that it has the `TARGET`, `OUT_DIR`, `OPT_LEVEL`, +//! and `HOST` variables. +//! +//! [cargo]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#inputs-to-the-build-script +//! +//! # Optional features +//! +//! ## Parallel +//! +//! Currently cc-rs supports parallel compilation (think `make -jN`) but this +//! feature is turned off by default. To enable cc-rs to compile C/C++ in parallel, +//! you can change your dependency to: +//! +//! ```toml +//! [build-dependencies] +//! cc = { version = "1.0", features = ["parallel"] } +//! ``` +//! +//! By default cc-rs will limit parallelism to `$NUM_JOBS`, or if not present it +//! will limit it to the number of cpus on the machine. If you are using cargo, +//! use `-jN` option of `build`, `test` and `run` commands as `$NUM_JOBS` +//! is supplied by cargo. +//! +//! # Compile-time Requirements +//! +//! To work properly this crate needs access to a C compiler when the build script +//! is being run. This crate does not ship a C compiler with it. The compiler +//! required varies per platform, but there are three broad categories: +//! +//! * Unix platforms require `cc` to be the C compiler. This can be found by +//! installing cc/clang on Linux distributions and Xcode on macOS, for example. +//! * Windows platforms targeting MSVC (e.g. your target triple ends in `-msvc`) +//! require Visual Studio to be installed. `cc-rs` attempts to locate it, and +//! if it fails, `cl.exe` is expected to be available in `PATH`. This can be +//! set up by running the appropriate developer tools shell. +//! * Windows platforms targeting MinGW (e.g. your target triple ends in `-gnu`) +//! require `cc` to be available in `PATH`. We recommend the +//! [MinGW-w64](https://www.mingw-w64.org/) distribution. +//! You may also acquire it via +//! [MSYS2](https://www.msys2.org/), as explained [here][msys2-help]. Make sure +//! to install the appropriate architecture corresponding to your installation of +//! rustc. GCC from older [MinGW](http://www.mingw.org/) project is compatible +//! only with 32-bit rust compiler. +//! +//! [msys2-help]: https://github.com/rust-lang/rust/blob/master/INSTALL.md#building-on-windows +//! +//! # C++ support +//! +//! `cc-rs` supports C++ libraries compilation by using the `cpp` method on +//! `Build`: +//! +//! ```rust,no_run +//! cc::Build::new() +//! .cpp(true) // Switch to C++ library compilation. +//! .file("foo.cpp") +//! .compile("foo"); +//! ``` +//! +//! For C++ libraries, the `CXX` and `CXXFLAGS` environment variables are used instead of `CC` and `CFLAGS`. +//! +//! The C++ standard library may be linked to the crate target. By default it's `libc++` for macOS, FreeBSD, and OpenBSD, `libc++_shared` for Android, nothing for MSVC, and `libstdc++` for anything else. It can be changed in one of two ways: +//! +//! 1. by using the `cpp_link_stdlib` method on `Build`: +//! ```rust,no_run +//! cc::Build::new() +//! .cpp(true) +//! .file("foo.cpp") +//! .cpp_link_stdlib("stdc++") // use libstdc++ +//! .compile("foo"); +//! ``` +//! 2. by setting the `CXXSTDLIB` environment variable. +//! +//! In particular, for Android you may want to [use `c++_static` if you have at most one shared library](https://developer.android.com/ndk/guides/cpp-support). +//! +//! Remember that C++ does name mangling so `extern "C"` might be required to enable Rust linker to find your functions. +//! +//! # CUDA C++ support +//! +//! `cc-rs` also supports compiling CUDA C++ libraries by using the `cuda` method +//! on `Build`: +//! +//! ```rust,no_run +//! cc::Build::new() +//! // Switch to CUDA C++ library compilation using NVCC. +//! .cuda(true) +//! .cudart("static") +//! // Generate code for Maxwell (GTX 970, 980, 980 Ti, Titan X). +//! .flag("-gencode").flag("arch=compute_52,code=sm_52") +//! // Generate code for Maxwell (Jetson TX1). +//! .flag("-gencode").flag("arch=compute_53,code=sm_53") +//! // Generate code for Pascal (GTX 1070, 1080, 1080 Ti, Titan Xp). +//! .flag("-gencode").flag("arch=compute_61,code=sm_61") +//! // Generate code for Pascal (Tesla P100). +//! .flag("-gencode").flag("arch=compute_60,code=sm_60") +//! // Generate code for Pascal (Jetson TX2). +//! .flag("-gencode").flag("arch=compute_62,code=sm_62") +//! // Generate code in parallel +//! .flag("-t0") +//! .file("bar.cu") +//! .compile("bar"); +//! ``` + +#![doc(html_root_url = "https://docs.rs/cc/1.0")] +#![deny(warnings)] +#![deny(missing_docs)] +#![deny(clippy::disallowed_methods)] +#![warn(clippy::doc_markdown)] + +use std::borrow::Cow; +use std::collections::HashMap; +use std::env; +use std::ffi::{OsStr, OsString}; +use std::fmt::{self, Display, Formatter}; +use std::fs; +use std::io::{self, Write}; +use std::path::{Component, Path, PathBuf}; +#[cfg(feature = "parallel")] +use std::process::Child; +use std::process::Command; +use std::sync::{Arc, RwLock}; + +use shlex::Shlex; + +#[cfg(feature = "parallel")] +mod parallel; +mod windows; +// Regardless of whether this should be in this crate's public API, +// it has been since 2015, so don't break it. +pub use windows::find_tools as windows_registry; + +mod command_helpers; +use command_helpers::*; + +mod tool; +pub use tool::Tool; +use tool::ToolFamily; + +mod target_info; +mod tempfile; + +mod utilities; +use utilities::*; + +#[derive(Debug, Eq, PartialEq, Hash)] +struct CompilerFlag { + compiler: Box, + flag: Box, +} + +type Env = Option>; + +/// A builder for compilation of a native library. +/// +/// A `Build` is the main type of the `cc` crate and is used to control all the +/// various configuration options and such of a compile. You'll find more +/// documentation on each method itself. +#[derive(Clone, Debug)] +pub struct Build { + include_directories: Vec>, + definitions: Vec<(Arc, Option>)>, + objects: Vec>, + flags: Vec>, + flags_supported: Vec>, + known_flag_support_status_cache: Arc>>, + ar_flags: Vec>, + asm_flags: Vec>, + no_default_flags: bool, + files: Vec>, + cpp: bool, + cpp_link_stdlib: Option>>, + cpp_set_stdlib: Option>, + cuda: bool, + cudart: Option>, + ccbin: bool, + std: Option>, + target: Option>, + /// The host compiler. + /// + /// Try to not access this directly, and instead prefer `cfg!(...)`. + host: Option>, + out_dir: Option>, + opt_level: Option>, + debug: Option, + force_frame_pointer: Option, + env: Vec<(Arc, Arc)>, + compiler: Option>, + archiver: Option>, + ranlib: Option>, + cargo_output: CargoOutput, + link_lib_modifiers: Vec>, + pic: Option, + use_plt: Option, + static_crt: Option, + shared_flag: Option, + static_flag: Option, + warnings_into_errors: bool, + warnings: Option, + extra_warnings: Option, + env_cache: Arc, Env>>>, + apple_sdk_root_cache: Arc, Arc>>>, + apple_versions_cache: Arc, Arc>>>, + emit_rerun_if_env_changed: bool, + cached_compiler_family: Arc, ToolFamily>>>, + shell_escaped_flags: Option, +} + +/// Represents the types of errors that may occur while using cc-rs. +#[derive(Clone, Debug)] +enum ErrorKind { + /// Error occurred while performing I/O. + IOError, + /// Invalid architecture supplied. + ArchitectureInvalid, + /// Environment variable not found, with the var in question as extra info. + EnvVarNotFound, + /// Error occurred while using external tools (ie: invocation of compiler). + ToolExecError, + /// Error occurred due to missing external tools. + ToolNotFound, + /// One of the function arguments failed validation. + InvalidArgument, + /// No known macro is defined for the compiler when discovering tool family + ToolFamilyMacroNotFound, + /// Invalid target + InvalidTarget, + #[cfg(feature = "parallel")] + /// jobserver helpthread failure + JobserverHelpThreadError, +} + +/// Represents an internal error that occurred, with an explanation. +#[derive(Clone, Debug)] +pub struct Error { + /// Describes the kind of error that occurred. + kind: ErrorKind, + /// More explanation of error that occurred. + message: Cow<'static, str>, +} + +impl Error { + fn new(kind: ErrorKind, message: impl Into>) -> Error { + Error { + kind, + message: message.into(), + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Error { + Error::new(ErrorKind::IOError, format!("{}", e)) + } +} + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}: {}", self.kind, self.message) + } +} + +impl std::error::Error for Error {} + +/// Represents an object. +/// +/// This is a source file -> object file pair. +#[derive(Clone, Debug)] +struct Object { + src: PathBuf, + dst: PathBuf, +} + +impl Object { + /// Create a new source file -> object file pair. + fn new(src: PathBuf, dst: PathBuf) -> Object { + Object { src, dst } + } +} + +impl Build { + /// Construct a new instance of a blank set of configuration. + /// + /// This builder is finished with the [`compile`] function. + /// + /// [`compile`]: struct.Build.html#method.compile + pub fn new() -> Build { + Build { + include_directories: Vec::new(), + definitions: Vec::new(), + objects: Vec::new(), + flags: Vec::new(), + flags_supported: Vec::new(), + known_flag_support_status_cache: Arc::new(RwLock::new(HashMap::new())), + ar_flags: Vec::new(), + asm_flags: Vec::new(), + no_default_flags: false, + files: Vec::new(), + shared_flag: None, + static_flag: None, + cpp: false, + cpp_link_stdlib: None, + cpp_set_stdlib: None, + cuda: false, + cudart: None, + ccbin: true, + std: None, + target: None, + host: None, + out_dir: None, + opt_level: None, + debug: None, + force_frame_pointer: None, + env: Vec::new(), + compiler: None, + archiver: None, + ranlib: None, + cargo_output: CargoOutput::new(), + link_lib_modifiers: Vec::new(), + pic: None, + use_plt: None, + static_crt: None, + warnings: None, + extra_warnings: None, + warnings_into_errors: false, + env_cache: Arc::new(RwLock::new(HashMap::new())), + apple_sdk_root_cache: Arc::new(RwLock::new(HashMap::new())), + apple_versions_cache: Arc::new(RwLock::new(HashMap::new())), + emit_rerun_if_env_changed: true, + cached_compiler_family: Arc::default(), + shell_escaped_flags: None, + } + } + + /// Add a directory to the `-I` or include path for headers + /// + /// # Example + /// + /// ```no_run + /// use std::path::Path; + /// + /// let library_path = Path::new("/path/to/library"); + /// + /// cc::Build::new() + /// .file("src/foo.c") + /// .include(library_path) + /// .include("src") + /// .compile("foo"); + /// ``` + pub fn include>(&mut self, dir: P) -> &mut Build { + self.include_directories.push(dir.as_ref().into()); + self + } + + /// Add multiple directories to the `-I` include path. + /// + /// # Example + /// + /// ```no_run + /// # use std::path::Path; + /// # let condition = true; + /// # + /// let mut extra_dir = None; + /// if condition { + /// extra_dir = Some(Path::new("/path/to")); + /// } + /// + /// cc::Build::new() + /// .file("src/foo.c") + /// .includes(extra_dir) + /// .compile("foo"); + /// ``` + pub fn includes

(&mut self, dirs: P) -> &mut Build + where + P: IntoIterator, + P::Item: AsRef, + { + for dir in dirs { + self.include(dir); + } + self + } + + /// Specify a `-D` variable with an optional value. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .define("FOO", "BAR") + /// .define("BAZ", None) + /// .compile("foo"); + /// ``` + pub fn define<'a, V: Into>>(&mut self, var: &str, val: V) -> &mut Build { + self.definitions + .push((var.into(), val.into().map(Into::into))); + self + } + + /// Add an arbitrary object file to link in + pub fn object>(&mut self, obj: P) -> &mut Build { + self.objects.push(obj.as_ref().into()); + self + } + + /// Add arbitrary object files to link in + pub fn objects

(&mut self, objs: P) -> &mut Build + where + P: IntoIterator, + P::Item: AsRef, + { + for obj in objs { + self.object(obj); + } + self + } + + /// Add an arbitrary flag to the invocation of the compiler + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .flag("-ffunction-sections") + /// .compile("foo"); + /// ``` + pub fn flag(&mut self, flag: impl AsRef) -> &mut Build { + self.flags.push(flag.as_ref().into()); + self + } + + /// Removes a compiler flag that was added by [`Build::flag`]. + /// + /// Will not remove flags added by other means (default flags, + /// flags from env, and so on). + /// + /// # Example + /// ``` + /// cc::Build::new() + /// .file("src/foo.c") + /// .flag("unwanted_flag") + /// .remove_flag("unwanted_flag"); + /// ``` + + pub fn remove_flag(&mut self, flag: &str) -> &mut Build { + self.flags.retain(|other_flag| &**other_flag != flag); + self + } + + /// Add a flag to the invocation of the ar + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .file("src/bar.c") + /// .ar_flag("/NODEFAULTLIB:libc.dll") + /// .compile("foo"); + /// ``` + pub fn ar_flag(&mut self, flag: impl AsRef) -> &mut Build { + self.ar_flags.push(flag.as_ref().into()); + self + } + + /// Add a flag that will only be used with assembly files. + /// + /// The flag will be applied to input files with either a `.s` or + /// `.asm` extension (case insensitive). + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .asm_flag("-Wa,-defsym,abc=1") + /// .file("src/foo.S") // The asm flag will be applied here + /// .file("src/bar.c") // The asm flag will not be applied here + /// .compile("foo"); + /// ``` + pub fn asm_flag(&mut self, flag: impl AsRef) -> &mut Build { + self.asm_flags.push(flag.as_ref().into()); + self + } + + fn ensure_check_file(&self) -> Result { + let out_dir = self.get_out_dir()?; + let src = if self.cuda { + assert!(self.cpp); + out_dir.join("flag_check.cu") + } else if self.cpp { + out_dir.join("flag_check.cpp") + } else { + out_dir.join("flag_check.c") + }; + + if !src.exists() { + let mut f = fs::File::create(&src)?; + write!(f, "int main(void) {{ return 0; }}")?; + } + + Ok(src) + } + + /// Run the compiler to test if it accepts the given flag. + /// + /// For a convenience method for setting flags conditionally, + /// see `flag_if_supported()`. + /// + /// It may return error if it's unable to run the compiler with a test file + /// (e.g. the compiler is missing or a write to the `out_dir` failed). + /// + /// Note: Once computed, the result of this call is stored in the + /// `known_flag_support` field. If `is_flag_supported(flag)` + /// is called again, the result will be read from the hash table. + pub fn is_flag_supported(&self, flag: impl AsRef) -> Result { + self.is_flag_supported_inner( + flag.as_ref(), + self.get_base_compiler()?.path(), + &self.get_target()?, + ) + } + + fn is_flag_supported_inner( + &self, + flag: &OsStr, + compiler_path: &Path, + target: &str, + ) -> Result { + let compiler_flag = CompilerFlag { + compiler: compiler_path.into(), + flag: flag.into(), + }; + + if let Some(is_supported) = self + .known_flag_support_status_cache + .read() + .unwrap() + .get(&compiler_flag) + .cloned() + { + return Ok(is_supported); + } + + let out_dir = self.get_out_dir()?; + let src = self.ensure_check_file()?; + let obj = out_dir.join("flag_check"); + + let mut compiler = { + let mut cfg = Build::new(); + cfg.flag(flag) + .compiler(compiler_path) + .cargo_metadata(self.cargo_output.metadata) + .target(target) + .opt_level(0) + .debug(false) + .cpp(self.cpp) + .cuda(self.cuda) + .emit_rerun_if_env_changed(self.emit_rerun_if_env_changed); + if let Some(host) = &self.host { + cfg.host(host); + } + cfg.try_get_compiler()? + }; + + // Clang uses stderr for verbose output, which yields a false positive + // result if the CFLAGS/CXXFLAGS include -v to aid in debugging. + if compiler.family.verbose_stderr() { + compiler.remove_arg("-v".into()); + } + if compiler.is_like_clang() { + // Avoid reporting that the arg is unsupported just because the + // compiler complains that it wasn't used. + compiler.push_cc_arg("-Wno-unused-command-line-argument".into()); + } + + let mut cmd = compiler.to_command(); + let is_arm = target.contains("aarch64") || target.contains("arm"); + let clang = compiler.is_like_clang(); + let gnu = compiler.family == ToolFamily::Gnu; + command_add_output_file( + &mut cmd, + &obj, + CmdAddOutputFileArgs { + cuda: self.cuda, + is_assembler_msvc: false, + msvc: compiler.is_like_msvc(), + clang, + gnu, + is_asm: false, + is_arm, + }, + ); + + // Checking for compiler flags does not require linking + cmd.arg("-c"); + + cmd.arg(&src); + + let output = cmd.output()?; + let is_supported = output.status.success() && output.stderr.is_empty(); + + self.known_flag_support_status_cache + .write() + .unwrap() + .insert(compiler_flag, is_supported); + + Ok(is_supported) + } + + /// Add an arbitrary flag to the invocation of the compiler if it supports it + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .flag_if_supported("-Wlogical-op") // only supported by GCC + /// .flag_if_supported("-Wunreachable-code") // only supported by clang + /// .compile("foo"); + /// ``` + pub fn flag_if_supported(&mut self, flag: impl AsRef) -> &mut Build { + self.flags_supported.push(flag.as_ref().into()); + self + } + + /// Add flags from the specified environment variable. + /// + /// Normally the `cc` crate will consult with the standard set of environment + /// variables (such as `CFLAGS` and `CXXFLAGS`) to construct the compiler invocation. Use of + /// this method provides additional levers for the end user to use when configuring the build + /// process. + /// + /// Just like the standard variables, this method will search for an environment variable with + /// appropriate target prefixes, when appropriate. + /// + /// # Examples + /// + /// This method is particularly beneficial in introducing the ability to specify crate-specific + /// flags. + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .try_flags_from_environment(concat!(env!("CARGO_PKG_NAME"), "_CFLAGS")) + /// .expect("the environment variable must be specified and UTF-8") + /// .compile("foo"); + /// ``` + /// + pub fn try_flags_from_environment(&mut self, environ_key: &str) -> Result<&mut Build, Error> { + let flags = self.envflags(environ_key)?; + self.flags.extend( + flags + .into_iter() + .map(|flag| Arc::from(OsString::from(flag).as_os_str())), + ); + Ok(self) + } + + /// Set the `-shared` flag. + /// + /// When enabled, the compiler will produce a shared object which can + /// then be linked with other objects to form an executable. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .shared_flag(true) + /// .compile("libfoo.so"); + /// ``` + pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build { + self.shared_flag = Some(shared_flag); + self + } + + /// Set the `-static` flag. + /// + /// When enabled on systems that support dynamic linking, this prevents + /// linking with the shared libraries. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .shared_flag(true) + /// .static_flag(true) + /// .compile("foo"); + /// ``` + pub fn static_flag(&mut self, static_flag: bool) -> &mut Build { + self.static_flag = Some(static_flag); + self + } + + /// Disables the generation of default compiler flags. The default compiler + /// flags may cause conflicts in some cross compiling scenarios. + /// + /// Setting the `CRATE_CC_NO_DEFAULTS` environment variable has the same + /// effect as setting this to `true`. The presence of the environment + /// variable and the value of `no_default_flags` will be OR'd together. + pub fn no_default_flags(&mut self, no_default_flags: bool) -> &mut Build { + self.no_default_flags = no_default_flags; + self + } + + /// Add a file which will be compiled + pub fn file>(&mut self, p: P) -> &mut Build { + self.files.push(p.as_ref().into()); + self + } + + /// Add files which will be compiled + pub fn files

(&mut self, p: P) -> &mut Build + where + P: IntoIterator, + P::Item: AsRef, + { + for file in p.into_iter() { + self.file(file); + } + self + } + + /// Get the files which will be compiled + pub fn get_files(&self) -> impl Iterator { + self.files.iter().map(AsRef::as_ref) + } + + /// Set C++ support. + /// + /// The other `cpp_*` options will only become active if this is set to + /// `true`. + /// + /// The name of the C++ standard library to link is decided by: + /// 1. If [`cpp_link_stdlib`](Build::cpp_link_stdlib) is set, use its value. + /// 2. Else if the `CXXSTDLIB` environment variable is set, use its value. + /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android, + /// `None` for MSVC and `stdc++` for anything else. + pub fn cpp(&mut self, cpp: bool) -> &mut Build { + self.cpp = cpp; + self + } + + /// Set CUDA C++ support. + /// + /// Enabling CUDA will invoke the CUDA compiler, NVCC. While NVCC accepts + /// the most common compiler flags, e.g. `-std=c++17`, some project-specific + /// flags might have to be prefixed with "-Xcompiler" flag, for example as + /// `.flag("-Xcompiler").flag("-fpermissive")`. See the documentation for + /// `nvcc`, the CUDA compiler driver, at + /// for more information. + /// + /// If enabled, this also implicitly enables C++ support. + pub fn cuda(&mut self, cuda: bool) -> &mut Build { + self.cuda = cuda; + if cuda { + self.cpp = true; + self.cudart = Some("static".into()); + } + self + } + + /// Link CUDA run-time. + /// + /// This option mimics the `--cudart` NVCC command-line option. Just like + /// the original it accepts `{none|shared|static}`, with default being + /// `static`. The method has to be invoked after `.cuda(true)`, or not + /// at all, if the default is right for the project. + pub fn cudart(&mut self, cudart: &str) -> &mut Build { + if self.cuda { + self.cudart = Some(cudart.into()); + } + self + } + + /// Set CUDA host compiler. + /// + /// By default, a `-ccbin` flag will be passed to NVCC to specify the + /// underlying host compiler. The value of `-ccbin` is the same as the + /// chosen C++ compiler. This is not always desired, because NVCC might + /// not support that compiler. In this case, you can remove the `-ccbin` + /// flag so that NVCC will choose the host compiler by itself. + pub fn ccbin(&mut self, ccbin: bool) -> &mut Build { + self.ccbin = ccbin; + self + } + + /// Specify the C or C++ language standard version. + /// + /// These values are common to modern versions of GCC, Clang and MSVC: + /// - `c11` for ISO/IEC 9899:2011 + /// - `c17` for ISO/IEC 9899:2018 + /// - `c++14` for ISO/IEC 14882:2014 + /// - `c++17` for ISO/IEC 14882:2017 + /// - `c++20` for ISO/IEC 14882:2020 + /// + /// Other values have less broad support, e.g. MSVC does not support `c++11` + /// (`c++14` is the minimum), `c89` (omit the flag instead) or `c99`. + /// + /// For compiling C++ code, you should also set `.cpp(true)`. + /// + /// The default is that no standard flag is passed to the compiler, so the + /// language version will be the compiler's default. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/modern.cpp") + /// .cpp(true) + /// .std("c++17") + /// .compile("modern"); + /// ``` + pub fn std(&mut self, std: &str) -> &mut Build { + self.std = Some(std.into()); + self + } + + /// Set warnings into errors flag. + /// + /// Disabled by default. + /// + /// Warning: turning warnings into errors only make sense + /// if you are a developer of the crate using cc-rs. + /// Some warnings only appear on some architecture or + /// specific version of the compiler. Any user of this crate, + /// or any other crate depending on it, could fail during + /// compile time. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .warnings_into_errors(true) + /// .compile("libfoo.a"); + /// ``` + pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build { + self.warnings_into_errors = warnings_into_errors; + self + } + + /// Set warnings flags. + /// + /// Adds some flags: + /// - "-Wall" for MSVC. + /// - "-Wall", "-Wextra" for GNU and Clang. + /// + /// Enabled by default. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .warnings(false) + /// .compile("libfoo.a"); + /// ``` + pub fn warnings(&mut self, warnings: bool) -> &mut Build { + self.warnings = Some(warnings); + self.extra_warnings = Some(warnings); + self + } + + /// Set extra warnings flags. + /// + /// Adds some flags: + /// - nothing for MSVC. + /// - "-Wextra" for GNU and Clang. + /// + /// Enabled by default. + /// + /// # Example + /// + /// ```no_run + /// // Disables -Wextra, -Wall remains enabled: + /// cc::Build::new() + /// .file("src/foo.c") + /// .extra_warnings(false) + /// .compile("libfoo.a"); + /// ``` + pub fn extra_warnings(&mut self, warnings: bool) -> &mut Build { + self.extra_warnings = Some(warnings); + self + } + + /// Set the standard library to link against when compiling with C++ + /// support. + /// + /// If the `CXXSTDLIB` environment variable is set, its value will + /// override the default value, but not the value explicitly set by calling + /// this function. + /// + /// A value of `None` indicates that no automatic linking should happen, + /// otherwise cargo will link against the specified library. + /// + /// The given library name must not contain the `lib` prefix. + /// + /// Common values: + /// - `stdc++` for GNU + /// - `c++` for Clang + /// - `c++_shared` or `c++_static` for Android + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .shared_flag(true) + /// .cpp_link_stdlib("stdc++") + /// .compile("libfoo.so"); + /// ``` + pub fn cpp_link_stdlib<'a, V: Into>>( + &mut self, + cpp_link_stdlib: V, + ) -> &mut Build { + self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(Arc::from)); + self + } + + /// Force the C++ compiler to use the specified standard library. + /// + /// Setting this option will automatically set `cpp_link_stdlib` to the same + /// value. + /// + /// The default value of this option is always `None`. + /// + /// This option has no effect when compiling for a Visual Studio based + /// target. + /// + /// This option sets the `-stdlib` flag, which is only supported by some + /// compilers (clang, icc) but not by others (gcc). The library will not + /// detect which compiler is used, as such it is the responsibility of the + /// caller to ensure that this option is only used in conjunction with a + /// compiler which supports the `-stdlib` flag. + /// + /// A value of `None` indicates that no specific C++ standard library should + /// be used, otherwise `-stdlib` is added to the compile invocation. + /// + /// The given library name must not contain the `lib` prefix. + /// + /// Common values: + /// - `stdc++` for GNU + /// - `c++` for Clang + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .cpp_set_stdlib("c++") + /// .compile("libfoo.a"); + /// ``` + pub fn cpp_set_stdlib<'a, V: Into>>( + &mut self, + cpp_set_stdlib: V, + ) -> &mut Build { + let cpp_set_stdlib = cpp_set_stdlib.into().map(Arc::from); + self.cpp_set_stdlib.clone_from(&cpp_set_stdlib); + self.cpp_link_stdlib = Some(cpp_set_stdlib); + self + } + + /// Configures the target this configuration will be compiling for. + /// + /// This option is automatically scraped from the `TARGET` environment + /// variable by build scripts, so it's not required to call this function. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .target("aarch64-linux-android") + /// .compile("foo"); + /// ``` + pub fn target(&mut self, target: &str) -> &mut Build { + self.target = Some(target.into()); + self + } + + /// Configures the host assumed by this configuration. + /// + /// This option is automatically scraped from the `HOST` environment + /// variable by build scripts, so it's not required to call this function. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .host("arm-linux-gnueabihf") + /// .compile("foo"); + /// ``` + pub fn host(&mut self, host: &str) -> &mut Build { + self.host = Some(host.into()); + self + } + + /// Configures the optimization level of the generated object files. + /// + /// This option is automatically scraped from the `OPT_LEVEL` environment + /// variable by build scripts, so it's not required to call this function. + pub fn opt_level(&mut self, opt_level: u32) -> &mut Build { + self.opt_level = Some(opt_level.to_string().into()); + self + } + + /// Configures the optimization level of the generated object files. + /// + /// This option is automatically scraped from the `OPT_LEVEL` environment + /// variable by build scripts, so it's not required to call this function. + pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build { + self.opt_level = Some(opt_level.into()); + self + } + + /// Configures whether the compiler will emit debug information when + /// generating object files. + /// + /// This option is automatically scraped from the `DEBUG` environment + /// variable by build scripts, so it's not required to call this function. + pub fn debug(&mut self, debug: bool) -> &mut Build { + self.debug = Some(debug); + self + } + + /// Configures whether the compiler will emit instructions to store + /// frame pointers during codegen. + /// + /// This option is automatically enabled when debug information is emitted. + /// Otherwise the target platform compiler's default will be used. + /// You can use this option to force a specific setting. + pub fn force_frame_pointer(&mut self, force: bool) -> &mut Build { + self.force_frame_pointer = Some(force); + self + } + + /// Configures the output directory where all object files and static + /// libraries will be located. + /// + /// This option is automatically scraped from the `OUT_DIR` environment + /// variable by build scripts, so it's not required to call this function. + pub fn out_dir>(&mut self, out_dir: P) -> &mut Build { + self.out_dir = Some(out_dir.as_ref().into()); + self + } + + /// Configures the compiler to be used to produce output. + /// + /// This option is automatically determined from the target platform or a + /// number of environment variables, so it's not required to call this + /// function. + pub fn compiler>(&mut self, compiler: P) -> &mut Build { + self.compiler = Some(compiler.as_ref().into()); + self + } + + /// Configures the tool used to assemble archives. + /// + /// This option is automatically determined from the target platform or a + /// number of environment variables, so it's not required to call this + /// function. + pub fn archiver>(&mut self, archiver: P) -> &mut Build { + self.archiver = Some(archiver.as_ref().into()); + self + } + + /// Configures the tool used to index archives. + /// + /// This option is automatically determined from the target platform or a + /// number of environment variables, so it's not required to call this + /// function. + pub fn ranlib>(&mut self, ranlib: P) -> &mut Build { + self.ranlib = Some(ranlib.as_ref().into()); + self + } + + /// Define whether metadata should be emitted for cargo allowing it to + /// automatically link the binary. Defaults to `true`. + /// + /// The emitted metadata is: + /// + /// - `rustc-link-lib=static=`*compiled lib* + /// - `rustc-link-search=native=`*target folder* + /// - When target is MSVC, the ATL-MFC libs are added via `rustc-link-search=native=` + /// - When C++ is enabled, the C++ stdlib is added via `rustc-link-lib` + /// - If `emit_rerun_if_env_changed` is not `false`, `rerun-if-env-changed=`*env* + /// + pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build { + self.cargo_output.metadata = cargo_metadata; + self + } + + /// Define whether compile warnings should be emitted for cargo. Defaults to + /// `true`. + /// + /// If disabled, compiler messages will not be printed. + /// Issues unrelated to the compilation will always produce cargo warnings regardless of this setting. + pub fn cargo_warnings(&mut self, cargo_warnings: bool) -> &mut Build { + self.cargo_output.warnings = cargo_warnings; + self + } + + /// Define whether debug information should be emitted for cargo. Defaults to whether + /// or not the environment variable `CC_ENABLE_DEBUG_OUTPUT` is set. + /// + /// If enabled, the compiler will emit debug information when generating object files, + /// such as the command invoked and the exit status. + pub fn cargo_debug(&mut self, cargo_debug: bool) -> &mut Build { + self.cargo_output.debug = cargo_debug; + self + } + + /// Define whether compiler output (to stdout) should be emitted. Defaults to `true` + /// (forward compiler stdout to this process' stdout) + /// + /// Some compilers emit errors to stdout, so if you *really* need stdout to be clean + /// you should also set this to `false`. + pub fn cargo_output(&mut self, cargo_output: bool) -> &mut Build { + self.cargo_output.output = if cargo_output { + OutputKind::Forward + } else { + OutputKind::Discard + }; + self + } + + /// Adds a native library modifier that will be added to the + /// `rustc-link-lib=static:MODIFIERS=LIBRARY_NAME` metadata line + /// emitted for cargo if `cargo_metadata` is enabled. + /// See + /// for the list of modifiers accepted by rustc. + pub fn link_lib_modifier(&mut self, link_lib_modifier: impl AsRef) -> &mut Build { + self.link_lib_modifiers + .push(link_lib_modifier.as_ref().into()); + self + } + + /// Configures whether the compiler will emit position independent code. + /// + /// This option defaults to `false` for `windows-gnu` and bare metal targets and + /// to `true` for all other targets. + pub fn pic(&mut self, pic: bool) -> &mut Build { + self.pic = Some(pic); + self + } + + /// Configures whether the Procedure Linkage Table is used for indirect + /// calls into shared libraries. + /// + /// The PLT is used to provide features like lazy binding, but introduces + /// a small performance loss due to extra pointer indirection. Setting + /// `use_plt` to `false` can provide a small performance increase. + /// + /// Note that skipping the PLT requires a recent version of GCC/Clang. + /// + /// This only applies to ELF targets. It has no effect on other platforms. + pub fn use_plt(&mut self, use_plt: bool) -> &mut Build { + self.use_plt = Some(use_plt); + self + } + + /// Define whether metadata should be emitted for cargo to detect environment + /// changes that should trigger a rebuild. + /// + /// NOTE that cc does not emit metadata to detect changes for `PATH`, since it could + /// be changed every comilation yet does not affect the result of compilation + /// (i.e. rust-analyzer adds temporary directory to `PATH`). + /// + /// cc in general, has no way detecting changes to compiler, as there are so many ways to + /// change it and sidestep the detection, for example the compiler might be wrapped in a script + /// so detecting change of the file, or using checksum won't work. + /// + /// We recommend users to decide for themselves, if they want rebuild if the compiler has been upgraded + /// or changed, and how to detect that. + /// + /// This has no effect if the `cargo_metadata` option is `false`. + /// + /// This option defaults to `true`. + pub fn emit_rerun_if_env_changed(&mut self, emit_rerun_if_env_changed: bool) -> &mut Build { + self.emit_rerun_if_env_changed = emit_rerun_if_env_changed; + self + } + + /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools. + /// + /// This option defaults to `false`, and affect only msvc targets. + pub fn static_crt(&mut self, static_crt: bool) -> &mut Build { + self.static_crt = Some(static_crt); + self + } + + /// Configure whether *FLAGS variables are parsed using `shlex`, similarly to `make` and + /// `cmake`. + /// + /// This option defaults to `false`. + pub fn shell_escaped_flags(&mut self, shell_escaped_flags: bool) -> &mut Build { + self.shell_escaped_flags = Some(shell_escaped_flags); + self + } + + #[doc(hidden)] + pub fn __set_env(&mut self, a: A, b: B) -> &mut Build + where + A: AsRef, + B: AsRef, + { + self.env.push((a.as_ref().into(), b.as_ref().into())); + self + } + + /// Run the compiler, generating the file `output` + /// + /// This will return a result instead of panicking; see [`Self::compile()`] for + /// the complete description. + pub fn try_compile(&self, output: &str) -> Result<(), Error> { + let mut output_components = Path::new(output).components(); + match (output_components.next(), output_components.next()) { + (Some(Component::Normal(_)), None) => {} + _ => { + return Err(Error::new( + ErrorKind::InvalidArgument, + "argument of `compile` must be a single normal path component", + )); + } + } + + let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") { + (&output[3..output.len() - 2], output.to_owned()) + } else { + let mut gnu = String::with_capacity(5 + output.len()); + gnu.push_str("lib"); + gnu.push_str(output); + gnu.push_str(".a"); + (output, gnu) + }; + let dst = self.get_out_dir()?; + + let objects = objects_from_files(&self.files, &dst)?; + + self.compile_objects(&objects)?; + self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?; + + let target = self.get_target()?; + if target.contains("msvc") { + let compiler = self.get_base_compiler()?; + let atlmfc_lib = compiler + .env() + .iter() + .find(|&(var, _)| var.as_os_str() == OsStr::new("LIB")) + .and_then(|(_, lib_paths)| { + env::split_paths(lib_paths).find(|path| { + let sub = Path::new("atlmfc/lib"); + path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub)) + }) + }); + + if let Some(atlmfc_lib) = atlmfc_lib { + self.cargo_output.print_metadata(&format_args!( + "cargo:rustc-link-search=native={}", + atlmfc_lib.display() + )); + } + } + + if self.link_lib_modifiers.is_empty() { + self.cargo_output + .print_metadata(&format_args!("cargo:rustc-link-lib=static={}", lib_name)); + } else { + self.cargo_output.print_metadata(&format_args!( + "cargo:rustc-link-lib=static:{}={}", + JoinOsStrs { + slice: &self.link_lib_modifiers, + delimiter: ',' + }, + lib_name + )); + } + self.cargo_output.print_metadata(&format_args!( + "cargo:rustc-link-search=native={}", + dst.display() + )); + + // Add specific C++ libraries, if enabled. + if self.cpp { + if let Some(stdlib) = self.get_cpp_link_stdlib()? { + self.cargo_output + .print_metadata(&format_args!("cargo:rustc-link-lib={}", stdlib.display())); + } + // Link c++ lib from WASI sysroot + if Build::is_wasi_target(target.as_ref()) { + if let Ok(wasi_sysroot) = self.wasi_sysroot() { + self.cargo_output.print_metadata(&format_args!( + "cargo:rustc-flags=-L {}/lib/{} -lstatic=c++ -lstatic=c++abi", + Path::new(&wasi_sysroot).display(), + target + )); + } + } + } + + let cudart = match &self.cudart { + Some(opt) => opt, // {none|shared|static} + None => "none", + }; + if cudart != "none" { + if let Some(nvcc) = self.which(&self.get_compiler().path, None) { + // Try to figure out the -L search path. If it fails, + // it's on user to specify one by passing it through + // RUSTFLAGS environment variable. + let mut libtst = false; + let mut libdir = nvcc; + libdir.pop(); // remove 'nvcc' + libdir.push(".."); + let target_arch = self.getenv_unwrap_str("CARGO_CFG_TARGET_ARCH")?; + if cfg!(target_os = "linux") { + libdir.push("targets"); + libdir.push(target_arch.to_owned() + "-linux"); + libdir.push("lib"); + libtst = true; + } else if cfg!(target_env = "msvc") { + libdir.push("lib"); + match target_arch.as_str() { + "x86_64" => { + libdir.push("x64"); + libtst = true; + } + "x86" => { + libdir.push("Win32"); + libtst = true; + } + _ => libtst = false, + } + } + if libtst && libdir.is_dir() { + self.cargo_output.print_metadata(&format_args!( + "cargo:rustc-link-search=native={}", + libdir.to_str().unwrap() + )); + } + + // And now the -l flag. + let lib = match cudart { + "shared" => "cudart", + "static" => "cudart_static", + bad => panic!("unsupported cudart option: {}", bad), + }; + self.cargo_output + .print_metadata(&format_args!("cargo:rustc-link-lib={}", lib)); + } + } + + Ok(()) + } + + /// Run the compiler, generating the file `output` + /// + /// # Library name + /// + /// The `output` string argument determines the file name for the compiled + /// library. The Rust compiler will create an assembly named "lib"+output+".a". + /// MSVC will create a file named output+".lib". + /// + /// The choice of `output` is close to arbitrary, but: + /// + /// - must be nonempty, + /// - must not contain a path separator (`/`), + /// - must be unique across all `compile` invocations made by the same build + /// script. + /// + /// If your build script compiles a single source file, the base name of + /// that source file would usually be reasonable: + /// + /// ```no_run + /// cc::Build::new().file("blobstore.c").compile("blobstore"); + /// ``` + /// + /// Compiling multiple source files, some people use their crate's name, or + /// their crate's name + "-cc". + /// + /// Otherwise, please use your imagination. + /// + /// For backwards compatibility, if `output` starts with "lib" *and* ends + /// with ".a", a second "lib" prefix and ".a" suffix do not get added on, + /// but this usage is deprecated; please omit `lib` and `.a` in the argument + /// that you pass. + /// + /// # Panics + /// + /// Panics if `output` is not formatted correctly or if one of the underlying + /// compiler commands fails. It can also panic if it fails reading file names + /// or creating directories. + pub fn compile(&self, output: &str) { + if let Err(e) = self.try_compile(output) { + fail(&e.message); + } + } + + /// Run the compiler, generating intermediate files, but without linking + /// them into an archive file. + /// + /// This will return a list of compiled object files, in the same order + /// as they were passed in as `file`/`files` methods. + pub fn compile_intermediates(&self) -> Vec { + match self.try_compile_intermediates() { + Ok(v) => v, + Err(e) => fail(&e.message), + } + } + + /// Run the compiler, generating intermediate files, but without linking + /// them into an archive file. + /// + /// This will return a result instead of panicking; see `compile_intermediates()` for the complete description. + pub fn try_compile_intermediates(&self) -> Result, Error> { + let dst = self.get_out_dir()?; + let objects = objects_from_files(&self.files, &dst)?; + + self.compile_objects(&objects)?; + + Ok(objects.into_iter().map(|v| v.dst).collect()) + } + + #[cfg(feature = "parallel")] + fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> { + use std::cell::Cell; + + use parallel::async_executor::{block_on, YieldOnce}; + + if objs.len() <= 1 { + for obj in objs { + let (mut cmd, name) = self.create_compile_object_cmd(obj)?; + run(&mut cmd, &name, &self.cargo_output)?; + } + + return Ok(()); + } + + // Limit our parallelism globally with a jobserver. + let mut tokens = parallel::job_token::ActiveJobTokenServer::new(); + + // When compiling objects in parallel we do a few dirty tricks to speed + // things up: + // + // * First is that we use the `jobserver` crate to limit the parallelism + // of this build script. The `jobserver` crate will use a jobserver + // configured by Cargo for build scripts to ensure that parallelism is + // coordinated across C compilations and Rust compilations. Before we + // compile anything we make sure to wait until we acquire a token. + // + // Note that this jobserver is cached globally so we only used one per + // process and only worry about creating it once. + // + // * Next we use spawn the process to actually compile objects in + // parallel after we've acquired a token to perform some work + // + // With all that in mind we compile all objects in a loop here, after we + // acquire the appropriate tokens, Once all objects have been compiled + // we wait on all the processes and propagate the results of compilation. + + let pendings = Cell::new(Vec::<( + Command, + Cow<'static, Path>, + KillOnDrop, + parallel::job_token::JobToken, + )>::new()); + let is_disconnected = Cell::new(false); + let has_made_progress = Cell::new(false); + + let wait_future = async { + let mut error = None; + // Buffer the stdout + let mut stdout = io::BufWriter::with_capacity(128, io::stdout()); + + loop { + // If the other end of the pipe is already disconnected, then we're not gonna get any new jobs, + // so it doesn't make sense to reuse the tokens; in fact, + // releasing them as soon as possible (once we know that the other end is disconnected) is beneficial. + // Imagine that the last file built takes an hour to finish; in this scenario, + // by not releasing the tokens before that last file is done we would effectively block other processes from + // starting sooner - even though we only need one token for that last file, not N others that were acquired. + + let mut pendings_is_empty = false; + + cell_update(&pendings, |mut pendings| { + // Try waiting on them. + pendings.retain_mut(|(cmd, program, child, _token)| { + match try_wait_on_child( + cmd, + program, + &mut child.0, + &mut stdout, + &mut child.1, + ) { + Ok(Some(())) => { + // Task done, remove the entry + has_made_progress.set(true); + false + } + Ok(None) => true, // Task still not finished, keep the entry + Err(err) => { + // Task fail, remove the entry. + // Since we can only return one error, log the error to make + // sure users always see all the compilation failures. + has_made_progress.set(true); + + if self.cargo_output.warnings { + let _ = writeln!(stdout, "cargo:warning={}", err); + } + error = Some(err); + + false + } + } + }); + pendings_is_empty = pendings.is_empty(); + pendings + }); + + if pendings_is_empty && is_disconnected.get() { + break if let Some(err) = error { + Err(err) + } else { + Ok(()) + }; + } + + YieldOnce::default().await; + } + }; + let spawn_future = async { + for obj in objs { + let (mut cmd, program) = self.create_compile_object_cmd(obj)?; + let token = tokens.acquire().await?; + let mut child = spawn(&mut cmd, &program, &self.cargo_output)?; + let mut stderr_forwarder = StderrForwarder::new(&mut child); + stderr_forwarder.set_non_blocking()?; + + cell_update(&pendings, |mut pendings| { + pendings.push((cmd, program, KillOnDrop(child, stderr_forwarder), token)); + pendings + }); + + has_made_progress.set(true); + } + is_disconnected.set(true); + + Ok::<_, Error>(()) + }; + + return block_on(wait_future, spawn_future, &has_made_progress); + + struct KillOnDrop(Child, StderrForwarder); + + impl Drop for KillOnDrop { + fn drop(&mut self) { + let child = &mut self.0; + + child.kill().ok(); + } + } + + fn cell_update(cell: &Cell, f: F) + where + T: Default, + F: FnOnce(T) -> T, + { + let old = cell.take(); + let new = f(old); + cell.set(new); + } + } + + #[cfg(not(feature = "parallel"))] + fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> { + for obj in objs { + let (mut cmd, name) = self.create_compile_object_cmd(obj)?; + run(&mut cmd, &name, &self.cargo_output)?; + } + + Ok(()) + } + + fn create_compile_object_cmd( + &self, + obj: &Object, + ) -> Result<(Command, Cow<'static, Path>), Error> { + let asm_ext = AsmFileExt::from_path(&obj.src); + let is_asm = asm_ext.is_some(); + let target = self.get_target()?; + let msvc = target.contains("msvc"); + let compiler = self.try_get_compiler()?; + let clang = compiler.is_like_clang(); + let gnu = compiler.family == ToolFamily::Gnu; + + let is_assembler_msvc = msvc && asm_ext == Some(AsmFileExt::DotAsm); + let (mut cmd, name) = if is_assembler_msvc { + let (cmd, name) = self.msvc_macro_assembler()?; + (cmd, Cow::Borrowed(Path::new(name))) + } else { + let mut cmd = compiler.to_command(); + for (a, b) in self.env.iter() { + cmd.env(a, b); + } + ( + cmd, + compiler + .path + .file_name() + .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path.")) + .map(PathBuf::from) + .map(Cow::Owned)?, + ) + }; + let is_arm = target.contains("aarch64") || target.contains("arm"); + command_add_output_file( + &mut cmd, + &obj.dst, + CmdAddOutputFileArgs { + cuda: self.cuda, + is_assembler_msvc, + msvc: compiler.is_like_msvc(), + clang, + gnu, + is_asm, + is_arm, + }, + ); + // armasm and armasm64 don't requrie -c option + if !is_assembler_msvc || !is_arm { + cmd.arg("-c"); + } + if self.cuda && self.cuda_file_count() > 1 { + cmd.arg("--device-c"); + } + if is_asm { + cmd.args(self.asm_flags.iter().map(std::ops::Deref::deref)); + } + if compiler.family == (ToolFamily::Msvc { clang_cl: true }) && !is_assembler_msvc { + // #513: For `clang-cl`, separate flags/options from the input file. + // When cross-compiling macOS -> Windows, this avoids interpreting + // common `/Users/...` paths as the `/U` flag and triggering + // `-Wslash-u-filename` warning. + cmd.arg("--"); + } + cmd.arg(&obj.src); + if cfg!(target_os = "macos") { + self.fix_env_for_apple_os(&mut cmd)?; + } + + Ok((cmd, name)) + } + + /// This will return a result instead of panicking; see [`Self::expand()`] for + /// the complete description. + pub fn try_expand(&self) -> Result, Error> { + let compiler = self.try_get_compiler()?; + let mut cmd = compiler.to_command(); + for (a, b) in self.env.iter() { + cmd.env(a, b); + } + cmd.arg("-E"); + + assert!( + self.files.len() <= 1, + "Expand may only be called for a single file" + ); + + let is_asm = self + .files + .iter() + .map(std::ops::Deref::deref) + .find_map(AsmFileExt::from_path) + .is_some(); + + if compiler.family == (ToolFamily::Msvc { clang_cl: true }) && !is_asm { + // #513: For `clang-cl`, separate flags/options from the input file. + // When cross-compiling macOS -> Windows, this avoids interpreting + // common `/Users/...` paths as the `/U` flag and triggering + // `-Wslash-u-filename` warning. + cmd.arg("--"); + } + + cmd.args(self.files.iter().map(std::ops::Deref::deref)); + + let name = compiler + .path + .file_name() + .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))?; + + run_output(&mut cmd, name, &self.cargo_output) + } + + /// Run the compiler, returning the macro-expanded version of the input files. + /// + /// This is only relevant for C and C++ files. + /// + /// # Panics + /// Panics if more than one file is present in the config, or if compiler + /// path has an invalid file name. + /// + /// # Example + /// ```no_run + /// let out = cc::Build::new().file("src/foo.c").expand(); + /// ``` + pub fn expand(&self) -> Vec { + match self.try_expand() { + Err(e) => fail(&e.message), + Ok(v) => v, + } + } + + /// Get the compiler that's in use for this configuration. + /// + /// This function will return a `Tool` which represents the culmination + /// of this configuration at a snapshot in time. The returned compiler can + /// be inspected (e.g. the path, arguments, environment) to forward along to + /// other tools, or the `to_command` method can be used to invoke the + /// compiler itself. + /// + /// This method will take into account all configuration such as debug + /// information, optimization level, include directories, defines, etc. + /// Additionally, the compiler binary in use follows the standard + /// conventions for this path, e.g. looking at the explicitly set compiler, + /// environment variables (a number of which are inspected here), and then + /// falling back to the default configuration. + /// + /// # Panics + /// + /// Panics if an error occurred while determining the architecture. + pub fn get_compiler(&self) -> Tool { + match self.try_get_compiler() { + Ok(tool) => tool, + Err(e) => fail(&e.message), + } + } + + /// Get the compiler that's in use for this configuration. + /// + /// This will return a result instead of panicking; see + /// [`get_compiler()`](Self::get_compiler) for the complete description. + pub fn try_get_compiler(&self) -> Result { + let opt_level = self.get_opt_level()?; + let target = self.get_target()?; + + let mut cmd = self.get_base_compiler()?; + + // Disable default flag generation via `no_default_flags` or environment variable + let no_defaults = self.no_default_flags || self.getenv_boolean("CRATE_CC_NO_DEFAULTS"); + + if !no_defaults { + self.add_default_flags(&mut cmd, &target, &opt_level)?; + } + + if let Some(ref std) = self.std { + let separator = match cmd.family { + ToolFamily::Msvc { .. } => ':', + ToolFamily::Gnu | ToolFamily::Clang { .. } => '=', + }; + cmd.push_cc_arg(format!("-std{}{}", separator, std).into()); + } + + for directory in self.include_directories.iter() { + cmd.args.push("-I".into()); + cmd.args.push(directory.as_os_str().into()); + } + + if let Ok(flags) = self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" }) { + for arg in flags { + cmd.push_cc_arg(arg.into()); + } + } + + // If warnings and/or extra_warnings haven't been explicitly set, + // then we set them only if the environment doesn't already have + // CFLAGS/CXXFLAGS, since those variables presumably already contain + // the desired set of warnings flags. + + if self.warnings.unwrap_or(!self.has_flags()) { + let wflags = cmd.family.warnings_flags().into(); + cmd.push_cc_arg(wflags); + } + + if self.extra_warnings.unwrap_or(!self.has_flags()) { + if let Some(wflags) = cmd.family.extra_warnings_flags() { + cmd.push_cc_arg(wflags.into()); + } + } + + for flag in self.flags.iter() { + cmd.args.push((**flag).into()); + } + + for flag in self.flags_supported.iter() { + if self + .is_flag_supported_inner(flag, &cmd.path, &target) + .unwrap_or(false) + { + cmd.push_cc_arg((**flag).into()); + } + } + + for (key, value) in self.definitions.iter() { + if let Some(ref value) = *value { + cmd.args.push(format!("-D{}={}", key, value).into()); + } else { + cmd.args.push(format!("-D{}", key).into()); + } + } + + if self.warnings_into_errors { + let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into(); + cmd.push_cc_arg(warnings_to_errors_flag); + } + + Ok(cmd) + } + + fn add_default_flags( + &self, + cmd: &mut Tool, + target: &str, + opt_level: &str, + ) -> Result<(), Error> { + // Non-target flags + // If the flag is not conditioned on target variable, it belongs here :) + match cmd.family { + ToolFamily::Msvc { .. } => { + cmd.push_cc_arg("-nologo".into()); + + let crt_flag = match self.static_crt { + Some(true) => "-MT", + Some(false) => "-MD", + None => { + let features = self.getenv("CARGO_CFG_TARGET_FEATURE"); + let features = features.as_deref().unwrap_or_default(); + if features.to_string_lossy().contains("crt-static") { + "-MT" + } else { + "-MD" + } + } + }; + cmd.push_cc_arg(crt_flag.into()); + + match opt_level { + // Msvc uses /O1 to enable all optimizations that minimize code size. + "z" | "s" | "1" => cmd.push_opt_unless_duplicate("-O1".into()), + // -O3 is a valid value for gcc and clang compilers, but not msvc. Cap to /O2. + "2" | "3" => cmd.push_opt_unless_duplicate("-O2".into()), + _ => {} + } + } + ToolFamily::Gnu | ToolFamily::Clang { .. } => { + // arm-linux-androideabi-gcc 4.8 shipped with Android NDK does + // not support '-Oz' + if opt_level == "z" && !cmd.is_like_clang() { + cmd.push_opt_unless_duplicate("-Os".into()); + } else { + cmd.push_opt_unless_duplicate(format!("-O{}", opt_level).into()); + } + + if cmd.is_like_clang() && target.contains("windows") { + // Disambiguate mingw and msvc on Windows. Problem is that + // depending on the origin clang can default to a mismatchig + // run-time. + cmd.push_cc_arg(format!("--target={}", target).into()); + } + + if cmd.is_like_clang() && target.contains("android") { + // For compatibility with code that doesn't use pre-defined `__ANDROID__` macro. + // If compiler used via ndk-build or cmake (officially supported build methods) + // this macros is defined. + // See https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/cmake/android.toolchain.cmake#456 + // https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/build/core/build-binary.mk#141 + cmd.push_opt_unless_duplicate("-DANDROID".into()); + } + + if !target.contains("apple-ios") + && !target.contains("apple-watchos") + && !target.contains("apple-tvos") + && !target.contains("apple-visionos") + { + cmd.push_cc_arg("-ffunction-sections".into()); + cmd.push_cc_arg("-fdata-sections".into()); + } + // Disable generation of PIC on bare-metal for now: rust-lld doesn't support this yet + if self.pic.unwrap_or_else(|| { + !target.contains("windows") + && !target.contains("-none-") + && !target.ends_with("-none") + && !target.contains("uefi") + && !Build::is_wasi_target(target) + }) { + cmd.push_cc_arg("-fPIC".into()); + // PLT only applies if code is compiled with PIC support, + // and only for ELF targets. + if target.contains("linux") && !self.use_plt.unwrap_or(true) { + cmd.push_cc_arg("-fno-plt".into()); + } + } + if Build::is_wasi_target(target) { + // WASI does not support exceptions yet. + // https://github.com/WebAssembly/exception-handling + cmd.push_cc_arg("-fno-exceptions".into()); + // Link clang sysroot + if let Ok(wasi_sysroot) = self.wasi_sysroot() { + cmd.push_cc_arg( + format!("--sysroot={}", Path::new(&wasi_sysroot).display()).into(), + ); + } + + if target.contains("threads") { + cmd.push_cc_arg("-pthread".into()); + } + } + } + } + + if self.get_debug() { + if self.cuda { + // NVCC debug flag + cmd.args.push("-G".into()); + } + let family = cmd.family; + family.add_debug_flags(cmd, self.get_dwarf_version()); + } + + if self.get_force_frame_pointer() { + let family = cmd.family; + family.add_force_frame_pointer(cmd); + } + + if !cmd.is_like_msvc() { + if target.contains("i686") || target.contains("i586") { + cmd.args.push("-m32".into()); + } else if target == "x86_64-unknown-linux-gnux32" { + cmd.args.push("-mx32".into()); + } else if target.contains("x86_64") || target.contains("powerpc64") { + cmd.args.push("-m64".into()); + } + } + + // Target flags + match cmd.family { + ToolFamily::Clang { .. } => { + if !(cmd.has_internal_target_arg + || (target.contains("android") + && android_clang_compiler_uses_target_arg_internally(&cmd.path))) + { + let (arch, rest) = target.split_once('-').ok_or_else(|| { + Error::new( + ErrorKind::InvalidTarget, + format!("Invalid target `{}`: no `-` in it", target), + ) + })?; + + if target.contains("darwin") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + cmd.args + .push(format!("--target={}-apple-darwin", arch).into()); + } + } else if target.contains("macabi") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + cmd.args + .push(format!("--target={}-apple-ios-macabi", arch).into()); + } + } else if target.contains("ios-sim") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + let sdk_details = + apple_os_sdk_parts(AppleOs::Ios, &AppleArchSpec::Simulator("")); + let deployment_target = + self.apple_deployment_version(AppleOs::Ios, None, &sdk_details.sdk); + cmd.args.push( + format!( + "--target={}-apple-ios{}-simulator", + arch, deployment_target + ) + .into(), + ); + } + } else if target.contains("watchos-sim") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + let sdk_details = + apple_os_sdk_parts(AppleOs::WatchOs, &AppleArchSpec::Simulator("")); + let deployment_target = self.apple_deployment_version( + AppleOs::WatchOs, + None, + &sdk_details.sdk, + ); + cmd.args.push( + format!( + "--target={}-apple-watchos{}-simulator", + arch, deployment_target + ) + .into(), + ); + } + } else if target.contains("tvos-sim") || target.contains("x86_64-apple-tvos") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + let sdk_details = + apple_os_sdk_parts(AppleOs::TvOs, &AppleArchSpec::Simulator("")); + let deployment_target = self.apple_deployment_version( + AppleOs::TvOs, + None, + &sdk_details.sdk, + ); + cmd.args.push( + format!( + "--target={}-apple-tvos{}-simulator", + arch, deployment_target + ) + .into(), + ); + } + } else if target.contains("aarch64-apple-tvos") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + let sdk_details = + apple_os_sdk_parts(AppleOs::TvOs, &AppleArchSpec::Device("")); + let deployment_target = self.apple_deployment_version( + AppleOs::TvOs, + None, + &sdk_details.sdk, + ); + cmd.args.push( + format!("--target={}-apple-tvos{}", arch, deployment_target).into(), + ); + } + } else if target.contains("visionos-sim") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + let sdk_details = apple_os_sdk_parts( + AppleOs::VisionOS, + &AppleArchSpec::Simulator(""), + ); + let deployment_target = self.apple_deployment_version( + AppleOs::VisionOS, + None, + &sdk_details.sdk, + ); + cmd.args.push( + format!( + "--target={}-apple-xros{}-simulator", + arch, deployment_target + ) + .into(), + ); + } + } else if target.contains("visionos") { + if let Some(arch) = + map_darwin_target_from_rust_to_compiler_architecture(target) + { + let sdk_details = + apple_os_sdk_parts(AppleOs::VisionOS, &AppleArchSpec::Device("")); + let deployment_target = self.apple_deployment_version( + AppleOs::VisionOS, + None, + &sdk_details.sdk, + ); + cmd.args.push( + format!("--target={}-apple-xros{}", arch, deployment_target).into(), + ); + } + } else if let Ok(index) = target_info::RISCV_ARCH_MAPPING + .binary_search_by_key(&arch, |(arch, _)| arch) + { + cmd.args.push( + format!( + "--target={}-{}", + target_info::RISCV_ARCH_MAPPING[index].1, + rest + ) + .into(), + ); + } else if target.contains("uefi") { + if target.contains("x86_64") { + cmd.args.push("--target=x86_64-unknown-windows-gnu".into()); + } else if target.contains("i686") { + cmd.args.push("--target=i686-unknown-windows-gnu".into()) + } else if target.contains("aarch64") { + cmd.args.push("--target=aarch64-unknown-windows-gnu".into()) + } + } else if target.ends_with("-freebsd") { + // FreeBSD only supports C++11 and above when compiling against libc++ + // (available from FreeBSD 10 onwards). Under FreeBSD, clang uses libc++ by + // default on FreeBSD 10 and newer unless `--target` is manually passed to + // the compiler, in which case its default behavior differs: + // * If --target=xxx-unknown-freebsdX(.Y) is specified and X is greater than + // or equal to 10, clang++ uses libc++ + // * If --target=xxx-unknown-freebsd is specified (without a version), + // clang++ cannot assume libc++ is available and reverts to a default of + // libstdc++ (this behavior was changed in llvm 14). + // + // This breaks C++11 (or greater) builds if targeting FreeBSD with the + // generic xxx-unknown-freebsd triple on clang 13 or below *without* + // explicitly specifying that libc++ should be used. + // When cross-compiling, we can't infer from the rust/cargo target triple + // which major version of FreeBSD we are targeting, so we need to make sure + // that libc++ is used (unless the user has explicitly specified otherwise). + // There's no compelling reason to use a different approach when compiling + // natively. + if self.cpp && self.cpp_set_stdlib.is_none() { + cmd.push_cc_arg("-stdlib=libc++".into()); + } + + cmd.push_cc_arg(format!("--target={}", target).into()); + } else if let Ok(index) = target_info::WINDOWS_TRIPLE_MAPPING + .binary_search_by_key(&target, |(target, _)| target) + { + cmd.args.push( + format!( + "--target={}-{}", + target_info::WINDOWS_TRIPLE_MAPPING[index].1, + rest + ) + .into(), + ) + } else { + cmd.push_cc_arg(format!("--target={}", target).into()); + } + } + } + ToolFamily::Msvc { clang_cl } => { + // This is an undocumented flag from MSVC but helps with making + // builds more reproducible by avoiding putting timestamps into + // files. + cmd.push_cc_arg("-Brepro".into()); + + if clang_cl { + if target.contains("x86_64") { + cmd.push_cc_arg("-m64".into()); + } else if target.contains("86") { + cmd.push_cc_arg("-m32".into()); + cmd.push_cc_arg("-arch:IA32".into()); + } else { + cmd.push_cc_arg(format!("--target={}", target).into()); + } + } else if target.contains("i586") { + cmd.push_cc_arg("-arch:IA32".into()); + } else if target.contains("arm64ec") { + cmd.push_cc_arg("-arm64EC".into()); + } + // There is a check in corecrt.h that will generate a + // compilation error if + // _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE is + // not defined to 1. The check was added in Windows + // 8 days because only store apps were allowed on ARM. + // This changed with the release of Windows 10 IoT Core. + // The check will be going away in future versions of + // the SDK, but for all released versions of the + // Windows SDK it is required. + if target.contains("arm") || target.contains("thumb") { + cmd.args + .push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into()); + } + } + ToolFamily::Gnu => { + if target.contains("darwin") { + if let Some(arch) = map_darwin_target_from_rust_to_compiler_architecture(target) + { + cmd.args.push("-arch".into()); + cmd.args.push(arch.into()); + } + } + + if target.contains("-kmc-solid_") { + cmd.args.push("-finput-charset=utf-8".into()); + } + + if self.static_flag.is_none() { + let features = self.getenv("CARGO_CFG_TARGET_FEATURE"); + let features = features.as_deref().unwrap_or_default(); + if features.to_string_lossy().contains("crt-static") { + cmd.args.push("-static".into()); + } + } + + // armv7 targets get to use armv7 instructions + if (target.starts_with("armv7") || target.starts_with("thumbv7")) + && (target.contains("-linux-") || target.contains("-kmc-solid_")) + { + cmd.args.push("-march=armv7-a".into()); + + if target.ends_with("eabihf") { + // lowest common denominator FPU + cmd.args.push("-mfpu=vfpv3-d16".into()); + } + } + + // (x86 Android doesn't say "eabi") + if target.contains("-androideabi") && target.contains("v7") { + // -march=armv7-a handled above + cmd.args.push("-mthumb".into()); + if !target.contains("neon") { + // On android we can guarantee some extra float instructions + // (specified in the android spec online) + // NEON guarantees even more; see below. + cmd.args.push("-mfpu=vfpv3-d16".into()); + } + cmd.args.push("-mfloat-abi=softfp".into()); + } + + if target.contains("neon") { + cmd.args.push("-mfpu=neon-vfpv4".into()); + } + + if target.starts_with("armv4t-unknown-linux-") { + cmd.args.push("-march=armv4t".into()); + cmd.args.push("-marm".into()); + cmd.args.push("-mfloat-abi=soft".into()); + } + + if target.starts_with("armv5te-unknown-linux-") { + cmd.args.push("-march=armv5te".into()); + cmd.args.push("-marm".into()); + cmd.args.push("-mfloat-abi=soft".into()); + } + + // For us arm == armv6 by default + if target.starts_with("arm-unknown-linux-") { + cmd.args.push("-march=armv6".into()); + cmd.args.push("-marm".into()); + if target.ends_with("hf") { + cmd.args.push("-mfpu=vfp".into()); + } else { + cmd.args.push("-mfloat-abi=soft".into()); + } + } + + // We can guarantee some settings for FRC + if target.starts_with("arm-frc-") { + cmd.args.push("-march=armv7-a".into()); + cmd.args.push("-mcpu=cortex-a9".into()); + cmd.args.push("-mfpu=vfpv3".into()); + cmd.args.push("-mfloat-abi=softfp".into()); + cmd.args.push("-marm".into()); + } + + // Turn codegen down on i586 to avoid some instructions. + if target.starts_with("i586-unknown-linux-") { + cmd.args.push("-march=pentium".into()); + } + + // Set codegen level for i686 correctly + if target.starts_with("i686-unknown-linux-") { + cmd.args.push("-march=i686".into()); + } + + // Looks like `musl-gcc` makes it hard for `-m32` to make its way + // all the way to the linker, so we need to actually instruct the + // linker that we're generating 32-bit executables as well. This'll + // typically only be used for build scripts which transitively use + // these flags that try to compile executables. + if target == "i686-unknown-linux-musl" || target == "i586-unknown-linux-musl" { + cmd.args.push("-Wl,-melf_i386".into()); + } + + if (target.starts_with("arm") || target.starts_with("thumb")) + && target.ends_with("-none-eabihf") + { + cmd.args.push("-mfloat-abi=hard".into()) + } + if target.starts_with("thumb") { + cmd.args.push("-mthumb".into()); + } + if target.starts_with("thumbv6m") { + cmd.args.push("-march=armv6s-m".into()); + } + if target.starts_with("thumbv7em") { + cmd.args.push("-march=armv7e-m".into()); + + if target.ends_with("eabihf") { + cmd.args.push("-mfpu=fpv4-sp-d16".into()) + } + } + if target.starts_with("thumbv7m") { + cmd.args.push("-march=armv7-m".into()); + } + if target.starts_with("thumbv8m.base") { + cmd.args.push("-march=armv8-m.base".into()); + } + if target.starts_with("thumbv8m.main") { + cmd.args.push("-march=armv8-m.main".into()); + + if target.ends_with("eabihf") { + cmd.args.push("-mfpu=fpv5-sp-d16".into()) + } + } + if target.starts_with("armebv7r") | target.starts_with("armv7r") { + if target.starts_with("armeb") { + cmd.args.push("-mbig-endian".into()); + } else { + cmd.args.push("-mlittle-endian".into()); + } + + // ARM mode + cmd.args.push("-marm".into()); + + // R Profile + cmd.args.push("-march=armv7-r".into()); + + if target.ends_with("eabihf") { + // lowest common denominator FPU + // (see Cortex-R4 technical reference manual) + cmd.args.push("-mfpu=vfpv3-d16".into()) + } + } + if target.starts_with("armv7a") { + cmd.args.push("-march=armv7-a".into()); + + if target.ends_with("eabihf") { + // lowest common denominator FPU + cmd.args.push("-mfpu=vfpv3-d16".into()); + } + } + if target.starts_with("riscv32") || target.starts_with("riscv64") { + // get the 32i/32imac/32imc/64gc/64imac/... part + let mut parts = target.split('-'); + if let Some(arch) = parts.next() { + let arch = &arch[5..]; + if arch.starts_with("64") { + if target.contains("linux") + | target.contains("freebsd") + | target.contains("netbsd") + | target.contains("linux") + { + cmd.args.push(("-march=rv64gc").into()); + cmd.args.push("-mabi=lp64d".into()); + } else { + cmd.args.push(("-march=rv".to_owned() + arch).into()); + cmd.args.push("-mabi=lp64".into()); + } + } else if arch.starts_with("32") { + if target.contains("linux") { + cmd.args.push(("-march=rv32gc").into()); + cmd.args.push("-mabi=ilp32d".into()); + } else { + cmd.args.push(("-march=rv".to_owned() + arch).into()); + cmd.args.push("-mabi=ilp32".into()); + } + } else { + cmd.args.push("-mcmodel=medany".into()); + } + } + } + } + } + + if target.contains("-apple-") { + self.apple_flags(cmd)?; + } + + if self.static_flag.unwrap_or(false) { + cmd.args.push("-static".into()); + } + if self.shared_flag.unwrap_or(false) { + cmd.args.push("-shared".into()); + } + + if self.cpp { + match (self.cpp_set_stdlib.as_ref(), cmd.family) { + (None, _) => {} + (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang { .. }) => { + cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into()); + } + _ => { + self.cargo_output.print_warning(&format_args!("cpp_set_stdlib is specified, but the {:?} compiler does not support this option, ignored", cmd.family)); + } + } + } + + Ok(()) + } + + fn has_flags(&self) -> bool { + let flags_env_var_name = if self.cpp { "CXXFLAGS" } else { "CFLAGS" }; + let flags_env_var_value = self.getenv_with_target_prefixes(flags_env_var_name); + flags_env_var_value.is_ok() + } + + fn msvc_macro_assembler(&self) -> Result<(Command, &'static str), Error> { + let target = self.get_target()?; + let tool = if target.contains("x86_64") { + "ml64.exe" + } else if target.contains("arm") { + "armasm.exe" + } else if target.contains("aarch64") { + "armasm64.exe" + } else { + "ml.exe" + }; + let mut cmd = self + .windows_registry_find(&target, tool) + .unwrap_or_else(|| self.cmd(tool)); + cmd.arg("-nologo"); // undocumented, yet working with armasm[64] + for directory in self.include_directories.iter() { + cmd.arg("-I").arg(&**directory); + } + if target.contains("aarch64") || target.contains("arm") { + if self.get_debug() { + cmd.arg("-g"); + } + + for (key, value) in self.definitions.iter() { + cmd.arg("-PreDefine"); + if let Some(ref value) = *value { + if let Ok(i) = value.parse::() { + cmd.arg(format!("{} SETA {}", key, i)); + } else if value.starts_with('"') && value.ends_with('"') { + cmd.arg(format!("{} SETS {}", key, value)); + } else { + cmd.arg(format!("{} SETS \"{}\"", key, value)); + } + } else { + cmd.arg(format!("{} SETL {}", key, "{TRUE}")); + } + } + } else { + if self.get_debug() { + cmd.arg("-Zi"); + } + + for (key, value) in self.definitions.iter() { + if let Some(ref value) = *value { + cmd.arg(format!("-D{}={}", key, value)); + } else { + cmd.arg(format!("-D{}", key)); + } + } + } + + if target.contains("i686") || target.contains("i586") { + cmd.arg("-safeseh"); + } + + Ok((cmd, tool)) + } + + fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> { + // Delete the destination if it exists as we want to + // create on the first iteration instead of appending. + let _ = fs::remove_file(dst); + + // Add objects to the archive in limited-length batches. This helps keep + // the length of the command line within a reasonable length to avoid + // blowing system limits on limiting platforms like Windows. + let objs: Vec<_> = objs + .iter() + .map(|o| o.dst.as_path()) + .chain(self.objects.iter().map(std::ops::Deref::deref)) + .collect(); + for chunk in objs.chunks(100) { + self.assemble_progressive(dst, chunk)?; + } + + if self.cuda && self.cuda_file_count() > 0 { + // Link the device-side code and add it to the target library, + // so that non-CUDA linker can link the final binary. + + let out_dir = self.get_out_dir()?; + let dlink = out_dir.join(lib_name.to_owned() + "_dlink.o"); + let mut nvcc = self.get_compiler().to_command(); + nvcc.arg("--device-link").arg("-o").arg(&dlink).arg(dst); + run(&mut nvcc, "nvcc", &self.cargo_output)?; + self.assemble_progressive(dst, &[dlink.as_path()])?; + } + + let target = self.get_target()?; + if target.contains("msvc") { + // The Rust compiler will look for libfoo.a and foo.lib, but the + // MSVC linker will also be passed foo.lib, so be sure that both + // exist for now. + + let lib_dst = dst.with_file_name(format!("{}.lib", lib_name)); + let _ = fs::remove_file(&lib_dst); + match fs::hard_link(dst, &lib_dst).or_else(|_| { + // if hard-link fails, just copy (ignoring the number of bytes written) + fs::copy(dst, &lib_dst).map(|_| ()) + }) { + Ok(_) => (), + Err(_) => { + return Err(Error::new( + ErrorKind::IOError, + "Could not copy or create a hard-link to the generated lib file.", + )); + } + }; + } else { + // Non-msvc targets (those using `ar`) need a separate step to add + // the symbol table to archives since our construction command of + // `cq` doesn't add it for us. + let (mut ar, cmd, _any_flags) = self.get_ar()?; + + // NOTE: We add `s` even if flags were passed using $ARFLAGS/ar_flag, because `s` + // here represents a _mode_, not an arbitrary flag. Further discussion of this choice + // can be seen in https://github.com/rust-lang/cc-rs/pull/763. + run(ar.arg("s").arg(dst), &cmd, &self.cargo_output)?; + } + + Ok(()) + } + + fn assemble_progressive(&self, dst: &Path, objs: &[&Path]) -> Result<(), Error> { + let target = self.get_target()?; + + let (mut cmd, program, any_flags) = self.get_ar()?; + if target.contains("msvc") && !program.to_string_lossy().contains("llvm-ar") { + // NOTE: -out: here is an I/O flag, and so must be included even if $ARFLAGS/ar_flag is + // in use. -nologo on the other hand is just a regular flag, and one that we'll skip if + // the caller has explicitly dictated the flags they want. See + // https://github.com/rust-lang/cc-rs/pull/763 for further discussion. + let mut out = OsString::from("-out:"); + out.push(dst); + cmd.arg(out); + if !any_flags { + cmd.arg("-nologo"); + } + // If the library file already exists, add the library name + // as an argument to let lib.exe know we are appending the objs. + if dst.exists() { + cmd.arg(dst); + } + cmd.args(objs); + run(&mut cmd, &program, &self.cargo_output)?; + } else { + // Set an environment variable to tell the OSX archiver to ensure + // that all dates listed in the archive are zero, improving + // determinism of builds. AFAIK there's not really official + // documentation of this but there's a lot of references to it if + // you search google. + // + // You can reproduce this locally on a mac with: + // + // $ touch foo.c + // $ cc -c foo.c -o foo.o + // + // # Notice that these two checksums are different + // $ ar crus libfoo1.a foo.o && sleep 2 && ar crus libfoo2.a foo.o + // $ md5sum libfoo*.a + // + // # Notice that these two checksums are the same + // $ export ZERO_AR_DATE=1 + // $ ar crus libfoo1.a foo.o && sleep 2 && touch foo.o && ar crus libfoo2.a foo.o + // $ md5sum libfoo*.a + // + // In any case if this doesn't end up getting read, it shouldn't + // cause that many issues! + cmd.env("ZERO_AR_DATE", "1"); + + // NOTE: We add cq here regardless of whether $ARFLAGS/ar_flag have been used because + // it dictates the _mode_ ar runs in, which the setter of $ARFLAGS/ar_flag can't + // dictate. See https://github.com/rust-lang/cc-rs/pull/763 for further discussion. + run( + cmd.arg("cq").arg(dst).args(objs), + &program, + &self.cargo_output, + )?; + } + + Ok(()) + } + + fn apple_flags(&self, cmd: &mut Tool) -> Result<(), Error> { + let target = self.get_target()?; + let os = if target.contains("-darwin") { + AppleOs::MacOs + } else if target.contains("-watchos") { + AppleOs::WatchOs + } else if target.contains("-tvos") { + AppleOs::TvOs + } else if target.contains("-visionos") { + AppleOs::VisionOS + } else { + AppleOs::Ios + }; + let is_mac = matches!(os, AppleOs::MacOs); + + let arch_str = target.split('-').nth(0).ok_or_else(|| { + Error::new( + ErrorKind::ArchitectureInvalid, + format!("Unknown architecture for {:?} target.", os), + ) + })?; + + let is_catalyst = match target.split('-').nth(3) { + Some(v) => v == "macabi", + None => false, + }; + + let is_arm_sim = match target.split('-').nth(3) { + Some(v) => v == "sim", + None => false, + }; + + let arch = if is_mac { + match arch_str { + "i686" => AppleArchSpec::Device("-m32"), + "x86_64" | "x86_64h" | "aarch64" | "arm64e" => AppleArchSpec::Device("-m64"), + _ => { + return Err(Error::new( + ErrorKind::ArchitectureInvalid, + "Unknown architecture for macOS target.", + )); + } + } + } else if is_catalyst { + match arch_str { + "arm64e" => AppleArchSpec::Catalyst("arm64e"), + "arm64" | "aarch64" => AppleArchSpec::Catalyst("arm64"), + "x86_64" | "x86_64h" => AppleArchSpec::Catalyst("-m64"), + _ => { + return Err(Error::new( + ErrorKind::ArchitectureInvalid, + "Unknown architecture for iOS target.", + )); + } + } + } else if is_arm_sim { + match arch_str { + "arm64" | "aarch64" => AppleArchSpec::Simulator("arm64"), + "x86_64" | "x86_64h" => AppleArchSpec::Simulator("-m64"), + _ => { + return Err(Error::new( + ErrorKind::ArchitectureInvalid, + "Unknown architecture for simulator target.", + )); + } + } + } else { + match arch_str { + "arm" | "armv7" | "thumbv7" => AppleArchSpec::Device("armv7"), + "armv7k" => AppleArchSpec::Device("armv7k"), + "armv7s" | "thumbv7s" => AppleArchSpec::Device("armv7s"), + "arm64e" => AppleArchSpec::Device("arm64e"), + "arm64" | "aarch64" => AppleArchSpec::Device("arm64"), + "arm64_32" => AppleArchSpec::Device("arm64_32"), + "i386" | "i686" => AppleArchSpec::Simulator("-m32"), + "x86_64" | "x86_64h" => AppleArchSpec::Simulator("-m64"), + _ => { + return Err(Error::new( + ErrorKind::ArchitectureInvalid, + format!("Unknown architecture for {:?} target.", os), + )); + } + } + }; + + let sdk_details = apple_os_sdk_parts(os, &arch); + let min_version = self.apple_deployment_version(os, Some(arch_str), &sdk_details.sdk); + + match arch { + AppleArchSpec::Device(_) if is_mac => { + cmd.args + .push(format!("-mmacosx-version-min={}", min_version).into()); + } + AppleArchSpec::Device(arch) => { + cmd.args.push("-arch".into()); + cmd.args.push(arch.into()); + // `-mxros-version-min` does not exist + // https://github.com/llvm/llvm-project/issues/88271 + if os != AppleOs::VisionOS { + cmd.args.push( + format!("-m{}os-version-min={}", sdk_details.sdk_prefix, min_version) + .into(), + ); + } + } + AppleArchSpec::Simulator(arch) => { + if arch.starts_with('-') { + // -m32 or -m64 + cmd.args.push(arch.into()); + } else { + cmd.args.push("-arch".into()); + cmd.args.push(arch.into()); + } + if os != AppleOs::VisionOS { + cmd.args.push( + format!( + "-m{}simulator-version-min={}", + sdk_details.sim_prefix, min_version + ) + .into(), + ); + } + } + AppleArchSpec::Catalyst(_) => {} + }; + + // AppleClang sometimes requires sysroot even for darwin + if cmd.is_xctoolchain_clang() || !target.ends_with("-darwin") { + self.cargo_output.print_metadata(&format_args!( + "Detecting {:?} SDK path for {}", + os, sdk_details.sdk + )); + let sdk_path = self.apple_sdk_root(&sdk_details.sdk)?; + + cmd.args.push("-isysroot".into()); + cmd.args.push(OsStr::new(&sdk_path).to_owned()); + + if let AppleArchSpec::Catalyst(_) = arch { + // Mac Catalyst uses the macOS SDK, but to compile against and + // link to iOS-specific frameworks, we should have the support + // library stubs in the include and library search path. + let ios_support = Path::new(&sdk_path).join("System/iOSSupport"); + + cmd.args.extend([ + // Header search path + OsString::from("-isystem"), + ios_support.join("usr/include").into(), + // Framework header search path + OsString::from("-iframework"), + ios_support.join("System/Library/Frameworks").into(), + // Library search path + { + let mut s = OsString::from("-L"); + s.push(ios_support.join("usr/lib")); + s + }, + // Framework linker search path + { + // Technically, we _could_ avoid emitting `-F`, as + // `-iframework` implies it, but let's keep it in for + // clarity. + let mut s = OsString::from("-F"); + s.push(ios_support.join("System/Library/Frameworks")); + s + }, + ]); + } + } + + Ok(()) + } + + fn cmd>(&self, prog: P) -> Command { + let mut cmd = Command::new(prog); + for (a, b) in self.env.iter() { + cmd.env(a, b); + } + cmd + } + + fn get_base_compiler(&self) -> Result { + let out_dir = self.get_out_dir().ok(); + let out_dir = out_dir.as_deref(); + + if let Some(c) = &self.compiler { + return Ok(Tool::new( + (**c).to_owned(), + &self.cached_compiler_family, + &self.cargo_output, + out_dir, + )); + } + let target = self.get_target()?; + let target = &*target; + let (env, msvc, gnu, traditional, clang) = if self.cpp { + ("CXX", "cl.exe", "g++", "c++", "clang++") + } else { + ("CC", "cl.exe", "gcc", "cc", "clang") + }; + + // On historical Solaris systems, "cc" may have been Sun Studio, which + // is not flag-compatible with "gcc". This history casts a long shadow, + // and many modern illumos distributions today ship GCC as "gcc" without + // also making it available as "cc". + let default = if cfg!(target_os = "solaris") || cfg!(target_os = "illumos") { + gnu + } else { + traditional + }; + + let cl_exe = self.windows_registry_find_tool(target, "cl.exe"); + + let tool_opt: Option = self + .env_tool(env) + .map(|(tool, wrapper, args)| { + // find the driver mode, if any + const DRIVER_MODE: &str = "--driver-mode="; + let driver_mode = args + .iter() + .find(|a| a.starts_with(DRIVER_MODE)) + .map(|a| &a[DRIVER_MODE.len()..]); + // Chop off leading/trailing whitespace to work around + // semi-buggy build scripts which are shared in + // makefiles/configure scripts (where spaces are far more + // lenient) + let mut t = Tool::with_clang_driver( + tool, + driver_mode, + &self.cached_compiler_family, + &self.cargo_output, + out_dir, + ); + if let Some(cc_wrapper) = wrapper { + t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned()); + } + for arg in args { + t.cc_wrapper_args.push(arg.into()); + } + t + }) + .or_else(|| { + if target.contains("emscripten") { + let tool = if self.cpp { "em++" } else { "emcc" }; + // Windows uses bat file so we have to be a bit more specific + if cfg!(windows) { + let mut t = Tool::with_family( + PathBuf::from("cmd"), + ToolFamily::Clang { zig_cc: false }, + ); + t.args.push("/c".into()); + t.args.push(format!("{}.bat", tool).into()); + Some(t) + } else { + Some(Tool::new( + PathBuf::from(tool), + &self.cached_compiler_family, + &self.cargo_output, + out_dir, + )) + } + } else { + None + } + }) + .or_else(|| cl_exe.clone()); + + let tool = match tool_opt { + Some(t) => t, + None => { + let compiler = if cfg!(windows) && target.contains("windows") { + if target.contains("msvc") { + msvc.to_string() + } else { + let cc = if target.contains("llvm") { clang } else { gnu }; + format!("{}.exe", cc) + } + } else if target.contains("apple-ios") + | target.contains("apple-watchos") + | target.contains("apple-tvos") + | target.contains("apple-visionos") + { + clang.to_string() + } else if target.contains("android") { + autodetect_android_compiler(target, gnu, clang) + } else if target.contains("cloudabi") { + format!("{}-{}", target, traditional) + } else if Build::is_wasi_target(target) { + if self.cpp { + "clang++".to_string() + } else { + "clang".to_string() + } + } else if target.contains("vxworks") { + if self.cpp { + "wr-c++".to_string() + } else { + "wr-cc".to_string() + } + } else if target.starts_with("armv7a-kmc-solid_") { + format!("arm-kmc-eabi-{}", gnu) + } else if target.starts_with("aarch64-kmc-solid_") { + format!("aarch64-kmc-elf-{}", gnu) + } else if self.get_is_cross_compile()? { + let prefix = self.prefix_for_target(target); + match prefix { + Some(prefix) => { + let cc = if target.contains("llvm") { clang } else { gnu }; + format!("{}-{}", prefix, cc) + } + None => default.to_string(), + } + } else { + default.to_string() + }; + + let mut t = Tool::new( + PathBuf::from(compiler), + &self.cached_compiler_family, + &self.cargo_output, + out_dir, + ); + if let Some(cc_wrapper) = self.rustc_wrapper_fallback() { + t.cc_wrapper_path = Some(Path::new(&cc_wrapper).to_owned()); + } + t + } + }; + + let mut tool = if self.cuda { + assert!( + tool.args.is_empty(), + "CUDA compilation currently assumes empty pre-existing args" + ); + let nvcc = match self.getenv_with_target_prefixes("NVCC") { + Err(_) => PathBuf::from("nvcc"), + Ok(nvcc) => PathBuf::from(&*nvcc), + }; + let mut nvcc_tool = Tool::with_features( + nvcc, + None, + self.cuda, + &self.cached_compiler_family, + &self.cargo_output, + out_dir, + ); + if self.ccbin { + nvcc_tool + .args + .push(format!("-ccbin={}", tool.path.display()).into()); + } + nvcc_tool.family = tool.family; + nvcc_tool + } else { + tool + }; + + // New "standalone" C/C++ cross-compiler executables from recent Android NDK + // are just shell scripts that call main clang binary (from Android NDK) with + // proper `--target` argument. + // + // For example, armv7a-linux-androideabi16-clang passes + // `--target=armv7a-linux-androideabi16` to clang. + // + // As the shell script calls the main clang binary, the command line limit length + // on Windows is restricted to around 8k characters instead of around 32k characters. + // To remove this limit, we call the main clang binary directly and construct the + // `--target=` ourselves. + if cfg!(windows) && android_clang_compiler_uses_target_arg_internally(&tool.path) { + if let Some(path) = tool.path.file_name() { + let file_name = path.to_str().unwrap().to_owned(); + let (target, clang) = file_name.split_at(file_name.rfind('-').unwrap()); + + tool.has_internal_target_arg = true; + tool.path.set_file_name(clang.trim_start_matches('-')); + tool.path.set_extension("exe"); + tool.args.push(format!("--target={}", target).into()); + + // Additionally, shell scripts for target i686-linux-android versions 16 to 24 + // pass the `mstackrealign` option so we do that here as well. + if target.contains("i686-linux-android") { + let (_, version) = target.split_at(target.rfind('d').unwrap() + 1); + if let Ok(version) = version.parse::() { + if version > 15 && version < 25 { + tool.args.push("-mstackrealign".into()); + } + } + } + }; + } + + // If we found `cl.exe` in our environment, the tool we're returning is + // an MSVC-like tool, *and* no env vars were set then set env vars for + // the tool that we're returning. + // + // Env vars are needed for things like `link.exe` being put into PATH as + // well as header include paths sometimes. These paths are automatically + // included by default but if the `CC` or `CXX` env vars are set these + // won't be used. This'll ensure that when the env vars are used to + // configure for invocations like `clang-cl` we still get a "works out + // of the box" experience. + if let Some(cl_exe) = cl_exe { + if tool.family == (ToolFamily::Msvc { clang_cl: true }) + && tool.env.is_empty() + && target.contains("msvc") + { + for (k, v) in cl_exe.env.iter() { + tool.env.push((k.to_owned(), v.to_owned())); + } + } + } + + if target.contains("msvc") && tool.family == ToolFamily::Gnu { + self.cargo_output + .print_warning(&"GNU compiler is not supported for this target"); + } + + Ok(tool) + } + + /// Returns a fallback `cc_compiler_wrapper` by introspecting `RUSTC_WRAPPER` + fn rustc_wrapper_fallback(&self) -> Option> { + // No explicit CC wrapper was detected, but check if RUSTC_WRAPPER + // is defined and is a build accelerator that is compatible with + // C/C++ compilers (e.g. sccache) + const VALID_WRAPPERS: &[&str] = &["sccache", "cachepot", "buildcache"]; + + let rustc_wrapper = self.getenv("RUSTC_WRAPPER")?; + let wrapper_path = Path::new(&rustc_wrapper); + let wrapper_stem = wrapper_path.file_stem()?; + + if VALID_WRAPPERS.contains(&wrapper_stem.to_str()?) { + Some(rustc_wrapper) + } else { + None + } + } + + /// Returns compiler path, optional modifier name from whitelist, and arguments vec + fn env_tool(&self, name: &str) -> Option<(PathBuf, Option>, Vec)> { + let tool = self.getenv_with_target_prefixes(name).ok()?; + let tool = tool.to_string_lossy(); + let tool = tool.trim(); + + if tool.is_empty() { + return None; + } + + // If this is an exact path on the filesystem we don't want to do any + // interpretation at all, just pass it on through. This'll hopefully get + // us to support spaces-in-paths. + if Path::new(tool).exists() { + return Some(( + PathBuf::from(tool), + self.rustc_wrapper_fallback(), + Vec::new(), + )); + } + + // Ok now we want to handle a couple of scenarios. We'll assume from + // here on out that spaces are splitting separate arguments. Two major + // features we want to support are: + // + // CC='sccache cc' + // + // aka using `sccache` or any other wrapper/caching-like-thing for + // compilations. We want to know what the actual compiler is still, + // though, because our `Tool` API support introspection of it to see + // what compiler is in use. + // + // additionally we want to support + // + // CC='cc -flag' + // + // where the CC env var is used to also pass default flags to the C + // compiler. + // + // It's true that everything here is a bit of a pain, but apparently if + // you're not literally make or bash then you get a lot of bug reports. + let mut known_wrappers = vec![ + "ccache", + "distcc", + "sccache", + "icecc", + "cachepot", + "buildcache", + ]; + let custom_wrapper = self.getenv("CC_KNOWN_WRAPPER_CUSTOM"); + if custom_wrapper.is_some() { + known_wrappers.push(custom_wrapper.as_deref().unwrap().to_str().unwrap()); + } + + let mut parts = tool.split_whitespace(); + let maybe_wrapper = match parts.next() { + Some(s) => s, + None => return None, + }; + + let file_stem = Path::new(maybe_wrapper).file_stem()?.to_str()?; + if known_wrappers.contains(&file_stem) { + if let Some(compiler) = parts.next() { + return Some(( + compiler.into(), + Some(Arc::::from(OsStr::new(&maybe_wrapper))), + parts.map(|s| s.to_string()).collect(), + )); + } + } + + Some(( + maybe_wrapper.into(), + self.rustc_wrapper_fallback(), + parts.map(|s| s.to_string()).collect(), + )) + } + + /// Returns the C++ standard library: + /// 1. If [`cpp_link_stdlib`](cc::Build::cpp_link_stdlib) is set, uses its value. + /// 2. Else if the `CXXSTDLIB` environment variable is set, uses its value. + /// 3. Else the default is `c++` for OS X and BSDs, `c++_shared` for Android, + /// `None` for MSVC and `stdc++` for anything else. + fn get_cpp_link_stdlib(&self) -> Result>, Error> { + match &self.cpp_link_stdlib { + Some(s) => Ok(s.as_deref().map(Path::new).map(Cow::Borrowed)), + None => { + if let Ok(stdlib) = self.getenv_with_target_prefixes("CXXSTDLIB") { + if stdlib.is_empty() { + Ok(None) + } else { + Ok(Some(Cow::Owned(Path::new(&stdlib).to_owned()))) + } + } else { + let target = self.get_target()?; + if target.contains("msvc") { + Ok(None) + } else if target.contains("apple") + | target.contains("freebsd") + | target.contains("openbsd") + | target.contains("aix") + | target.contains("linux-ohos") + | target.contains("-wasi") + { + Ok(Some(Cow::Borrowed(Path::new("c++")))) + } else if target.contains("android") { + Ok(Some(Cow::Borrowed(Path::new("c++_shared")))) + } else { + Ok(Some(Cow::Borrowed(Path::new("stdc++")))) + } + } + } + } + } + + fn get_ar(&self) -> Result<(Command, PathBuf, bool), Error> { + self.try_get_archiver_and_flags() + } + + /// Get the archiver (ar) that's in use for this configuration. + /// + /// You can use [`Command::get_program`] to get just the path to the command. + /// + /// This method will take into account all configuration such as debug + /// information, optimization level, include directories, defines, etc. + /// Additionally, the compiler binary in use follows the standard + /// conventions for this path, e.g. looking at the explicitly set compiler, + /// environment variables (a number of which are inspected here), and then + /// falling back to the default configuration. + /// + /// # Panics + /// + /// Panics if an error occurred while determining the architecture. + pub fn get_archiver(&self) -> Command { + match self.try_get_archiver() { + Ok(tool) => tool, + Err(e) => fail(&e.message), + } + } + + /// Get the archiver that's in use for this configuration. + /// + /// This will return a result instead of panicking; + /// see [`Self::get_archiver`] for the complete description. + pub fn try_get_archiver(&self) -> Result { + Ok(self.try_get_archiver_and_flags()?.0) + } + + fn try_get_archiver_and_flags(&self) -> Result<(Command, PathBuf, bool), Error> { + let (mut cmd, name) = self.get_base_archiver()?; + let mut any_flags = false; + if let Ok(flags) = self.envflags("ARFLAGS") { + any_flags |= !flags.is_empty(); + cmd.args(flags); + } + for flag in &self.ar_flags { + any_flags = true; + cmd.arg(&**flag); + } + Ok((cmd, name, any_flags)) + } + + fn get_base_archiver(&self) -> Result<(Command, PathBuf), Error> { + if let Some(ref a) = self.archiver { + let archiver = &**a; + return Ok((self.cmd(archiver), archiver.into())); + } + + self.get_base_archiver_variant("AR", "ar") + } + + /// Get the ranlib that's in use for this configuration. + /// + /// You can use [`Command::get_program`] to get just the path to the command. + /// + /// This method will take into account all configuration such as debug + /// information, optimization level, include directories, defines, etc. + /// Additionally, the compiler binary in use follows the standard + /// conventions for this path, e.g. looking at the explicitly set compiler, + /// environment variables (a number of which are inspected here), and then + /// falling back to the default configuration. + /// + /// # Panics + /// + /// Panics if an error occurred while determining the architecture. + pub fn get_ranlib(&self) -> Command { + match self.try_get_ranlib() { + Ok(tool) => tool, + Err(e) => fail(&e.message), + } + } + + /// Get the ranlib that's in use for this configuration. + /// + /// This will return a result instead of panicking; + /// see [`Self::get_ranlib`] for the complete description. + pub fn try_get_ranlib(&self) -> Result { + let mut cmd = self.get_base_ranlib()?; + if let Ok(flags) = self.envflags("RANLIBFLAGS") { + cmd.args(flags); + } + Ok(cmd) + } + + fn get_base_ranlib(&self) -> Result { + if let Some(ref r) = self.ranlib { + return Ok(self.cmd(&**r)); + } + + Ok(self.get_base_archiver_variant("RANLIB", "ranlib")?.0) + } + + fn get_base_archiver_variant( + &self, + env: &str, + tool: &str, + ) -> Result<(Command, PathBuf), Error> { + let target = self.get_target()?; + let mut name = PathBuf::new(); + let tool_opt: Option = self + .env_tool(env) + .map(|(tool, _wrapper, args)| { + name.clone_from(&tool); + let mut cmd = self.cmd(tool); + cmd.args(args); + cmd + }) + .or_else(|| { + if target.contains("emscripten") { + // Windows use bat files so we have to be a bit more specific + if cfg!(windows) { + let mut cmd = self.cmd("cmd"); + name = format!("em{}.bat", tool).into(); + cmd.arg("/c").arg(&name); + Some(cmd) + } else { + name = format!("em{}", tool).into(); + Some(self.cmd(&name)) + } + } else if target.starts_with("wasm32") { + // Formally speaking one should be able to use this approach, + // parsing -print-search-dirs output, to cover all clang targets, + // including Android SDKs and other cross-compilation scenarios... + // And even extend it to gcc targets by searching for "ar" instead + // of "llvm-ar"... + let compiler = self.get_base_compiler().ok()?; + if compiler.is_like_clang() { + name = format!("llvm-{}", tool).into(); + self.search_programs( + &mut self.cmd(&compiler.path), + &name, + &self.cargo_output, + ) + .map(|name| self.cmd(name)) + } else { + None + } + } else { + None + } + }); + + let default = tool.to_string(); + let tool = match tool_opt { + Some(t) => t, + None => { + if target.contains("android") { + name = format!("llvm-{}", tool).into(); + match Command::new(&name).arg("--version").status() { + Ok(status) if status.success() => (), + _ => name = format!("{}-{}", target.replace("armv7", "arm"), tool).into(), + } + self.cmd(&name) + } else if target.contains("msvc") { + // NOTE: There isn't really a ranlib on msvc, so arguably we should return + // `None` somehow here. But in general, callers will already have to be aware + // of not running ranlib on Windows anyway, so it feels okay to return lib.exe + // here. + + let compiler = self.get_base_compiler()?; + let mut lib = String::new(); + if compiler.family == (ToolFamily::Msvc { clang_cl: true }) { + // See if there is 'llvm-lib' next to 'clang-cl' + // Another possibility could be to see if there is 'clang' + // next to 'clang-cl' and use 'search_programs()' to locate + // 'llvm-lib'. This is because 'clang-cl' doesn't support + // the -print-search-dirs option. + if let Some(mut cmd) = self.which(&compiler.path, None) { + cmd.pop(); + cmd.push("llvm-lib.exe"); + if let Some(llvm_lib) = self.which(&cmd, None) { + llvm_lib.to_str().unwrap().clone_into(&mut lib); + } + } + } + + if lib.is_empty() { + name = PathBuf::from("lib.exe"); + let mut cmd = match self.windows_registry_find(&target, "lib.exe") { + Some(t) => t, + None => self.cmd("lib.exe"), + }; + if target.contains("arm64ec") { + cmd.arg("/machine:arm64ec"); + } + cmd + } else { + name = lib.into(); + self.cmd(&name) + } + } else if target.contains("illumos") { + // The default 'ar' on illumos uses a non-standard flags, + // but the OS comes bundled with a GNU-compatible variant. + // + // Use the GNU-variant to match other Unix systems. + name = format!("g{}", tool).into(); + self.cmd(&name) + } else if self.get_is_cross_compile()? { + match self.prefix_for_target(&target) { + Some(p) => { + // GCC uses $target-gcc-ar, whereas binutils uses $target-ar -- try both. + // Prefer -ar if it exists, as builds of `-gcc-ar` have been observed to be + // outright broken (such as when targeting freebsd with `--disable-lto` + // toolchain where the archiver attempts to load the LTO plugin anyway but + // fails to find one). + // + // The same applies to ranlib. + let mut chosen = default; + for &infix in &["", "-gcc"] { + let target_p = format!("{}{}-{}", p, infix, tool); + if Command::new(&target_p).output().is_ok() { + chosen = target_p; + break; + } + } + name = chosen.into(); + self.cmd(&name) + } + None => { + name = default.into(); + self.cmd(&name) + } + } + } else { + name = default.into(); + self.cmd(&name) + } + } + }; + + Ok((tool, name)) + } + + fn prefix_for_target(&self, target: &str) -> Option> { + // CROSS_COMPILE is of the form: "arm-linux-gnueabi-" + self.getenv("CROSS_COMPILE") + .as_deref() + .map(|s| s.to_string_lossy().trim_end_matches('-').to_owned()) + .map(Cow::Owned) + .or_else(|| { + // Put aside RUSTC_LINKER's prefix to be used as second choice, after CROSS_COMPILE + self.getenv("RUSTC_LINKER").and_then(|var| { + var.to_string_lossy() + .strip_suffix("-gcc") + .map(str::to_string) + .map(Cow::Owned) + }) + }) + .or_else(|| { + match target { + // Note: there is no `aarch64-pc-windows-gnu` target, only `-gnullvm` + "aarch64-pc-windows-gnullvm" => Some("aarch64-w64-mingw32"), + "aarch64-uwp-windows-gnu" => Some("aarch64-w64-mingw32"), + "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"), + "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"), + "aarch64-unknown-netbsd" => Some("aarch64--netbsd"), + "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), + "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), + "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), + "armv5te-unknown-linux-musleabi" => Some("arm-linux-gnueabi"), + "arm-frc-linux-gnueabi" => Some("arm-frc-linux-gnueabi"), + "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), + "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"), + "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), + "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"), + "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"), + "armv7-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), + "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), + "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), + "armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), + "armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), + "thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), + "thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), + "thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), + "thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), + "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"), + "hexagon-unknown-linux-musl" => Some("hexagon-linux-musl"), + "i586-unknown-linux-musl" => Some("musl"), + "i686-pc-windows-gnu" => Some("i686-w64-mingw32"), + "i686-uwp-windows-gnu" => Some("i686-w64-mingw32"), + "i686-unknown-linux-gnu" => self.find_working_gnu_prefix(&[ + "i686-linux-gnu", + "x86_64-linux-gnu", // transparently support gcc-multilib + ]), // explicit None if not found, so caller knows to fall back + "i686-unknown-linux-musl" => Some("musl"), + "i686-unknown-netbsd" => Some("i486--netbsdelf"), + "loongarch64-unknown-linux-gnu" => Some("loongarch64-linux-gnu"), + "mips-unknown-linux-gnu" => Some("mips-linux-gnu"), + "mips-unknown-linux-musl" => Some("mips-linux-musl"), + "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"), + "mipsel-unknown-linux-musl" => Some("mipsel-linux-musl"), + "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"), + "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"), + "mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"), + "mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"), + "mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"), + "mipsisa64r6el-unknown-linux-gnuabi64" => Some("mipsisa64r6el-linux-gnuabi64"), + "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"), + "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"), + "powerpc-unknown-netbsd" => Some("powerpc--netbsd"), + "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"), + "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"), + "riscv32i-unknown-none-elf" => self.find_working_gnu_prefix(&[ + "riscv32-unknown-elf", + "riscv64-unknown-elf", + "riscv-none-embed", + ]), + "riscv32imac-esp-espidf" => Some("riscv32-esp-elf"), + "riscv32imac-unknown-none-elf" => self.find_working_gnu_prefix(&[ + "riscv32-unknown-elf", + "riscv64-unknown-elf", + "riscv-none-embed", + ]), + "riscv32imac-unknown-xous-elf" => self.find_working_gnu_prefix(&[ + "riscv32-unknown-elf", + "riscv64-unknown-elf", + "riscv-none-embed", + ]), + "riscv32imc-esp-espidf" => Some("riscv32-esp-elf"), + "riscv32imc-unknown-none-elf" => self.find_working_gnu_prefix(&[ + "riscv32-unknown-elf", + "riscv64-unknown-elf", + "riscv-none-embed", + ]), + "riscv64gc-unknown-none-elf" => self.find_working_gnu_prefix(&[ + "riscv64-unknown-elf", + "riscv32-unknown-elf", + "riscv-none-embed", + ]), + "riscv64imac-unknown-none-elf" => self.find_working_gnu_prefix(&[ + "riscv64-unknown-elf", + "riscv32-unknown-elf", + "riscv-none-embed", + ]), + "riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"), + "riscv32gc-unknown-linux-gnu" => Some("riscv32-linux-gnu"), + "riscv64gc-unknown-linux-musl" => Some("riscv64-linux-musl"), + "riscv32gc-unknown-linux-musl" => Some("riscv32-linux-musl"), + "riscv64gc-unknown-netbsd" => Some("riscv64--netbsd"), + "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"), + "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"), + "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"), + "sparc64-unknown-netbsd" => Some("sparc64--netbsd"), + "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"), + "armv7a-none-eabi" => Some("arm-none-eabi"), + "armv7a-none-eabihf" => Some("arm-none-eabi"), + "armebv7r-none-eabi" => Some("arm-none-eabi"), + "armebv7r-none-eabihf" => Some("arm-none-eabi"), + "armv7r-none-eabi" => Some("arm-none-eabi"), + "armv7r-none-eabihf" => Some("arm-none-eabi"), + "armv8r-none-eabihf" => Some("arm-none-eabi"), + "thumbv6m-none-eabi" => Some("arm-none-eabi"), + "thumbv7em-none-eabi" => Some("arm-none-eabi"), + "thumbv7em-none-eabihf" => Some("arm-none-eabi"), + "thumbv7m-none-eabi" => Some("arm-none-eabi"), + "thumbv8m.base-none-eabi" => Some("arm-none-eabi"), + "thumbv8m.main-none-eabi" => Some("arm-none-eabi"), + "thumbv8m.main-none-eabihf" => Some("arm-none-eabi"), + "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"), + "x86_64-pc-windows-gnullvm" => Some("x86_64-w64-mingw32"), + "x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"), + "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"), + "x86_64-unknown-linux-gnu" => self.find_working_gnu_prefix(&[ + "x86_64-linux-gnu", // rustfmt wrap + ]), // explicit None if not found, so caller knows to fall back + "x86_64-unknown-linux-musl" => Some("musl"), + "x86_64-unknown-netbsd" => Some("x86_64--netbsd"), + _ => None, + } + .map(Cow::Borrowed) + }) + } + + /// Some platforms have multiple, compatible, canonical prefixes. Look through + /// each possible prefix for a compiler that exists and return it. The prefixes + /// should be ordered from most-likely to least-likely. + fn find_working_gnu_prefix(&self, prefixes: &[&'static str]) -> Option<&'static str> { + let suffix = if self.cpp { "-g++" } else { "-gcc" }; + let extension = std::env::consts::EXE_SUFFIX; + + // Loop through PATH entries searching for each toolchain. This ensures that we + // are more likely to discover the toolchain early on, because chances are good + // that the desired toolchain is in one of the higher-priority paths. + self.getenv("PATH") + .as_ref() + .and_then(|path_entries| { + env::split_paths(path_entries).find_map(|path_entry| { + for prefix in prefixes { + let target_compiler = format!("{}{}{}", prefix, suffix, extension); + if path_entry.join(&target_compiler).exists() { + return Some(prefix); + } + } + None + }) + }) + .copied() + // If no toolchain was found, provide the first toolchain that was passed in. + // This toolchain has been shown not to exist, however it will appear in the + // error that is shown to the user which should make it easier to search for + // where it should be obtained. + .or_else(|| prefixes.first().copied()) + } + + fn get_target(&self) -> Result, Error> { + match &self.target { + Some(t) => Ok(Cow::Borrowed(t)), + None => self.getenv_unwrap_str("TARGET").map(Cow::Owned), + } + } + + fn get_is_cross_compile(&self) -> Result { + let target = self.get_target()?; + let host: Cow<'_, str> = match &self.host { + Some(h) => Cow::Borrowed(h), + None => Cow::Owned(self.getenv_unwrap_str("HOST")?), + }; + Ok(host != target) + } + + fn get_opt_level(&self) -> Result, Error> { + match &self.opt_level { + Some(ol) => Ok(Cow::Borrowed(ol)), + None => self.getenv_unwrap_str("OPT_LEVEL").map(Cow::Owned), + } + } + + fn get_debug(&self) -> bool { + self.debug.unwrap_or_else(|| self.getenv_boolean("DEBUG")) + } + + fn get_shell_escaped_flags(&self) -> bool { + self.shell_escaped_flags + .unwrap_or_else(|| self.getenv_boolean("CC_SHELL_ESCAPED_FLAGS")) + } + + fn get_dwarf_version(&self) -> Option { + // Tentatively matches the DWARF version defaults as of rustc 1.62. + let target = self.get_target().ok()?; + if target.contains("android") + || target.contains("apple") + || target.contains("dragonfly") + || target.contains("freebsd") + || target.contains("netbsd") + || target.contains("openbsd") + || target.contains("windows-gnu") + { + Some(2) + } else if target.contains("linux") { + Some(4) + } else { + None + } + } + + fn get_force_frame_pointer(&self) -> bool { + self.force_frame_pointer.unwrap_or_else(|| self.get_debug()) + } + + fn get_out_dir(&self) -> Result, Error> { + match &self.out_dir { + Some(p) => Ok(Cow::Borrowed(&**p)), + None => self + .getenv("OUT_DIR") + .as_deref() + .map(PathBuf::from) + .map(Cow::Owned) + .ok_or_else(|| { + Error::new( + ErrorKind::EnvVarNotFound, + "Environment variable OUT_DIR not defined.", + ) + }), + } + } + + #[allow(clippy::disallowed_methods)] + fn getenv(&self, v: &str) -> Option> { + // Returns true for environment variables cargo sets for build scripts: + // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts + // + // This handles more of the vars than we actually use (it tries to check + // complete-ish set), just to avoid needing maintenance if/when new + // calls to `getenv`/`getenv_unwrap` are added. + fn provided_by_cargo(envvar: &str) -> bool { + match envvar { + v if v.starts_with("CARGO") || v.starts_with("RUSTC") => true, + "HOST" | "TARGET" | "RUSTDOC" | "OUT_DIR" | "OPT_LEVEL" | "DEBUG" | "PROFILE" + | "NUM_JOBS" | "RUSTFLAGS" => true, + _ => false, + } + } + if let Some(val) = self.env_cache.read().unwrap().get(v).cloned() { + return val; + } + if self.emit_rerun_if_env_changed && !provided_by_cargo(v) && v != "PATH" { + self.cargo_output + .print_metadata(&format_args!("cargo:rerun-if-env-changed={}", v)); + } + let r = env::var_os(v).map(Arc::from); + self.cargo_output.print_metadata(&format_args!( + "{} = {}", + v, + OptionOsStrDisplay(r.as_deref()) + )); + self.env_cache.write().unwrap().insert(v.into(), r.clone()); + r + } + + /// get boolean flag that is either true or false + fn getenv_boolean(&self, v: &str) -> bool { + match self.getenv(v) { + Some(s) => &*s != "0" && &*s != "false" && !s.is_empty(), + None => false, + } + } + + fn getenv_unwrap(&self, v: &str) -> Result, Error> { + match self.getenv(v) { + Some(s) => Ok(s), + None => Err(Error::new( + ErrorKind::EnvVarNotFound, + format!("Environment variable {} not defined.", v), + )), + } + } + + fn getenv_unwrap_str(&self, v: &str) -> Result { + let env = self.getenv_unwrap(v)?; + env.to_str().map(String::from).ok_or_else(|| { + Error::new( + ErrorKind::EnvVarNotFound, + format!("Environment variable {} is not valid utf-8.", v), + ) + }) + } + + fn getenv_with_target_prefixes(&self, var_base: &str) -> Result, Error> { + let target = self.get_target()?; + let kind = if self.get_is_cross_compile()? { + "TARGET" + } else { + "HOST" + }; + let target_u = target.replace('-', "_"); + let res = self + .getenv(&format!("{}_{}", var_base, target)) + .or_else(|| self.getenv(&format!("{}_{}", var_base, target_u))) + .or_else(|| self.getenv(&format!("{}_{}", kind, var_base))) + .or_else(|| self.getenv(var_base)); + + match res { + Some(res) => Ok(res), + None => Err(Error::new( + ErrorKind::EnvVarNotFound, + format!("Could not find environment variable {}.", var_base), + )), + } + } + + fn envflags(&self, name: &str) -> Result, Error> { + let env_os = self.getenv_with_target_prefixes(name)?; + let env = env_os.to_string_lossy(); + + if self.get_shell_escaped_flags() { + Ok(Shlex::new(&env).collect()) + } else { + Ok(env + .split_ascii_whitespace() + .map(ToString::to_string) + .collect()) + } + } + + fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> { + let target = self.get_target()?; + if cfg!(target_os = "macos") && target.contains("apple-darwin") { + // Additionally, `IPHONEOS_DEPLOYMENT_TARGET` must not be set when using the Xcode linker at + // "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld", + // although this is apparently ignored when using the linker at "/usr/bin/ld". + cmd.env_remove("IPHONEOS_DEPLOYMENT_TARGET"); + } + Ok(()) + } + + fn apple_sdk_root_inner(&self, sdk: &str) -> Result, Error> { + // Code copied from rustc's compiler/rustc_codegen_ssa/src/back/link.rs. + if let Some(sdkroot) = self.getenv("SDKROOT") { + let p = Path::new(&sdkroot); + let does_sdkroot_contain = |strings: &[&str]| { + let sdkroot_str = p.to_string_lossy(); + strings.iter().any(|s| sdkroot_str.contains(s)) + }; + match sdk { + // Ignore `SDKROOT` if it's clearly set for the wrong platform. + "appletvos" + if does_sdkroot_contain(&["TVSimulator.platform", "MacOSX.platform"]) => {} + "appletvsimulator" + if does_sdkroot_contain(&["TVOS.platform", "MacOSX.platform"]) => {} + "iphoneos" + if does_sdkroot_contain(&["iPhoneSimulator.platform", "MacOSX.platform"]) => {} + "iphonesimulator" + if does_sdkroot_contain(&["iPhoneOS.platform", "MacOSX.platform"]) => {} + "macosx10.15" + if does_sdkroot_contain(&["iPhoneOS.platform", "iPhoneSimulator.platform"]) => { + } + "watchos" + if does_sdkroot_contain(&["WatchSimulator.platform", "MacOSX.platform"]) => {} + "watchsimulator" + if does_sdkroot_contain(&["WatchOS.platform", "MacOSX.platform"]) => {} + "xros" if does_sdkroot_contain(&["XRSimulator.platform", "MacOSX.platform"]) => {} + "xrsimulator" if does_sdkroot_contain(&["XROS.platform", "MacOSX.platform"]) => {} + // Ignore `SDKROOT` if it's not a valid path. + _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {} + _ => return Ok(sdkroot), + } + } + + let sdk_path = run_output( + self.cmd("xcrun") + .arg("--show-sdk-path") + .arg("--sdk") + .arg(sdk), + "xcrun", + &self.cargo_output, + )?; + + let sdk_path = match String::from_utf8(sdk_path) { + Ok(p) => p, + Err(_) => { + return Err(Error::new( + ErrorKind::IOError, + "Unable to determine Apple SDK path.", + )); + } + }; + Ok(Arc::from(OsStr::new(sdk_path.trim()))) + } + + fn apple_sdk_root(&self, sdk: &str) -> Result, Error> { + if let Some(ret) = self + .apple_sdk_root_cache + .read() + .expect("apple_sdk_root_cache lock failed") + .get(sdk) + .cloned() + { + return Ok(ret); + } + let sdk_path = self.apple_sdk_root_inner(sdk)?; + self.apple_sdk_root_cache + .write() + .expect("apple_sdk_root_cache lock failed") + .insert(sdk.into(), sdk_path.clone()); + Ok(sdk_path) + } + + fn apple_deployment_version(&self, os: AppleOs, arch_str: Option<&str>, sdk: &str) -> Arc { + if let Some(ret) = self + .apple_versions_cache + .read() + .expect("apple_versions_cache lock failed") + .get(sdk) + .cloned() + { + return ret; + } + + let default_deployment_from_sdk = || -> Option> { + let version = run_output( + self.cmd("xcrun") + .arg("--show-sdk-version") + .arg("--sdk") + .arg(sdk), + "xcrun", + &self.cargo_output, + ) + .ok()?; + + Some(Arc::from(std::str::from_utf8(&version).ok()?.trim())) + }; + + let deployment_from_env = |name: &str| -> Option> { + // note that self.env isn't hit in production codepaths, its mostly just for tests which don't + // set the real env + self.env + .iter() + .find(|(k, _)| &**k == OsStr::new(name)) + .map(|(_, v)| v) + .cloned() + .or_else(|| self.getenv(name))? + .to_str() + .map(Arc::from) + }; + + // Determines if the acquired deployment target is too low to support modern C++ on some Apple platform. + // + // A long time ago they used libstdc++, but since macOS 10.9 and iOS 7 libc++ has been the library the SDKs provide to link against. + // If a `cc`` config wants to use C++, we round up to these versions as the baseline. + let maybe_cpp_version_baseline = |deployment_target_ver: Arc| -> Option> { + if !self.cpp { + return Some(deployment_target_ver); + } + + let mut deployment_target = deployment_target_ver + .split('.') + .map(|v| v.parse::().expect("integer version")); + + match os { + AppleOs::MacOs => { + let major = deployment_target.next().unwrap_or(0); + let minor = deployment_target.next().unwrap_or(0); + + // If below 10.9, we ignore it and let the SDK's target definitions handle it. + if major == 10 && minor < 9 { + self.cargo_output.print_warning(&format_args!( + "macOS deployment target ({}) too low, it will be increased", + deployment_target_ver + )); + return None; + } + } + AppleOs::Ios => { + let major = deployment_target.next().unwrap_or(0); + + // If below 10.7, we ignore it and let the SDK's target definitions handle it. + if major < 7 { + self.cargo_output.print_warning(&format_args!( + "iOS deployment target ({}) too low, it will be increased", + deployment_target_ver + )); + return None; + } + } + // watchOS, tvOS, visionOS, and others are all new enough that libc++ is their baseline. + _ => {} + } + + // If the deployment target met or exceeded the C++ baseline + Some(deployment_target_ver) + }; + + // The hardcoded minimums here are subject to change in a future compiler release, + // and only exist as last resort fallbacks. Don't consider them stable. + // `cc` doesn't use rustc's `--print deployment-target`` because the compiler's defaults + // don't align well with Apple's SDKs and other third-party libraries that require ~generally~ higher + // deployment targets. rustc isn't interested in those by default though so its fine to be different here. + // + // If no explicit target is passed, `cc` defaults to the current Xcode SDK's `DefaultDeploymentTarget` for better + // compatibility. This is also the crate's historical behavior and what has become a relied-on value. + // + // The ordering of env -> XCode SDK -> old rustc defaults is intentional for performance when using + // an explicit target. + let version: Arc = match os { + AppleOs::MacOs => deployment_from_env("MACOSX_DEPLOYMENT_TARGET") + .and_then(maybe_cpp_version_baseline) + .or_else(default_deployment_from_sdk) + .unwrap_or_else(|| { + if arch_str == Some("aarch64") { + "11.0".into() + } else { + let default: Arc = Arc::from("10.7"); + maybe_cpp_version_baseline(default.clone()).unwrap_or(default) + } + }), + + AppleOs::Ios => deployment_from_env("IPHONEOS_DEPLOYMENT_TARGET") + .and_then(maybe_cpp_version_baseline) + .or_else(default_deployment_from_sdk) + .unwrap_or_else(|| "7.0".into()), + + AppleOs::WatchOs => deployment_from_env("WATCHOS_DEPLOYMENT_TARGET") + .or_else(default_deployment_from_sdk) + .unwrap_or_else(|| "5.0".into()), + + AppleOs::TvOs => deployment_from_env("TVOS_DEPLOYMENT_TARGET") + .or_else(default_deployment_from_sdk) + .unwrap_or_else(|| "9.0".into()), + + AppleOs::VisionOS => deployment_from_env("XROS_DEPLOYMENT_TARGET") + .or_else(default_deployment_from_sdk) + .unwrap_or_else(|| "1.0".into()), + }; + + self.apple_versions_cache + .write() + .expect("apple_versions_cache lock failed") + .insert(sdk.into(), version.clone()); + + version + } + + fn wasi_sysroot(&self) -> Result, Error> { + if let Some(wasi_sysroot_path) = self.getenv("WASI_SYSROOT") { + Ok(wasi_sysroot_path) + } else { + Err(Error::new( + ErrorKind::EnvVarNotFound, + "Environment variable WASI_SYSROOT not defined. Download sysroot from GitHub & setup environment variable WASI_SYSROOT targeting the folder.", + )) + } + } + fn is_wasi_target(target: &str) -> bool { + const TARGETS: [&str; 7] = [ + "wasm32-wasi", + "wasm32-wasip1", + "wasm32-wasip1-threads", + "wasm32-wasip2", + "wasm32-wasi-threads", + "wasm32-unknown-wasi", + "wasm32-unknown-unknown", + ]; + TARGETS.contains(&target) + } + + fn cuda_file_count(&self) -> usize { + self.files + .iter() + .filter(|file| file.extension() == Some(OsStr::new("cu"))) + .count() + } + + fn which(&self, tool: &Path, path_entries: Option<&OsStr>) -> Option { + fn check_exe(mut exe: PathBuf) -> Option { + let exe_ext = std::env::consts::EXE_EXTENSION; + let check = + exe.exists() || (!exe_ext.is_empty() && exe.set_extension(exe_ext) && exe.exists()); + check.then_some(exe) + } + + // Loop through PATH entries searching for the |tool|. + let find_exe_in_path = |path_entries: &OsStr| -> Option { + env::split_paths(path_entries).find_map(|path_entry| check_exe(path_entry.join(tool))) + }; + + // If |tool| is not just one "word," assume it's an actual path... + if tool.components().count() > 1 { + check_exe(PathBuf::from(tool)) + } else { + path_entries + .and_then(find_exe_in_path) + .or_else(|| find_exe_in_path(&self.getenv("PATH")?)) + } + } + + /// search for |prog| on 'programs' path in '|cc| -print-search-dirs' output + fn search_programs( + &self, + cc: &mut Command, + prog: &Path, + cargo_output: &CargoOutput, + ) -> Option { + let search_dirs = run_output( + cc.arg("-print-search-dirs"), + "cc", + // this doesn't concern the compilation so we always want to show warnings. + cargo_output, + ) + .ok()?; + // clang driver appears to be forcing UTF-8 output even on Windows, + // hence from_utf8 is assumed to be usable in all cases. + let search_dirs = std::str::from_utf8(&search_dirs).ok()?; + for dirs in search_dirs.split(['\r', '\n']) { + if let Some(path) = dirs.strip_prefix("programs: =") { + return self.which(prog, Some(OsStr::new(path))); + } + } + None + } + + fn windows_registry_find(&self, target: &str, tool: &str) -> Option { + self.windows_registry_find_tool(target, tool) + .map(|c| c.to_command()) + } + + fn windows_registry_find_tool(&self, target: &str, tool: &str) -> Option { + struct BuildEnvGetter<'s>(&'s Build); + + impl windows_registry::EnvGetter for BuildEnvGetter<'_> { + fn get_env(&self, name: &str) -> Option { + self.0.getenv(name).map(windows_registry::Env::Arced) + } + } + + windows_registry::find_tool_inner(target, tool, &BuildEnvGetter(self)) + } +} + +impl Default for Build { + fn default() -> Build { + Build::new() + } +} + +fn fail(s: &str) -> ! { + eprintln!("\n\nerror occurred: {}\n\n", s); + std::process::exit(1); +} + +#[derive(Clone, Copy, PartialEq)] +enum AppleOs { + MacOs, + Ios, + WatchOs, + TvOs, + VisionOS, +} + +impl std::fmt::Debug for AppleOs { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + match self { + AppleOs::MacOs => f.write_str("macOS"), + AppleOs::Ios => f.write_str("iOS"), + AppleOs::WatchOs => f.write_str("WatchOS"), + AppleOs::TvOs => f.write_str("AppleTVOS"), + AppleOs::VisionOS => f.write_str("visionOS"), + } + } +} + +struct AppleSdkTargetParts { + sdk_prefix: &'static str, + sim_prefix: &'static str, + sdk: Cow<'static, str>, +} + +fn apple_os_sdk_parts(os: AppleOs, arch: &AppleArchSpec) -> AppleSdkTargetParts { + let (sdk_prefix, sim_prefix) = match os { + AppleOs::MacOs => ("macosx", ""), + AppleOs::Ios => ("iphone", "ios-"), + AppleOs::WatchOs => ("watch", "watch"), + AppleOs::TvOs => ("appletv", "appletv"), + AppleOs::VisionOS => ("xr", "xr"), + }; + let sdk = match arch { + AppleArchSpec::Device(_) if os == AppleOs::MacOs => Cow::Borrowed("macosx"), + AppleArchSpec::Device(_) => format!("{}os", sdk_prefix).into(), + AppleArchSpec::Simulator(_) => format!("{}simulator", sdk_prefix).into(), + AppleArchSpec::Catalyst(_) => Cow::Borrowed("macosx"), + }; + + AppleSdkTargetParts { + sdk_prefix, + sim_prefix, + sdk, + } +} + +#[allow(dead_code)] +enum AppleArchSpec { + Device(&'static str), + Simulator(&'static str), + #[allow(dead_code)] + Catalyst(&'static str), +} + +// Use by default minimum available API level +// See note about naming here +// https://android.googlesource.com/platform/ndk/+/refs/heads/ndk-release-r21/docs/BuildSystemMaintainers.md#Clang +static NEW_STANDALONE_ANDROID_COMPILERS: [&str; 4] = [ + "aarch64-linux-android21-clang", + "armv7a-linux-androideabi16-clang", + "i686-linux-android16-clang", + "x86_64-linux-android21-clang", +]; + +// New "standalone" C/C++ cross-compiler executables from recent Android NDK +// are just shell scripts that call main clang binary (from Android NDK) with +// proper `--target` argument. +// +// For example, armv7a-linux-androideabi16-clang passes +// `--target=armv7a-linux-androideabi16` to clang. +// So to construct proper command line check if +// `--target` argument would be passed or not to clang +fn android_clang_compiler_uses_target_arg_internally(clang_path: &Path) -> bool { + if let Some(filename) = clang_path.file_name() { + if let Some(filename_str) = filename.to_str() { + if let Some(idx) = filename_str.rfind('-') { + return filename_str.split_at(idx).0.contains("android"); + } + } + } + false +} + +fn autodetect_android_compiler(target: &str, gnu: &str, clang: &str) -> String { + let new_clang_key = match target { + "aarch64-linux-android" => Some("aarch64"), + "armv7-linux-androideabi" => Some("armv7a"), + "i686-linux-android" => Some("i686"), + "x86_64-linux-android" => Some("x86_64"), + _ => None, + }; + + let new_clang = new_clang_key + .map(|key| { + NEW_STANDALONE_ANDROID_COMPILERS + .iter() + .find(|x| x.starts_with(key)) + }) + .unwrap_or(None); + + if let Some(new_clang) = new_clang { + if Command::new(new_clang).output().is_ok() { + return (*new_clang).into(); + } + } + + let target = target + .replace("armv7neon", "arm") + .replace("armv7", "arm") + .replace("thumbv7neon", "arm") + .replace("thumbv7", "arm"); + let gnu_compiler = format!("{}-{}", target, gnu); + let clang_compiler = format!("{}-{}", target, clang); + + // On Windows, the Android clang compiler is provided as a `.cmd` file instead + // of a `.exe` file. `std::process::Command` won't run `.cmd` files unless the + // `.cmd` is explicitly appended to the command name, so we do that here. + let clang_compiler_cmd = format!("{}-{}.cmd", target, clang); + + // Check if gnu compiler is present + // if not, use clang + if Command::new(&gnu_compiler).output().is_ok() { + gnu_compiler + } else if cfg!(windows) && Command::new(&clang_compiler_cmd).output().is_ok() { + clang_compiler_cmd + } else { + clang_compiler + } +} + +// Rust and clang/cc don't agree on how to name the target. +fn map_darwin_target_from_rust_to_compiler_architecture(target: &str) -> Option<&'static str> { + if target.contains("x86_64h") { + Some("x86_64h") + } else if target.contains("x86_64") { + Some("x86_64") + } else if target.contains("arm64e") { + Some("arm64e") + } else if target.contains("aarch64") { + Some("arm64") + } else if target.contains("i686") { + Some("i386") + } else if target.contains("powerpc") { + Some("ppc") + } else if target.contains("powerpc64") { + Some("ppc64") + } else { + None + } +} + +#[derive(Clone, Copy, PartialEq)] +enum AsmFileExt { + /// `.asm` files. On MSVC targets, we assume these should be passed to MASM + /// (`ml{,64}.exe`). + DotAsm, + /// `.s` or `.S` files, which do not have the special handling on MSVC targets. + DotS, +} + +impl AsmFileExt { + fn from_path(file: &Path) -> Option { + if let Some(ext) = file.extension() { + if let Some(ext) = ext.to_str() { + let ext = ext.to_lowercase(); + match &*ext { + "asm" => return Some(AsmFileExt::DotAsm), + "s" => return Some(AsmFileExt::DotS), + _ => return None, + } + } + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_android_clang_compiler_uses_target_arg_internally() { + for version in 16..21 { + assert!(android_clang_compiler_uses_target_arg_internally( + &PathBuf::from(format!("armv7a-linux-androideabi{}-clang", version)) + )); + assert!(android_clang_compiler_uses_target_arg_internally( + &PathBuf::from(format!("armv7a-linux-androideabi{}-clang++", version)) + )); + } + assert!(!android_clang_compiler_uses_target_arg_internally( + &PathBuf::from("clang-i686-linux-android") + )); + assert!(!android_clang_compiler_uses_target_arg_internally( + &PathBuf::from("clang") + )); + assert!(!android_clang_compiler_uses_target_arg_internally( + &PathBuf::from("clang++") + )); + } +} diff --git a/bitbox02-bt/vendor/cc/src/parallel/async_executor.rs b/bitbox02-bt/vendor/cc/src/parallel/async_executor.rs new file mode 100644 index 0000000..9ebd1ad --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/parallel/async_executor.rs @@ -0,0 +1,118 @@ +use std::{ + cell::Cell, + future::Future, + pin::Pin, + ptr, + task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, + thread, + time::Duration, +}; + +use crate::Error; + +const NOOP_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( + // Cloning just returns a new no-op raw waker + |_| NOOP_RAW_WAKER, + // `wake` does nothing + |_| {}, + // `wake_by_ref` does nothing + |_| {}, + // Dropping does nothing as we don't allocate anything + |_| {}, +); +const NOOP_RAW_WAKER: RawWaker = RawWaker::new(ptr::null(), &NOOP_WAKER_VTABLE); + +#[derive(Default)] +pub(crate) struct YieldOnce(bool); + +impl Future for YieldOnce { + type Output = (); + + fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> { + let flag = &mut std::pin::Pin::into_inner(self).0; + if !*flag { + *flag = true; + Poll::Pending + } else { + Poll::Ready(()) + } + } +} + +/// Execute the futures and return when they are all done. +/// +/// Here we use our own homebrew async executor since cc is used in the build +/// script of many popular projects, pulling in additional dependencies would +/// significantly slow down its compilation. +pub(crate) fn block_on( + mut fut1: Fut1, + mut fut2: Fut2, + has_made_progress: &Cell, +) -> Result<(), Error> +where + Fut1: Future>, + Fut2: Future>, +{ + // Shadows the future so that it can never be moved and is guaranteed + // to be pinned. + // + // The same trick used in `pin!` macro. + // + // TODO: Once MSRV is bumped to 1.68, replace this with `std::pin::pin!` + let mut fut1 = Some(unsafe { Pin::new_unchecked(&mut fut1) }); + let mut fut2 = Some(unsafe { Pin::new_unchecked(&mut fut2) }); + + // TODO: Once `Waker::noop` stablised and our MSRV is bumped to the version + // which it is stablised, replace this with `Waker::noop`. + let waker = unsafe { Waker::from_raw(NOOP_RAW_WAKER) }; + let mut context = Context::from_waker(&waker); + + let mut backoff_cnt = 0; + + loop { + has_made_progress.set(false); + + if let Some(fut) = fut2.as_mut() { + if let Poll::Ready(res) = fut.as_mut().poll(&mut context) { + fut2 = None; + res?; + } + } + + if let Some(fut) = fut1.as_mut() { + if let Poll::Ready(res) = fut.as_mut().poll(&mut context) { + fut1 = None; + res?; + } + } + + if fut1.is_none() && fut2.is_none() { + return Ok(()); + } + + if !has_made_progress.get() { + if backoff_cnt > 3 { + // We have yielded at least three times without making' + // any progress, so we will sleep for a while. + let duration = Duration::from_millis(100 * (backoff_cnt - 3).min(10)); + thread::sleep(duration); + } else { + // Given that we spawned a lot of compilation tasks, it is unlikely + // that OS cannot find other ready task to execute. + // + // If all of them are done, then we will yield them and spawn more, + // or simply return. + // + // Thus this will not be turned into a busy-wait loop and it will not + // waste CPU resource. + thread::yield_now(); + } + } + + backoff_cnt = if has_made_progress.get() { + 0 + } else { + backoff_cnt + 1 + }; + } +} diff --git a/bitbox02-bt/vendor/cc/src/parallel/job_token.rs b/bitbox02-bt/vendor/cc/src/parallel/job_token.rs new file mode 100644 index 0000000..2640cea --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/parallel/job_token.rs @@ -0,0 +1,273 @@ +use std::marker::PhantomData; + +use crate::Error; + +use super::once_lock::OnceLock; + +pub(crate) struct JobToken(PhantomData<()>); + +impl JobToken { + fn new() -> Self { + Self(PhantomData) + } +} + +impl Drop for JobToken { + fn drop(&mut self) { + match JobTokenServer::new() { + JobTokenServer::Inherited(jobserver) => jobserver.release_token_raw(), + JobTokenServer::InProcess(jobserver) => jobserver.release_token_raw(), + } + } +} + +enum JobTokenServer { + Inherited(inherited_jobserver::JobServer), + InProcess(inprocess_jobserver::JobServer), +} + +impl JobTokenServer { + /// This function returns a static reference to the jobserver because + /// - creating a jobserver from env is a bit fd-unsafe (e.g. the fd might + /// be closed by other jobserver users in the process) and better do it + /// at the start of the program. + /// - in case a jobserver cannot be created from env (e.g. it's not + /// present), we will create a global in-process only jobserver + /// that has to be static so that it will be shared by all cc + /// compilation. + fn new() -> &'static Self { + // TODO: Replace with a OnceLock once MSRV is 1.70 + static JOBSERVER: OnceLock = OnceLock::new(); + + JOBSERVER.get_or_init(|| { + unsafe { inherited_jobserver::JobServer::from_env() } + .map(Self::Inherited) + .unwrap_or_else(|| Self::InProcess(inprocess_jobserver::JobServer::new())) + }) + } +} + +pub(crate) enum ActiveJobTokenServer { + Inherited(inherited_jobserver::ActiveJobServer<'static>), + InProcess(&'static inprocess_jobserver::JobServer), +} + +impl ActiveJobTokenServer { + pub(crate) fn new() -> Self { + match JobTokenServer::new() { + JobTokenServer::Inherited(inherited_jobserver) => { + Self::Inherited(inherited_jobserver.enter_active()) + } + JobTokenServer::InProcess(inprocess_jobserver) => Self::InProcess(inprocess_jobserver), + } + } + + pub(crate) async fn acquire(&mut self) -> Result { + match self { + Self::Inherited(jobserver) => jobserver.acquire().await, + Self::InProcess(jobserver) => Ok(jobserver.acquire().await), + } + } +} + +mod inherited_jobserver { + use super::JobToken; + + use crate::{parallel::async_executor::YieldOnce, Error, ErrorKind}; + + use std::{ + io, mem, + sync::{mpsc, Mutex, MutexGuard, PoisonError}, + }; + + pub(super) struct JobServer { + /// Implicit token for this process which is obtained and will be + /// released in parent. Since JobTokens only give back what they got, + /// there should be at most one global implicit token in the wild. + /// + /// Since Rust does not execute any `Drop` for global variables, + /// we can't just put it back to jobserver and then re-acquire it at + /// the end of the process. + /// + /// Use `Mutex` to avoid race between acquire and release. + /// If an `AtomicBool` is used, then it's possible for: + /// - `release_token_raw`: Tries to set `global_implicit_token` to true, but it is already + /// set to `true`, continue to release it to jobserver + /// - `acquire` takes the global implicit token, set `global_implicit_token` to false + /// - `release_token_raw` now writes the token back into the jobserver, while + /// `global_implicit_token` is `false` + /// + /// If the program exits here, then cc effectively increases parallelism by one, which is + /// incorrect, hence we use a `Mutex` here. + global_implicit_token: Mutex, + inner: jobserver::Client, + } + + impl JobServer { + pub(super) unsafe fn from_env() -> Option { + jobserver::Client::from_env().map(|inner| Self { + inner, + global_implicit_token: Mutex::new(true), + }) + } + + fn get_global_implicit_token(&self) -> MutexGuard<'_, bool> { + self.global_implicit_token + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + /// All tokens except for the global implicit token will be put back into the jobserver + /// immediately and they cannot be cached, since Rust does not call `Drop::drop` on + /// global variables. + pub(super) fn release_token_raw(&self) { + let mut global_implicit_token = self.get_global_implicit_token(); + + if *global_implicit_token { + // There's already a global implicit token, so this token must + // be released back into jobserver. + // + // `release_raw` should not block + let _ = self.inner.release_raw(); + } else { + *global_implicit_token = true; + } + } + + pub(super) fn enter_active(&self) -> ActiveJobServer<'_> { + ActiveJobServer { + jobserver: self, + helper_thread: None, + } + } + } + + struct HelperThread { + inner: jobserver::HelperThread, + /// When rx is dropped, all the token stored within it will be dropped. + rx: mpsc::Receiver>, + } + + impl HelperThread { + fn new(jobserver: &JobServer) -> Result { + let (tx, rx) = mpsc::channel(); + + Ok(Self { + rx, + inner: jobserver.inner.clone().into_helper_thread(move |res| { + let _ = tx.send(res); + })?, + }) + } + } + + pub(crate) struct ActiveJobServer<'a> { + jobserver: &'a JobServer, + helper_thread: Option, + } + + impl<'a> ActiveJobServer<'a> { + pub(super) async fn acquire(&mut self) -> Result { + let mut has_requested_token = false; + + loop { + // Fast path + if mem::replace(&mut *self.jobserver.get_global_implicit_token(), false) { + break Ok(JobToken::new()); + } + + match self.jobserver.inner.try_acquire() { + Ok(Some(acquired)) => { + acquired.drop_without_releasing(); + break Ok(JobToken::new()); + } + Ok(None) => YieldOnce::default().await, + Err(err) if err.kind() == io::ErrorKind::Unsupported => { + // Fallback to creating a help thread with blocking acquire + let helper_thread = if let Some(thread) = self.helper_thread.as_ref() { + thread + } else { + self.helper_thread + .insert(HelperThread::new(self.jobserver)?) + }; + + match helper_thread.rx.try_recv() { + Ok(res) => { + let acquired = res?; + acquired.drop_without_releasing(); + break Ok(JobToken::new()); + } + Err(mpsc::TryRecvError::Disconnected) => break Err(Error::new( + ErrorKind::JobserverHelpThreadError, + "jobserver help thread has returned before ActiveJobServer is dropped", + )), + Err(mpsc::TryRecvError::Empty) => { + if !has_requested_token { + helper_thread.inner.request_token(); + has_requested_token = true; + } + YieldOnce::default().await + } + } + } + Err(err) => break Err(err.into()), + } + } + } + } +} + +mod inprocess_jobserver { + use super::JobToken; + + use crate::parallel::async_executor::YieldOnce; + + use std::{ + env::var, + sync::atomic::{ + AtomicU32, + Ordering::{AcqRel, Acquire}, + }, + }; + + pub(crate) struct JobServer(AtomicU32); + + impl JobServer { + pub(super) fn new() -> Self { + // Use `NUM_JOBS` if set (it's configured by Cargo) and otherwise + // just fall back to a semi-reasonable number. + // + // Note that we could use `num_cpus` here but it's an extra + // dependency that will almost never be used, so + // it's generally not too worth it. + let mut parallelism = 4; + // TODO: Use std::thread::available_parallelism as an upper bound + // when MSRV is bumped. + if let Ok(amt) = var("NUM_JOBS") { + if let Ok(amt) = amt.parse() { + parallelism = amt; + } + } + + Self(AtomicU32::new(parallelism)) + } + + pub(super) async fn acquire(&self) -> JobToken { + loop { + let res = self + .0 + .fetch_update(AcqRel, Acquire, |tokens| tokens.checked_sub(1)); + + if res.is_ok() { + break JobToken::new(); + } + + YieldOnce::default().await + } + } + + pub(super) fn release_token_raw(&self) { + self.0.fetch_add(1, AcqRel); + } + } +} diff --git a/bitbox02-bt/vendor/cc/src/parallel/mod.rs b/bitbox02-bt/vendor/cc/src/parallel/mod.rs new file mode 100644 index 0000000..70a56e7 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/parallel/mod.rs @@ -0,0 +1,4 @@ +pub(crate) mod async_executor; +pub(crate) mod job_token; +pub(crate) mod once_lock; +pub(crate) mod stderr; diff --git a/bitbox02-bt/vendor/cc/src/parallel/once_lock.rs b/bitbox02-bt/vendor/cc/src/parallel/once_lock.rs new file mode 100644 index 0000000..c48dbb7 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/parallel/once_lock.rs @@ -0,0 +1,47 @@ +use std::{ + cell::UnsafeCell, + marker::PhantomData, + mem::MaybeUninit, + panic::{RefUnwindSafe, UnwindSafe}, + sync::Once, +}; + +pub(crate) struct OnceLock { + once: Once, + value: UnsafeCell>, + _marker: PhantomData, +} + +impl OnceLock { + pub(crate) const fn new() -> Self { + Self { + once: Once::new(), + value: UnsafeCell::new(MaybeUninit::uninit()), + _marker: PhantomData, + } + } + + pub(crate) fn get_or_init(&self, f: impl FnOnce() -> T) -> &T { + self.once.call_once(|| { + unsafe { &mut *self.value.get() }.write(f()); + }); + unsafe { (&*self.value.get()).assume_init_ref() } + } +} + +unsafe impl Sync for OnceLock {} +unsafe impl Send for OnceLock {} + +impl RefUnwindSafe for OnceLock {} +impl UnwindSafe for OnceLock {} + +impl Drop for OnceLock { + #[inline] + fn drop(&mut self) { + if self.once.is_completed() { + // SAFETY: The cell is initialized and being dropped, so it can't + // be accessed again. + unsafe { self.value.get_mut().assume_init_drop() }; + } + } +} diff --git a/bitbox02-bt/vendor/cc/src/parallel/stderr.rs b/bitbox02-bt/vendor/cc/src/parallel/stderr.rs new file mode 100644 index 0000000..7018686 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/parallel/stderr.rs @@ -0,0 +1,91 @@ +#![cfg_attr(target_family = "wasm", allow(unused))] +/// Helpers functions for [ChildStderr]. +use std::{convert::TryInto, process::ChildStderr}; + +use crate::{Error, ErrorKind}; + +#[cfg(all(not(unix), not(windows), not(target_family = "wasm")))] +compile_error!("Only unix and windows support non-blocking pipes! For other OSes, disable the parallel feature."); + +#[cfg(unix)] +fn get_flags(fd: std::os::unix::io::RawFd) -> Result { + let flags = unsafe { libc::fcntl(fd, libc::F_GETFL, 0) }; + if flags == -1 { + Err(Error::new( + ErrorKind::IOError, + format!( + "Failed to get flags for pipe {}: {}", + fd, + std::io::Error::last_os_error() + ), + )) + } else { + Ok(flags) + } +} + +#[cfg(unix)] +fn set_flags(fd: std::os::unix::io::RawFd, flags: std::os::raw::c_int) -> Result<(), Error> { + if unsafe { libc::fcntl(fd, libc::F_SETFL, flags) } == -1 { + Err(Error::new( + ErrorKind::IOError, + format!( + "Failed to set flags for pipe {}: {}", + fd, + std::io::Error::last_os_error() + ), + )) + } else { + Ok(()) + } +} + +#[cfg(unix)] +pub fn set_non_blocking(pipe: &impl std::os::unix::io::AsRawFd) -> Result<(), Error> { + // On Unix, switch the pipe to non-blocking mode. + // On Windows, we have a different way to be non-blocking. + let fd = pipe.as_raw_fd(); + + let flags = get_flags(fd)?; + set_flags(fd, flags | libc::O_NONBLOCK) +} + +pub fn bytes_available(stderr: &mut ChildStderr) -> Result { + let mut bytes_available = 0; + #[cfg(windows)] + { + use crate::windows::windows_sys::PeekNamedPipe; + use std::os::windows::io::AsRawHandle; + use std::ptr::null_mut; + if unsafe { + PeekNamedPipe( + stderr.as_raw_handle(), + null_mut(), + 0, + null_mut(), + &mut bytes_available, + null_mut(), + ) + } == 0 + { + return Err(Error::new( + ErrorKind::IOError, + format!( + "PeekNamedPipe failed with {}", + std::io::Error::last_os_error() + ), + )); + } + } + #[cfg(unix)] + { + use std::os::unix::io::AsRawFd; + if unsafe { libc::ioctl(stderr.as_raw_fd(), libc::FIONREAD, &mut bytes_available) } != 0 { + return Err(Error::new( + ErrorKind::IOError, + format!("ioctl failed with {}", std::io::Error::last_os_error()), + )); + } + } + Ok(bytes_available.try_into().unwrap()) +} diff --git a/bitbox02-bt/vendor/cc/src/target_info.rs b/bitbox02-bt/vendor/cc/src/target_info.rs new file mode 100644 index 0000000..085412a --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/target_info.rs @@ -0,0 +1,29 @@ +//! This file is generated code. Please edit the generator +//! in dev-tools/gen-target-info if you need to make changes. + +pub const RISCV_ARCH_MAPPING: &[(&str, &str)] = &[ + ("riscv32e", "riscv32"), + ("riscv32em", "riscv32"), + ("riscv32emc", "riscv32"), + ("riscv32gc", "riscv32"), + ("riscv32i", "riscv32"), + ("riscv32im", "riscv32"), + ("riscv32ima", "riscv32"), + ("riscv32imac", "riscv32"), + ("riscv32imafc", "riscv32"), + ("riscv32imc", "riscv32"), + ("riscv64gc", "riscv64"), + ("riscv64imac", "riscv64"), +]; +pub const WINDOWS_TRIPLE_MAPPING: &[(&str, &str)] = &[ + ("aarch64-pc-windows-gnullvm", "aarch64-pc-windows-gnu"), + ("aarch64-uwp-windows-msvc", "aarch64-pc-windows-msvc"), + ("i686-pc-windows-gnullvm", "i686-pc-windows-gnu"), + ("i686-uwp-windows-gnu", "i686-pc-windows-gnu"), + ("i686-uwp-windows-msvc", "i686-pc-windows-msvc"), + ("i686-win7-windows-msvc", "i686-pc-windows-msvc"), + ("thumbv7a-uwp-windows-msvc", "thumbv7a-pc-windows-msvc"), + ("x86_64-pc-windows-gnullvm", "x86_64-pc-windows-gnu"), + ("x86_64-uwp-windows-gnu", "x86_64-pc-windows-gnu"), + ("x86_64-uwp-windows-msvc", "x86_64-pc-windows-msvc"), +]; diff --git a/bitbox02-bt/vendor/cc/src/tempfile.rs b/bitbox02-bt/vendor/cc/src/tempfile.rs new file mode 100644 index 0000000..833e6f2 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/tempfile.rs @@ -0,0 +1,86 @@ +#![cfg_attr(target_family = "wasm", allow(unused))] + +use std::{ + collections::hash_map::RandomState, + fs::{remove_file, File, OpenOptions}, + hash::{BuildHasher, Hasher}, + io, os, + path::{Path, PathBuf}, +}; + +#[cfg(not(any(unix, target_family = "wasm", windows)))] +compile_error!("Your system is not supported since cc cannot create named tempfile"); + +fn rand() -> u64 { + RandomState::new().build_hasher().finish() +} + +fn tmpname(suffix: &str) -> String { + format!("{}{}", rand(), suffix) +} + +fn create_named(path: &Path) -> io::Result { + let mut open_options = OpenOptions::new(); + + open_options.read(true).write(true).create_new(true); + + #[cfg(all(unix, not(target_os = "wasi")))] + ::mode(&mut open_options, 0o600); + + #[cfg(windows)] + ::custom_flags( + &mut open_options, + crate::windows::windows_sys::FILE_ATTRIBUTE_TEMPORARY, + ); + + open_options.open(path) +} + +pub(super) struct NamedTempfile { + path: PathBuf, + file: Option, +} + +impl NamedTempfile { + pub(super) fn new(base: &Path, suffix: &str) -> io::Result { + for _ in 0..10 { + let path = base.join(tmpname(suffix)); + match create_named(&path) { + Ok(file) => { + return Ok(Self { + file: Some(file), + path, + }) + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + }; + } + + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!( + "too many temporary files exist in base `{}` with suffix `{}`", + base.display(), + suffix + ), + )) + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + + pub(super) fn take_file(&mut self) -> Option { + self.file.take() + } +} + +impl Drop for NamedTempfile { + fn drop(&mut self) { + // On Windows you have to close all handle to it before + // removing the file. + self.file.take(); + let _ = remove_file(&self.path); + } +} diff --git a/bitbox02-bt/vendor/cc/src/tool.rs b/bitbox02-bt/vendor/cc/src/tool.rs new file mode 100644 index 0000000..c34bc2b --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/tool.rs @@ -0,0 +1,476 @@ +use std::{ + borrow::Cow, + collections::HashMap, + env, + ffi::{OsStr, OsString}, + io::Write, + path::{Path, PathBuf}, + process::Command, + sync::RwLock, +}; + +use crate::{ + command_helpers::{run_output, CargoOutput}, + run, + tempfile::NamedTempfile, + Error, ErrorKind, OutputKind, +}; + +/// Configuration used to represent an invocation of a C compiler. +/// +/// This can be used to figure out what compiler is in use, what the arguments +/// to it are, and what the environment variables look like for the compiler. +/// This can be used to further configure other build systems (e.g. forward +/// along CC and/or CFLAGS) or the `to_command` method can be used to run the +/// compiler itself. +#[derive(Clone, Debug)] +#[allow(missing_docs)] +pub struct Tool { + pub(crate) path: PathBuf, + pub(crate) cc_wrapper_path: Option, + pub(crate) cc_wrapper_args: Vec, + pub(crate) args: Vec, + pub(crate) env: Vec<(OsString, OsString)>, + pub(crate) family: ToolFamily, + pub(crate) cuda: bool, + pub(crate) removed_args: Vec, + pub(crate) has_internal_target_arg: bool, +} + +impl Tool { + pub(crate) fn new( + path: PathBuf, + cached_compiler_family: &RwLock, ToolFamily>>, + cargo_output: &CargoOutput, + out_dir: Option<&Path>, + ) -> Self { + Self::with_features( + path, + None, + false, + cached_compiler_family, + cargo_output, + out_dir, + ) + } + + pub(crate) fn with_clang_driver( + path: PathBuf, + clang_driver: Option<&str>, + cached_compiler_family: &RwLock, ToolFamily>>, + cargo_output: &CargoOutput, + out_dir: Option<&Path>, + ) -> Self { + Self::with_features( + path, + clang_driver, + false, + cached_compiler_family, + cargo_output, + out_dir, + ) + } + + /// Explicitly set the `ToolFamily`, skipping name-based detection. + pub(crate) fn with_family(path: PathBuf, family: ToolFamily) -> Self { + Self { + path, + cc_wrapper_path: None, + cc_wrapper_args: Vec::new(), + args: Vec::new(), + env: Vec::new(), + family, + cuda: false, + removed_args: Vec::new(), + has_internal_target_arg: false, + } + } + + pub(crate) fn with_features( + path: PathBuf, + clang_driver: Option<&str>, + cuda: bool, + cached_compiler_family: &RwLock, ToolFamily>>, + cargo_output: &CargoOutput, + out_dir: Option<&Path>, + ) -> Self { + fn is_zig_cc(path: &Path, cargo_output: &CargoOutput) -> bool { + run_output( + Command::new(path).arg("--version"), + path, + // tool detection issues should always be shown as warnings + cargo_output, + ) + .map(|o| String::from_utf8_lossy(&o).contains("ziglang")) + .unwrap_or_default() + } + + fn detect_family_inner( + path: &Path, + cargo_output: &CargoOutput, + out_dir: Option<&Path>, + ) -> Result { + let out_dir = out_dir + .map(Cow::Borrowed) + .unwrap_or_else(|| Cow::Owned(env::temp_dir())); + + // Ensure all the parent directories exist otherwise temp file creation + // will fail + std::fs::create_dir_all(&out_dir).map_err(|err| Error { + kind: ErrorKind::IOError, + message: format!("failed to create OUT_DIR '{}': {}", out_dir.display(), err) + .into(), + })?; + + let mut tmp = + NamedTempfile::new(&out_dir, "detect_compiler_family.c").map_err(|err| Error { + kind: ErrorKind::IOError, + message: format!( + "failed to create detect_compiler_family.c temp file in '{}': {}", + out_dir.display(), + err + ) + .into(), + })?; + let mut tmp_file = tmp.take_file().unwrap(); + tmp_file.write_all(include_bytes!("detect_compiler_family.c"))?; + // Close the file handle *now*, otherwise the compiler may fail to open it on Windows + // (#1082). The file stays on disk and its path remains valid until `tmp` is dropped. + tmp_file.flush()?; + tmp_file.sync_data()?; + drop(tmp_file); + + let stdout = run_output( + Command::new(path).arg("-E").arg(tmp.path()), + path, + // When expanding the file, the compiler prints a lot of information to stderr + // that it is not an error, but related to expanding itself. + // + // cc would have to disable warning here to prevent generation of too many warnings. + &{ + let mut cargo_output = cargo_output.clone(); + cargo_output.warnings = cargo_output.debug; + cargo_output + }, + )?; + let stdout = String::from_utf8_lossy(&stdout); + + cargo_output.print_debug(&stdout); + + // https://gitlab.kitware.com/cmake/cmake/-/blob/69a2eeb9dff5b60f2f1e5b425002a0fd45b7cadb/Modules/CMakeDetermineCompilerId.cmake#L267-271 + let accepts_cl_style_flags = run(Command::new(path).arg("-?"), path, &{ + // the errors are not errors! + let mut cargo_output = cargo_output.clone(); + cargo_output.warnings = cargo_output.debug; + cargo_output.output = OutputKind::Discard; + cargo_output + }) + .is_ok(); + + let clang = stdout.contains(r#""clang""#); + let gcc = stdout.contains(r#""gcc""#); + let emscripten = stdout.contains(r#""emscripten""#); + let vxworks = stdout.contains(r#""VxWorks""#); + + match (clang, accepts_cl_style_flags, gcc, emscripten, vxworks) { + (clang_cl, true, _, false, false) => Ok(ToolFamily::Msvc { clang_cl }), + (true, _, _, _, false) | (_, _, _, true, false) => Ok(ToolFamily::Clang { + zig_cc: is_zig_cc(path, cargo_output), + }), + (false, false, true, _, false) | (_, _, _, _, true) => Ok(ToolFamily::Gnu), + (false, false, false, false, false) => { + cargo_output.print_warning(&"Compiler family detection failed since it does not define `__clang__`, `__GNUC__`, `__EMSCRIPTEN__` or `__VXWORKS__`, also does not accept cl style flag `-?`, fallback to treating it as GNU"); + Err(Error::new( + ErrorKind::ToolFamilyMacroNotFound, + "Expects macro `__clang__`, `__GNUC__` or `__EMSCRIPTEN__`, `__VXWORKS__` or accepts cl style flag `-?`, but found none", + )) + } + } + } + let detect_family = |path: &Path| -> Result { + if let Some(family) = cached_compiler_family.read().unwrap().get(path) { + return Ok(*family); + } + + let family = detect_family_inner(path, cargo_output, out_dir)?; + cached_compiler_family + .write() + .unwrap() + .insert(path.into(), family); + Ok(family) + }; + + let family = detect_family(&path).unwrap_or_else(|e| { + cargo_output.print_warning(&format_args!( + "Compiler family detection failed due to error: {}", + e + )); + match path.file_name().map(OsStr::to_string_lossy) { + Some(fname) if fname.contains("clang-cl") => ToolFamily::Msvc { clang_cl: true }, + Some(fname) if fname.ends_with("cl") || fname == "cl.exe" => { + ToolFamily::Msvc { clang_cl: false } + } + Some(fname) if fname.contains("clang") => match clang_driver { + Some("cl") => ToolFamily::Msvc { clang_cl: true }, + _ => ToolFamily::Clang { + zig_cc: is_zig_cc(&path, cargo_output), + }, + }, + Some(fname) if fname.contains("zig") => ToolFamily::Clang { zig_cc: true }, + _ => ToolFamily::Gnu, + } + }); + + Tool { + path, + cc_wrapper_path: None, + cc_wrapper_args: Vec::new(), + args: Vec::new(), + env: Vec::new(), + family, + cuda, + removed_args: Vec::new(), + has_internal_target_arg: false, + } + } + + /// Add an argument to be stripped from the final command arguments. + pub(crate) fn remove_arg(&mut self, flag: OsString) { + self.removed_args.push(flag); + } + + /// Push an "exotic" flag to the end of the compiler's arguments list. + /// + /// Nvidia compiler accepts only the most common compiler flags like `-D`, + /// `-I`, `-c`, etc. Options meant specifically for the underlying + /// host C++ compiler have to be prefixed with `-Xcompiler`. + /// [Another possible future application for this function is passing + /// clang-specific flags to clang-cl, which otherwise accepts only + /// MSVC-specific options.] + pub(crate) fn push_cc_arg(&mut self, flag: OsString) { + if self.cuda { + self.args.push("-Xcompiler".into()); + } + self.args.push(flag); + } + + /// Checks if an argument or flag has already been specified or conflicts. + /// + /// Currently only checks optimization flags. + pub(crate) fn is_duplicate_opt_arg(&self, flag: &OsString) -> bool { + let flag = flag.to_str().unwrap(); + let mut chars = flag.chars(); + + // Only duplicate check compiler flags + if self.is_like_msvc() { + if chars.next() != Some('/') { + return false; + } + } else if (self.is_like_gnu() || self.is_like_clang()) && chars.next() != Some('-') { + return false; + } + + // Check for existing optimization flags (-O, /O) + if chars.next() == Some('O') { + return self + .args() + .iter() + .any(|a| a.to_str().unwrap_or("").chars().nth(1) == Some('O')); + } + + // TODO Check for existing -m..., -m...=..., /arch:... flags + false + } + + /// Don't push optimization arg if it conflicts with existing args. + pub(crate) fn push_opt_unless_duplicate(&mut self, flag: OsString) { + if self.is_duplicate_opt_arg(&flag) { + eprintln!("Info: Ignoring duplicate arg {:?}", &flag); + } else { + self.push_cc_arg(flag); + } + } + + /// Converts this compiler into a `Command` that's ready to be run. + /// + /// This is useful for when the compiler needs to be executed and the + /// command returned will already have the initial arguments and environment + /// variables configured. + pub fn to_command(&self) -> Command { + let mut cmd = match self.cc_wrapper_path { + Some(ref cc_wrapper_path) => { + let mut cmd = Command::new(cc_wrapper_path); + cmd.arg(&self.path); + cmd + } + None => Command::new(&self.path), + }; + cmd.args(&self.cc_wrapper_args); + + let value = self + .args + .iter() + .filter(|a| !self.removed_args.contains(a)) + .collect::>(); + cmd.args(&value); + + for (k, v) in self.env.iter() { + cmd.env(k, v); + } + cmd + } + + /// Returns the path for this compiler. + /// + /// Note that this may not be a path to a file on the filesystem, e.g. "cc", + /// but rather something which will be resolved when a process is spawned. + pub fn path(&self) -> &Path { + &self.path + } + + /// Returns the default set of arguments to the compiler needed to produce + /// executables for the target this compiler generates. + pub fn args(&self) -> &[OsString] { + &self.args + } + + /// Returns the set of environment variables needed for this compiler to + /// operate. + /// + /// This is typically only used for MSVC compilers currently. + pub fn env(&self) -> &[(OsString, OsString)] { + &self.env + } + + /// Returns the compiler command in format of CC environment variable. + /// Or empty string if CC env was not present + /// + /// This is typically used by configure script + pub fn cc_env(&self) -> OsString { + match self.cc_wrapper_path { + Some(ref cc_wrapper_path) => { + let mut cc_env = cc_wrapper_path.as_os_str().to_owned(); + cc_env.push(" "); + cc_env.push(self.path.to_path_buf().into_os_string()); + for arg in self.cc_wrapper_args.iter() { + cc_env.push(" "); + cc_env.push(arg); + } + cc_env + } + None => OsString::from(""), + } + } + + /// Returns the compiler flags in format of CFLAGS environment variable. + /// Important here - this will not be CFLAGS from env, its internal gcc's flags to use as CFLAGS + /// This is typically used by configure script + pub fn cflags_env(&self) -> OsString { + let mut flags = OsString::new(); + for (i, arg) in self.args.iter().enumerate() { + if i > 0 { + flags.push(" "); + } + flags.push(arg); + } + flags + } + + /// Whether the tool is GNU Compiler Collection-like. + pub fn is_like_gnu(&self) -> bool { + self.family == ToolFamily::Gnu + } + + /// Whether the tool is Clang-like. + pub fn is_like_clang(&self) -> bool { + matches!(self.family, ToolFamily::Clang { .. }) + } + + /// Whether the tool is AppleClang under .xctoolchain + #[cfg(target_vendor = "apple")] + pub(crate) fn is_xctoolchain_clang(&self) -> bool { + let path = self.path.to_string_lossy(); + path.contains(".xctoolchain/") + } + #[cfg(not(target_vendor = "apple"))] + pub(crate) fn is_xctoolchain_clang(&self) -> bool { + false + } + + /// Whether the tool is MSVC-like. + pub fn is_like_msvc(&self) -> bool { + matches!(self.family, ToolFamily::Msvc { .. }) + } +} + +/// Represents the family of tools this tool belongs to. +/// +/// Each family of tools differs in how and what arguments they accept. +/// +/// Detection of a family is done on best-effort basis and may not accurately reflect the tool. +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum ToolFamily { + /// Tool is GNU Compiler Collection-like. + Gnu, + /// Tool is Clang-like. It differs from the GCC in a sense that it accepts superset of flags + /// and its cross-compilation approach is different. + Clang { zig_cc: bool }, + /// Tool is the MSVC cl.exe. + Msvc { clang_cl: bool }, +} + +impl ToolFamily { + /// What the flag to request debug info for this family of tools look like + pub(crate) fn add_debug_flags(&self, cmd: &mut Tool, dwarf_version: Option) { + match *self { + ToolFamily::Msvc { .. } => { + cmd.push_cc_arg("-Z7".into()); + } + ToolFamily::Gnu | ToolFamily::Clang { .. } => { + cmd.push_cc_arg( + dwarf_version + .map_or_else(|| "-g".into(), |v| format!("-gdwarf-{}", v)) + .into(), + ); + } + } + } + + /// What the flag to force frame pointers. + pub(crate) fn add_force_frame_pointer(&self, cmd: &mut Tool) { + match *self { + ToolFamily::Gnu | ToolFamily::Clang { .. } => { + cmd.push_cc_arg("-fno-omit-frame-pointer".into()); + } + _ => (), + } + } + + /// What the flags to enable all warnings + pub(crate) fn warnings_flags(&self) -> &'static str { + match *self { + ToolFamily::Msvc { .. } => "-W4", + ToolFamily::Gnu | ToolFamily::Clang { .. } => "-Wall", + } + } + + /// What the flags to enable extra warnings + pub(crate) fn extra_warnings_flags(&self) -> Option<&'static str> { + match *self { + ToolFamily::Msvc { .. } => None, + ToolFamily::Gnu | ToolFamily::Clang { .. } => Some("-Wextra"), + } + } + + /// What the flag to turn warning into errors + pub(crate) fn warnings_to_errors_flag(&self) -> &'static str { + match *self { + ToolFamily::Msvc { .. } => "-WX", + ToolFamily::Gnu | ToolFamily::Clang { .. } => "-Werror", + } + } + + pub(crate) fn verbose_stderr(&self) -> bool { + matches!(*self, ToolFamily::Clang { .. }) + } +} diff --git a/bitbox02-bt/vendor/cc/src/utilities.rs b/bitbox02-bt/vendor/cc/src/utilities.rs new file mode 100644 index 0000000..073e617 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/utilities.rs @@ -0,0 +1,45 @@ +use std::{ + ffi::OsStr, + fmt::{self, Write}, + path::Path, +}; + +pub(super) struct JoinOsStrs<'a, T> { + pub(super) slice: &'a [T], + pub(super) delimiter: char, +} + +impl fmt::Display for JoinOsStrs<'_, T> +where + T: AsRef, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let len = self.slice.len(); + for (index, os_str) in self.slice.iter().enumerate() { + // TODO: Use OsStr::display once it is stablised, + // Path and OsStr has the same `Display` impl + write!(f, "{}", Path::new(os_str).display())?; + if index + 1 < len { + f.write_char(self.delimiter)?; + } + } + Ok(()) + } +} + +pub(super) struct OptionOsStrDisplay(pub(super) Option); + +impl fmt::Display for OptionOsStrDisplay +where + T: AsRef, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // TODO: Use OsStr::display once it is stablised + // Path and OsStr has the same `Display` impl + if let Some(os_str) = self.0.as_ref() { + write!(f, "Some({})", Path::new(os_str).display()) + } else { + f.write_str("None") + } + } +} diff --git a/bitbox02-bt/vendor/cc/src/windows/com.rs b/bitbox02-bt/vendor/cc/src/windows/com.rs new file mode 100644 index 0000000..0391b5a --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/com.rs @@ -0,0 +1,110 @@ +// Copyright © 2017 winapi-rs developers +// Licensed under the Apache License, Version 2.0 +// or the MIT license +// , at your option. +// All files in the project carrying such notice may not be copied, modified, or distributed +// except according to those terms. + +use crate::windows::{ + winapi::{IUnknown, Interface}, + windows_sys::{ + CoInitializeEx, SysFreeString, SysStringLen, BSTR, COINIT_MULTITHREADED, HRESULT, S_FALSE, + S_OK, + }, +}; +use std::{ + convert::TryInto, + ffi::OsString, + ops::Deref, + os::windows::ffi::OsStringExt, + ptr::{null, null_mut}, + slice::from_raw_parts, +}; + +pub fn initialize() -> Result<(), HRESULT> { + let err = unsafe { CoInitializeEx(null(), COINIT_MULTITHREADED.try_into().unwrap()) }; + if err != S_OK && err != S_FALSE { + // S_FALSE just means COM is already initialized + Err(err) + } else { + Ok(()) + } +} + +pub struct ComPtr(*mut T) +where + T: Interface; +impl ComPtr +where + T: Interface, +{ + /// Creates a `ComPtr` to wrap a raw pointer. + /// It takes ownership over the pointer which means it does __not__ call `AddRef`. + /// `T` __must__ be a COM interface that inherits from `IUnknown`. + pub unsafe fn from_raw(ptr: *mut T) -> ComPtr { + assert!(!ptr.is_null()); + ComPtr(ptr) + } + /// For internal use only. + fn as_unknown(&self) -> &IUnknown { + unsafe { &*(self.0 as *mut IUnknown) } + } + /// Performs `QueryInterface` fun. + pub fn cast(&self) -> Result, i32> + where + U: Interface, + { + let mut obj = null_mut(); + let err = unsafe { self.as_unknown().QueryInterface(&U::uuidof(), &mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { ComPtr::from_raw(obj as *mut U) }) + } +} +impl Deref for ComPtr +where + T: Interface, +{ + type Target = T; + fn deref(&self) -> &T { + unsafe { &*self.0 } + } +} +impl Clone for ComPtr +where + T: Interface, +{ + fn clone(&self) -> Self { + unsafe { + self.as_unknown().AddRef(); + ComPtr::from_raw(self.0) + } + } +} +impl Drop for ComPtr +where + T: Interface, +{ + fn drop(&mut self) { + unsafe { + self.as_unknown().Release(); + } + } +} +pub struct BStr(BSTR); +impl BStr { + pub unsafe fn from_raw(s: BSTR) -> BStr { + BStr(s) + } + pub fn to_osstring(&self) -> OsString { + let len = unsafe { SysStringLen(self.0) }; + let slice = unsafe { from_raw_parts(self.0, len as usize) }; + OsStringExt::from_wide(slice) + } +} +impl Drop for BStr { + fn drop(&mut self) { + unsafe { SysFreeString(self.0) }; + } +} diff --git a/bitbox02-bt/vendor/cc/src/windows/find_tools.rs b/bitbox02-bt/vendor/cc/src/windows/find_tools.rs new file mode 100644 index 0000000..54470f3 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/find_tools.rs @@ -0,0 +1,1191 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A helper module to looking for windows-specific tools: +//! 1. On Windows host, probe the Windows Registry if needed; +//! 2. On non-Windows host, check specified environment variables. + +#![allow(clippy::upper_case_acronyms)] + +use std::{ + env, + ffi::{OsStr, OsString}, + ops::Deref, + path::PathBuf, + process::Command, + sync::Arc, +}; + +use crate::Tool; +use crate::ToolFamily; + +const MSVC_FAMILY: ToolFamily = ToolFamily::Msvc { clang_cl: false }; + +#[derive(Copy, Clone)] +struct TargetArch<'a>(pub &'a str); + +impl PartialEq<&str> for TargetArch<'_> { + fn eq(&self, other: &&str) -> bool { + self.0 == *other + } +} + +impl<'a> From> for &'a str { + fn from(target: TargetArch<'a>) -> Self { + target.0 + } +} + +pub(crate) enum Env { + Owned(OsString), + Arced(Arc), +} + +impl AsRef for Env { + fn as_ref(&self) -> &OsStr { + self.deref() + } +} + +impl Deref for Env { + type Target = OsStr; + + fn deref(&self) -> &Self::Target { + match self { + Env::Owned(os_str) => os_str, + Env::Arced(os_str) => os_str, + } + } +} + +impl From for PathBuf { + fn from(env: Env) -> Self { + match env { + Env::Owned(os_str) => PathBuf::from(os_str), + Env::Arced(os_str) => PathBuf::from(os_str.deref()), + } + } +} + +pub(crate) trait EnvGetter { + fn get_env(&self, name: &'static str) -> Option; +} + +struct StdEnvGetter; + +impl EnvGetter for StdEnvGetter { + #[allow(clippy::disallowed_methods)] + fn get_env(&self, name: &'static str) -> Option { + env::var_os(name).map(Env::Owned) + } +} + +/// Attempts to find a tool within an MSVC installation using the Windows +/// registry as a point to search from. +/// +/// The `target` argument is the target that the tool should work for (e.g. +/// compile or link for) and the `tool` argument is the tool to find (e.g. +/// `cl.exe` or `link.exe`). +/// +/// This function will return `None` if the tool could not be found, or it will +/// return `Some(cmd)` which represents a command that's ready to execute the +/// tool with the appropriate environment variables set. +/// +/// Note that this function always returns `None` for non-MSVC targets. +pub fn find(target: &str, tool: &str) -> Option { + find_tool(target, tool).map(|c| c.to_command()) +} + +/// Similar to the `find` function above, this function will attempt the same +/// operation (finding a MSVC tool in a local install) but instead returns a +/// `Tool` which may be introspected. +pub fn find_tool(target: &str, tool: &str) -> Option { + find_tool_inner(target, tool, &StdEnvGetter) +} + +pub(crate) fn find_tool_inner( + target: &str, + tool: &str, + env_getter: &dyn EnvGetter, +) -> Option { + // This logic is all tailored for MSVC, if we're not that then bail out + // early. + if !target.contains("msvc") { + return None; + } + + // Split the target to get the arch. + let target = TargetArch(target.split_once('-')?.0); + + // Looks like msbuild isn't located in the same location as other tools like + // cl.exe and lib.exe. + if tool.contains("msbuild") { + return impl_::find_msbuild(target, env_getter); + } + + // Looks like devenv isn't located in the same location as other tools like + // cl.exe and lib.exe. + if tool.contains("devenv") { + return impl_::find_devenv(target, env_getter); + } + + // Ok, if we're here, now comes the fun part of the probing. Default shells + // or shells like MSYS aren't really configured to execute `cl.exe` and the + // various compiler tools shipped as part of Visual Studio. Here we try to + // first find the relevant tool, then we also have to be sure to fill in + // environment variables like `LIB`, `INCLUDE`, and `PATH` to ensure that + // the tool is actually usable. + + impl_::find_msvc_environment(tool, target, env_getter) + .or_else(|| impl_::find_msvc_15plus(tool, target, env_getter)) + .or_else(|| impl_::find_msvc_14(tool, target, env_getter)) +} + +/// A version of Visual Studio +#[derive(Debug, PartialEq, Eq, Copy, Clone)] +#[non_exhaustive] +pub enum VsVers { + /// Visual Studio 12 (2013) + #[deprecated( + note = "Visual Studio 12 is no longer supported. cc will never return this value." + )] + Vs12, + /// Visual Studio 14 (2015) + Vs14, + /// Visual Studio 15 (2017) + Vs15, + /// Visual Studio 16 (2019) + Vs16, + /// Visual Studio 17 (2022) + Vs17, +} + +/// Find the most recent installed version of Visual Studio +/// +/// This is used by the cmake crate to figure out the correct +/// generator. +#[allow(clippy::disallowed_methods)] +pub fn find_vs_version() -> Result { + fn has_msbuild_version(version: &str) -> bool { + impl_::has_msbuild_version(version, &StdEnvGetter) + } + + match std::env::var("VisualStudioVersion") { + Ok(version) => match &version[..] { + "17.0" => Ok(VsVers::Vs17), + "16.0" => Ok(VsVers::Vs16), + "15.0" => Ok(VsVers::Vs15), + "14.0" => Ok(VsVers::Vs14), + vers => Err(format!( + "\n\n\ + unsupported or unknown VisualStudio version: {}\n\ + if another version is installed consider running \ + the appropriate vcvars script before building this \ + crate\n\ + ", + vers + )), + }, + _ => { + // Check for the presence of a specific registry key + // that indicates visual studio is installed. + if has_msbuild_version("17.0") { + Ok(VsVers::Vs17) + } else if has_msbuild_version("16.0") { + Ok(VsVers::Vs16) + } else if has_msbuild_version("15.0") { + Ok(VsVers::Vs15) + } else if has_msbuild_version("14.0") { + Ok(VsVers::Vs14) + } else { + Err("\n\n\ + couldn't determine visual studio generator\n\ + if VisualStudio is installed, however, consider \ + running the appropriate vcvars script before building \ + this crate\n\ + " + .to_string()) + } + } + } +} + +/// Windows Implementation. +#[cfg(windows)] +mod impl_ { + use crate::windows::com; + use crate::windows::registry::{RegistryKey, LOCAL_MACHINE}; + use crate::windows::setup_config::SetupConfiguration; + use crate::windows::vs_instances::{VsInstances, VswhereInstance}; + use crate::windows::windows_sys::{ + GetMachineTypeAttributes, GetProcAddress, LoadLibraryA, UserEnabled, HMODULE, + IMAGE_FILE_MACHINE_AMD64, MACHINE_ATTRIBUTES, S_OK, + }; + use std::convert::TryFrom; + use std::env; + use std::ffi::OsString; + use std::fs::File; + use std::io::Read; + use std::iter; + use std::mem; + use std::path::{Path, PathBuf}; + use std::process::Command; + use std::str::FromStr; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Once; + + use super::{EnvGetter, TargetArch, MSVC_FAMILY}; + use crate::Tool; + + struct MsvcTool { + tool: PathBuf, + libs: Vec, + path: Vec, + include: Vec, + } + + struct LibraryHandle(HMODULE); + + impl LibraryHandle { + fn new(name: &[u8]) -> Option { + let handle = unsafe { LoadLibraryA(name.as_ptr() as _) }; + (!handle.is_null()).then_some(Self(handle)) + } + + /// Get a function pointer to a function in the library. + /// # SAFETY + /// + /// The caller must ensure that the function signature matches the actual function. + /// The easiest way to do this is to add an entry to windows_sys_no_link.list and use the + /// generated function for `func_signature`. + /// + /// The function returned cannot be used after the handle is dropped. + unsafe fn get_proc_address(&self, name: &[u8]) -> Option { + let symbol = GetProcAddress(self.0, name.as_ptr() as _); + symbol.map(|symbol| mem::transmute_copy(&symbol)) + } + } + + type GetMachineTypeAttributesFuncType = + unsafe extern "system" fn(u16, *mut MACHINE_ATTRIBUTES) -> i32; + const _: () = { + // Ensure that our hand-written signature matches the actual function signature. + // We can't use `GetMachineTypeAttributes` outside of a const scope otherwise we'll end up statically linking to + // it, which will fail to load on older versions of Windows. + let _: GetMachineTypeAttributesFuncType = GetMachineTypeAttributes; + }; + + fn is_amd64_emulation_supported_inner() -> Option { + // GetMachineTypeAttributes is only available on Win11 22000+, so dynamically load it. + let kernel32 = LibraryHandle::new(b"kernel32.dll\0")?; + // SAFETY: GetMachineTypeAttributesFuncType is checked to match the real function signature. + let get_machine_type_attributes = unsafe { + kernel32 + .get_proc_address::(b"GetMachineTypeAttributes\0") + }?; + let mut attributes = Default::default(); + if unsafe { get_machine_type_attributes(IMAGE_FILE_MACHINE_AMD64, &mut attributes) } == S_OK + { + Some((attributes & UserEnabled) != 0) + } else { + Some(false) + } + } + + fn is_amd64_emulation_supported() -> bool { + // TODO: Replace with a OnceLock once MSRV is 1.70. + static LOAD_VALUE: Once = Once::new(); + static IS_SUPPORTED: AtomicBool = AtomicBool::new(false); + + // Using Relaxed ordering since the Once is providing synchronization. + LOAD_VALUE.call_once(|| { + IS_SUPPORTED.store( + is_amd64_emulation_supported_inner().unwrap_or(false), + Ordering::Relaxed, + ); + }); + IS_SUPPORTED.load(Ordering::Relaxed) + } + + impl MsvcTool { + fn new(tool: PathBuf) -> MsvcTool { + MsvcTool { + tool, + libs: Vec::new(), + path: Vec::new(), + include: Vec::new(), + } + } + + fn into_tool(self, env_getter: &dyn EnvGetter) -> Tool { + let MsvcTool { + tool, + libs, + path, + include, + } = self; + let mut tool = Tool::with_family(tool, MSVC_FAMILY); + add_env(&mut tool, "LIB", libs, env_getter); + add_env(&mut tool, "PATH", path, env_getter); + add_env(&mut tool, "INCLUDE", include, env_getter); + tool + } + } + + /// Checks to see if the `VSCMD_ARG_TGT_ARCH` environment variable matches the + /// given target's arch. Returns `None` if the variable does not exist. + fn is_vscmd_target(target: TargetArch<'_>, env_getter: &dyn EnvGetter) -> Option { + let vscmd_arch = env_getter.get_env("VSCMD_ARG_TGT_ARCH")?; + // Convert the Rust target arch to its VS arch equivalent. + let arch = match target.into() { + "x86_64" => "x64", + "aarch64" | "arm64ec" => "arm64", + "i686" | "i586" => "x86", + "thumbv7a" => "arm", + // An unrecognized arch. + _ => return Some(false), + }; + Some(vscmd_arch.as_ref() == arch) + } + + /// Attempt to find the tool using environment variables set by vcvars. + pub(super) fn find_msvc_environment( + tool: &str, + target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option { + // Early return if the environment isn't one that is known to have compiler toolsets in PATH + // `VCINSTALLDIR` is set from vcvarsall.bat (developer command prompt) + // `VSTEL_MSBuildProjectFullPath` is set by msbuild when invoking custom build steps + // NOTE: `VisualStudioDir` used to be used but this isn't set when invoking msbuild from the commandline + if env_getter.get_env("VCINSTALLDIR").is_none() + && env_getter.get_env("VSTEL_MSBuildProjectFullPath").is_none() + { + return None; + } + + // If the vscmd target differs from the requested target then + // attempt to get the tool using the VS install directory. + if is_vscmd_target(target, env_getter) == Some(false) { + // We will only get here with versions 15+. + let vs_install_dir: PathBuf = env_getter.get_env("VSINSTALLDIR")?.into(); + tool_from_vs15plus_instance(tool, target, &vs_install_dir, env_getter) + } else { + // Fallback to simply using the current environment. + env_getter + .get_env("PATH") + .and_then(|path| { + env::split_paths(&path) + .map(|p| p.join(tool)) + .find(|p| p.exists()) + }) + .map(|path| Tool::with_family(path, MSVC_FAMILY)) + } + } + + fn find_msbuild_vs17(target: TargetArch<'_>, env_getter: &dyn EnvGetter) -> Option { + find_tool_in_vs16plus_path(r"MSBuild\Current\Bin\MSBuild.exe", target, "17", env_getter) + } + + #[allow(bare_trait_objects)] + fn vs16plus_instances( + target: TargetArch<'_>, + version: &'static str, + env_getter: &dyn EnvGetter, + ) -> Box> { + let instances = if let Some(instances) = vs15plus_instances(target, env_getter) { + instances + } else { + return Box::new(iter::empty()); + }; + Box::new(instances.into_iter().filter_map(move |instance| { + let installation_name = instance.installation_name()?; + if installation_name.starts_with(&format!("VisualStudio/{}.", version)) + || installation_name.starts_with(&format!("VisualStudioPreview/{}.", version)) + { + Some(instance.installation_path()?) + } else { + None + } + })) + } + + fn find_tool_in_vs16plus_path( + tool: &str, + target: TargetArch<'_>, + version: &'static str, + env_getter: &dyn EnvGetter, + ) -> Option { + vs16plus_instances(target, version, env_getter) + .filter_map(|path| { + let path = path.join(tool); + if !path.is_file() { + return None; + } + let mut tool = Tool::with_family(path, MSVC_FAMILY); + if target == "x86_64" { + tool.env.push(("Platform".into(), "X64".into())); + } + if target == "aarch64" || target == "arm64ec" { + tool.env.push(("Platform".into(), "ARM64".into())); + } + Some(tool) + }) + .next() + } + + fn find_msbuild_vs16(target: TargetArch<'_>, env_getter: &dyn EnvGetter) -> Option { + find_tool_in_vs16plus_path(r"MSBuild\Current\Bin\MSBuild.exe", target, "16", env_getter) + } + + // In MSVC 15 (2017) MS once again changed the scheme for locating + // the tooling. Now we must go through some COM interfaces, which + // is super fun for Rust. + // + // Note that much of this logic can be found [online] wrt paths, COM, etc. + // + // [online]: https://blogs.msdn.microsoft.com/vcblog/2017/03/06/finding-the-visual-c-compiler-tools-in-visual-studio-2017/ + // + // Returns MSVC 15+ instances (15, 16 right now), the order should be consider undefined. + // + // However, on ARM64 this method doesn't work because VS Installer fails to register COM component on ARM64. + // Hence, as the last resort we try to use vswhere.exe to list available instances. + fn vs15plus_instances( + target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option { + vs15plus_instances_using_com() + .or_else(|| vs15plus_instances_using_vswhere(target, env_getter)) + } + + fn vs15plus_instances_using_com() -> Option { + com::initialize().ok()?; + + let config = SetupConfiguration::new().ok()?; + let enum_setup_instances = config.enum_all_instances().ok()?; + + Some(VsInstances::ComBased(enum_setup_instances)) + } + + fn vs15plus_instances_using_vswhere( + target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option { + let program_files_path = env_getter + .get_env("ProgramFiles(x86)") + .or_else(|| env_getter.get_env("ProgramFiles"))?; + + let program_files_path = Path::new(program_files_path.as_ref()); + + let vswhere_path = + program_files_path.join(r"Microsoft Visual Studio\Installer\vswhere.exe"); + + if !vswhere_path.exists() { + return None; + } + + let tools_arch = match target.into() { + "i586" | "i686" | "x86_64" => Some("x86.x64"), + "arm" | "thumbv7a" => Some("ARM"), + "aarch64" | "arm64ec" => Some("ARM64"), + _ => None, + }; + + let vswhere_output = Command::new(vswhere_path) + .args([ + "-latest", + "-products", + "*", + "-requires", + &format!("Microsoft.VisualStudio.Component.VC.Tools.{}", tools_arch?), + "-format", + "text", + "-nologo", + ]) + .stderr(std::process::Stdio::inherit()) + .output() + .ok()?; + + let vs_instances = + VsInstances::VswhereBased(VswhereInstance::try_from(&vswhere_output.stdout).ok()?); + + Some(vs_instances) + } + + // Inspired from official microsoft/vswhere ParseVersionString + // i.e. at most four u16 numbers separated by '.' + fn parse_version(version: &str) -> Option> { + version + .split('.') + .map(|chunk| u16::from_str(chunk).ok()) + .collect() + } + + pub(super) fn find_msvc_15plus( + tool: &str, + target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option { + let iter = vs15plus_instances(target, env_getter)?; + iter.into_iter() + .filter_map(|instance| { + let version = parse_version(&instance.installation_version()?)?; + let instance_path = instance.installation_path()?; + let tool = tool_from_vs15plus_instance(tool, target, &instance_path, env_getter)?; + Some((version, tool)) + }) + .max_by(|(a_version, _), (b_version, _)| a_version.cmp(b_version)) + .map(|(_version, tool)| tool) + } + + // While the paths to Visual Studio 2017's devenv and MSBuild could + // potentially be retrieved from the registry, finding them via + // SetupConfiguration has shown to be [more reliable], and is preferred + // according to Microsoft. To help head off potential regressions though, + // we keep the registry method as a fallback option. + // + // [more reliable]: https://github.com/rust-lang/cc-rs/pull/331 + fn find_tool_in_vs15_path( + tool: &str, + target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option { + let mut path = match vs15plus_instances(target, env_getter) { + Some(instances) => instances + .into_iter() + .filter_map(|instance| instance.installation_path()) + .map(|path| path.join(tool)) + .find(|path| path.is_file()), + None => None, + }; + + if path.is_none() { + let key = r"SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"; + path = LOCAL_MACHINE + .open(key.as_ref()) + .ok() + .and_then(|key| key.query_str("15.0").ok()) + .map(|path| PathBuf::from(path).join(tool)) + .and_then(|path| if path.is_file() { Some(path) } else { None }); + } + + path.map(|path| { + let mut tool = Tool::with_family(path, MSVC_FAMILY); + if target == "x86_64" { + tool.env.push(("Platform".into(), "X64".into())); + } else if target == "aarch64" { + tool.env.push(("Platform".into(), "ARM64".into())); + } + tool + }) + } + + fn tool_from_vs15plus_instance( + tool: &str, + target: TargetArch<'_>, + instance_path: &Path, + env_getter: &dyn EnvGetter, + ) -> Option { + let (root_path, bin_path, host_dylib_path, lib_path, alt_lib_path, include_path) = + vs15plus_vc_paths(target, instance_path, env_getter)?; + let tool_path = bin_path.join(tool); + if !tool_path.exists() { + return None; + }; + + let mut tool = MsvcTool::new(tool_path); + tool.path.push(bin_path.clone()); + tool.path.push(host_dylib_path); + if let Some(alt_lib_path) = alt_lib_path { + tool.libs.push(alt_lib_path); + } + tool.libs.push(lib_path); + tool.include.push(include_path); + + if let Some((atl_lib_path, atl_include_path)) = atl_paths(target, &root_path) { + tool.libs.push(atl_lib_path); + tool.include.push(atl_include_path); + } + + add_sdks(&mut tool, target, env_getter)?; + + Some(tool.into_tool(env_getter)) + } + + fn vs15plus_vc_paths( + target: TargetArch<'_>, + instance_path: &Path, + env_getter: &dyn EnvGetter, + ) -> Option<(PathBuf, PathBuf, PathBuf, PathBuf, Option, PathBuf)> { + let version = vs15plus_vc_read_version(instance_path)?; + + let hosts = match host_arch() { + X86 => &["X86"], + X86_64 => &["X64"], + // Starting with VS 17.4, there is a natively hosted compiler on ARM64: + // https://devblogs.microsoft.com/visualstudio/arm64-visual-studio-is-officially-here/ + // On older versions of VS, we use x64 if running under emulation is supported, + // otherwise use x86. + AARCH64 => { + if is_amd64_emulation_supported() { + &["ARM64", "X64", "X86"][..] + } else { + &["ARM64", "X86"] + } + } + _ => return None, + }; + let target = lib_subdir(target)?; + // The directory layout here is MSVC/bin/Host$host/$target/ + let path = instance_path.join(r"VC\Tools\MSVC").join(version); + // We use the first available host architecture that can build for the target + let (host_path, host) = hosts.iter().find_map(|&x| { + let candidate = path.join("bin").join(format!("Host{}", x)); + if candidate.join(target).exists() { + Some((candidate, x)) + } else { + None + } + })?; + // This is the path to the toolchain for a particular target, running + // on a given host + let bin_path = host_path.join(target); + // But! we also need PATH to contain the target directory for the host + // architecture, because it contains dlls like mspdb140.dll compiled for + // the host architecture. + let host_dylib_path = host_path.join(host.to_lowercase()); + let lib_fragment = if use_spectre_mitigated_libs(env_getter) { + r"lib\spectre" + } else { + "lib" + }; + let lib_path = path.join(lib_fragment).join(target); + let alt_lib_path = (target == "arm64ec").then(|| path.join(lib_fragment).join("arm64ec")); + let include_path = path.join("include"); + Some(( + path, + bin_path, + host_dylib_path, + lib_path, + alt_lib_path, + include_path, + )) + } + + fn vs15plus_vc_read_version(dir: &Path) -> Option { + // Try to open the default version file. + let mut version_path: PathBuf = + dir.join(r"VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt"); + let mut version_file = if let Ok(f) = File::open(&version_path) { + f + } else { + // If the default doesn't exist, search for other version files. + // These are in the form Microsoft.VCToolsVersion.v143.default.txt + // where `143` is any three decimal digit version number. + // This sorts versions by lexical order and selects the highest version. + let mut version_file = String::new(); + version_path.pop(); + for file in version_path.read_dir().ok()? { + let name = file.ok()?.file_name(); + let name = name.to_str()?; + if name.starts_with("Microsoft.VCToolsVersion.v") + && name.ends_with(".default.txt") + && name > &version_file + { + version_file.replace_range(.., name); + } + } + if version_file.is_empty() { + return None; + } + version_path.push(version_file); + File::open(version_path).ok()? + }; + + // Get the version string from the file we found. + let mut version = String::new(); + version_file.read_to_string(&mut version).ok()?; + version.truncate(version.trim_end().len()); + Some(version) + } + + fn use_spectre_mitigated_libs(env_getter: &dyn EnvGetter) -> bool { + env_getter + .get_env("VSCMD_ARG_VCVARS_SPECTRE") + .map(|env| env.as_ref() == "spectre") + .unwrap_or_default() + } + + fn atl_paths(target: TargetArch<'_>, path: &Path) -> Option<(PathBuf, PathBuf)> { + let atl_path = path.join("atlmfc"); + let sub = lib_subdir(target)?; + if atl_path.exists() { + Some((atl_path.join("lib").join(sub), atl_path.join("include"))) + } else { + None + } + } + + // For MSVC 14 we need to find the Universal CRT as well as either + // the Windows 10 SDK or Windows 8.1 SDK. + pub(super) fn find_msvc_14( + tool: &str, + target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option { + let vcdir = get_vc_dir("14.0")?; + let mut tool = get_tool(tool, &vcdir, target)?; + add_sdks(&mut tool, target, env_getter)?; + Some(tool.into_tool(env_getter)) + } + + fn add_sdks( + tool: &mut MsvcTool, + target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option<()> { + let sub = lib_subdir(target)?; + let (ucrt, ucrt_version) = get_ucrt_dir()?; + + let host = match host_arch() { + X86 => "x86", + X86_64 => "x64", + AARCH64 => "arm64", + _ => return None, + }; + + tool.path + .push(ucrt.join("bin").join(&ucrt_version).join(host)); + + let ucrt_include = ucrt.join("include").join(&ucrt_version); + tool.include.push(ucrt_include.join("ucrt")); + + let ucrt_lib = ucrt.join("lib").join(&ucrt_version); + tool.libs.push(ucrt_lib.join("ucrt").join(sub)); + + if let Some((sdk, version)) = get_sdk10_dir(env_getter) { + tool.path.push(sdk.join("bin").join(host)); + let sdk_lib = sdk.join("lib").join(&version); + tool.libs.push(sdk_lib.join("um").join(sub)); + let sdk_include = sdk.join("include").join(&version); + tool.include.push(sdk_include.join("um")); + tool.include.push(sdk_include.join("cppwinrt")); + tool.include.push(sdk_include.join("winrt")); + tool.include.push(sdk_include.join("shared")); + } else if let Some(sdk) = get_sdk81_dir() { + tool.path.push(sdk.join("bin").join(host)); + let sdk_lib = sdk.join("lib").join("winv6.3"); + tool.libs.push(sdk_lib.join("um").join(sub)); + let sdk_include = sdk.join("include"); + tool.include.push(sdk_include.join("um")); + tool.include.push(sdk_include.join("winrt")); + tool.include.push(sdk_include.join("shared")); + } + + Some(()) + } + + fn add_env( + tool: &mut Tool, + env: &'static str, + paths: Vec, + env_getter: &dyn EnvGetter, + ) { + let prev = env_getter.get_env(env); + let prev = prev.as_ref().map(AsRef::as_ref).unwrap_or_default(); + let prev = env::split_paths(&prev); + let new = paths.into_iter().chain(prev); + tool.env + .push((env.to_string().into(), env::join_paths(new).unwrap())); + } + + // Given a possible MSVC installation directory, we look for the linker and + // then add the MSVC library path. + fn get_tool(tool: &str, path: &Path, target: TargetArch<'_>) -> Option { + bin_subdir(target) + .into_iter() + .map(|(sub, host)| { + ( + path.join("bin").join(sub).join(tool), + path.join("bin").join(host), + ) + }) + .filter(|(path, _)| path.is_file()) + .map(|(path, host)| { + let mut tool = MsvcTool::new(path); + tool.path.push(host); + tool + }) + .filter_map(|mut tool| { + let sub = vc_lib_subdir(target)?; + tool.libs.push(path.join("lib").join(sub)); + tool.include.push(path.join("include")); + let atlmfc_path = path.join("atlmfc"); + if atlmfc_path.exists() { + tool.libs.push(atlmfc_path.join("lib").join(sub)); + tool.include.push(atlmfc_path.join("include")); + } + Some(tool) + }) + .next() + } + + // To find MSVC we look in a specific registry key for the version we are + // trying to find. + fn get_vc_dir(ver: &str) -> Option { + let key = r"SOFTWARE\Microsoft\VisualStudio\SxS\VC7"; + let key = LOCAL_MACHINE.open(key.as_ref()).ok()?; + let path = key.query_str(ver).ok()?; + Some(path.into()) + } + + // To find the Universal CRT we look in a specific registry key for where + // all the Universal CRTs are located and then sort them asciibetically to + // find the newest version. While this sort of sorting isn't ideal, it is + // what vcvars does so that's good enough for us. + // + // Returns a pair of (root, version) for the ucrt dir if found + fn get_ucrt_dir() -> Option<(PathBuf, String)> { + let key = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots"; + let key = LOCAL_MACHINE.open(key.as_ref()).ok()?; + let root = key.query_str("KitsRoot10").ok()?; + let readdir = Path::new(&root).join("lib").read_dir().ok()?; + let max_libdir = readdir + .filter_map(|dir| dir.ok()) + .map(|dir| dir.path()) + .filter(|dir| { + dir.components() + .last() + .and_then(|c| c.as_os_str().to_str()) + .map(|c| c.starts_with("10.") && dir.join("ucrt").is_dir()) + .unwrap_or(false) + }) + .max()?; + let version = max_libdir.components().last().unwrap(); + let version = version.as_os_str().to_str().unwrap().to_string(); + Some((root.into(), version)) + } + + // Vcvars finds the correct version of the Windows 10 SDK by looking + // for the include `um\Windows.h` because sometimes a given version will + // only have UCRT bits without the rest of the SDK. Since we only care about + // libraries and not includes, we instead look for `um\x64\kernel32.lib`. + // Since the 32-bit and 64-bit libraries are always installed together we + // only need to bother checking x64, making this code a tiny bit simpler. + // Like we do for the Universal CRT, we sort the possibilities + // asciibetically to find the newest one as that is what vcvars does. + // Before doing that, we check the "WindowsSdkDir" and "WindowsSDKVersion" + // environment variables set by vcvars to use the environment sdk version + // if one is already configured. + fn get_sdk10_dir(env_getter: &dyn EnvGetter) -> Option<(PathBuf, String)> { + if let (Some(root), Some(version)) = ( + env_getter.get_env("WindowsSdkDir"), + env_getter + .get_env("WindowsSDKVersion") + .as_ref() + .and_then(|version| version.as_ref().to_str()), + ) { + return Some(( + PathBuf::from(root), + version.trim_end_matches('\\').to_string(), + )); + } + + let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0"; + let key = LOCAL_MACHINE.open(key.as_ref()).ok()?; + let root = key.query_str("InstallationFolder").ok()?; + let readdir = Path::new(&root).join("lib").read_dir().ok()?; + let mut dirs = readdir + .filter_map(|dir| dir.ok()) + .map(|dir| dir.path()) + .collect::>(); + dirs.sort(); + let dir = dirs + .into_iter() + .rev() + .find(|dir| dir.join("um").join("x64").join("kernel32.lib").is_file())?; + let version = dir.components().last().unwrap(); + let version = version.as_os_str().to_str().unwrap().to_string(); + Some((root.into(), version)) + } + + // Interestingly there are several subdirectories, `win7` `win8` and + // `winv6.3`. Vcvars seems to only care about `winv6.3` though, so the same + // applies to us. Note that if we were targeting kernel mode drivers + // instead of user mode applications, we would care. + fn get_sdk81_dir() -> Option { + let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1"; + let key = LOCAL_MACHINE.open(key.as_ref()).ok()?; + let root = key.query_str("InstallationFolder").ok()?; + Some(root.into()) + } + + const PROCESSOR_ARCHITECTURE_INTEL: u16 = 0; + const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9; + const PROCESSOR_ARCHITECTURE_ARM64: u16 = 12; + const X86: u16 = PROCESSOR_ARCHITECTURE_INTEL; + const X86_64: u16 = PROCESSOR_ARCHITECTURE_AMD64; + const AARCH64: u16 = PROCESSOR_ARCHITECTURE_ARM64; + + // When choosing the tool to use, we have to choose the one which matches + // the target architecture. Otherwise we end up in situations where someone + // on 32-bit Windows is trying to cross compile to 64-bit and it tries to + // invoke the native 64-bit compiler which won't work. + // + // For the return value of this function, the first member of the tuple is + // the folder of the tool we will be invoking, while the second member is + // the folder of the host toolchain for that tool which is essential when + // using a cross linker. We return a Vec since on x64 there are often two + // linkers that can target the architecture we desire. The 64-bit host + // linker is preferred, and hence first, due to 64-bit allowing it more + // address space to work with and potentially being faster. + fn bin_subdir(target: TargetArch<'_>) -> Vec<(&'static str, &'static str)> { + match (target.into(), host_arch()) { + ("i586", X86) | ("i686", X86) => vec![("", "")], + ("i586", X86_64) | ("i686", X86_64) => vec![("amd64_x86", "amd64"), ("", "")], + ("x86_64", X86) => vec![("x86_amd64", "")], + ("x86_64", X86_64) => vec![("amd64", "amd64"), ("x86_amd64", "")], + ("arm", X86) | ("thumbv7a", X86) => vec![("x86_arm", "")], + ("arm", X86_64) | ("thumbv7a", X86_64) => vec![("amd64_arm", "amd64"), ("x86_arm", "")], + _ => vec![], + } + } + + fn lib_subdir(target: TargetArch<'_>) -> Option<&'static str> { + match target.into() { + "i586" | "i686" => Some("x86"), + "x86_64" => Some("x64"), + "arm" | "thumbv7a" => Some("arm"), + "aarch64" | "arm64ec" => Some("arm64"), + _ => None, + } + } + + // MSVC's x86 libraries are not in a subfolder + fn vc_lib_subdir(target: TargetArch<'_>) -> Option<&'static str> { + match target.into() { + "i586" | "i686" => Some(""), + "x86_64" => Some("amd64"), + "arm" | "thumbv7a" => Some("arm"), + "aarch64" => Some("arm64"), + _ => None, + } + } + + #[allow(bad_style)] + fn host_arch() -> u16 { + type DWORD = u32; + type WORD = u16; + type LPVOID = *mut u8; + type DWORD_PTR = usize; + + #[repr(C)] + struct SYSTEM_INFO { + wProcessorArchitecture: WORD, + _wReserved: WORD, + _dwPageSize: DWORD, + _lpMinimumApplicationAddress: LPVOID, + _lpMaximumApplicationAddress: LPVOID, + _dwActiveProcessorMask: DWORD_PTR, + _dwNumberOfProcessors: DWORD, + _dwProcessorType: DWORD, + _dwAllocationGranularity: DWORD, + _wProcessorLevel: WORD, + _wProcessorRevision: WORD, + } + + extern "system" { + fn GetNativeSystemInfo(lpSystemInfo: *mut SYSTEM_INFO); + } + + unsafe { + let mut info = mem::zeroed(); + GetNativeSystemInfo(&mut info); + info.wProcessorArchitecture + } + } + + // Given a registry key, look at all the sub keys and find the one which has + // the maximal numeric value. + // + // Returns the name of the maximal key as well as the opened maximal key. + fn max_version(key: &RegistryKey) -> Option<(OsString, RegistryKey)> { + let mut max_vers = 0; + let mut max_key = None; + for subkey in key.iter().filter_map(|k| k.ok()) { + let val = subkey + .to_str() + .and_then(|s| s.trim_start_matches('v').replace('.', "").parse().ok()); + let val = match val { + Some(s) => s, + None => continue, + }; + if val > max_vers { + if let Ok(k) = key.open(&subkey) { + max_vers = val; + max_key = Some((subkey, k)); + } + } + } + max_key + } + + #[inline(always)] + pub(super) fn has_msbuild_version(version: &str, env_getter: &dyn EnvGetter) -> bool { + match version { + "17.0" => { + find_msbuild_vs17(TargetArch("x86_64"), env_getter).is_some() + || find_msbuild_vs17(TargetArch("i686"), env_getter).is_some() + || find_msbuild_vs17(TargetArch("aarch64"), env_getter).is_some() + } + "16.0" => { + find_msbuild_vs16(TargetArch("x86_64"), env_getter).is_some() + || find_msbuild_vs16(TargetArch("i686"), env_getter).is_some() + || find_msbuild_vs16(TargetArch("aarch64"), env_getter).is_some() + } + "15.0" => { + find_msbuild_vs15(TargetArch("x86_64"), env_getter).is_some() + || find_msbuild_vs15(TargetArch("i686"), env_getter).is_some() + || find_msbuild_vs15(TargetArch("aarch64"), env_getter).is_some() + } + "14.0" => LOCAL_MACHINE + .open(&OsString::from(format!( + "SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\{}", + version + ))) + .is_ok(), + _ => false, + } + } + + pub(super) fn find_devenv(target: TargetArch<'_>, env_getter: &dyn EnvGetter) -> Option { + find_devenv_vs15(target, env_getter) + } + + fn find_devenv_vs15(target: TargetArch<'_>, env_getter: &dyn EnvGetter) -> Option { + find_tool_in_vs15_path(r"Common7\IDE\devenv.exe", target, env_getter) + } + + // see http://stackoverflow.com/questions/328017/path-to-msbuild + pub(super) fn find_msbuild(target: TargetArch<'_>, env_getter: &dyn EnvGetter) -> Option { + // VS 15 (2017) changed how to locate msbuild + if let Some(r) = find_msbuild_vs17(target, env_getter) { + Some(r) + } else if let Some(r) = find_msbuild_vs16(target, env_getter) { + return Some(r); + } else if let Some(r) = find_msbuild_vs15(target, env_getter) { + return Some(r); + } else { + find_old_msbuild(target) + } + } + + fn find_msbuild_vs15(target: TargetArch<'_>, env_getter: &dyn EnvGetter) -> Option { + find_tool_in_vs15_path(r"MSBuild\15.0\Bin\MSBuild.exe", target, env_getter) + } + + fn find_old_msbuild(target: TargetArch<'_>) -> Option { + let key = r"SOFTWARE\Microsoft\MSBuild\ToolsVersions"; + LOCAL_MACHINE + .open(key.as_ref()) + .ok() + .and_then(|key| { + max_version(&key).and_then(|(_vers, key)| key.query_str("MSBuildToolsPath").ok()) + }) + .map(|path| { + let mut path = PathBuf::from(path); + path.push("MSBuild.exe"); + let mut tool = Tool::with_family(path, MSVC_FAMILY); + if target == "x86_64" { + tool.env.push(("Platform".into(), "X64".into())); + } + tool + }) + } +} + +/// Non-Windows Implementation. +#[cfg(not(windows))] +mod impl_ { + use std::{env, ffi::OsStr}; + + use super::{EnvGetter, TargetArch, MSVC_FAMILY}; + use crate::Tool; + + /// Finding msbuild.exe tool under unix system is not currently supported. + /// Maybe can check it using an environment variable looks like `MSBUILD_BIN`. + #[inline(always)] + pub(super) fn find_msbuild(_target: TargetArch<'_>, _: &dyn EnvGetter) -> Option { + None + } + + // Finding devenv.exe tool under unix system is not currently supported. + // Maybe can check it using an environment variable looks like `DEVENV_BIN`. + #[inline(always)] + pub(super) fn find_devenv(_target: TargetArch<'_>, _: &dyn EnvGetter) -> Option { + None + } + + /// Attempt to find the tool using environment variables set by vcvars. + pub(super) fn find_msvc_environment( + tool: &str, + _target: TargetArch<'_>, + env_getter: &dyn EnvGetter, + ) -> Option { + // Early return if the environment doesn't contain a VC install. + let vc_install_dir = env_getter.get_env("VCINSTALLDIR")?; + let vs_install_dir = env_getter.get_env("VSINSTALLDIR")?; + + let get_tool = |install_dir: &OsStr| { + env::split_paths(install_dir) + .map(|p| p.join(tool)) + .find(|p| p.exists()) + .map(|path| Tool::with_family(path, MSVC_FAMILY)) + }; + + // Take the path of tool for the vc install directory. + get_tool(vc_install_dir.as_ref()) + // Take the path of tool for the vs install directory. + .or_else(|| get_tool(vs_install_dir.as_ref())) + // Take the path of tool for the current path environment. + .or_else(|| { + env_getter + .get_env("PATH") + .as_ref() + .map(|path| path.as_ref()) + .and_then(get_tool) + }) + } + + #[inline(always)] + pub(super) fn find_msvc_15plus( + _tool: &str, + _target: TargetArch<'_>, + _: &dyn EnvGetter, + ) -> Option { + None + } + + // For MSVC 14 we need to find the Universal CRT as well as either + // the Windows 10 SDK or Windows 8.1 SDK. + #[inline(always)] + pub(super) fn find_msvc_14( + _tool: &str, + _target: TargetArch<'_>, + _: &dyn EnvGetter, + ) -> Option { + None + } + + #[inline(always)] + pub(super) fn has_msbuild_version(_version: &str, _: &dyn EnvGetter) -> bool { + false + } +} diff --git a/bitbox02-bt/vendor/cc/src/windows/mod.rs b/bitbox02-bt/vendor/cc/src/windows/mod.rs new file mode 100644 index 0000000..ccf22b0 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/mod.rs @@ -0,0 +1,22 @@ +//! These modules are all glue to support reading the MSVC version from +//! the registry and from COM interfaces. + +// This is used in the crate's public API, so don't use #[cfg(windows)] +pub mod find_tools; + +#[cfg(windows)] +pub(crate) mod windows_sys; +#[cfg(windows)] +mod windows_targets; + +#[cfg(windows)] +mod registry; +#[cfg(windows)] +#[macro_use] +mod winapi; +#[cfg(windows)] +mod com; +#[cfg(windows)] +mod setup_config; +#[cfg(windows)] +mod vs_instances; diff --git a/bitbox02-bt/vendor/cc/src/windows/registry.rs b/bitbox02-bt/vendor/cc/src/windows/registry.rs new file mode 100644 index 0000000..8398303 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/registry.rs @@ -0,0 +1,191 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use crate::windows::windows_sys::{ + RegCloseKey, RegEnumKeyExW, RegOpenKeyExW, RegQueryValueExW, ERROR_NO_MORE_ITEMS, + ERROR_SUCCESS, HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, REG_SZ, +}; +use std::{ + ffi::{OsStr, OsString}, + io, + ops::RangeFrom, + os::windows::prelude::*, + ptr::null_mut, +}; + +/// Must never be `HKEY_PERFORMANCE_DATA`. +pub(crate) struct RegistryKey(Repr); + +#[allow(clippy::upper_case_acronyms)] +type DWORD = u32; + +struct OwnedKey(HKEY); + +/// Note: must not encode `HKEY_PERFORMANCE_DATA` or one of its subkeys. +enum Repr { + /// `HKEY_LOCAL_MACHINE`. + LocalMachine, + /// A subkey of `HKEY_LOCAL_MACHINE`. + Owned(OwnedKey), +} + +pub struct Iter<'a> { + idx: RangeFrom, + key: &'a RegistryKey, +} + +unsafe impl Sync for Repr {} +unsafe impl Send for Repr {} + +pub(crate) const LOCAL_MACHINE: RegistryKey = RegistryKey(Repr::LocalMachine); + +impl RegistryKey { + fn raw(&self) -> HKEY { + match self.0 { + Repr::LocalMachine => HKEY_LOCAL_MACHINE, + Repr::Owned(ref val) => val.0, + } + } + + /// Open a sub-key of `self`. + pub fn open(&self, key: &OsStr) -> io::Result { + let key = key.encode_wide().chain(Some(0)).collect::>(); + let mut ret = null_mut(); + let err = unsafe { + RegOpenKeyExW( + self.raw(), + key.as_ptr(), + 0, + KEY_READ | KEY_WOW64_32KEY, + &mut ret, + ) + }; + if err == ERROR_SUCCESS { + Ok(RegistryKey(Repr::Owned(OwnedKey(ret)))) + } else { + Err(io::Error::from_raw_os_error(err as i32)) + } + } + + pub fn iter(&self) -> Iter { + Iter { + idx: 0.., + key: self, + } + } + + pub fn query_str(&self, name: &str) -> io::Result { + let name: &OsStr = name.as_ref(); + let name = name.encode_wide().chain(Some(0)).collect::>(); + let mut len = 0; + let mut kind = 0; + unsafe { + let err = RegQueryValueExW( + self.raw(), + name.as_ptr(), + null_mut(), + &mut kind, + null_mut(), + &mut len, + ); + if err != ERROR_SUCCESS { + return Err(io::Error::from_raw_os_error(err as i32)); + } + if kind != REG_SZ { + return Err(io::Error::new( + io::ErrorKind::Other, + "registry key wasn't a string", + )); + } + + // The length here is the length in bytes, but we're using wide + // characters so we need to be sure to halve it for the length + // passed in. + assert!(len % 2 == 0, "impossible wide string size: {} bytes", len); + let vlen = len as usize / 2; + // Defensively initialized, see comment about + // `HKEY_PERFORMANCE_DATA` below. + let mut v = vec![0u16; vlen]; + let err = RegQueryValueExW( + self.raw(), + name.as_ptr(), + null_mut(), + null_mut(), + v.as_mut_ptr() as *mut _, + &mut len, + ); + // We don't check for `ERROR_MORE_DATA` (which would if the value + // grew between the first and second call to `RegQueryValueExW`), + // both because it's extremely unlikely, and this is a bit more + // defensive more defensive against weird types of registry keys. + if err != ERROR_SUCCESS { + return Err(io::Error::from_raw_os_error(err as i32)); + } + // The length is allowed to change, but should still be even, as + // well as smaller. + assert!(len % 2 == 0, "impossible wide string size: {} bytes", len); + // If the length grew but returned a success code, it *probably* + // indicates we're `HKEY_PERFORMANCE_DATA` or a subkey(?). We + // consider this UB, since those keys write "undefined" or + // "unpredictable" values to len, and need to use a completely + // different loop structure. This should be impossible (and enforce + // it in the API to the best of our ability), but to mitigate the + // damage we do some smoke-checks on the len, and ensure `v` has + // been fully initialized (rather than trusting the result of + // `RegQueryValueExW`). + let actual_len = len as usize / 2; + assert!(actual_len <= v.len()); + v.truncate(actual_len); + // Some registry keys may have a terminating nul character, but + // we're not interested in that, so chop it off if it's there. + if !v.is_empty() && v[v.len() - 1] == 0 { + v.pop(); + } + Ok(OsString::from_wide(&v)) + } + } +} + +impl Drop for OwnedKey { + fn drop(&mut self) { + unsafe { + RegCloseKey(self.0); + } + } +} + +impl<'a> Iterator for Iter<'a> { + type Item = io::Result; + + fn next(&mut self) -> Option> { + self.idx.next().and_then(|i| unsafe { + let mut v = Vec::with_capacity(256); + let mut len = v.capacity() as DWORD; + let ret = RegEnumKeyExW( + self.key.raw(), + i, + v.as_mut_ptr(), + &mut len, + null_mut(), + null_mut(), + null_mut(), + null_mut(), + ); + if ret == ERROR_NO_MORE_ITEMS { + None + } else if ret != ERROR_SUCCESS { + Some(Err(io::Error::from_raw_os_error(ret as i32))) + } else { + v.set_len(len as usize); + Some(Ok(OsString::from_wide(&v))) + } + }) + } +} diff --git a/bitbox02-bt/vendor/cc/src/windows/setup_config.rs b/bitbox02-bt/vendor/cc/src/windows/setup_config.rs new file mode 100644 index 0000000..5739ecf --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/setup_config.rs @@ -0,0 +1,283 @@ +// Copyright © 2017 winapi-rs developers +// Licensed under the Apache License, Version 2.0 +// or the MIT license +// , at your option. +// All files in the project carrying such notice may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] +#![allow(unused)] + +use crate::windows::{ + com::{BStr, ComPtr}, + winapi::{ + IUnknown, IUnknownVtbl, Interface, LCID, LPCOLESTR, LPCWSTR, LPFILETIME, LPSAFEARRAY, + PULONGLONG, ULONG, + }, + windows_sys::{CoCreateInstance, BSTR, CLSCTX_ALL, HRESULT, S_FALSE}, +}; + +use std::{ + ffi::OsString, + ptr::{null, null_mut}, +}; + +// Bindings to the Setup.Configuration stuff +pub type InstanceState = u32; + +pub const eNone: InstanceState = 0; +pub const eLocal: InstanceState = 1; +pub const eRegistered: InstanceState = 2; +pub const eNoRebootRequired: InstanceState = 4; +pub const eComplete: InstanceState = -1i32 as u32; + +RIDL! {#[uuid(0xb41463c3, 0x8866, 0x43b5, 0xbc, 0x33, 0x2b, 0x06, 0x76, 0xf7, 0xf4, 0x2e)] +interface ISetupInstance(ISetupInstanceVtbl): IUnknown(IUnknownVtbl) { + fn GetInstanceId( + pbstrInstanceId: *mut BSTR, + ) -> HRESULT, + fn GetInstallDate( + pInstallDate: LPFILETIME, + ) -> HRESULT, + fn GetInstallationName( + pbstrInstallationName: *mut BSTR, + ) -> HRESULT, + fn GetInstallationPath( + pbstrInstallationPath: *mut BSTR, + ) -> HRESULT, + fn GetInstallationVersion( + pbstrInstallationVersion: *mut BSTR, + ) -> HRESULT, + fn GetDisplayName( + lcid: LCID, + pbstrDisplayName: *mut BSTR, + ) -> HRESULT, + fn GetDescription( + lcid: LCID, + pbstrDescription: *mut BSTR, + ) -> HRESULT, + fn ResolvePath( + pwszRelativePath: LPCOLESTR, + pbstrAbsolutePath: *mut BSTR, + ) -> HRESULT, +}} + +RIDL! {#[uuid(0x89143c9a, 0x05af, 0x49b0, 0xb7, 0x17, 0x72, 0xe2, 0x18, 0xa2, 0x18, 0x5c)] +interface ISetupInstance2(ISetupInstance2Vtbl): ISetupInstance(ISetupInstanceVtbl) { + fn GetState( + pState: *mut InstanceState, + ) -> HRESULT, + fn GetPackages( + ppsaPackages: *mut LPSAFEARRAY, + ) -> HRESULT, + fn GetProduct( + ppPackage: *mut *mut ISetupPackageReference, + ) -> HRESULT, + fn GetProductPath( + pbstrProductPath: *mut BSTR, + ) -> HRESULT, +}} + +RIDL! {#[uuid(0x6380bcff, 0x41d3, 0x4b2e, 0x8b, 0x2e, 0xbf, 0x8a, 0x68, 0x10, 0xc8, 0x48)] +interface IEnumSetupInstances(IEnumSetupInstancesVtbl): IUnknown(IUnknownVtbl) { + fn Next( + celt: ULONG, + rgelt: *mut *mut ISetupInstance, + pceltFetched: *mut ULONG, + ) -> HRESULT, + fn Skip( + celt: ULONG, + ) -> HRESULT, + fn Reset() -> HRESULT, + fn Clone( + ppenum: *mut *mut IEnumSetupInstances, + ) -> HRESULT, +}} + +RIDL! {#[uuid(0x42843719, 0xdb4c, 0x46c2, 0x8e, 0x7c, 0x64, 0xf1, 0x81, 0x6e, 0xfd, 0x5b)] +interface ISetupConfiguration(ISetupConfigurationVtbl): IUnknown(IUnknownVtbl) { + fn EnumInstances( + ppEnumInstances: *mut *mut IEnumSetupInstances, + ) -> HRESULT, + fn GetInstanceForCurrentProcess( + ppInstance: *mut *mut ISetupInstance, + ) -> HRESULT, + fn GetInstanceForPath( + wzPath: LPCWSTR, + ppInstance: *mut *mut ISetupInstance, + ) -> HRESULT, +}} + +RIDL! {#[uuid(0x26aab78c, 0x4a60, 0x49d6, 0xaf, 0x3b, 0x3c, 0x35, 0xbc, 0x93, 0x36, 0x5d)] +interface ISetupConfiguration2(ISetupConfiguration2Vtbl): + ISetupConfiguration(ISetupConfigurationVtbl) { + fn EnumAllInstances( + ppEnumInstances: *mut *mut IEnumSetupInstances, + ) -> HRESULT, +}} + +RIDL! {#[uuid(0xda8d8a16, 0xb2b6, 0x4487, 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5)] +interface ISetupPackageReference(ISetupPackageReferenceVtbl): IUnknown(IUnknownVtbl) { + fn GetId( + pbstrId: *mut BSTR, + ) -> HRESULT, + fn GetVersion( + pbstrVersion: *mut BSTR, + ) -> HRESULT, + fn GetChip( + pbstrChip: *mut BSTR, + ) -> HRESULT, + fn GetLanguage( + pbstrLanguage: *mut BSTR, + ) -> HRESULT, + fn GetBranch( + pbstrBranch: *mut BSTR, + ) -> HRESULT, + fn GetType( + pbstrType: *mut BSTR, + ) -> HRESULT, + fn GetUniqueId( + pbstrUniqueId: *mut BSTR, + ) -> HRESULT, +}} + +RIDL! {#[uuid(0x42b21b78, 0x6192, 0x463e, 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c)] +interface ISetupHelper(ISetupHelperVtbl): IUnknown(IUnknownVtbl) { + fn ParseVersion( + pwszVersion: LPCOLESTR, + pullVersion: PULONGLONG, + ) -> HRESULT, + fn ParseVersionRange( + pwszVersionRange: LPCOLESTR, + pullMinVersion: PULONGLONG, + pullMaxVersion: PULONGLONG, + ) -> HRESULT, +}} + +DEFINE_GUID! {CLSID_SetupConfiguration, +0x177f0c4a, 0x1cd3, 0x4de7, 0xa3, 0x2c, 0x71, 0xdb, 0xbb, 0x9f, 0xa3, 0x6d} + +// Safe wrapper around the COM interfaces +pub struct SetupConfiguration(ComPtr); + +impl SetupConfiguration { + pub fn new() -> Result { + let mut obj = null_mut(); + let err = unsafe { + CoCreateInstance( + &CLSID_SetupConfiguration, + null_mut(), + CLSCTX_ALL, + &ISetupConfiguration::uuidof(), + &mut obj, + ) + }; + if err < 0 { + return Err(err); + } + let obj = unsafe { ComPtr::from_raw(obj as *mut ISetupConfiguration) }; + Ok(SetupConfiguration(obj)) + } + pub fn get_instance_for_current_process(&self) -> Result { + let mut obj = null_mut(); + let err = unsafe { self.0.GetInstanceForCurrentProcess(&mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { SetupInstance::from_raw(obj) }) + } + pub fn enum_instances(&self) -> Result { + let mut obj = null_mut(); + let err = unsafe { self.0.EnumInstances(&mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { EnumSetupInstances::from_raw(obj) }) + } + pub fn enum_all_instances(&self) -> Result { + let mut obj = null_mut(); + let this = self.0.cast::()?; + let err = unsafe { this.EnumAllInstances(&mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { EnumSetupInstances::from_raw(obj) }) + } +} + +pub struct SetupInstance(ComPtr); + +impl SetupInstance { + pub unsafe fn from_raw(obj: *mut ISetupInstance) -> SetupInstance { + SetupInstance(ComPtr::from_raw(obj)) + } + pub fn instance_id(&self) -> Result { + let mut s = null(); + let err = unsafe { self.0.GetInstanceId(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn installation_name(&self) -> Result { + let mut s = null(); + let err = unsafe { self.0.GetInstallationName(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn installation_path(&self) -> Result { + let mut s = null(); + let err = unsafe { self.0.GetInstallationPath(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn installation_version(&self) -> Result { + let mut s = null(); + let err = unsafe { self.0.GetInstallationVersion(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn product_path(&self) -> Result { + let mut s = null(); + let this = self.0.cast::()?; + let err = unsafe { this.GetProductPath(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } +} + +pub struct EnumSetupInstances(ComPtr); + +impl EnumSetupInstances { + pub unsafe fn from_raw(obj: *mut IEnumSetupInstances) -> EnumSetupInstances { + EnumSetupInstances(ComPtr::from_raw(obj)) + } +} + +impl Iterator for EnumSetupInstances { + type Item = Result; + fn next(&mut self) -> Option> { + let mut obj = null_mut(); + let err = unsafe { self.0.Next(1, &mut obj, null_mut()) }; + if err < 0 { + return Some(Err(err)); + } + if err == S_FALSE { + return None; + } + Some(Ok(unsafe { SetupInstance::from_raw(obj) })) + } +} diff --git a/bitbox02-bt/vendor/cc/src/windows/vs_instances.rs b/bitbox02-bt/vendor/cc/src/windows/vs_instances.rs new file mode 100644 index 0000000..3e6eeed --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/vs_instances.rs @@ -0,0 +1,199 @@ +use std::borrow::Cow; +use std::collections::HashMap; +use std::convert::TryFrom; +use std::io::BufRead; +use std::path::PathBuf; + +use crate::windows::setup_config::{EnumSetupInstances, SetupInstance}; + +pub enum VsInstance { + Com(SetupInstance), + Vswhere(VswhereInstance), +} + +impl VsInstance { + pub fn installation_name(&self) -> Option> { + match self { + VsInstance::Com(s) => s + .installation_name() + .ok() + .and_then(|s| s.into_string().ok()) + .map(Cow::from), + VsInstance::Vswhere(v) => v.map.get("installationName").map(Cow::from), + } + } + + pub fn installation_path(&self) -> Option { + match self { + VsInstance::Com(s) => s.installation_path().ok().map(PathBuf::from), + VsInstance::Vswhere(v) => v.map.get("installationPath").map(PathBuf::from), + } + } + + pub fn installation_version(&self) -> Option> { + match self { + VsInstance::Com(s) => s + .installation_version() + .ok() + .and_then(|s| s.into_string().ok()) + .map(Cow::from), + VsInstance::Vswhere(v) => v.map.get("installationVersion").map(Cow::from), + } + } +} + +pub enum VsInstances { + ComBased(EnumSetupInstances), + VswhereBased(VswhereInstance), +} + +impl IntoIterator for VsInstances { + type Item = VsInstance; + #[allow(bare_trait_objects)] + type IntoIter = Box>; + + fn into_iter(self) -> Self::IntoIter { + match self { + VsInstances::ComBased(e) => { + Box::new(e.into_iter().filter_map(Result::ok).map(VsInstance::Com)) + } + VsInstances::VswhereBased(v) => Box::new(std::iter::once(VsInstance::Vswhere(v))), + } + } +} + +#[derive(Debug)] +pub struct VswhereInstance { + map: HashMap, +} + +impl TryFrom<&Vec> for VswhereInstance { + type Error = &'static str; + + fn try_from(output: &Vec) -> Result { + let map: HashMap<_, _> = output + .lines() + .map_while(Result::ok) + .filter_map(|s| { + let mut splitn = s.splitn(2, ": "); + Some((splitn.next()?.to_owned(), splitn.next()?.to_owned())) + }) + .collect(); + + if !map.contains_key("installationName") + || !map.contains_key("installationPath") + || !map.contains_key("installationVersion") + { + return Err("required properties not found"); + } + + Ok(Self { map }) + } +} + +#[cfg(test)] +mod tests_ { + use std::borrow::Cow; + use std::convert::TryFrom; + use std::path::PathBuf; + + #[test] + fn it_parses_vswhere_output_correctly() { + let output = br"instanceId: 58104422 +installDate: 21/02/2021 21:50:33 +installationName: VisualStudio/16.9.2+31112.23 +installationPath: C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools +installationVersion: 16.9.31112.23 +productId: Microsoft.VisualStudio.Product.BuildTools +productPath: C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\LaunchDevCmd.bat +state: 4294967295 +isComplete: 1 +isLaunchable: 1 +isPrerelease: 0 +isRebootRequired: 0 +displayName: Visual Studio Build Tools 2019 +description: The Visual Studio Build Tools allows you to build native and managed MSBuild-based applications without requiring the Visual Studio IDE. There are options to install the Visual C++ compilers and libraries, MFC, ATL, and C++/CLI support. +channelId: VisualStudio.16.Release +channelUri: https://aka.ms/vs/16/release/channel +enginePath: C:\Program Files (x86)\Microsoft Visual Studio\Installer\resources\app\ServiceHub\Services\Microsoft.VisualStudio.Setup.Service +releaseNotes: https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes-v16.9#16.9.2 +thirdPartyNotices: https://go.microsoft.com/fwlink/?LinkId=660909 +updateDate: 2021-03-17T21:16:46.5963702Z +catalog_buildBranch: d16.9 +catalog_buildVersion: 16.9.31112.23 +catalog_id: VisualStudio/16.9.2+31112.23 +catalog_localBuild: build-lab +catalog_manifestName: VisualStudio +catalog_manifestType: installer +catalog_productDisplayVersion: 16.9.2 +catalog_productLine: Dev16 +catalog_productLineVersion: 2019 +catalog_productMilestone: RTW +catalog_productMilestoneIsPreRelease: False +catalog_productName: Visual Studio +catalog_productPatchVersion: 2 +catalog_productPreReleaseMilestoneSuffix: 1.0 +catalog_productSemanticVersion: 16.9.2+31112.23 +catalog_requiredEngineVersion: 2.9.3365.38425 +properties_campaignId: 156063665.1613940062 +properties_channelManifestId: VisualStudio.16.Release/16.9.2+31112.23 +properties_nickname: +properties_setupEngineFilePath: C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installershell.exe +" + .to_vec(); + + let vswhere_instance = super::VswhereInstance::try_from(&output); + assert!(vswhere_instance.is_ok()); + + let vs_instance = super::VsInstance::Vswhere(vswhere_instance.unwrap()); + assert_eq!( + vs_instance.installation_name(), + Some(Cow::from("VisualStudio/16.9.2+31112.23")) + ); + assert_eq!( + vs_instance.installation_path(), + Some(PathBuf::from( + r"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools" + )) + ); + assert_eq!( + vs_instance.installation_version(), + Some(Cow::from("16.9.31112.23")) + ); + } + + #[test] + fn it_returns_an_error_for_empty_output() { + let output = b"".to_vec(); + + let vswhere_instance = super::VswhereInstance::try_from(&output); + + assert!(vswhere_instance.is_err()); + } + + #[test] + fn it_returns_an_error_for_output_consisting_of_empty_lines() { + let output = br" + +" + .to_vec(); + + let vswhere_instance = super::VswhereInstance::try_from(&output); + + assert!(vswhere_instance.is_err()); + } + + #[test] + fn it_returns_an_error_for_output_without_required_properties() { + let output = br"instanceId: 58104422 +installDate: 21/02/2021 21:50:33 +productId: Microsoft.VisualStudio.Product.BuildTools +productPath: C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\LaunchDevCmd.bat +" + .to_vec(); + + let vswhere_instance = super::VswhereInstance::try_from(&output); + + assert!(vswhere_instance.is_err()); + } +} diff --git a/bitbox02-bt/vendor/cc/src/windows/winapi.rs b/bitbox02-bt/vendor/cc/src/windows/winapi.rs new file mode 100644 index 0000000..09965da --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/winapi.rs @@ -0,0 +1,146 @@ +// Copyright © 2015-2017 winapi-rs developers +// Licensed under the Apache License, Version 2.0 +// or the MIT license +// , at your option. +// All files in the project carrying such notice may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style, clippy::upper_case_acronyms)] + +use std::os::raw; + +pub type wchar_t = u16; + +pub use crate::windows::windows_sys::{FILETIME, GUID, HRESULT, SAFEARRAY}; + +pub type REFIID = *const IID; +pub type IID = GUID; +pub type ULONG = raw::c_ulong; +pub type DWORD = u32; +pub type LPFILETIME = *mut FILETIME; +pub type OLECHAR = WCHAR; +pub type WCHAR = wchar_t; +pub type LPCOLESTR = *const OLECHAR; +pub type LCID = DWORD; +pub type LPCWSTR = *const WCHAR; +pub type PULONGLONG = *mut ULONGLONG; +pub type ULONGLONG = u64; + +pub trait Interface { + fn uuidof() -> GUID; +} + +pub type LPSAFEARRAY = *mut SAFEARRAY; + +macro_rules! DEFINE_GUID { + ( + $name:ident, $l:expr, $w1:expr, $w2:expr, + $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, $b6:expr, $b7:expr, $b8:expr + ) => { + pub const $name: $crate::windows::winapi::GUID = $crate::windows::winapi::GUID { + data1: $l, + data2: $w1, + data3: $w2, + data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], + }; + }; +} + +macro_rules! RIDL { + (#[uuid($($uuid:expr),+)] + interface $interface:ident ($vtbl:ident) {$( + fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, + )+}) => ( + #[repr(C)] + pub struct $vtbl { + $(pub $method: unsafe extern "system" fn( + This: *mut $interface, + $($p: $t),* + ) -> $rtr,)+ + } + #[repr(C)] + pub struct $interface { + pub lpVtbl: *const $vtbl, + } + RIDL!{@impl $interface {$(fn $method($($p: $t,)*) -> $rtr,)+}} + RIDL!{@uuid $interface $($uuid),+} + ); + (#[uuid($($uuid:expr),+)] + interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) { + }) => ( + #[repr(C)] + pub struct $vtbl { + pub parent: $pvtbl, + } + #[repr(C)] + pub struct $interface { + pub lpVtbl: *const $vtbl, + } + RIDL!{@deref $interface $pinterface} + RIDL!{@uuid $interface $($uuid),+} + ); + (#[uuid($($uuid:expr),+)] + interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) {$( + fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, + )+}) => ( + #[repr(C)] + pub struct $vtbl { + pub parent: $pvtbl, + $(pub $method: unsafe extern "system" fn( + This: *mut $interface, + $($p: $t,)* + ) -> $rtr,)+ + } + #[repr(C)] + pub struct $interface { + pub lpVtbl: *const $vtbl, + } + RIDL!{@impl $interface {$(fn $method($($p: $t,)*) -> $rtr,)+}} + RIDL!{@deref $interface $pinterface} + RIDL!{@uuid $interface $($uuid),+} + ); + (@deref $interface:ident $pinterface:ident) => ( + impl ::std::ops::Deref for $interface { + type Target = $pinterface; + #[inline] + fn deref(&self) -> &$pinterface { + unsafe { &*(self as *const $interface as *const $pinterface) } + } + } + ); + (@impl $interface:ident {$( + fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, + )+}) => ( + impl $interface { + $(#[inline] pub unsafe fn $method(&self, $($p: $t,)*) -> $rtr { + ((*self.lpVtbl).$method)(self as *const _ as *mut _, $($p,)*) + })+ + } + ); + (@uuid $interface:ident + $l:expr, $w1:expr, $w2:expr, + $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, $b6:expr, $b7:expr, $b8:expr + ) => ( + impl $crate::windows::winapi::Interface for $interface { + #[inline] + fn uuidof() -> $crate::windows::winapi::GUID { + $crate::windows::winapi::GUID { + data1: $l, + data2: $w1, + data3: $w2, + data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], + } + } + } + ); +} + +RIDL! {#[uuid(0x00000000, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46)] +interface IUnknown(IUnknownVtbl) { + fn QueryInterface( + riid: REFIID, + ppvObject: *mut *mut raw::c_void, + ) -> HRESULT, + fn AddRef() -> ULONG, + fn Release() -> ULONG, +}} diff --git a/bitbox02-bt/vendor/cc/src/windows/windows_sys.rs b/bitbox02-bt/vendor/cc/src/windows/windows_sys.rs new file mode 100644 index 0000000..fd177e6 --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/windows_sys.rs @@ -0,0 +1,121 @@ +// This file is autogenerated. +// +// To add bindings, edit windows_sys.lst then run: +// +// ``` +// cd generate-windows-sys/ +// cargo run +// ``` +// Bindings generated by `windows-bindgen` 0.58.0 + +#![allow( + non_snake_case, + non_upper_case_globals, + non_camel_case_types, + dead_code, + clippy::all +)] +windows_targets::link!("advapi32.dll" "system" fn RegCloseKey(hkey : HKEY) -> WIN32_ERROR); +windows_targets::link!("advapi32.dll" "system" fn RegEnumKeyExW(hkey : HKEY, dwindex : u32, lpname : PWSTR, lpcchname : *mut u32, lpreserved : *const u32, lpclass : PWSTR, lpcchclass : *mut u32, lpftlastwritetime : *mut FILETIME) -> WIN32_ERROR); +windows_targets::link!("advapi32.dll" "system" fn RegOpenKeyExW(hkey : HKEY, lpsubkey : PCWSTR, uloptions : u32, samdesired : REG_SAM_FLAGS, phkresult : *mut HKEY) -> WIN32_ERROR); +windows_targets::link!("advapi32.dll" "system" fn RegQueryValueExW(hkey : HKEY, lpvaluename : PCWSTR, lpreserved : *const u32, lptype : *mut REG_VALUE_TYPE, lpdata : *mut u8, lpcbdata : *mut u32) -> WIN32_ERROR); +windows_targets::link!("kernel32.dll" "system" fn FreeLibrary(hlibmodule : HMODULE) -> BOOL); +windows_targets::link!("kernel32.dll" "system" fn GetMachineTypeAttributes(machine : u16, machinetypeattributes : *mut MACHINE_ATTRIBUTES) -> HRESULT); +windows_targets::link!("kernel32.dll" "system" fn GetProcAddress(hmodule : HMODULE, lpprocname : PCSTR) -> FARPROC); +windows_targets::link!("kernel32.dll" "system" fn LoadLibraryA(lplibfilename : PCSTR) -> HMODULE); +windows_targets::link!("kernel32.dll" "system" fn OpenSemaphoreA(dwdesiredaccess : u32, binherithandle : BOOL, lpname : PCSTR) -> HANDLE); +windows_targets::link!("kernel32.dll" "system" fn PeekNamedPipe(hnamedpipe : HANDLE, lpbuffer : *mut core::ffi::c_void, nbuffersize : u32, lpbytesread : *mut u32, lptotalbytesavail : *mut u32, lpbytesleftthismessage : *mut u32) -> BOOL); +windows_targets::link!("kernel32.dll" "system" fn ReleaseSemaphore(hsemaphore : HANDLE, lreleasecount : i32, lppreviouscount : *mut i32) -> BOOL); +windows_targets::link!("kernel32.dll" "system" fn WaitForSingleObject(hhandle : HANDLE, dwmilliseconds : u32) -> WAIT_EVENT); +windows_targets::link!("ole32.dll" "system" fn CoCreateInstance(rclsid : *const GUID, punkouter : * mut core::ffi::c_void, dwclscontext : CLSCTX, riid : *const GUID, ppv : *mut *mut core::ffi::c_void) -> HRESULT); +windows_targets::link!("ole32.dll" "system" fn CoInitializeEx(pvreserved : *const core::ffi::c_void, dwcoinit : u32) -> HRESULT); +windows_targets::link!("oleaut32.dll" "system" fn SysFreeString(bstrstring : BSTR)); +windows_targets::link!("oleaut32.dll" "system" fn SysStringLen(pbstr : BSTR) -> u32); +pub type ADVANCED_FEATURE_FLAGS = u16; +pub type BOOL = i32; +pub type BSTR = *const u16; +pub type CLSCTX = u32; +pub const CLSCTX_ALL: CLSCTX = 23u32; +pub type COINIT = i32; +pub const COINIT_MULTITHREADED: COINIT = 0i32; +pub const ERROR_NO_MORE_ITEMS: WIN32_ERROR = 259u32; +pub const ERROR_SUCCESS: WIN32_ERROR = 0u32; +pub const FALSE: BOOL = 0i32; +pub type FARPROC = Option isize>; +#[repr(C)] +#[derive(Clone, Copy)] +pub struct FILETIME { + pub dwLowDateTime: u32, + pub dwHighDateTime: u32, +} +pub const FILE_ATTRIBUTE_TEMPORARY: FILE_FLAGS_AND_ATTRIBUTES = 256u32; +pub type FILE_FLAGS_AND_ATTRIBUTES = u32; +#[repr(C)] +#[derive(Clone, Copy)] +pub struct GUID { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], +} +impl GUID { + pub const fn from_u128(uuid: u128) -> Self { + Self { + data1: (uuid >> 96) as u32, + data2: (uuid >> 80 & 0xffff) as u16, + data3: (uuid >> 64 & 0xffff) as u16, + data4: (uuid as u64).to_be_bytes(), + } + } +} +pub type HANDLE = *mut core::ffi::c_void; +pub type HKEY = *mut core::ffi::c_void; +pub const HKEY_LOCAL_MACHINE: HKEY = -2147483646i32 as _; +pub type HMODULE = *mut core::ffi::c_void; +pub type HRESULT = i32; +pub type IMAGE_FILE_MACHINE = u16; +pub const IMAGE_FILE_MACHINE_AMD64: IMAGE_FILE_MACHINE = 34404u16; +pub const KEY_READ: REG_SAM_FLAGS = 131097u32; +pub const KEY_WOW64_32KEY: REG_SAM_FLAGS = 512u32; +pub type MACHINE_ATTRIBUTES = i32; +pub type PCSTR = *const u8; +pub type PCWSTR = *const u16; +pub type PWSTR = *mut u16; +pub type REG_SAM_FLAGS = u32; +pub const REG_SZ: REG_VALUE_TYPE = 1u32; +pub type REG_VALUE_TYPE = u32; +#[repr(C)] +#[derive(Clone, Copy)] +pub struct SAFEARRAY { + pub cDims: u16, + pub fFeatures: ADVANCED_FEATURE_FLAGS, + pub cbElements: u32, + pub cLocks: u32, + pub pvData: *mut core::ffi::c_void, + pub rgsabound: [SAFEARRAYBOUND; 1], +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct SAFEARRAYBOUND { + pub cElements: u32, + pub lLbound: i32, +} +pub const SEMAPHORE_MODIFY_STATE: SYNCHRONIZATION_ACCESS_RIGHTS = 2u32; +pub type SYNCHRONIZATION_ACCESS_RIGHTS = u32; +pub const S_FALSE: HRESULT = 0x1_u32 as _; +pub const S_OK: HRESULT = 0x0_u32 as _; +pub type THREAD_ACCESS_RIGHTS = u32; +pub const THREAD_SYNCHRONIZE: THREAD_ACCESS_RIGHTS = 1048576u32; +pub const UserEnabled: MACHINE_ATTRIBUTES = 1i32; +pub const WAIT_ABANDONED: WAIT_EVENT = 128u32; +pub type WAIT_EVENT = u32; +pub const WAIT_FAILED: WAIT_EVENT = 4294967295u32; +pub const WAIT_OBJECT_0: WAIT_EVENT = 0u32; +pub const WAIT_TIMEOUT: WAIT_EVENT = 258u32; +pub type WIN32_ERROR = u32; + +#[link(name = "advapi32")] +#[link(name = "ole32")] +#[link(name = "oleaut32")] +extern "C" {} +use super::windows_targets; diff --git a/bitbox02-bt/vendor/cc/src/windows/windows_targets.rs b/bitbox02-bt/vendor/cc/src/windows/windows_targets.rs new file mode 100644 index 0000000..d08affe --- /dev/null +++ b/bitbox02-bt/vendor/cc/src/windows/windows_targets.rs @@ -0,0 +1,19 @@ +//! Provides the `link!` macro used by the generated windows bindings. +//! +//! This is a simple wrapper around an `extern` block with a `#[link]` attribute. +//! It's very roughly equivalent to the windows-targets crate. + +macro_rules! link_macro { + ($library:literal $abi:literal $($link_name:literal)? $(#[$doc:meta])? fn $($function:tt)*) => ( + // Note: the windows-targets crate uses a pre-built Windows.lib import library which we don't + // have in this repo. So instead we always link kernel32.lib and add the rest of the import + // libraries below by using an empty extern block. This works because extern blocks are not + // connected to the library given in the #[link] attribute. + #[link(name = "kernel32")] + extern $abi { + $(#[link_name=$link_name])? + pub fn $($function)*; + } + ) +} +pub(crate) use link_macro as link; diff --git a/bitbox02-bt/vendor/cortex-m/.cargo-checksum.json b/bitbox02-bt/vendor/cortex-m/.cargo-checksum.json new file mode 100644 index 0000000..373e919 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"0746746ed1d76c49bcb397844b176e7bb14511d56df37a66dc38cea98bcff9e6","CODE_OF_CONDUCT.md":"3746a267d008534cec6d7242f09ca6284c5d37e48306531b878461e6c4d33fee","Cargo.toml":"e50cf067b659be75f8f927b342d3446243bdcd86a4b10ea4daff819f6d9ddebd","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0a633406531735659d570e7903394ec52f7707195a3c4af10279f06eec7acc76","README.md":"2e2e489b55b8506d174782d8587db6708162f82f1fb4c3272746d079e5972837","asm-toolchain":"5479b28f90ce42bbefc9fed083182e0de8eafc1b69f92fbfc5221d766862682f","asm/inline.rs":"6e9605c595d6c8deddcd2bcb1f9f4d270a10492823e82955888be8ce3b553f3b","asm/lib.rs":"8d7eb1aee66e9d8ff8b5ff5d0a8687d6d255d3403b9c238d7b5620a01602d9b5","bin/thumbv6m-none-eabi-lto.a":"4d13ae583b33613b476b8d2dbf435d363ad25a2135388eb5257b132868461535","bin/thumbv6m-none-eabi.a":"b5002ce424d6baf97639ee188f12a9c7152b1dbc90a1b4393556049f8475be54","bin/thumbv7em-none-eabi-lto.a":"a3dd53e4e7a874f9d7d27acb273eaa17ae72222205e939a7dccc4c02ebb7a3ba","bin/thumbv7em-none-eabi.a":"2ae0edab580e3d1c95bedb4bc9a8a646e2b3ea9fa5bf2768d859fb5a30b8741a","bin/thumbv7em-none-eabihf-lto.a":"71d4bd5af31d3933969aee825400ac105f3d3b826abfb968bfa2c8f3658ecd50","bin/thumbv7em-none-eabihf.a":"0ebff8ad140fe35494fb51ed4184ce19ffab41e9ac62af6a5c5c7b0ea26b9e53","bin/thumbv7m-none-eabi-lto.a":"da3ed6ec4b9fc8803336e280cd71524911fee459e2dac88e29d0e82d043b90d7","bin/thumbv7m-none-eabi.a":"3de841b242e33066555fa06e127f01008711ec08728a2f75d525731d04ae442e","bin/thumbv8m.base-none-eabi-lto.a":"73189749f0c42de0990e76ce531621e17370c0dd00940297e6044a622302df38","bin/thumbv8m.base-none-eabi.a":"b2ff0d88db4aa539ead58c1fb37ef3d171d08462b979a8b7c897ef4148119572","bin/thumbv8m.main-none-eabi-lto.a":"12b43c063fcdb33fb57335c5fc2a0c62e2a427a3c6e8727fb2a4437615e2c07d","bin/thumbv8m.main-none-eabi.a":"9217dcbbd3ef909caa39a5ee75684127b4cf4f51447e41027164462e42a33018","bin/thumbv8m.main-none-eabihf-lto.a":"18aae9047b017ad4003e2311d74b0888701b84333ccf4379d09e6890b1799174","bin/thumbv8m.main-none-eabihf.a":"39fdf845895f31e473fc863fbb21f3590237a571dbfb97c66c7190475a615efb","build.rs":"fe2c0bd4cd56adabf5d3912a9810546e6a32708f165d9ad2dcfe0407df092516","src/asm.rs":"079aaf47d696aa1995ddcf5b38f59ed22e8a48967c261d14676d1757308b534a","src/call_asm.rs":"024486575710dc864613c3c2917887ec9527ae2b66cde183b3233f663a9e790b","src/cmse.rs":"9e868ec9ac0a6296b1e9d943478f6343a3f43979c0f068780adf114f52643707","src/critical_section.rs":"2013adbc5289d71c9f5ccb8353fbc47a2df7f7003180be65b6b07b8c948ca684","src/delay.rs":"27f2adeaf9dc924ac16f1fea9da510469e5c4961d9223aab253d95ee3e0af191","src/interrupt.rs":"41d6338784b86d4c4837e3673c5eff26dd35c851962e741c00f7c933a7e8d218","src/itm.rs":"b50d9d6cad2ec4c841d0f3008df93edb378f8038696a9f096763a488d14df53c","src/lib.rs":"079c614ec9e3ba81bb5ab9638f7f465551805555ab41aab04e62f9015d85fe4a","src/macros.rs":"22d8af93ebe59cd9f6e468cf78c8a342c4444d83f263043d3044358811ffec41","src/peripheral/ac.rs":"b6b228637b09f2fa3ac5344a0759cd4fb852782050f252c2c9bd670660b9a768","src/peripheral/cbp.rs":"9a42efc512ac43278a5efd2fb650043a5672be031e7121c748b41ead97ed4e39","src/peripheral/cpuid.rs":"94285da95a2e6a00f09b049f59c9aede6683dab4be4b218d8bd0cd4183e7a746","src/peripheral/dcb.rs":"3c630cc575c93791f1553607565fdc76d91bb990351deedf9de3efa9184eceb0","src/peripheral/dwt.rs":"780a1094958abc2c8c7d8d196c07637eed619c72d010fcf29235b95c0b1abce3","src/peripheral/fpb.rs":"00eba6fae97614a503e9545f95158083f9e02b6b400fab647be1c0e4747293d7","src/peripheral/fpu.rs":"3bb8d5af0cdce5b25a4f9826fa6bddd75c58f4d61745afd9ed49a5d0e849c2f9","src/peripheral/icb.rs":"fcc13f2652ae39035c4b0f04468d19b3e94bfe3b05832eabc60638dcca9842ae","src/peripheral/itm.rs":"f8c8587ffa60f76e4f4fa293322386727ecf491f1b36672258b7e743b6e37a26","src/peripheral/mod.rs":"900f099bbcae804cde74bf8b5bcb9f84e9dde3018f5efe1098768c5b64021b0b","src/peripheral/mpu.rs":"20d36443ae9928cbf9a7d546298b5ce784c3cae3f2f236a8935b227f9fdbdb06","src/peripheral/nvic.rs":"ae9889495edb21d6a4f09ced401b4b21cdfb2c1ac86e593156e462cc42b5794d","src/peripheral/sau.rs":"32fb6816a3f9c81203b23b1803c8f499059a0460e2fa082e44bff3be9936f467","src/peripheral/scb.rs":"fd56eba0edace3b9278f5b26495eedd42926ed7a7dde2dad41273d26f743c8ff","src/peripheral/syst.rs":"267ac1f7e83cfa6fec1c0d651fa6babcfac90ea5254331b49f305ad0b2034711","src/peripheral/test.rs":"0f0a44af38bc78a4d3bf8995d6c79b1ee4fcb3ffb797db1c41a09d361a075828","src/peripheral/tpiu.rs":"88a86ba957ab94a38b08a5486b9a2c6c20e1b116a92f17666f4ab9b2207e63d1","src/prelude.rs":"cb4e3b91223b64a0a1c1301e6b38318f3ba031ba776ad11983444607735a8175","src/register/apsr.rs":"27ff0eda2861162b6103bb9705c37a877811bc2320785a9ab6d1ea566fa0b2cb","src/register/basepri.rs":"283b98d9befce7a1b623599cf5cfcd889425c69af2d136eef3ca7775c6809e9e","src/register/basepri_max.rs":"849f9bb522d6ea348f646930943481506c80be57613abb64f34319f0f58b6f21","src/register/control.rs":"5a666c93a82c1dea29094c7021ebe0e2a5b7dc67dd7aa7f7c923a25c6dabf992","src/register/faultmask.rs":"6a0d06a48790a25836e2c770ddc136ae5c32ce5290e3865526c8a749bf576d5a","src/register/fpscr.rs":"5d09ecb377a0231876570e3a9d95e3e013cc9ad58a338062a7000b66030f0de4","src/register/lr.rs":"02769270d9b096ccf2d9cf9101e51db142c747536e676fc04b64d4494b0a41b5","src/register/mod.rs":"8d452276b5f0751de0be7fa93ae809f4c08ab2b3db5b03210c7a9541716f1c72","src/register/msp.rs":"59a8294f63272ef1bc8b2691de2d7be51171728602733500b9e28bc285df6148","src/register/msplim.rs":"43c7648180cda21da11df04c55ccd3c5d21ec3ae08b5fa5174a0e9239ee31f61","src/register/pc.rs":"2797c309ee2a5780e8849a955dc3abd0063b442d92c878a51ca83543026a678b","src/register/primask.rs":"cfeb772e1bc6fc1ffe8192a201e12d491bdb570881d0575b5a6727876d11a766","src/register/psp.rs":"2898e262cf821b6f0d59633012e06cef0de0ee4aef0dc603000ea78f877b8de0","src/register/psplim.rs":"d4cabb7d7cfca9338e82c51658ae409e501e2fd4ba15e0162eb57e2f55649d67","triagebot.toml":"a135e10c777cd13459559bdf74fb704c1379af7c9b0f70bc49fa6f5a837daa81"},"package":"8ec610d8f49840a5b376c69663b6369e71f4b34484b9b2eb29fb918d92516cb9"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/cortex-m/CHANGELOG.md b/bitbox02-bt/vendor/cortex-m/CHANGELOG.md new file mode 100644 index 0000000..ca9609c --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/CHANGELOG.md @@ -0,0 +1,807 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.7.7] - 2023-01-03 + +- Add missing documentation for `critical-section-single-core` feature added + in v0.7.6. + +## [v0.7.6] - 2022-08-12 + +- Added `critical-section-single-core` feature which provides an implementation for the `critical-section` crate for single-core systems, based on disabling all interrupts. (#448) + +## [v0.7.5] - 2022-05-15 + +### Deprecated +- the `ptr()` function on all peripherals register blocks in favor of + the associated constant `PTR` (#386). + +### Changed + +- The `inline-asm` feature no longer requires a nightly Rust compiler, but + does require Rust 1.59 or above. + +### Fixed +- Fixed `singleton!()` statics sometimes ending up in `.data` instead of `.bss` (#364, #380). + (Backported from upcoming 0.8 release). + +## [v0.7.4] - 2021-12-31 + +### Added + +- Added support for additional DWT counters (#349) + - CPI counter + - Exception overhead counter + - LSU counter + - Folded-instruction counter +- Added `DWT.set_cycle_count` (#347). +- Added support for the Cortex-M7 TCM and cache access control registers. + There is a feature `cm7` to enable access to these (#352). +- Add derives for serde, Hash, and PartialOrd to VectActive behind feature + gates for host-platform use (#363). +- Support host platforms besides x86_64 (#369). +- Added `delay::Delay::with_source`, a constructor that lets you specify + the SysTick clock source (#374). + +### Fixed + +- Fix incorrect AIRCR PRIGROUP mask (#338, #339). +- Fix nightly users of inline-asm breaking now that the asm macro is removed + from the prelude (#372). + +### Deprecated + +- `DWT::get_cycle_count` has been deprecated in favor of `DWT::cycle_count`. + This change was made for consistency with the [C-GETTER] convention. (#349) + +[C-GETTER]: https://rust-lang.github.io/api-guidelines/naming.html#c-getter + +## [v0.7.3] - 2021-07-03 + +### Fixed + +- Fixed compilation for native targets on non-x86 host systems (#336, #337). + +### Added + +- The `Delay` struct now offers direct `delay_us()` and `delay_ms()` methods + without having to go through the embedded-hal traits (#344). + +## [v0.7.2] - 2021-03-07 + +### Fixed + +- Fixed a bug where calling `asm::delay()` with an argument of 0 or 1 would + underflow, leading to a very long delay. + +## [v0.7.1] - 2021-01-25 + +### Added + +- New assembly methods `asm::semihosting_syscall`, `asm::bootstrap`, and + `asm::bootload`. + +### Deprecated + +- `msp::write` has been deprecated in favor of `asm::bootstrap`. It was not + possible to use `msp::write` without causing Undefined Behavior, so all + existing users are encouraged to migrate. + +### Fixed + +- Fixed a bug in `asm::delay` which could lead to incorrect codegen and + infinite loops. +- Improved timing guarantees of `asm::delay` on multiple-issue CPU cores. +- Additional compiler fences added to inline assembly where necessary. +- Fixed DWARF debug information in pre-built assembly binaries. + +## [v0.7.0] - 2020-11-09 + +### Added + +- New `InterruptNumber` trait is now required on interrupt arguments to the + various NVIC functions, replacing the previous use of `Nr` from bare-metal. + For backwards compatibility, `InterruptNumber` is implemented for types + which are `Nr + Copy`, but this will be removed in a future version. +- Associated const `PTR` is introduced to Core Peripherals to + eventually replace the existing `ptr()` API. +- A delay driver based on SysTick. +- You can now use LTO to inline assembly calls, even on stable Rust. + See the `asm/lib.rs` documentation for more details. +- Initial ARMv8-M MPU support +- ICTR and ACTLR registers added +- Support for the Security Attribution Unit on ARMv8-M + +### Changed + +- Previously, asm calls without the `inline-asm` feature enabled used pre-built + objects which were built by a GCC compiler, while `inline-asm` enabled the + use of `llvm_asm!` calls. The asm system has been replaced with a new + technique which generates Rust static libs for stable calling, and uses the + new `asm!` macro with `inline-asm`. See the `asm/lib.rs` documentation for + more details. +- Cache enabling now uses an assembly sequence to ensure correctness. +- `ptr()` methods are now `const`. + +### Breaking Changes +- `SCB::invalidate_dcache` and related methods are now unsafe, see #188 +- `Peripherals` struct is now non-exhaustive, so fields may be added in future + non-breaking changes +- Removed `aligned` dependency +- Removed const-fn feature +- Removed previously deprecated APIs + - `NVIC::clear_pending` + - `NVIC::disable` + - `NVIC::enable` + - `NVIC::set_pending` + - `SCB::system_reset` +- Removed `basepri`, `basepri_max`, and `faultmask` registers from thumbv8m.base + +## [v0.6.7] - 2021-01-26 + +### Fixed + +- Fixed missing `peripheral::itm` reexport. + +## [v0.6.6] - 2021-01-26 + +### Fixed + +- Fixed missing ITM reexport on `thumbv8m.base` targets. + +## [v0.6.5] - 2021-01-24 + +### Changed + +- This release is forwards-compatible with cortex-m 0.7, and depends on and + re-exports many types from that version. Both 0.6.5 and 0.7 may co-exist + in a build. + +## [v0.6.4] - 2020-10-26 + +### Changed + +- MSRV bumped to 1.36.0 due to `aligned` dependency. + +### Fixed + +- Drop AT&T syntax from inline asm, which was causing miscompilations with newer versions of the compiler. + +## [v0.6.3] - 2020-07-20 + +### Added + +- Initial Cortex-M Security Extension support for armv8m +- `UDF` intrinsic +- Methods to enable/disable exceptions in SCB + +### Fixed + +- Fix bug in `asm::delay` not updating status clobber flags +- Swapped to `llvm_asm!` to support inline assembly on new nightlies +- Our precompiled assembly routines have additional debug information +- ITM `is_fifo_ready` improved to support armv8 +- Cache enabling moved to pre-built assembly routines to prevent possible + undefined behaviour + +## [v0.6.2] - 2020-01-12 + +### Added + +- Allow writing to the `CONTROL` register via `register::control::write` +- Add `DWT::unlock()` for a safe way to unlock the DWT + +### Deprecation + +- Deprecated incorrectly included registers (`BASPRI`, `BASEPRI_MAX`, `FAULTMASK`) on `thumbv8.base` + +## [v0.6.1] - 2019-08-21 + +### Fixed + +- Better `Debug`, `PartialEq` and `Eq` for more types +- The `delay` function is fixed for Cortex-M0 MCUs + +### Added + +- Static version of `system_reset` as `system_reset2` +- Now uses `links = "cortex-m"` to not link multiple versions of the crate +- Masking of the NVIC is added `NVIC::{mask,unmask}` +- Now Rust 2018 edition +- `{M,P}SPLIM` access is now possible on ARMv8-M + +### Deprecation + +- `system_reset` is deprecated in favor of `sys_reset` + +## [v0.6.0] - 2019-03-12 + +### Fixed + +- Fix numerous registers which were incorrectly included for thumbv6 +- `SHCRS` renamed to `SHCSR` in `SCB` + +### Added + +- Support for ARMv8-M (`thumbv8.base` and `thumbv8.main`) + +- `SCB` gained methods to set and clear `SLEEPONEXIT` bit + +- `NVIC` gained `STIR` register and methods to request an interrupt + +- `DCB` gained methods to check if debugger is attached + +## [v0.5.8] - 2018-10-27 + +### Added + +- `SCB` gained methods to set, clear and check the pending state of the PendSV + exception. + +- `SCB` gained methods to set, clear and check the pending state of the SysTick + exception. + +- `SCB` gained methods to set and get the priority of system handlers like + SVCall and SysTick. + +- `NVIC` gained *static* methods, `pend` and `unpend`, to set and clear the + pending state of interrupts. + +### Changed + +- The `NVIC.{clear,set}_pending` methods have been deprecated in favor of + `NVIC::{unpend,pend}`. + +## [v0.5.7] - 2018-09-06 + +### Added + +- `DCB::enable_trace()` and `DCB::disable_trace()` + +### Changed + +- `iprintln!` no longer depends on `iprint!`. `cortex_m::iprintln!` will work + even if `cortex_m::iprint` has not been imported. + +## [v0.5.6] - 2018-08-27 + +### Fixed + +- Removed duplicated symbols from binary blobs + +- The check-blobs.sh script + +## [v0.5.5] - 2018-08-27 - YANKED + +### Changed + +- This crate no longer depends on `arm-none-eabi-gcc`. + +## [v0.5.4] - 2018-08-11 + +### Added + +- A method to trigger a system reset. See `SCB.system_reset`. + +### Fixed + +- Made the VTOR register (see peripheral::SCB) available on `thumbv6m-none-eabi`. This register is + present on Cortex-M0+, but not on Cortex-M0. + +- Linking with LLD by marking all external assembly functions as `.thumb_func`. See + https://bugs.llvm.org/show_bug.cgi?id=38435 for details. + +## [v0.5.3] - 2018-08-02 + +### Fixed + +- Don't assemble basepri*.s and faultmask.s for ARMv6-M. This fix the build when using `clang` as + the assembler. + +## [v0.5.2] - 2018-05-18 + +### Added + +- `SCB` gained a pair of safe methods to set / clear the DEEPSLEEP bit. + +- `asm::delay`, delay loops whose execution time doesn't depend on the optimization level. + +## [v0.5.1] - 2018-05-13 + +### Added + +- An opt-in `"const-fn"` feature that makes `Mutex.new` constructor into a `const fn`. This feature + requires a nightly toolchain. + +## [v0.5.0] - 2018-05-11 + +### Added + +- `DebugMonitor` and `SecureFault` variants to the `Exception` enumeration. + +- An optional `"inline-asm"` feature + +### Changed + +- [breaking-change] This crate now requires `arm-none-eabi-gcc` to be installed and available in + `$PATH` when built with the `"inline-asm"` feature disabled (which is disabled by default). + +- [breaking-change] The `register::{apsr,lr,pc}` modules are now behind the `"inline-asm"` feature. + +- [breaking-change] Some variants of the `Exception` enumeration are no longer available on + `thumbv6m-none-eabi`. See API docs for details. + +- [breaking-change] Several of the variants of the `Exception` enumeration have been renamed to + match the CMSIS specification. + +- [breaking-change] fixed typo in `shcrs` field of `scb::RegisterBlock`; it was previously named + `shpcrs`. + +- [breaking-change] removed several fields from `scb::RegisterBlock` on ARMv6-M. These registers are + not available on that sub-architecture. + +- [breaking-change] changed the type of `scb::RegisterBlock.shpr` from `RW` to `RW` on + ARMv6-M. These registers are word accessible only on that sub-architecture. + +- [breaking-change] renamed the `mmar` field of `scb::RegisterBlock` to `mmfar` to match the CMSIS + name. + +- [breaking-change] removed the `iabr` field from `scb::RegisterBlock` on ARMv6-M. This register is + not available on that sub-architecture. + +- [breaking-change] removed several fields from `cpuid::RegisterBlock` on ARMv6-M. These registers + are not available on that sub-architecture. + +- [breaking-change] The `Mutex.new` constructor is not a `const fn` by default. To make it a `const + fn` you have to opt into the `"const-fn"` feature, which was added in v0.5.1, and switch to a + nightly compiler. + +### Removed + +- [breaking-change] The `exception` module has been removed. A replacement for `Exception::active` + can be found in `SCB::vect_active`. A modified version `exception::Exception` can be found in the + `peripheral::scb` module. + +## [v0.4.3] - 2018-01-25 + +### Changed + +- The initial value of a `singleton!` no longer needs to be evaluable in const context; it can now + be a value computed at runtime, or even a capture of some other local variable. + +## [v0.4.2] - 2018-01-17 + +### Fixed + +- Added a missing `Send` implementation to all the peripherals. + +## [v0.4.1] - 2018-01-16 + +### Changed + +- `peripheral::Peripherals` is now re-exported at the root of the crate. + +## [v0.4.0] - 2018-01-15 + +### Added + +- Formatter and Flush Control register (FFCR) accessor to the TPIU register block. + +- A `singleton!` macro that creates mutable reference to a statically allocated variable. + +- A Cargo feature, `cm7-r0p1`, to work around a silicon erratum that affects writes to BASEPRI on + Cortex-M7 r0p1 devices. + +### Changed + +- [breaking-change] All peripherals are now exposed as scoped singletons and they need to be `take`n + into scope to become accessible. + +- [breaking-change] The signatures of methods exposed by peripheral proxies have changed to + better match the new scoped singletons semantics. + +- All the thin wrappers around assembly instructions now panic when executed on non-ARM devices. + +### Removed + +- [breaking-change] APIs specific to ARMv7-M (`peripheral::{cbp, fpb, fpu, itm, tpiu}`, `itm`) when + compiling for `thumb6m-none-eabi`. + +## [v0.3.1] - 2017-07-20 + +### Changed + +- `{basepri,basepri_max}::write` are now compiler barriers for the same reason + that `interrupt::{disable,enable}` are: they are used to create critical + sections. + +## [v0.3.0] - 2017-07-07 + +### Changed + +- [breaking-change] Renamed `StackedRergisters` to `ExceptionFrame` to better + reflect the ARM documentation. + +- [breaking-change] Renamed the variants of `Exception` to better match the + ARM documentation. + +- [breaking-change] Renamed `Exception::current` to `Exception::active` and + changed the signature to return `None` when no exception is being serviced. + +- Moved bits non specific to the Cortex-M architecture into the [`bare-metal`] + crate with the goal of sharing code between this crate and crates tailored for + other (microcontroller) architectures. + +[`bare-metal`]: https://crates.io/crates/bare-metal + +### Removed + +- [breaking-change] The `ctxt` module along with the exception "tokens" in the + `exception` module. The `cortex-m-rt` crate v0.3.0 provides a more ergonomic + mechanism to add state to interrupts / exceptions; replace your uses of + `Local` with that. + +- [breaking-change] `default_handler`, `DEFAULT_HANDLERS` and `Handlers` from + the `exception` module as well as `Reserved` from the root of the crate. + `cortex-m-rt` v0.3.0 provides a mechanism to override exceptions and the + default exception handler. Change your use of these `Handlers` and others to + that. + +### Fixed + +- `interrupt::{enable,disable}` are now compiler barriers. The compiler should + not reorder code around these function calls for memory safety; that is the + case now. + +## [v0.2.11] - 2017-06-16 + +### Added + +- An API to maintain the different caches (DCache, ICache) on Cortex M7 devices. + +### Fixed + +- the definition of the `ehprint!` macro. +- the implementation of the FPU API. + +## [v0.2.10] - 2017-06-05 + +### Added + +- Functions for the instructions DMB, ISB and DSB + +### Changed + +- All the functions in the `asm` module are now `inline(always)` + +## [v0.2.9] - 2017-05-30 + +### Fixed + +- A bug in `itm::write_all` where it would ignore the length of the buffer and + serialize contents that come after the buffer. + +## [v0.2.8] - 2017-05-30 - YANKED + +### Added + +- An `itm::write_aligned` function to write 4 byte aligned buffers to an ITM + port. This function is faster than `itm::write_all` for small buffers but + requires the buffer to be aligned. + +## [v0.2.7] - 2017-05-23 + +### Added + +- `Dwt.enable_cycle_counter` + +## [v0.2.6] - 2017-05-08 + +### Fixed + +- [breaking-change]. MEMORY UNSAFETY. `Mutex` could be used as a channel to send + interrupt tokens from one interrupt to other thus breaking the context `Local` + abstraction. See reproduction case below. This has been fixed by making + `Mutex` `Sync` only if the protected data is `Send`. + +``` rust +#![feature(const_fn)] +#![feature(used)] +#![no_std] + +use core::cell::RefCell; + +use cortex_m::ctxt::Local; +use cortex_m::interrupt::Mutex; +use stm32f30x::interrupt::{self, Exti0, Exti1}; + +fn main() { + // .. + + // trigger exti0 + // then trigger exti0 again +} + +static CHANNEL: Mutex>> = Mutex::new(RefCell::new(None)); +// Supposedly task *local* data +static LOCAL: Local = Local::new(0); + +extern "C" fn exti0(mut ctxt: Exti0) { + static FIRST: Local = Local::new(true); + + let first = *FIRST.borrow(&ctxt); + + // toggle + if first { + *FIRST.borrow_mut(&mut ctxt) = false; + } + + if first { + cortex_m::interrupt::free( + |cs| { + let channel = CHANNEL.borrow(cs); + + // BAD: transfer interrupt token to another interrupt + *channel.borrow_mut() = Some(ctxt); + }, + ); + + return; + } + let _local = LOCAL.borrow_mut(&mut ctxt); + + // .. + + // trigger exti1 here + + // .. + + // `LOCAL` mutably borrowed up to this point +} + +extern "C" fn exti1(_ctxt: Exti1) { + cortex_m::interrupt::free(|cs| { + let channel = CHANNEL.borrow(cs); + let mut channel = channel.borrow_mut(); + + if let Some(mut other_task) = channel.take() { + // BAD: `exti1` has access to `exti0`'s interrupt token + // so it can now mutably access local while `exti0` is also using it + let _local = LOCAL.borrow_mut(&mut other_task); + } + }); +} + +#[allow(dead_code)] +#[used] +#[link_section = ".rodata.interrupts"] +static INTERRUPTS: interrupt::Handlers = interrupt::Handlers { + Exti0: exti0, + Exti1: exti1, + ..interrupt::DEFAULT_HANDLERS +}; +``` + +## [v0.2.5] - 2017-05-07 - YANKED + +### Added + +- Higher level API for the SysTick and FPU peripherals + +### Fixed + +- [breaking-change]. MEMORY UNSAFETY. `interrupt::enable` was safe to call + inside an `interrupt::free` critical section thus breaking the preemption + protection. The `interrupt::enable` method is now `unsafe`. + +## [v0.2.4] - 2017-04-20 - YANKED + +### Fixed + +- [breaking-change]. MEMORY UNSAFETY. `interrupt::free` leaked the critical + section making it possible to access a `Mutex` when interrupts are enabled + (see below). This has been fixed by changing the signature of + `interrupt::free`. + +``` rust +static FOO: Mutex = Mutex::new(false); + +fn main() { + let cs = cortex_m::interrupt::free(|cs| cs); + // interrupts are enabled at this point + let foo = FOO.borrow(&cs); +} +``` + +## [v0.2.3] - 2017-04-11 - YANKED + +### Fixed + +- [breaking-change]. MEMORY UNSAFETY. Some concurrency models that use "partial" + critical sections (cf. BASEPRI) can be broken by changing the priority of + interrupts or by changing BASEPRI in some scenarios. For this reason + `NVIC.set_priority` and `register::basepri::write` are now `unsafe`. + +## [v0.2.2] - 2017-04-08 - YANKED + +### Fixed + +- [breaking-change]. MEMORY UNSAFETY. The `Mutex.borrow_mut` method has been + removed as it can be used to bypass Rust's borrow checker and get, for + example, two mutable references to the same data. + +``` rust +static FOO: Mutex = Mutex::new(false); + +fn main() { + cortex_m::interrupt::free(|mut cs1| { + cortex_m::interrupt::free(|mut cs2| { + let foo: &mut bool = FOO.borrow_mut(&mut cs1); + let and_foo: &mut bool = FOO.borrow_mut(&mut cs2); + }); + }); +} +``` + +## [v0.2.1] - 2017-03-12 - YANKED + +### Changed + +- The default exception handler now identifies the exception that's being + serviced. + +## [v0.2.0] - 2017-03-11 - YANKED + +### Added + +- Semihosting functionality in the `semihosting` module. + +- `exception::Handlers` struct that represent the section of the vector table + that contains the exception handlers. + +- A default exception handler + +- A high level API for the NVIC peripheral. + +- Context local data. + +- `borrow`/`borrow_mut` methods to `Mutex` that replace `lock`. + +- API and macros to send bytes / (formatted) strings through ITM + +### Changed + +- [breaking-change] `StackFrame` has been renamed to `StackedRegisters` and + moved into the `exceptions` module. + +- [breaking-change] Core peripherals can now be modified via a `&-` reference + and are no longer `Sync`. + +- [breaking-change] `interrupt::free`'s closure now includes a critical section + token, `CriticalSection`. + +- [breaking-change] the core register API has been revamped for type safety. + +- The safety of assembly wrappers like `wfi` and `interrupt::free` has been + reviewed. In many cases, the functions are no longer unsafe. + +- [breaking-change] `bkpt!` has been turned into a function. It no longer + accepts an immediate value. + +### Removed + +- `vector_table` and its associated `struct`, `VectorTable`. It's not a good + idea to give people a simple way to call the exception handlers. + +- `Mutex`'s `lock` method as it's unsound. You could use it to get multiple + `&mut -` references to the wrapped data. + +## [v0.1.6] - 2017-01-22 + +### Added + +- `Exception` a enumeration of the kind of exceptions the processor can service. + There's also a `Exception::current` constructor that returns the `Exception` + that's currently being serviced. + +## [v0.1.5] + +### Added + +- `interrupt::Mutex`, a "mutex" based on critical sections. + +### Changed + +- The closure that `interrupt::free` takes can now return a value. + +## [v0.1.4] + +### Added + +- `asm::nop`, a wrapper over the NOP instruction + +## [v0.1.3] + +### Added + +- a StackFrame data structure + +## [v0.1.2] - 2016-10-04 + +### Fixed + +- Read/write Operations on registers (lr, cr, msp, etc.) which were reversed. + +## [v0.1.1] - 2016-10-03 - YANKED + +### Changed + +- Small, non user visible change to make this crate compile further for $HOST (e.g. x86_64) with the + goal of making it possible to test, on the HOST, downstream crates that depend on this one. + +## v0.1.0 - 2016-09-27 - YANKED + +### Added + +- Functions to access core peripherals like NVIC, SCB and SysTick. +- Functions to access core registers like CONTROL, MSP and PSR. +- Functions to enable/disable interrupts +- Functions to get the vector table +- Wrappers over miscellaneous instructions like `bkpt` + +[Unreleased]: https://github.com/rust-embedded/cortex-m/compare/v0.7.7...HEAD +[v0.7.7]: https://github.com/rust-embedded/cortex-m/compare/v0.7.6...v0.7.7 +[v0.7.6]: https://github.com/rust-embedded/cortex-m/compare/v0.7.5...v0.7.6 +[v0.7.5]: https://github.com/rust-embedded/cortex-m/compare/v0.7.4...v0.7.5 +[v0.7.4]: https://github.com/rust-embedded/cortex-m/compare/v0.7.3...v0.7.4 +[v0.7.3]: https://github.com/rust-embedded/cortex-m/compare/v0.7.2...v0.7.3 +[v0.7.2]: https://github.com/rust-embedded/cortex-m/compare/v0.7.1...v0.7.2 +[v0.7.1]: https://github.com/rust-embedded/cortex-m/compare/v0.7.0...v0.7.1 +[v0.7.0]: https://github.com/rust-embedded/cortex-m/compare/v0.6.4...v0.7.0 +[v0.6.7]: https://github.com/rust-embedded/cortex-m/compare/v0.6.6...v0.6.7 +[v0.6.6]: https://github.com/rust-embedded/cortex-m/compare/v0.6.5...v0.6.6 +[v0.6.5]: https://github.com/rust-embedded/cortex-m/compare/v0.6.4...v0.6.5 +[v0.6.4]: https://github.com/rust-embedded/cortex-m/compare/v0.6.3...v0.6.4 +[v0.6.3]: https://github.com/rust-embedded/cortex-m/compare/v0.6.2...v0.6.3 +[v0.6.2]: https://github.com/rust-embedded/cortex-m/compare/v0.6.1...v0.6.2 +[v0.6.1]: https://github.com/rust-embedded/cortex-m/compare/v0.6.0...v0.6.1 +[v0.6.0]: https://github.com/rust-embedded/cortex-m/compare/v0.5.8...v0.6.0 +[v0.5.8]: https://github.com/rust-embedded/cortex-m/compare/v0.5.7...v0.5.8 +[v0.5.7]: https://github.com/rust-embedded/cortex-m/compare/v0.5.6...v0.5.7 +[v0.5.6]: https://github.com/rust-embedded/cortex-m/compare/v0.5.5...v0.5.6 +[v0.5.5]: https://github.com/rust-embedded/cortex-m/compare/v0.5.4...v0.5.5 +[v0.5.4]: https://github.com/rust-embedded/cortex-m/compare/v0.5.3...v0.5.4 +[v0.5.3]: https://github.com/rust-embedded/cortex-m/compare/v0.5.2...v0.5.3 +[v0.5.2]: https://github.com/rust-embedded/cortex-m/compare/v0.5.1...v0.5.2 +[v0.5.1]: https://github.com/rust-embedded/cortex-m/compare/v0.5.0...v0.5.1 +[v0.5.0]: https://github.com/rust-embedded/cortex-m/compare/v0.4.3...v0.5.0 +[v0.4.3]: https://github.com/rust-embedded/cortex-m/compare/v0.4.2...v0.4.3 +[v0.4.2]: https://github.com/rust-embedded/cortex-m/compare/v0.4.1...v0.4.2 +[v0.4.1]: https://github.com/rust-embedded/cortex-m/compare/v0.4.0...v0.4.1 +[v0.4.0]: https://github.com/rust-embedded/cortex-m/compare/v0.3.1...v0.4.0 +[v0.3.1]: https://github.com/rust-embedded/cortex-m/compare/v0.3.0...v0.3.1 +[v0.3.0]: https://github.com/rust-embedded/cortex-m/compare/v0.2.11...v0.3.0 +[v0.2.11]: https://github.com/rust-embedded/cortex-m/compare/v0.2.10...v0.2.11 +[v0.2.10]: https://github.com/rust-embedded/cortex-m/compare/v0.2.9...v0.2.10 +[v0.2.9]: https://github.com/rust-embedded/cortex-m/compare/v0.2.8...v0.2.9 +[v0.2.8]: https://github.com/rust-embedded/cortex-m/compare/v0.2.7...v0.2.8 +[v0.2.7]: https://github.com/rust-embedded/cortex-m/compare/v0.2.6...v0.2.7 +[v0.2.6]: https://github.com/rust-embedded/cortex-m/compare/v0.2.5...v0.2.6 +[v0.2.5]: https://github.com/rust-embedded/cortex-m/compare/v0.2.4...v0.2.5 +[v0.2.4]: https://github.com/rust-embedded/cortex-m/compare/v0.2.3...v0.2.4 +[v0.2.3]: https://github.com/rust-embedded/cortex-m/compare/v0.2.2...v0.2.3 +[v0.2.2]: https://github.com/rust-embedded/cortex-m/compare/v0.2.1...v0.2.2 +[v0.2.1]: https://github.com/rust-embedded/cortex-m/compare/v0.2.0...v0.2.1 +[v0.2.0]: https://github.com/rust-embedded/cortex-m/compare/v0.1.6...v0.2.0 +[v0.1.6]: https://github.com/rust-embedded/cortex-m/compare/v0.1.5...v0.1.6 +[v0.1.5]: https://github.com/rust-embedded/cortex-m/compare/v0.1.4...v0.1.5 +[v0.1.4]: https://github.com/rust-embedded/cortex-m/compare/v0.1.3...v0.1.4 +[v0.1.3]: https://github.com/rust-embedded/cortex-m/compare/v0.1.2...v0.1.3 +[v0.1.2]: https://github.com/rust-embedded/cortex-m/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/rust-embedded/cortex-m/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/cortex-m/CODE_OF_CONDUCT.md b/bitbox02-bt/vendor/cortex-m/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3ab76c6 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/CODE_OF_CONDUCT.md @@ -0,0 +1,37 @@ +# The Rust Code of Conduct + +## Conduct + +**Contact**: [Cortex-M team](https://github.com/rust-embedded/wg#the-cortex-m-team) + +* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. +* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. +* Please be kind and courteous. There's no need to be mean or rude. +* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. +* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. +* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. +* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [Cortex-M team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. +* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. + +## Moderation + +These are the policies for upholding our community's standards of conduct. + +1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) +2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. +3. Moderators will first respond to such remarks with a warning. +4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off. +5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded. +6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology. +7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed. +8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others. + +In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. + +And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. + +The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org). + +*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* + +[team]: https://github.com/rust-embedded/wg#the-cortex-m-team diff --git a/bitbox02-bt/vendor/cortex-m/Cargo.toml b/bitbox02-bt/vendor/cortex-m/Cargo.toml new file mode 100644 index 0000000..a86829c --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/Cargo.toml @@ -0,0 +1,77 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "cortex-m" +version = "0.7.7" +authors = [ + "The Cortex-M Team ", + "Jorge Aparicio ", +] +links = "cortex-m" +description = "Low level access to Cortex-M processors" +documentation = "https://docs.rs/cortex-m" +readme = "README.md" +keywords = [ + "arm", + "cortex-m", + "register", + "peripheral", +] +categories = [ + "embedded", + "hardware-support", + "no-std", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-embedded/cortex-m" + +[package.metadata.docs.rs] +targets = [ + "thumbv8m.main-none-eabihf", + "thumbv6m-none-eabi", + "thumbv7em-none-eabi", + "thumbv7em-none-eabihf", + "thumbv7m-none-eabi", + "thumbv8m.base-none-eabi", + "thumbv8m.main-none-eabi", +] + +[dependencies.bare-metal] +version = "0.2.4" +features = ["const-fn"] + +[dependencies.bitfield] +version = "0.13.2" + +[dependencies.critical-section] +version = "1.0.0" +optional = true + +[dependencies.embedded-hal] +version = "0.2.4" + +[dependencies.serde] +version = "1" +features = ["derive"] +optional = true + +[dependencies.volatile-register] +version = "0.2.0" + +[features] +cm7 = [] +cm7-r0p1 = ["cm7"] +critical-section-single-core = ["critical-section/restore-state-bool"] +inline-asm = [] +linker-plugin-lto = [] +std = [] diff --git a/bitbox02-bt/vendor/cortex-m/LICENSE-APACHE b/bitbox02-bt/vendor/cortex-m/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/cortex-m/LICENSE-MIT b/bitbox02-bt/vendor/cortex-m/LICENSE-MIT new file mode 100644 index 0000000..a43445e --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Jorge Aparicio + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/cortex-m/README.md b/bitbox02-bt/vendor/cortex-m/README.md new file mode 100644 index 0000000..6bd8aed --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/README.md @@ -0,0 +1,39 @@ +[![crates.io](https://img.shields.io/crates/d/cortex-m.svg)](https://crates.io/crates/cortex-m) +[![crates.io](https://img.shields.io/crates/v/cortex-m.svg)](https://crates.io/crates/cortex-m) + +# `cortex-m` + +> Low level access to Cortex-M processors + +This project is developed and maintained by the [Cortex-M team][team]. + +## [Documentation](https://docs.rs/crate/cortex-m) + +## Minimum Supported Rust Version (MSRV) + +This crate is guaranteed to compile on stable Rust 1.38 and up. It might compile with older versions but that may change in any new patch release. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the +work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. + +## Code of Conduct + +Contribution to this crate is organized under the terms of the [Rust Code of +Conduct][CoC], the maintainer of this crate, the [Cortex-M team][team], promises +to intervene to uphold that code of conduct. + +[CoC]: CODE_OF_CONDUCT.md +[team]: https://github.com/rust-embedded/wg#the-cortex-m-team diff --git a/bitbox02-bt/vendor/cortex-m/asm-toolchain b/bitbox02-bt/vendor/cortex-m/asm-toolchain new file mode 100644 index 0000000..cc5dbb2 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/asm-toolchain @@ -0,0 +1 @@ +nightly-2021-12-16 diff --git a/bitbox02-bt/vendor/cortex-m/asm/inline.rs b/bitbox02-bt/vendor/cortex-m/asm/inline.rs new file mode 100644 index 0000000..bbc04d2 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/asm/inline.rs @@ -0,0 +1,448 @@ +//! Inline assembly implementing the routines exposed in `cortex_m::asm`. +//! +//! If the `inline-asm` feature is enabled, these functions will be directly called by the +//! `cortex-m` wrappers. Otherwise, `cortex-m` links against them via prebuilt archives. +//! +//! All of these functions should be blanket-`unsafe`. `cortex-m` provides safe wrappers where +//! applicable. + +use core::arch::asm; +use core::sync::atomic::{compiler_fence, Ordering}; + +#[inline(always)] +pub unsafe fn __bkpt() { + asm!("bkpt", options(nomem, nostack, preserves_flags)); +} + +#[inline(always)] +pub unsafe fn __control_r() -> u32 { + let r; + asm!("mrs {}, CONTROL", out(reg) r, options(nomem, nostack, preserves_flags)); + r +} + +#[inline(always)] +pub unsafe fn __control_w(w: u32) { + // ISB is required after writing to CONTROL, + // per ARM architectural requirements (see Application Note 321). + asm!( + "msr CONTROL, {}", + "isb", + in(reg) w, + options(nomem, nostack, preserves_flags), + ); + + // Ensure memory accesses are not reordered around the CONTROL update. + compiler_fence(Ordering::SeqCst); +} + +#[inline(always)] +pub unsafe fn __cpsid() { + asm!("cpsid i", options(nomem, nostack, preserves_flags)); + + // Ensure no subsequent memory accesses are reordered to before interrupts are disabled. + compiler_fence(Ordering::SeqCst); +} + +#[inline(always)] +pub unsafe fn __cpsie() { + // Ensure no preceeding memory accesses are reordered to after interrupts are enabled. + compiler_fence(Ordering::SeqCst); + + asm!("cpsie i", options(nomem, nostack, preserves_flags)); +} + +#[inline(always)] +pub unsafe fn __delay(cyc: u32) { + // The loop will normally take 3 to 4 CPU cycles per iteration, but superscalar cores + // (eg. Cortex-M7) can potentially do it in 2, so we use that as the lower bound, since delaying + // for more cycles is okay. + // Add 1 to prevent an integer underflow which would cause a long freeze + let real_cyc = 1 + cyc / 2; + asm!( + // Use local labels to avoid R_ARM_THM_JUMP8 relocations which fail on thumbv6m. + "1:", + "subs {}, #1", + "bne 1b", + inout(reg) real_cyc => _, + options(nomem, nostack), + ); +} + +#[inline(always)] +pub unsafe fn __dmb() { + compiler_fence(Ordering::SeqCst); + asm!("dmb", options(nomem, nostack, preserves_flags)); + compiler_fence(Ordering::SeqCst); +} + +#[inline(always)] +pub unsafe fn __dsb() { + compiler_fence(Ordering::SeqCst); + asm!("dsb", options(nomem, nostack, preserves_flags)); + compiler_fence(Ordering::SeqCst); +} + +#[inline(always)] +pub unsafe fn __isb() { + compiler_fence(Ordering::SeqCst); + asm!("isb", options(nomem, nostack, preserves_flags)); + compiler_fence(Ordering::SeqCst); +} + +#[inline(always)] +pub unsafe fn __msp_r() -> u32 { + let r; + asm!("mrs {}, MSP", out(reg) r, options(nomem, nostack, preserves_flags)); + r +} + +#[inline(always)] +pub unsafe fn __msp_w(val: u32) { + // Technically is writing to the stack pointer "not pushing any data to the stack"? + // In any event, if we don't set `nostack` here, this method is useless as the new + // stack value is immediately mutated by returning. Really this is just not a good + // method and its higher-level use is marked as deprecated in cortex-m. + asm!("msr MSP, {}", in(reg) val, options(nomem, nostack, preserves_flags)); +} + +// NOTE: No FFI shim, this requires inline asm. +#[inline(always)] +pub unsafe fn __apsr_r() -> u32 { + let r; + asm!("mrs {}, APSR", out(reg) r, options(nomem, nostack, preserves_flags)); + r +} + +#[inline(always)] +pub unsafe fn __nop() { + // NOTE: This is a `pure` asm block, but applying that option allows the compiler to eliminate + // the nop entirely (or to collapse multiple subsequent ones). Since the user probably wants N + // nops when they call `nop` N times, let's not add that option. + asm!("nop", options(nomem, nostack, preserves_flags)); +} + +// NOTE: No FFI shim, this requires inline asm. +#[inline(always)] +pub unsafe fn __pc_r() -> u32 { + let r; + asm!("mov {}, pc", out(reg) r, options(nomem, nostack, preserves_flags)); + r +} + +// NOTE: No FFI shim, this requires inline asm. +#[inline(always)] +pub unsafe fn __pc_w(val: u32) { + asm!("mov pc, {}", in(reg) val, options(nomem, nostack, preserves_flags)); +} + +// NOTE: No FFI shim, this requires inline asm. +#[inline(always)] +pub unsafe fn __lr_r() -> u32 { + let r; + asm!("mov {}, lr", out(reg) r, options(nomem, nostack, preserves_flags)); + r +} + +// NOTE: No FFI shim, this requires inline asm. +#[inline(always)] +pub unsafe fn __lr_w(val: u32) { + asm!("mov lr, {}", in(reg) val, options(nomem, nostack, preserves_flags)); +} + +#[inline(always)] +pub unsafe fn __primask_r() -> u32 { + let r; + asm!("mrs {}, PRIMASK", out(reg) r, options(nomem, nostack, preserves_flags)); + r +} + +#[inline(always)] +pub unsafe fn __psp_r() -> u32 { + let r; + asm!("mrs {}, PSP", out(reg) r, options(nomem, nostack, preserves_flags)); + r +} + +#[inline(always)] +pub unsafe fn __psp_w(val: u32) { + // See comment on __msp_w. Unlike MSP, there are legitimate use-cases for modifying PSP + // if MSP is currently being used as the stack pointer. + asm!("msr PSP, {}", in(reg) val, options(nomem, nostack, preserves_flags)); +} + +#[inline(always)] +pub unsafe fn __sev() { + asm!("sev", options(nomem, nostack, preserves_flags)); +} + +#[inline(always)] +pub unsafe fn __udf() -> ! { + asm!("udf #0", options(noreturn, nomem, nostack, preserves_flags)); +} + +#[inline(always)] +pub unsafe fn __wfe() { + asm!("wfe", options(nomem, nostack, preserves_flags)); +} + +#[inline(always)] +pub unsafe fn __wfi() { + asm!("wfi", options(nomem, nostack, preserves_flags)); +} + +/// Semihosting syscall. +#[inline(always)] +pub unsafe fn __sh_syscall(mut nr: u32, arg: u32) -> u32 { + asm!("bkpt #0xab", inout("r0") nr, in("r1") arg, options(nomem, nostack, preserves_flags)); + nr +} + +/// Set CONTROL.SPSEL to 0, write `msp` to MSP, branch to `rv`. +#[inline(always)] +pub unsafe fn __bootstrap(msp: u32, rv: u32) -> ! { + asm!( + "mrs {tmp}, CONTROL", + "bics {tmp}, {spsel}", + "msr CONTROL, {tmp}", + "isb", + "msr MSP, {msp}", + "bx {rv}", + // `out(reg) _` is not permitted in a `noreturn` asm! call, + // so instead use `in(reg) 0` and don't restore it afterwards. + tmp = in(reg) 0, + spsel = in(reg) 2, + msp = in(reg) msp, + rv = in(reg) rv, + options(noreturn, nomem, nostack), + ); +} + +// v7m *AND* v8m.main, but *NOT* v8m.base +#[cfg(any(armv7m, armv8m_main))] +pub use self::v7m::*; +#[cfg(any(armv7m, armv8m_main))] +mod v7m { + use core::arch::asm; + use core::sync::atomic::{compiler_fence, Ordering}; + + #[inline(always)] + pub unsafe fn __basepri_max(val: u8) { + asm!("msr BASEPRI_MAX, {}", in(reg) val, options(nomem, nostack, preserves_flags)); + } + + #[inline(always)] + pub unsafe fn __basepri_r() -> u8 { + let r; + asm!("mrs {}, BASEPRI", out(reg) r, options(nomem, nostack, preserves_flags)); + r + } + + #[inline(always)] + pub unsafe fn __basepri_w(val: u8) { + asm!("msr BASEPRI, {}", in(reg) val, options(nomem, nostack, preserves_flags)); + } + + #[inline(always)] + pub unsafe fn __faultmask_r() -> u32 { + let r; + asm!("mrs {}, FAULTMASK", out(reg) r, options(nomem, nostack, preserves_flags)); + r + } + + #[inline(always)] + pub unsafe fn __enable_icache() { + asm!( + "ldr {0}, =0xE000ED14", // CCR + "mrs {2}, PRIMASK", // save critical nesting info + "cpsid i", // mask interrupts + "ldr {1}, [{0}]", // read CCR + "orr.w {1}, {1}, #(1 << 17)", // Set bit 17, IC + "str {1}, [{0}]", // write it back + "dsb", // ensure store completes + "isb", // synchronize pipeline + "msr PRIMASK, {2}", // unnest critical section + out(reg) _, + out(reg) _, + out(reg) _, + options(nostack), + ); + compiler_fence(Ordering::SeqCst); + } + + #[inline(always)] + pub unsafe fn __enable_dcache() { + asm!( + "ldr {0}, =0xE000ED14", // CCR + "mrs {2}, PRIMASK", // save critical nesting info + "cpsid i", // mask interrupts + "ldr {1}, [{0}]", // read CCR + "orr.w {1}, {1}, #(1 << 16)", // Set bit 16, DC + "str {1}, [{0}]", // write it back + "dsb", // ensure store completes + "isb", // synchronize pipeline + "msr PRIMASK, {2}", // unnest critical section + out(reg) _, + out(reg) _, + out(reg) _, + options(nostack), + ); + compiler_fence(Ordering::SeqCst); + } +} + +#[cfg(armv7em)] +pub use self::v7em::*; +#[cfg(armv7em)] +mod v7em { + use core::arch::asm; + + #[inline(always)] + pub unsafe fn __basepri_max_cm7_r0p1(val: u8) { + asm!( + "mrs {1}, PRIMASK", + "cpsid i", + "tst.w {1}, #1", + "msr BASEPRI_MAX, {0}", + "it ne", + "bxne lr", + "cpsie i", + in(reg) val, + out(reg) _, + options(nomem, nostack, preserves_flags), + ); + } + + #[inline(always)] + pub unsafe fn __basepri_w_cm7_r0p1(val: u8) { + asm!( + "mrs {1}, PRIMASK", + "cpsid i", + "tst.w {1}, #1", + "msr BASEPRI, {0}", + "it ne", + "bxne lr", + "cpsie i", + in(reg) val, + out(reg) _, + options(nomem, nostack, preserves_flags), + ); + } +} + +#[cfg(armv8m)] +pub use self::v8m::*; +/// Baseline and Mainline. +#[cfg(armv8m)] +mod v8m { + use core::arch::asm; + + #[inline(always)] + pub unsafe fn __tt(mut target: u32) -> u32 { + asm!( + "tt {target}, {target}", + target = inout(reg) target, + options(nomem, nostack, preserves_flags), + ); + target + } + + #[inline(always)] + pub unsafe fn __ttt(mut target: u32) -> u32 { + asm!( + "ttt {target}, {target}", + target = inout(reg) target, + options(nomem, nostack, preserves_flags), + ); + target + } + + #[inline(always)] + pub unsafe fn __tta(mut target: u32) -> u32 { + asm!( + "tta {target}, {target}", + target = inout(reg) target, + options(nomem, nostack, preserves_flags), + ); + target + } + + #[inline(always)] + pub unsafe fn __ttat(mut target: u32) -> u32 { + asm!( + "ttat {target}, {target}", + target = inout(reg) target, + options(nomem, nostack, preserves_flags), + ); + target + } + + #[inline(always)] + pub unsafe fn __msp_ns_r() -> u32 { + let r; + asm!("mrs {}, MSP_NS", out(reg) r, options(nomem, nostack, preserves_flags)); + r + } + + #[inline(always)] + pub unsafe fn __msp_ns_w(val: u32) { + asm!("msr MSP_NS, {}", in(reg) val, options(nomem, nostack, preserves_flags)); + } + + #[inline(always)] + pub unsafe fn __bxns(val: u32) { + asm!("BXNS {}", in(reg) val, options(nomem, nostack, preserves_flags)); + } +} + +#[cfg(armv8m_main)] +pub use self::v8m_main::*; +/// Mainline only. +#[cfg(armv8m_main)] +mod v8m_main { + use core::arch::asm; + + #[inline(always)] + pub unsafe fn __msplim_r() -> u32 { + let r; + asm!("mrs {}, MSPLIM", out(reg) r, options(nomem, nostack, preserves_flags)); + r + } + + #[inline(always)] + pub unsafe fn __msplim_w(val: u32) { + asm!("msr MSPLIM, {}", in(reg) val, options(nomem, nostack, preserves_flags)); + } + + #[inline(always)] + pub unsafe fn __psplim_r() -> u32 { + let r; + asm!("mrs {}, PSPLIM", out(reg) r, options(nomem, nostack, preserves_flags)); + r + } + + #[inline(always)] + pub unsafe fn __psplim_w(val: u32) { + asm!("msr PSPLIM, {}", in(reg) val, options(nomem, nostack, preserves_flags)); + } +} + +#[cfg(has_fpu)] +pub use self::fpu::*; +/// All targets with FPU. +#[cfg(has_fpu)] +mod fpu { + use core::arch::asm; + + #[inline(always)] + pub unsafe fn __fpscr_r() -> u32 { + let r; + asm!("vmrs {}, fpscr", out(reg) r, options(nomem, nostack, preserves_flags)); + r + } + + #[inline(always)] + pub unsafe fn __fpscr_w(val: u32) { + asm!("vmsr fpscr, {}", in(reg) val, options(nomem, nostack)); + } +} diff --git a/bitbox02-bt/vendor/cortex-m/asm/lib.rs b/bitbox02-bt/vendor/cortex-m/asm/lib.rs new file mode 100644 index 0000000..48f3dc2 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/asm/lib.rs @@ -0,0 +1,143 @@ +//! FFI shim around the inline assembly in `inline.rs`. +//! +//! We use this file to precompile some assembly stubs into the static libraries you can find in +//! `bin`. Apps using the `cortex-m` crate then link against those static libraries and don't need +//! to build this file themselves. +//! +//! Nowadays the assembly stubs are no longer actual assembly files, but actually just this small +//! Rust crate that uses unstable inline assembly, coupled with the `xtask` tool to invoke rustc +//! and build the files. +//! +//! Precompiling this to a static lib allows users to call assembly routines from stable Rust, but +//! also perform [linker plugin LTO] with the precompiled artifacts to completely inline the +//! assembly routines into their code, which brings the "outline assembly" on par with "real" inline +//! assembly. +//! +//! For developers and contributors to `cortex-m`, this setup means that they don't have to install +//! any binutils, assembler, or C compiler to hack on the crate. All they need is to run `cargo +//! xtask assemble` to rebuild the archives from this file. +//! +//! Cool, right? +//! +//! # Rust version management +//! +//! Since inline assembly is still unstable, and we want to ensure that the created blobs are +//! up-to-date in CI, we have to pin the nightly version we use for this. The nightly toolchain is +//! stored in `asm-toolchain`. +//! +//! The `cargo xtask` automation will automatically install the `asm-toolchain` as well as all +//! Cortex-M targets needed to generate the blobs. +//! +//! [linker plugin LTO]: https://doc.rust-lang.org/stable/rustc/linker-plugin-lto.html + +#![feature(asm)] +#![no_std] +#![crate_type = "staticlib"] +#![deny(warnings)] +// Don't warn about feature(asm) being stable on Rust >= 1.59.0 +#![allow(stable_features)] + +mod inline; + +macro_rules! shims { + ( + $( fn $name:ident( $($arg:ident: $argty:ty),* ) $(-> $ret:ty)?; )+ + ) => { + $( + #[no_mangle] + pub unsafe extern "C" fn $name( + $($arg: $argty),* + ) $(-> $ret)? { + crate::inline::$name($($arg),*) + } + )+ + }; +} + +shims! { + fn __bkpt(); + fn __control_r() -> u32; + fn __control_w(w: u32); + fn __cpsid(); + fn __cpsie(); + fn __delay(cyc: u32); + fn __dmb(); + fn __dsb(); + fn __isb(); + fn __msp_r() -> u32; + fn __msp_w(val: u32); + fn __nop(); + fn __primask_r() -> u32; + fn __psp_r() -> u32; + fn __psp_w(val: u32); + fn __sev(); + fn __udf() -> !; + fn __wfe(); + fn __wfi(); + fn __sh_syscall(nr: u32, arg: u32) -> u32; + fn __bootstrap(msp: u32, rv: u32) -> !; +} + +// v7m *AND* v8m.main, but *NOT* v8m.base +#[cfg(any(armv7m, armv8m_main))] +shims! { + fn __basepri_max(val: u8); + fn __basepri_r() -> u8; + fn __basepri_w(val: u8); + fn __faultmask_r() -> u32; + fn __enable_icache(); + fn __enable_dcache(); +} + +#[cfg(armv7em)] +shims! { + fn __basepri_max_cm7_r0p1(val: u8); + fn __basepri_w_cm7_r0p1(val: u8); +} + +// Baseline and Mainline. +#[cfg(armv8m)] +shims! { + fn __tt(target: u32) -> u32; + fn __ttt(target: u32) -> u32; + fn __tta(target: u32) -> u32; + fn __ttat(target: u32) -> u32; + fn __msp_ns_r() -> u32; + fn __msp_ns_w(val: u32); + fn __bxns(val: u32); +} + +// Mainline only. +#[cfg(armv8m_main)] +shims! { + fn __msplim_r() -> u32; + fn __msplim_w(val: u32); + fn __psplim_r() -> u32; + fn __psplim_w(val: u32); +} + +// All targets with FPU. +#[cfg(has_fpu)] +shims! { + fn __fpscr_r() -> u32; + fn __fpscr_w(val: u32); +} + +/// We *must* define a panic handler here, even though nothing here should ever be able to panic. +/// +/// We prove that nothing will ever panic by calling a function that doesn't exist. If the panic +/// handler gets linked in, this causes a linker error. We always build this file with optimizations +/// enabled, but even without them the panic handler should never be linked in. +#[panic_handler] +#[link_section = ".text.asm_panic_handler"] +fn panic(_: &core::panic::PanicInfo) -> ! { + extern "C" { + #[link_name = "cortex-m internal error: panic handler not optimized out, please file an \ + issue at https://github.com/rust-embedded/cortex-m"] + fn __cortex_m_should_not_panic() -> !; + } + + unsafe { + __cortex_m_should_not_panic(); + } +} diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv6m-none-eabi-lto.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv6m-none-eabi-lto.a new file mode 100644 index 0000000000000000000000000000000000000000..a203d7ae88015d7f659eb1f17053906bff22e8af GIT binary patch literal 11196 zcmcgy3v?URnZBdfD6%|O5+{)z*%>(rxJew39@ZmvK(doyAQUB#V5o~Vdc`Jw$dVn$ zVV909+j78V1t&dqx9P48p-W4;h&E+YHWbNrf*ZWlu#|df4r_-bIAEwDSx(x`q5I#F z#;@2L_O#tO(%hNnM*o(J^M`4I-M@n-l=fa z)E72YH`loinCc4Z8|u9UUe;ApP}|h7xuLWy{(ey=LKH&CrDQar*A>T|X+Kes!7-U1 zej~Ea9T`__8FebM-a)qVlux77ha7b^PW^%2M(CwTt3>GH5`@x3S|oyTR>GeQt$oTq zB)L&euvhf~(A z%8p}E=Wb6Wz0TXlWfKh1%iMuvx2U&uBUzTATPOb>(QSW(j;lD`j=Cq2u3s&=hd84S zuY>V+sS(-)1SY=grBEuaC1DRLxM@BTqQi=UEwq7A9z(X%Ta zpFgFa#h}HUDSh4%ofTGXsQD-gP8SP$j%N=JV zW!c*uvh}arf9#$P&7LoJbyV#c`$orIdj~!1@7??MzUN-p`%Inp%e~LEtXHZXKYWsS zE>tyzvQdI;%1XE|a=iH_fAIX-%Z@NUU=TzHm{-j(h6a~>>BFRT2!2#9t8!_`^-r<8udfAxeE<%NVDrN#KIc&pDUK?YHN?t<{_h<(?Y@LzMFok?T|Mvc$@^91Rx_ zJJzKbaYkAWk_UTs?YtVzzzF0%l6#ibOlWi7PvksCVM1JC>3D$Y0NdB-@4zM<0e zkXufdbt$u!1oY+f+EDjXPrbFRSC#K6(dkQ{jB20ll6mMdX#Y4;EU~M*{F(@>Y>TQo z8r7Xlxsx$Eol5&>3g_5Z0wFe7S6Ex)+8hXOE_Bzj_50|ZJNMp0=LedDO>X*tHxR68 zsHb(Ci>#ZOg8G_$)lIdnbiTXD>vrpk%nYq(^tu9_zCc&>wXc;l*YB@yXsN%=-4O5w zTkG9yQ$t;i``&=Z8>p$@*KFDCtz{2-Jy3Yrpx5qhY_1950tokc8_R-CzPhGB(*d2m zwq{>_owvSer`OlC8$YxRZoGj#$?;+E=Gvy+{Q2Jf+XI1ZURU!z`p$Y^1HCsnW1rEj z^B8olA}hn{eLkJeXw-WcozH0Y89hF$9$3bl*VNb6)O&$>vyS!piVSYnWnm45q9QkR zcI&+suTSrD>n+}7!)Aj%(15uqA zH&EsC*1Nq`4}IN;2QuP8OvyoXK$+b}XRbErEC7L9XE3@9UQ>~A`vJBVq0Unv7;rFc zOvPIHKvCP&I|;|$_%9M*W!;DP)YKQXE2%4m)Xf? zC)vW0YxjskrwE!1ax{{+(ML%9XoTW;yk9%TF>=Hyj+1ZUUd!=dqV;$%$5K34#TjM$ zn(IVB;YC=QHQ5!8k%rn5xES@NWUZpbJt9OY({+v^RANeX_Q=}f*q)0td z8P4q%Z5U>bC4MNw>`BhSB$^D8_|A58Ld1v}2XU};D&2&RBiR)V%4#Rnh-Av>G{aI6 zlNN6Z>B4BJ9~zH}plOs)9ZC2PkI39y+VceycHU>?4sVlln~_2C3x5;xA60W5kDLsx z?jo{#iF~-gKVsuGDcoi!Z@IRrUQEosCe6VuLlns+PYThMsCkXTzljJ4u zj-lu-#UKs`(2i_`s;XT3{Y{`A2GBQCQe{m^BItt-G}`4hvu>l=>$Vu#?Pz&B@s0I4 z$4AoQ8{(mjae^c0e%XuYln5Pv`pJq3X%*LTW<@q9wza1}OdOP=kybjS)apI!u4=Yj z7dgwO(hyoJlPqm>sw4(k$9?T#3)_tL~hI5wbT3)1q<;nJ-l*VihqVg zJ$oeMDDA$!D>hM9sb{Es!rFCB8t)uib!L5=rHk0K^QQ<6cJ^v+kq_kH`6aQj0XEV- zT>}=lzk_IVj&z46VJnbv0#3I_@dkl$I}m5-7RM6Zb~{N~kjbAEfKXwXfnO3oYLLh8?kU+U{90NT2e1VI zG#9xIdb7s}Cu~z0EI;<|)5_m%xa{nB80{sfdV)eqwA6G^I;KI+?=%gT7G4)^^88Db z(4f59DTQqd;@%W5@yMUjuI>Af&eNcKWYY6C3d47;f5TvClLW=IOr-HJL;Vt^eUHDj zMbbqOXG+)@h6FGq5s%@=7{i~R`(o4LOlPc6xu>1F#+L z1;lbJW3XY;0bh&B?&8?=eMM}r@1JGdQrLI_8xzC~MvKK_wip;UAM*=7QfW8 zC^ipKv$5fIx66LzzcC7UyPp)3gk`pv05DyIy`5G|cwOEOTZhH4>7S$5&48Pr*BNka zyo)>U_o^xzd&#pU??A9GR!0-J#qGDp2z9qzlYbs^4@lNXQ+KcF36;bMO)PZ#B#z>5 zPwKh}#^B{^nFMy02)*7blUG%FAOLN3x4LhDk*@$48IxOYHdSagpYnNQ2aZX2*}`F=WL=*d^%wSfXHzh$meN=Qza|zp_PXO8xSRU8}L(DirbICiMON3I&A|yacl#`ybZXB8(|v&9vz*d$GYur zkv-O&CiHLt9Amo*g@GY?s$VnX(1EFPHMRz*Fa%yG%u}eswNv2izV{k=b3u z>KWE$GFg(cu2t^6liYY!6jS)e6n^APMyxL)^un>VD-R`BIkhV)wJRWL$Q$St$o64K zqHiCHJ~a|leU`@U?GX7@D%wyarPeOymDa=3i1^nP*)7Oj<7cw%Yg_2Cy4W z{OZ_NN5zbXR>!;TpS{=r8`%XkG2`-P*^T}?ZjRrjo8cE+0KXu{kFgr{X4YgdSy_Wi z$E572{bu+PD=UeWi{kerkKfj`KNCM~+W!xJurOBW4OueU+c{3UIEWJ$lD-*wK4Q!Sb2u?tHDQ8e~-;!og|F&#wF)CZ^*BG&0B ze{p}mXBKYwK~0@c0B$%|<>8u+Qbnyv%y2G$Va(=*rYX#DRO<0TIAqfMideJNr8DBN z9^%rz8O;1Mm|d8$g?*a(KFthf^K4<`VMJBO6peHmfokPv*vhET*AUEdZs8IzKxe?bw2Yu4I_W&GjjG57obKwoSzTU64t^ zrzCJv59rvZ+9S@$(Cj^;KTuQ02KUd` zJ-kPpuEN6PhV+=v;&NGyRujWw1zg@fK7+x+`e(nj+J5VdEG6}Ca@(T%H`%_p{@weR z)W4mxFkHlLp_O0BZuu9qTRatDvziS$vq`TrK;qABbeWQ}L!?i~BMalE-BhjJG#|IF z?Tg~p)v+jUrz`%FxGiqCc(}fz-NNYHXt#JOV8)tRtH;PP9+L-BpO(~qMLUDp!gh-& zs3!_$F#Ae&OZ3oR*KVDDXueW|+|B6q&FvPOdlrny|7N#>-UBz-EuaC8MwidSdaQc4 z%TxrZ?v&lK&)~SQ-5M{b92amLyCD|7!EQ+_=d(D&-`w1md6v#e;Cfx>-J)l6hZ35& zQ#qF6aV?ZL#{114-wiwh4a-WA+vhTyOhsPC=e05^9@!gsY;(rvrthS$_@%Gl?X8`0 zh95u=6R1geb+VOQ`Wga9CW5)l+V_7G^NH?N^BeiacwET$jOW6ev=n~}`<@oxyxlwO zXMhI$Sxi=Qkrg=98N61HKIOwhH}Hou@U!T}pB3;Y~wrn`-kUy&A6ZFirh36~jSxq48SBo-Xl&D&!3NsR>9w zoPiy2$cWPqINkUfN;{@a6QNqwJ8X_gGS1l5lg>8gTtdPQVKtbSbKvui(>Vu@kMjte zcl5+??jSsqbJ(dCw$Z6{MGS|C(_P~h*bpZ-%jsFiae{4%Pd@Nz$mOzlR|qGQ=mZV9 zi|2OD%2ysqd<2a%Uc#gGz=_{pX0&+CE{|2`(R;zrxM8OX z@m%^Xa(>T|SGwOQnQ-DQZF7p0}5#y^5$JV*{yLwcLT>FpP^ zu)6@sY`P|`s7U7}6TW(gCEyDmH5tf0<+=V@1yX{D6-nt2D_flCM&T_^QW~RqK*fOOm~kRf#qQ zYJ>;y->t!v+tD?tdg>8Q^rg(=e2kO)L|$S0J5KiTl7q1qIQbK4J+W6g#gCLH(I}@p znLZkw;HckH*T(+HsV-%xKU)%7_FI+ZGj%94x(uNw6mK2*@b=tG*2y;>U>4f8LQ0{vm2;qir1pnFqvp%mz~K*!??r9f{?(S=f=A4t)KQlLMYq6?)!=YS3( zgM?C`cLNR2Unm9ocY%g;2||hK@=ZX1Cb|M;*;xonbQrpXcC@QVQmNsx$W!+SKmG;(+BqZ=k2(c{eY|lL-B(y>Z9hP7v1QHmtnro%C_R{REjv#{~ zAQ6Oc_ywL~%OJoGigCD1Y>WvIKN5IA97voO;b07o?Z7h*u@#d%8Rtyv(? zC3S!QU;kD0S9MiS^)6VND;IX0-*iT_JCTM7GpeHYCVdxCx=HM4s9+Zq6 zIMHyZVYTDM$<_a&&?id>m!*0MO}OgR39I)W5W3V*{0I?!)alFX!eNxXH-Ja&ePgo%<~6aJ{OI}Kr~Kv1_XEgXw6qE zWcbz#5<-{owwbppa0|bJ+fBGEtF8c0bvwz_jo}`uy9W1g-9c8X`a9tDMO@(*nyg8$ zIYbg7l+YJ=yNkC!#Z5c?CI~n^0#J4LlBs(D_fXwKxQB76(6gl2fbZdg?(+au_aYfw zleh6^h5iW;dJVURH*sr%DAZ~-P6MtWJ-r_NwwjtZl9@pU!+t54>sc|^YQ0UP7Bu__ zbQ5N7sKaWQ4qQgswpvyJM@eU_*1a03-_*RH^fJe3!;N4bV#Qjk;c?&(N%vX}{|anD zk3w6l#_7Oiq_3utX;z=(p=A{$qm-5qMxz!q><9f-^1H3Z2Z8@W`iouF0Em*3~ZEy3Qrll#4-MOa3LR^=6G!Z@twem72=ofM;cG;mBF`w6|D;f}|-c zK21$0Gl|R=j;CeQ$FyIt7DbyvOZ(xHWo_ZOTJ{X9mji1>sXmhrK1%~GIGttn&PL75 zKB=N8w5a}+xX;@E=^D>02%wk$gx+>n8y%&*<@C4K^~w zm?$!oXk?qN@idapG8%cRXqraObIrE!35UjFzc26O$mbp!v49Ux6s`u)I6t7FM?yDl z3)cvzld~^GY%UW{re|0ixll;j*ZDo5M^~a|mbI~@1-jX%!rt1#)kNom%ZclX3yQef z1q;SLh3fi2|GeYskandeZ$Ppq*Quu_P^_KrfbR47D~X}djU$D&=)SXVT8_Sq^oHq<>hkdKtdRHR!K zM#?2Mwr{wga+Q&xfr1*(s7|?OHijQJ0j9rSib= zcGW*rQRRx-9aZZ~{S~!|@zu)GaHUjMmksY69@#UjRtyeoA09%TDwoE_2VuQattyuh zLUU-38W0$!6Xgra(y&m?c zJ+w|RiwR~ixj$;2w8-m9WUn9o34(rE1H z*gz5X8T2EOh!%==yx;E6$8<9&t8K!NsdO@$$Ye6_;+XXZuUJT&C2Y z#4s@qBms5K%+d0|P;P9eZe6jE?oae*^7(8co3eAdb*?;Mi%yM7r?TmIG@Xh?=|5TM&!j=OL|S_Pf4@z-U(W-t>Yw41>+>e3LEHiU8YC8QzVrtc zv2#$RcM}_g>?p5;l*K)ygK=(Lgi5o&+zVRvi$z+2v*Alr&|685qpG*01E8_j@aHnO zog0DJcb*4uH@Qfx2h=^fhtA6NbBD${v=w@?do9)D#MS1HHN}PG+uFQ3z>h**wkuF- zC9di~^H;a*Ui@wD?uPu8#BJpjRAMi^8BpE)z^D~b+;TjvQ`T7^SH>cCR!wS|yrDrg zT5W2YHPf1`~Uh2+W)RRU$3sjB&kyeLE-fDw{5KiJlH%RvGB&Ey7jwOxBE_&h+|cX z#*?W`-pL;+@Im5>7rZ)8gfPyNLPk%p zdVLRfTXmuO`lj&JR-IMf7G4~|4;C~kAT2u5_H{L-gH~O*es=g9vkqz>KmD9lQ*EE4 z_Ghyq6RE*VQ}~`)x=CTUq28n#Et=C5Znf%XPKwmmPwLjrcAwNTpRW(#i%q;?*1As= z`}&=Z{)aO^nf}e9|Ng}KI?J|`$IU0TR!f&S(si|^FXGINL-gczH8O$`d{^X$ud8i; zLgaT$Apfn%Z<;`U0B3rPf5QavZ?vos){c|r&dp-?n`>*g`!|R`-}A}2PgP4;b*d4cyt66<6;@rU=#zH^ zD>cRT-Z=8;~zmT|W8JfPA^S-6vljkY5ns zFAVUj0{q$l|LFkFcdKd%tIg_LVENc^Z<~%Dm%)(dOrMVX0FXTQ>gky8PhiWa>bIza zK7I;jq*s4B-Y>lVW~mQF-|;_3@u_O(B*?)LF1)#c-}>H}Z=rRrtjxwlVO&iHl0hNY81h_Y;S z@-Uk`lS!22pc7xxG|v|>lumifJ7)^dvoVxTd3-zNoThWW)XQVp*)IG-!9{|L1v>=s z7_n&~#OD)3TtkGMO%0)vO$*_1VN-}~LMVnKYvCCp)U6bsSjx{8WWLES5nLg-T9D&O z`K5yVWJP|PU{P>LaKGU13;u!NZGv|R9ud4x@R;CZg5MGRuHXxTuL>R){Gs5F1%D>^ z?}EP)2!|P#3eR;5uO{ldQva&(ZxAu*-%;p**jeZU`Dub3g3E|gabiz|-X`Jmg8Kw-CE}qzOoZP3!hb{XMZq5tvHrY6gx-G( zUyt(uylSZ_MAYM}w#Kuhekl>_)J0OiQTVHgSUh$}{T|_OAYvWUpBUlq%ff$+h;{98 zBI^H2@MWogi`cHz&!zr-;lmiK&_aB(B(ipsu~HkQ{wm=Ih*%HD zr2bkW#_OQ)w+Y@&gx-@xtgFvS{oe`xK=2)rPnrxpv zo^Mdq^Cv^Z{OKWL{MQg++)KoGZY5&8wh=KtJBV;PN<`lG5|QTvMCA1lv0bU#iOAPs zBJy*TxLB!U#15q%A);R_Y$uwiv4IE%P0~1(h)!|KA|kYIKSFA3C*nCk2#s*9`-7Bf zw2A0fLNG&w)1`tvMD+7Q!8Jq#TQAs4M87u+ZY81-R|#$-A`eBu9Yi#4P;iupyi^4D z65Ey9FL;26Jl!C8h=|VIB6vFydHWN=!$frQh~QBo^7s`&q)3myK{Qo`uz8|MI=?X0 zyv|RZQW@cw5@EDPc-{X78GqPc#d_p2)*NMpU+rqy~oR9TG_z#H4a|8Dg#MAp{JLZe<^NGl_ z-ZvpXmpt;E5xL$sk!QVMLcX5$9q7NvuOcGP`uza&^)DC?`Fn|oy#0#UfN${BL!Oos zTa?oKEb?+EdF117h{(gQiRk|f_+r1KMD%wf5&hgnME~v}qF;{^(Vtg|3$cC@(f-CT z5bZvji1zY#nSQP!<+Zg{RzDG%hwD)_mD!IbW2@Lo_qIPH=c6);AZ=4>!zl_9BV9HN_6Ulf)UOS-vVCV}uQkX!M zhu*cF@L+rb3C__Y82d_&xNnHKs1k{0dDpjShNQkl(2Xg5mKI&U zj5}#8Pr4)o4Pg1wlnKy0^>P%Zfx^eT4o*Q=!WVAQBChpbH^TuuW#Kr588@B-38@CrcmTb3}{_-~@ z^xU{tfoEJ3!^FMJQwLIYc;eEp>F;B3?2TI#8Esfh++&WO8+Qj}jEn6=7Zdj@&@*kJ z!1ly#1#jZ=Zxg+7M@2>(7894hfxP{#K*qS{^w7i|4#drP;$n+)I>cR%=AdB!WY zFYY1mjEikj7ZaDhy#4L*#Kqsgx^buBS@6ca9Wpal=+N|cvZLqb`7mURYfd{&+%WXK zao2d_V(WI}{+E+KH`YF;XL-ng%TuN8Nhqvysw4xVur;9@axdAjP2yTcQAq3F@>>rOx1 zSZ|69pbOHb3;%c!|J}GhK`reUIbt{N-B9wz9reUL6S}6qw*=zy-M3bM4+i4?C-fK> z+k-Bqzt;xh?)Aj&fToGdGbQ|YV}0PE>Cp7IGZ2@5RnEAbR6;Rv7o*@J0aL5L3miQ+&oiONxLvqdOk9NV#XaPS8xcL)U60Efm%kZ|4~X3U?sN3qxa|_x zrV@&=83*m{@9mzr_=(~6cLfsZjmzIC#s~eGJo9V|A~){264!iPFg833^Ts{wiOY8Y z>ao9v193Ut#s|c1+*<>2`J0LMDJr2Do0|i1k9y*!MUQqoyMqgNOnWAXds-mwg%X#~ zD~pLcHxT!jC+-r_V_cpwdgHF2Anv=4o||W`bF^QIi^ar!8};5iKjMkIO!R2SKmNsk zx4-;NiJy3GLGyKa%F%P0HVe7!MopFq7g?h~H4J`+Ctnljlv4oAzxC_{-o$?P@f{6ythBz~9lu&bbrww;7l5cP4D1 T>XyTp^amiMpExe+O~v(p7qD$b literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabi-lto.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabi-lto.a new file mode 100644 index 0000000000000000000000000000000000000000..b34ac64f16c45cfe042eeb0e60f53b2942b9bae6 GIT binary patch literal 15280 zcmd6O3wTq0LR6lqPA{N!VPP(!G)&;8L18Y?k_?Y(5(dFAqw&?8KVrH%6iF} z{c}0lFedTCcSQ1$Bj;mVPOY4*bC9hZ<^3r2PLTQ}PW>mniO^*tjSQi`pN~+sNP|Ss zPCop|(DDQJ;f%W_a-H>AqFuH!Q(B{pO1Koy$m8V1M^G@YhuR7RJL^eZdd88hhj)kW1{bD(>fTcc? zQ|~#bT9oralzQKmbD7SuS^C7qC}Tr=Tgjm^>quE)x47gjv7fp;MnUOShKfsEQluTV z$q_9nj9tWSk?}lqC;9?KQPxp$EXSlciK#g@B|0m)nCvZd9o-FMkU+XH>@20X%EN3} zE?*dSl{&Xd@pPkwrhT@^zACc5FH&3-X{r)8w?MxmrlVwY1=-vZdE6f{6-E5=NaH9& zULKLW7sJ=77}-FR`xr7XB6&VawTwuvI?2Wu*<>SYojLV1*}~=b$;m*Ftd&#yP_pv- z+%2!-%DMd$4%bhI*1lTP{p!C3`p$i}t2xoRBbbYj9Qu_3KO0iSqo*sR2y;{r2uO;= zitU@9CZLF~h6pDrTlGFvfiK5+G?F>Xjgq_Y?df%l7U0ks?F`wkdlvN+{~#J}MWQ(B z-0`>rdV)Jcz)y}O%wbVS8$vYv!%qw%CaC$>Zzus`s9*yM$_Ns&pY7_su1ne3v%6hs zfl4#F^t}Og*6^QFUDu@#ahLGJr@Qn@WZCR4ZOntx8C|l4?XyrCTJW?8Mv#Wm3qPt_ z!to2H@@O9z`iLJG27#NAch`Jhf`ZUCjVp;TO8ee~Il~oz%A>UY?{4QSOr!L@+7c** zuMO&;42;t0fk*k33?M*jFmeC1bcYzl;UDG!M8M>}u(*B&jk54x?jw$l(vBT{1fsL? z1B>COQ}-wfa<@ji=iPSK$&9ikn;nvsukSc~Ux)I+FSd15J~;O6j(c_vdRE@Q^X%>; zFYbJ<*89cI=bBf_6prVgA&$&1a6I=tVyLyi@o5i{`HKQa-yx#og9699&k^4BOB@qF zAu{h-;`ryo#LD}ZIQo7;WEK=U-hP!BdaTg#+%JiaqlJz`zaozOrqJ=!uL!m^E z;JDJ4M{MXSv$PL%mj=n!7P6tIUUmiLyeFqV2~v7lsk%R*dZSnAV=}pFZG~sV8-~j^ zbc;8fY3T+5_P7*_C_hLtzqqL-;-@18XL6})QEHsYsbg|3O;J-0N-rN&y{%D>YE=EK z+Q;lKKG9Y@Qf56SE;-Rw(k?DOGnLomBpvdLpeoq1EqCQSXmYe~MGr7_n=(S2@wEJi}ctu*%aKWIH067aV*R*@~vNTVXs7>g9V@j%Y|DCZ*w zH4&vQ*>c8d>KcrKE>c}csQc~evl``vkov+H2yE56gxaUrX6Y+if2ghajAKP|AkGNL z!IqwFTR(~BUSJbk;;dagF}`?oT=h0|puC{CuWiGzw!-!S zOLv*|%s|QUgmriT##nNu{8+t|gkIGHfEAH~Kc1wnIdk3{lT6V$ml>=*K6Oxaa_SO8 z!QYR^Bv;3%2?zBVv;5*UR*6;9_~L6C)fJ6uP@{qwoYXA!(LXLeQMTc@*m|(ddZyw8 z%svcuAM~?4((I2EoHFNp#8B6!pv^WyTw&?>7SplMAF20uVATh_*GhwahlLzam(yik zvVwU5T{*ox)P3NH4Pb8IZZ$k~S4bv4zlwSk7U>)bVL-EMm8)}8m!MS;Byjc&Th8)&HBQ%7sp z8m()YHFedys~T%s=_0q$>vn66W`@==I_(;*ZjILXjc=6ft$VC)PjlTy_nv^ap|#G< zHtwmdcHbZHcmvgSyZ2hQdu!MhuLlw@+u*gk>-Sa%Z~}w}y!B-bjlSB(Kx32EUQ@lh zuGU-ExYg@x+>Rew27kPP2l@7)@x3*T+qvugk8KVFHhEopchh&*`S#E|`5yZWZmmbJ zbs4P;tMmD^T7yC7VYEJj*=O+htU4Gn9(i?LO?90Y25;7~UY}9#W?dFmuQwXqaI;(I zwRn9xpIc|~@)h^$b%8y2H0wBc)=k4;(7RZJR&O*}T#Qv`)iI2gHLzxb%V>a%7b6^C z1Fh>YFzXru?sXWQbv!)qbg#?e((7CXi^*-)TU{QrQOo*#9*^D(O=z`x_numRb&WSr z>GRgPy_FAt(|{W?;6_Y*BU+%O*U_4*e0s)cHu%gQBkMExjM~jjY)zB77Tco08(U7n z1wKreX<05EFo)yq1CE{XL;@6m{3WaxIK2|zan?@y{F2v$=S$bcUPFG=b=iims)V#j=82SXO9qjZ#ZdNO|FZ5fc`Po!B+n=^oWx{G zSH_afAUR{?@&`qsLBdAv4bn&&rjL>M(FnzHd%t&zN5~PUc#M1#-?b1oCR&LbbL8U2 zDo)BWirT|P-Tmd?vz6DQ&+RH&io&$?05<@xXTu32+*K;Ucg5!Er9Ta3;YSV;&aC7k z4Vqd^%?Q4?dXJv5i<^=rF3e(3H<^|K31ZFc0z$j zrp%VD&lNecdyw^jYQ-AjU$K zBbcJ7s6)SmI-++Z-&Y(DsgJfPjuW>_>c%9x1wFA{qodc(?;0L_W7o-dx6C_FFE^Qf zW%|Ku=2zCgrdzCkt?$)eZVNw%G5;CpI1QxPS%D(Z9pt_We-Fs30g%$xk%90P<;mXp zlXf+zHV|vPOwKo4a#HU&K-A|ek(eQMWxDfgnE)dA2R${mfbZR-Ig_|gkrP>Y^=&k*JJ)h zSVDSOlO}#yn|LCu87-`Om)p#`4Q8*~VqiC;h3$lF=iQMzy2T?|ew6J;PJRWvjL?gR z-T5a&N>6X7Lo$Zs^=%c%MW9AOIBy_xFQZZUK`~k`Y0nKi(P3*VG0e&5t|t9!V^! zvgbb%TGY9b5w~({}d5+(mxh`f!(S&zYlT(o+Fi^05Om)#~EP`vak^(_S%TQo*59s?tr)nIiDmwrFHAWqO1B`>2BVw4Wt8^nmm5v1OA?phWTTaT40M@qpf7Bwk;AiZj% zUWvZR{cRqldj_mq<&t{n|8fb5IQ;$}#_vB<_=!=sLP<))p~kFFF!cglz8nKYQIvWY z%JQ~AS*{eY{?_5Pw0Te$z0qwa(4Iaj9t}B>UNZDp_8$sg633vX$}$Pgf)=m6Z)c1F z5BL8^`dpL&U6_kZ$gk*pAnaC-vFfuSWt>(4g~xpbq&&}V;)oG$ox1%E)t;Gkxq(Q!o z3i{ea4K}hc48~S!&2ChE6ShulXvUg4iqmuEM`2kBHnHP@O=NDBv;X7 zx7|)YV?{O_IJ|T6=iHd|-XbPg|ECGBBqm> zn0!AS6K-w(uwS*}cN|YdXYd37;<70;Qi+`b0cWqLCg;SYf5w`{wynS?IgmHp6MWb2 zmG7#Lk*7=E0z+S{h$c41?RWMOif+5I=pw{tkfffb?p@jwD(NGXeW5$AVGI6Fo}bLn z2FFheGKwIJPQ@hB%1RFypRMjz_jT}b1ppsoa_h_ntIMGEdCidB9PqL=m2k(x_5@zX z1+c^n6)RQ0U?|%iar@dh5u9GNXI6=tq8%HHgf%TvPl(h=iI&yLvx6ll_=b3%M|wcB zy!Rb?nF?K6U{?+IF1i@Z7lDR2K5%@KlMF;NOJW@eom|tbyjrh!y)B)J66J2&aQ+sx!yUwoXM?sPpxa_)EHsTYF&7( zyFDJG*==NX4C^wPEIeOp=HEmwYZf^*i{|9(ogH|s|1K-@N{}*TT!t&ngWYPbPj4Hz%R zYS5Wklip-y^)4-wl#TYA;YH*-iTpY7dWOSmL-tq1Yxrx%3ta7+;8lGCynqIH!E!gU zCauoJTJ4gT3SBD(ZkD^u{tJQO2HOpj7 zVuh_mj}J^2lg?*k%~qGzfK6?%UwTtmMN_u+yJ^0LGSI6`VKvKsso(FUsz$QvZ4mOV zk)CCDEjuJ$GF)oq%*OCua7M5i;XG`?PVDF8Jys;VoekFYw4L}Lm^z6uF;<_K zWg$Fc1Urz&E|J3S#?fbYZ-H|wfp}TYb{;(%^{mm{w>KS{|#jmM+La7X1&&I(rNV&oO2so zCZ1;qYTAalFmQHf8Rbdwerx6ZVA! z*@XA)R&?Gg`iXitp^Q6aW63cthxB@Te6PoM-57y}`NQb;xy&Y$(aZR}Rwg+{_PQ~K zonsKw7!;wGo_*#a1@>@W4`#lOENGLR@wd$tElZcdo4{=bDe z?0Do>=WvekX|Q27xBhJQRbMxMK!fplO|V;G_UJ)tm|=Irn6y1^Hon9=-=$61a!= z_cwh5vZ$Mh6P1+>Rh12`4Q{rkrVjRAcF)8@t4ptd=iCeXJ_fhd3MQG?>eVJ~iWDYs zYC87&LDC*eC_N#=XvmP9bDMgG%&Vt@^TlgML~Cl6WjIwq9R8e0+GgGNW;7N>c6Ny$ zmLq4|2=zX*HWy-I&{~xSLCq+fKgm99&laH?`Its+%6NydD+bvx(+&1pQM&z>i~(?Q zJ}w3jJq0ZB+=~ZSsy!aT#|A&N+Xw7i{9ev?t6dc9*7)d;RIsTEH8ZJ{ml5d*Gimoy_7h}f;N`}RXWBse+qQW3iaIH=GN!v2&Gw$|=k(|FP>4Vr&@;e(O~Zpt!-K1lx?d zO)6Gzm3Nl((6W6np`SX#%v564Rewi4dYGUtLJ&@dw#j7|KzQs!!3WQ3vte`PmA)k( z_ANnVut+L_U{ZX;j9^k&g$gCX{3>>#22G*vd)u36j<2K$V#dedtN_G}!w@shfKBoG z{jfz%XTN9%?*KRuPDwpfF`wf=N6x2x2@Ba+PVTKBo1l9ap?fEZq>peU{9nKjIUHAT zlYMNO#|~z_hk0cLE?=VirgzBJgJ9$$JWjfb)zKQSHSx8;?x`S%dm*nYBiQ7N(bI(rDjMN-$b zbF$(-5TY=5upJG?b!9EvGE+|IVaHUfpHTs(*X?B(v)ScyF=m6o!eV0*e7BrwTN0&Y z1?RghSK@u5L`ghRl9Uy5+eZ#E-FFMOz6IP^nDpI3x#?^F$6v{JvoC}g|4{3STlC!= zX;@?5CL?m)K2#d$sePz*DV+H=1j;xC7_&5k8drd&~sN((CV-31nFpQb7@Po(E#ta#6E z3ihQoKfWS8rr^Z9F20qR!v9J4fxk5i$BE7tVLuPY6w=_E!L7V*|I0Yevf*drhyx8S zi`C1Ry$tN zUlGbrcf~oGzc$6MX>!5G!aU82u~=TYhMKfhldU}@LxXLGjWi~h`A~VsPHD$O6`9`Do?l)Q4JUWSx>0Pu znNZtzpgtINlbM%Q6LvTn#%*tFxb1D&=jJm`*$7R=gE^le8SMO=wf&IX7v&z*#XV>= zQ#VRlCL@nHhFSHX{q9JsoIJv#FfqR=Zhu)hsW9;|y>mW>f**FuKhKJ;dcrKE1){ zHn}+7(B$1FZ7TwsU>hji!=QBU0VA)cKZCV&%3EY0HXX=-a~y@w2AD{LEz;~%((KobvwY>Q@s9{BEx4^U1jUP?a2?`;mw*xURt zx$9Frb8i#$a(r>RUjA>)H}U^geB-$}-|$tiOwpMvMzh&s)#)r|lb+`r`y$wnTm}1) zJArS04t%o<_~r!gO%V7-o(%^N@^8X7_AO5PmO1$*|LQC1sEsU>NrWL;Z)OULUy)yQml`Xrs%YPxdHl= zjE`V7fzH9{kd(24ZAN#kxiY}`wKI)J13qh~15Z=1YtpO2)aqET#c1&8Oje!CV-R9R zY(Dr2Yd|JE40HP$%xxXa?HJ7MaL0pZ$FnY>VNZKU(qL zSaOd5?wUTg;{@5!Kf^D40&o?0Km+-~$Uq1BTk^nHnEe^Cg{)1Wb-|{XG55`XapsxS z%%>{Cy!*69uS;(*TXZg;mNj}o6@Z;!Ukqz{Ev)HBVBUWX^Zo?P`{yw4C~}i|pIqpl z{Hy2v_OEr`|KV2Vy_e=+O87~}ZyW^u0@CQ(yX2bELFxV_wl0}w*`_YJwsbosU*>Kf zJV9^j?8;s6QBYn`y8U7KGEaLJ%7cJrFbib@tHv^HETDLlaKITxIQX0gX9t6;P^Jiq zWVR445on@XJv8t=oX_9I7bU{jN2sU4#e-A_Lv2UDmnfVqLD5^J#s73L z<8x_+{7_KxPgyPU<3Z`~vU{Sx31(fE9gqGoDEn~!D7qG;y1_E~A}H^XD{|+D7VOWp zdu_1@)LMqU;K+A-mkP37hf5mhm73laK7)%#Zfo=mDZeK_R`dvx7kP7r~0v)#_ zqyqf`pkW+@RG>csG~B+B3UqIhE~Emz2I#nbArAIYqB&C-&#i+I_hUEQS(%Suf*TFq%)EzA9WpYwa(_c@1mu>JJkK5)+W z`CXph_qmP$k>q=IwJ!OE?`#xc-~QX1n_q4s~tm z&2CK=dKdKd_Z1ctGTH97ex=kk%T}N3I1X}da#X9TNJDbnxN z;Yqt($(45vPula?aQ{uVuJlmFKWpWkSK8RTa0>cn_h**w zmLAzPT(_rgxf{jwRkMfh)!_-d4t}jt-(ABKeD;Z+`i@?K7VR!QQ0s^?9eZQot*;)|#sDLpjdHD~;;;pRQl&_Xk6X3Q)0303UxAd#186b?tN zC5*#SqlTTecOauv6~}6(0F;P9sL_WV!`;Cct-vEYg_73%Ub9utemLS=s6J1s;`H> zu1$$sJ>ABXOVzKONX6KCTm$tnw=i^QWW|LJ4H8(}8Y|I0?o6k7e8pQdO=TZlu?cNx zU-PK;X}Ws#i>E8qe6k8pq;f<3CG{N$GSTa^aw5GZ)vACLVznlp?05@Jp*;-C)LJ#O zfthL0Om%5kVmd|YPpa2dP-;d@ip=y9E}o9MD|NC(QOkO%o-yu#;jEXGnQ95NOsiec z=fDMkz_Dqi*9<(9`H(Yi8E}C4l+&WsM$_*3RTV@J5%jWFidur%Yc z4BTZ~?{=-@PJ(3_t@|bZer>2bAG)p7f5mCs3A~s22c5e6fX^`h4X5rufWcbizwL|} z13ZKI?`f8X<>h?CdF8AczXtiMDL>^j+@O)}4WB4yRp1un$K8t4Q&her)q078uEzWX zx(2LOf!|Ozopnqb)wt=foKNfPQtEZL)Fsf}ME(Eh%E`#TsavY*J`2mUwEo#?dJ%Z? zXylu5%MC0*t~P>GiK+#TGfEG^0!N3fy&l@fX*tta&U7tGO<--&J<93e^m9VZzn}&Q zBd?t31ceJ%7T*p|N+-nHH2;=bBwZ9AhpsZnP&>juUe8907@>bQqnDlk`Z4?-dUUu zUM@~(8ohYMNE_adK%|s5Og|0z<!&%FV6G`_5)lLVmD%4_=)I$18*I&Eh z6gbb+LaXV*6j*K4o`AeG5wPb(0oR$5-hdYwwI?92Zv@EgS+?wBU`YmGHaxt3s-ep5U-Aii136-MZP;EiWjk}HjP zz2Nh*Mvp6wzmfrRBFRvql8stpRgw!5DtVH4no7p`vFyu{ix)g1z8Dq@ zmo#{s<@3-Zp)1$Hh0bl{v~$4Cwa)G7NzOX1cGB(Vc_W}jmqIheSy#{oUG0-l-s#|y zsQZI!VmTC7MG18!N|1XB-Svfjl^bf04rO&MS52#Hxl&F3w05$)_Fk>gP14t02NzW* zMDOOWdcEz*#l_Vh{6}7QwDPBw;O@-j+AEXd*IsWo_d9Qp zbXNfbjm{YFYUUQ@l8vGhPE>TZzo_oZ4leEfCe4vJliVtxNnx$g-Ru_Qy6-P`)^WvF zxth`E<5C!1quyo{aBw8d)|#Wr#GYc}V$Wps2DyYX8NYW!Q*I)%NWRTs&WYCo=?K0*5Kesp6lj*y>W%cS0oZr$~+A=tlYuQ>T4R-hUwS?Q^>9){< zzV6GrhI)3iwC3W4TrM0>hFT(_NO(awvLGBk?KG7c>|NN?ooy=(sq?arw!DRp6?C$qhfCl)e;1+^r1<(6)^0ijYC6|P)5IHWEp7i;)p_ZfD8z&-COSK_n+Jx%$*yoToXh5tnOrPc$faVLWy&@A3WUR*ow@$Lp;CWO zX9>k}p?Ex(3*|GRXebg2rCF?OS6iYHRXRb0ZHSPJ=c18hK88~`8q0?42;0;)mX5I( zW9-F*+lygndI!3D3Z>3sp)XfJm|`>(PsWPLd^}T(731M$=z7~l^|L>HbxESK1B2ap zluw}@u~;~l4@HZiVm6|yL0k1Aq)a5^;aDn_N~WTrTqu_}MGD6k$z#ZOphzf@izH*| zY%E+XB#~tiZBw}&IgDMVr;{1)AjRR+n`Iqy`FuQ?i)SLCOg527>C(N~D(-`H52a&~ zWF`?!q%+ZMIHa4DAFSfut=&0G`Ljbt*3 zSU8`KvO3yUy$A<8UqlBdBE@(nna+k|db+U4Hnla=<12<{_w^639q~jcT`XiWsX{T1 zVImJKK6lQ{fl_yGW^l8vT|Sq@L`Y?`=~y}u%IMma?Y^>T)POW9os5Q)iAXq_j)Zct zY=UIkR=o%tl}TpO`B)~DPvo=FNJ`HG7SVIpy4cX5!NOJ)h-HiUOgF6kU`o<|1)6cw4dC=N^ur@?D*SI|g%^o*uFkGSO%(mri3a3+V!`H`_t=l~ks5 zxjzVoDBIsZG&oesaA0GpLNc3Ahx3sFDxT9bu54GB7pk;XZB6$2!bG78M-d8(Cq}fh zH?tkVa)nSRnamcmp=2zU%IJZ!JgUWDbtDGYvQRitOr%m+$-pF4SQM9jq8N?EbBQd6#^ZD1IC&E%hhMwn$z&=WiKLQ=s2#`k!Ppf1 zgA=1Jg4tqPj?wAN^(H$@p@A?e7s(V-@mM~RNJp~ym^=5Yx%%qph7DE1ZnJ|H!|_5k z8cU`k*_5~Op*DLN{!C_X zB3^T4eJ`G;Ysh*={rnLSy% zo7ej^{yxf0*mXec!t!n}@s6$>-FV(qFVnTLFV;_Cs&Vo9wzkLxC>PG>%hRfapcqIT zm6`bvB-y#~r`PgMkiQ>sOT|Y%>?3agR5pGP)RHhx8NP>7&Rk@dM%qGYHL79s`E_bc zpixb5COMPU)ZjE{y7L}qwsWeZn&8Igni@R4I6E81H9$7cEy(I;8e2whdF*@^u>Jg%sP`ax%5`GF=D#g-r(jVDssP&$H*5N?REOfr^@$B-%T@urk1?O4bw zdf{Lxw@_b5yu$d@gQ)IeC4#%0QP4BIR-c0loti*x?bzUloEoRLF?ebleoI27eAc{c zZ8@*1wa2Lm)=mxn!{psM#*0@tRo!;DZeN((Hj*2nj1Ar~Syw5DF!UQ$rACv+1{>OH zYgg$wTaT-hC(PRj!`fXt`Mke~_M@9!|36Lo%lvN;|2IbV*Bu;kyKwz+wbj-$TS}BOtaI?p5 zua4v&uP*i2@h00!LDj5QdhE@XmE|X^l*c~VXP>6#dhGgTO4%o#oMdhBz2_PP3{VMWP}LnQ^(JXP?NpI0#=7gP(>dXIg9 z&mK}sJ$7z!D=Da=D&nz6D@NpkDxqe1>X@heVxRqN z^{mH!w$Hvy4S4L!eD)Qp(_>%Zv#(NXJoZ&S`xMittOIf={y#&6B?62MI_3 zhT7}le-FOjvgL$8ogR6fy2w+0fqF`0x4j|tlqX(PUEyg@Lh49pW)8e z0P4>bk;p4QfcR``;7oU)9%yGDK?br3fpgq(qRc7=upDtk4zw%9st`GTL{Mm4BDh@e zd_m5uK)X_x2yPP03-$``6#R(b#{_Q@yiIVQ;N61z1-~Zvh~Pg79uoYq;1R*+1b->` zlHh*{zAng(LZBV}gvmr~5}YPDN3c~eBp4H1B-k#vLU6rcMzA2*D|n^g4#BGguM@mp z@HWBE3w}}XD}s**J|_6M;8TJ}1YZ< zj1}Z(SCpp+wg|pY@HD}Q;9|k0f~y5TNCZbgWc{%grOSx$>k@gp;7x+} z5V8K=PlVsMM1GQp#q1f;KPPxh^bYzmfOWc_h;mazK81*Ndx7W|iM*0H6Te7`J}YuR z5$pO6(eD<#Mf6`FwkY+0=pPaJ5OKCr|04S5ME+0W9Ho9Q`gcSgHyZj=QBNZ3J4@s? zVyjXq(Jv)pT$YQxUNA?5-!(+sSNIVc<9t%^4#E4y{v;8L{WGF}PVkuM9n7Tw?nm`R z#5qaixkTKb!lFMzaHZ%!M2uiOMZZntYl*mzeM0n~7Wqqpj}dWydqV8bi2Q=!ABec` z)!@;K^=S~CNrXO3#LepcqCZFQBGGq?jP6!}v#`z+aXn&+=?LA8+)2dv z?lTZt%)DrrPjbibeq8bPi52UApII}!bKj^GL+$W{xk zC8FQf3vM8y5*r0K5z&u%!7d^y*CRMUM86IRZYQ=VwNr2x5&e9v;2t6xbEDwRMD+Wo z1oslr$bEu$5-|?<2<|7M@dpGSAYxn|6nvN%QtDB`gG7we_XH0SV@f?Oc$kQBdq(gG zF{RW|!RLt>#}@=KRC@jzoJM)6j2FfkRo61AsK*zfw7iIjLMudGO{|moi}D*OW1PFh z-a{NG^B4A=lrjJJi2X)llgwY(_ff_;?-%<4;v|{Bus=!}<9tZ$PZLr3BO)IqVw_(V z`51AgQg4dHS&@u3wR75;4wtp9cGU${6RA*!4aQuoDYfoG!cVyMC7AH zjI-VkV;sNC_SWEQXClV!bz&Vp@24NeX)$q}Qk#evmz#+gkAp;v!)rwJKR=dazt1P4 zzgH8{&pkx+?~O$C>j5JA^J(I2%r_$XuObJ72)IyR~85$~eXSWO$@EsSs z!woU8B|EfZ;5c1hrq`>>l<*muS7kJAAbbNcLKWPvO{#Z>`*}@uo9U>L;@a;ft4FAO z9#h?Jx_TrAev~sp$?{8KZFjq%yRXx6V=w&KU8R2zUJZugF~6z<`D|;MR#>- zzS*@%^+#})Tr6SeMkwmOXRaRB`$5GCedL{QbsxUUuWr#_rg^H~pBurIZ{Mp2;j8Hp zEckG&4YP14L)_6zoRe>hq}80Ewy-|yQzWGo`m9fpq*my&K1C8*q0jmhiED*E>r*7A z75c1Ck*HSavpz*4TA|O85o&CvpXXJ7^~M=j>*Ei!DiYQt?wO5^hNy_>b2y}5U=|~} zR3e!UEy!KIrA-^KaQ=nq6|AfHUrq(#hPNu#5AOn77-i?sSYd8$=HcN-B z3R%32YubA?I?CqFi;ZQN4DXQZSLW@4jl8(k>tuNOdxEJ84JnJa0kYxcWU+Y%#KtmA zhW8C*?Dh`9Mqcx#%J9ApKbyDR;%$Pz;bl3ScPC`i24u^;oVqse9?0ay7Dgw-%UCw= z3X69lY=-waUwdzc&CC@BH0}LYUqA1KjlAZ~n&JJCubC8c%=<|U zh&{dsVXMZ={WAWS=kp=>kr!J|oeVGkbjcpyE{pfQ@HFl1M&9N<47nO_r|VbdJp!4$ zvv4pO-VY*g^A1?Nv&E0)LhkiZ=6YUi0G-Ud;-47V?R^1OmY?Igm3e2w&*t53@xBkf zroG(9+wDCDTebGSeTIp_cnG5tKcIxE+}@P%;*m}#Q|1G{bz{H9n}ny~z0cR) z_7QmR^0oII;WcmG4ew`t?R~)F)557B61A zm3jHceh5*X!y6#r@w=R0)~VgcJ0!fEzf7jRi+sEXE#7wV%InU^4aNdo;VfuUWhoiXY3}gaV){kLe`DSc}Kgvm%-WaE9Ldc&UZ%I}EmidpQ&D0{EFS zP^+gKT|efTjBS-KUMp_UhoNJ<3=R|TGU)JMzwZI4NAcit6zwpHHXgh$6HVGXRVluk zHp$rLAY-@VP2B9w_~zkkcqjSdMQ~GCZh`?#ye3~fh2K_9yrLEF?|kF7!@kK_@fa9W zX24L<4AJj3s|72AT9DUe-C5oLxi_~- zTRJd4`aGMbz31kC&OP^>-}!%^6HOr#aF=h&SgBpF*HOt2oxG*E`_wB%X-%}=#I|u} zxGJjG*O%|Bay6K}Rr%F5)!uwB3N%On{ba+x zIJEMBeJJftkz8kej%byxPM74U)1Gz(v$hC|p35vcB-dqGB#OH;bUQmr`~#Ymn-@nq z<@V!n{_wL%D{#KEEjGC@ zO(7Ui+_{{QzVH%qciKObx}{5;C$}m(O$hCPm#l~P zNWEXYKTq6@`a-Hvf|}GQC&ra0L+W>(%CR1Gur5#B2(=}VT4XvJn!?Wu<-}r!yeua_ za*$O>_DL7{u}yZ4lG!Z1!UB}Gv9+b}`C{uxac-xu@ExI_JU2!{?T0iO6S*WvJ8F|7 zN|YOY5BDXGWue>A7pMzm92Q1pCdCO%mD!Z&l<2+0XkqB+PMCuT$|YfE5w%SoX2Np$ zlCZ1DxlMwX8!g$e-xk?lF0Sp36y!x3%7u+hFz$%yu(+{Q+}IR()E_bBMf~zey-i#< zN{i2ph(3zq>r_-+M~U~-;=qXLr7p5*MD(FkTptxT*u+&%SuG`QV(<6M#etx>N>1)a ziN+tZkGzf>FY23cxPCIY?)A#f*Z*Ij_w?00jq&zf!9@tkVQ6XaZ$pY$*U3@|!b}we z0+Jx1V&|5p38>Gtx7-{8rXn>(t?Ea{LgA|lr z`C<8TmSr%NL;JwsWo}{^1a?I( zdtpB@w8|vO`luG6ApsuIM)=pMyOlYMwsmzbxcQC~X~oO8I7F-8*mY=ooASOdcC?k< zH}>teyLJzFR^PMx)ZQ0g-Tgw9_lw;xG_IB^94|dfytpvO@xu3r!R8#tXWc~l-{&}b zpC{Tr$#GnGf$(lv?wI&7k$%^5$NxP@uFh}Az*I?kRX+WuMTm>4Do z&ng|SyhFVBEtRADcf{)Ns2qQDn%GjQa$G)5oO@N}_~Kn+@C}vY{J#_4lPbr^8RFb; zp)MjAd^OK@1Q7fOkpI7fx$7lC<-oYomql#sD7LircNPW3%}wIE?po=2B>PBCUI~(V zX_2}wu6nCS>7&!xW-YnH!i_`48#{#?hnqS<;XNwBD$Ng?&o69fiukEW&hR4gVi!41 z%c^PF`%~nUgVf6hRA)8HQH`pPQTym83y!xGj1*gs3JZ_76t)TrhNrR`oZ?5z#b&HZ z#pYnd4{FsZZpafiTup~=8-tNDNu*X033NxAyF+U~o+3XUBmaMlyhsaOLp{og9_285 zJ;NwZYLo*Z)k#Klx~teaRBY{LugCf=2a7Eo!h(bS>*1w;3KzU1Ea>f*zF86Rmqr5q zmilsWlQUAUh}1_TId9!7`xwbCJIIMH@_n0ZoFXs6ET}xynYg;ou0Ewvo(ZYXjDdnz zT_Dsx#STkv@rLJH3Wgo45)*MoKyNm6@7Q*wONJ3pKde5B*Z$7I447%85ym6IRwd9K+Vj4gyci?TIml1xmGM({ z^~CtH(Q(yT7(hu*L2t{(qb<3u{g%#R>u`VJvAA`pALdv%TynHlB8E}b0)VBFoPR$- zUUbSn8WT-XvU4=HHlI1jYB~8nO~Tht$3!2FkrNK`D!uZ(i;NPRvhigXHLCL()qq9? zD>$jS$w&Qd!SUja$As2{E!N@EO2_y}OdB z-b-!UwtG937uZ)<@1`2Ofx3#CYD&A#XkAC=S6A#Uudi&T^4vzR+pRU4X-Y@ywE0?H zzSel_t%dulAE~Zstls3V33%(8tKCd}O;v^ao`A<2sHon%&$827$uxOAP>)N-My0h9>L+$29>@&Ev9=+COw9<^u=hJEp2Azl2`V3~D!Q->)V9I#r71fm$ z)n1sqS<85RM!lPHSs1V|3PY@W9)>E{jXAa~Uiqw^?s> zdCW#FnWyBg>XTz6m zt5y4)qP@MDhx4xr9?nGK;85<6U@8;Q4kAr}q`R=eYFUUJQWL6k!lm9nT!%beRE+2> zmPe!LeR*2m+CEDfks;NR_F$14lgB81RwHQ7sQ6KO=W2O}676$}C4wL&DS8aQ6+XDX zDY!h27Mjo#@@L>Fn!ueo*v^*X&cfbdTWdJ4Q*dkNt_7{D#3*l+2qQ`ocHGK!0waql zK?|hid1817e?zwfGhW88>{gFxDshGbjQjOR>NHCV>T+JqUF~n_938#*?w)tg4qX^Mxo3E^@2&G&7nBm{Ww3V| zfFv^`kOy`|yuZ}n4Z5ozG`4l5KYU(!qG#cx9h*5&ah!h6HoWg7KX8EBmrY>hFZ;kj zUg-^n#LeLNf>mmYfJVhSxzzuBzvU=VaHwVD!G6IbVBnNz#+7F%|mX?s=Yu^q&!Wi zCkb?k=H{~Ej-jp{83RhFMq9x-D=Tw7;;#o$(t~W8IPo@dM35aVNWaT%X50p|*KIK{ zThNkLyL9)RZ>~8g9Lw;_GyTYkI*y0dqMsr3>YNk5#;Bgg)wK=L-D2M_Uwm3OWQZm!e(~PSb(`Xx84M| z=-0V;&hDD(`an%(SzzYGwc3;_n7*3^4d|vl46Ua@msz*K7+RU+{QcLQzx|E$1&R5e zA&_sWeZz3yuF1kKTf00*w|GCf;w_?AV~Ny086{nG=DqpgSZT^53;O(cz8p3-z$X2^ z!~GlJ`vd+2 z0WMm-!9`=<2}y636z3dy?%DhE#IdDgwq;}BowJ;BmO#7j6z3o8w+^1S>x zKPEjlhza%sQj}K$6E9$50{_8au~^I&J?*C59uAZ7>taH>2y$LbzMqN-E1NxGH9f-e zMDGlq06<(eg+?N>)1ct&2gnQaV$wH5X0e~k^9kl3!(G7(ey@B_ZB%@+@Evgag^I5D zrkMTqUP94nSLVG3xg8{`rO3N)>JAn563X7t?H92(e>=xdX6S?Er^RV`aEsoIiX>%a z9&kdN-OcVf@UayDA8m5$%m%B=p!IppaJwboWh%?yi6yPXLXhL-AY#VS)vBL5$l#h- zXkCm5PD}0ZZGy(`woQ4wObgVL0yR>i6*W{Q#LvOEgbO^91DcgRA5bn8dVg_9H5_01 zUNl<(79!SvY_lJt$@Id*Z3vxMT~rY5Uwg%l^`yNk(mYCo%{bDZ#?YWMqnyrUW&C9U zE90MIX)eJ!vUgg>4`p1z)G;jM6qfNZ@)LB18tb&bE$%KjE)2#Ip%-nr$pO(J&)G*D zxOFkBci+Lw`w_0QGp&@uQ4A}3)&4eg!f|;4%jKNhJ3;OT??{#Vy8v^3J#m{=?fP&? z`K}!sVXS9YLz$3w)-I>B^6sf}&0HEItXY){%evd+F`C^*Mn^L)lgYyIHM8(Kc3HF3 zrCB;JU+-?ivi_Tl^vNh`O8WqY#Ou5p;_o9xn7osW$7{c%8oNs}AEuTMarhW738ffvvKFA#SlW76tej8$)PTN8NoTo14DY}fewc%5MJ zdhM&?HSrDMB>_I))&9fqOEZ1R=u#h%&3TcWjNX=%(G;6pRp+1WLxTNbseq$PZ*_aT zdL6@<3|fy>&&g>#iQ~2X$M~}9__74w#Z<_-d(ol(wSOw=`P3%JDe?@JOje3pps}26kcoM5< z($~J25^E^ydz4A6X8A9*PX@{Iv5Z;==8@%gjKk+{?mEC<|{lqR-;Z6IAZ5yy(l&au3dw}um`yf@n!FJFzp1eJX z<76Dru{~G;sAbKn^>CypBDHt6g#Ry!vfn+zP`; z@%!2~%|E}HvD$Wcj^~$oVl|ZQ(JXyXljUPlVzngSq{eFgKt&Z(_sDEH!?D_Q6=one zq_lh%m&3WXJh};G z-;i$dUsE@+RDjEB)@#isomLM?I=8`P;&{e>J-jq)t2Jw9DPhR z{JM#S=>~NZMrE#UVyS=?V`i)#14DaE9!O7G5^)5R#Om6*iO8=f@{?HIkZuw@_>JhM z!3XD;-RtWnMtu?##h=qnb>4n6OzxT^hb!H?BLab?UY9ZSq{C6sgZ?>>)j&K!Y;`NQb; zxy&Y$(M$WhRyr}qo;h<2JEtJ0F(g1oo+BU3!x7FK9qDgC-gC2^Zkjh+ma2oddTAVF^ z)fKT!vVIJne<3`>#rvDt^nWKEBg)F^%FF7S>)cFbWi{-%2Q{pGACsN6Uk9ktslxa!C1_(mtf^ zieV;9WB;ur)qhLm0N6Yqn*%t^`fmtwd51DS#s1qQT)w2XEBNR(@dQ5R!etFovVAZ2 z;e@N~KiIk@qF6@=NB>luf_V1D9Vrc8;~KIK;x-)k;yNxp3j=`kY$DdhIl+M$xq<(a zver27XV{7+$=_$%*BosroRR10TXRg1Kh(FTH@t#`V?3WCk*8PYACXnEH?y8tVEK5S|Wpgjb69+GfUv_mdE3(DhB z6uj@0J@Z_Ue7$%1r@hOOIG869K{CmsA*oeA}I`3|6q*=a_AjlaX z?`LzyVaOS$?LQ0&cqBVdXTG`vq66T-CQIaj(q~u>^vkaH#!JNeO2rN3;zk(Wc^KYX zL?T9bO_1aYcCn97^VrdhPcW~H!sSak$zzEp*c=r5M69@w=fBtbFtf^7-rR1j1CV6u-Ac$Vp{Z6Pxi=ESJoJOq{L%v{Jd^?V6Vo|{hJA`$X}=zIfqv{UfJ1HFgU(j{-O5CStdcHdXdt{7SK#eF^0F2b)*j zVC?2d!5YUlX^}bmP${4%_o3D&apq(QjBygiS^H2d%2lvf}7W_b0nufnTXFYE%n z@bb(&S1hZjC%ZJ1of?X>I)7b~UsLpgkAVXx*NVn@y^zuX>ji_$&FDQYk3|b1lomS? zuz#GydUj0C@$C4f>hTn;xtM%x4$n^KzsByEH^$uZ_zYhCiute36kgo~_lF|-r_t)s zkaB`Z?3)6keh!XVPu3VB$D&y!8gkNBA#Uy#(-in-*h!;<=?|2&?UuAXP@3*d?)hak zP;ly3s2j!pn+dgi2ik*EH<^A;HDQNiV(j*|hTYzVeQxf?DIKB6SWtEqNnz*blSuTE&m8_Jc3ny6<(VKpbcgmeDDOceWqxiTS zj2Uhk;2dw0xOph@ILsUSmWCu>;FKu(Eo(2l)r_msTUOy_+~u>P2$nM-l$g;3c*E#6 z8}yKuH~I7iqub(tqJ7}xwZUFb25i1BomP0W1IL6> zx!o1NJt3&Gf{sgMu;D;jQ*XJ9q3Dzk(lf`H@TdX>r#ca}Z zd=pv<`;lv4Kk|Oyo1X&TIDu~lfN#2hZ|F=oc#wS^zOiq0*|*NiH`(944&QWsoqY2I z$Q7TXz`2Nl$op-}( zBF&&7o zah4>W4Sr_Z4_AGHWZWJBJT-l8CkncwZ$@1B7~snDfCladBK>XX>*Rs2u=+D{3mG^Q z4nD<}r2qFr=O(`@p_6W3Se-vP2!=Z*sv2BA*pb-g?belNL^DVf-28w91_A zr?qhLTXl83I_VR0e%hJsvtx^CKkdx+dHuBXvtNgwR*J`+zz*ll>LG6i*fDDG(-M%u zF+uLU;5cZssmNa`BDKl9S<>g7i{b3ZA{9d%R+!8lox!5l=^@LZ^WxKPEDt9!oU=#3 zV%Sqt-&2#s@P_sXivIA8>=Cs6;YQ+$9*R51_T#i)ISA?%q|vo@$TdX+k|&qjI;5Hv zn>*y%qMf9Cg}Zg&IJLRGW6|QvL3vKm&IjcyJgpfh3zF`^43rM)G@52(0Hwo(1J2pP zLH#T^-x|CPr3;`+Y75~ip#xrrGKehL3Jc!FJ(Xp%4{Ig{BPJQ>WmB0Uy76O;zY(W#3; z@`tjkQ(pw-Kand4GPJmRk%dr&vVOg|G`=yE{ZCm<2TDVV_m+0s9|gfxJ?L{tenJ79Ko? z&kp0g=JhZwI9|k_r-fUDWd?t6N#PPVg3p~$iRa{laxs+ndHmt)@jZnvi4R|oOPmqF zfdanAa>$oFeNlqWmpmO*7Q#*jU-ES917SK}@^l=4U^-v&bS==*;h!&gI^H+HbiU;2 z1qnJ|@^l-}asPbD)9*;o`I4u93+T9izU1lm0uAH9mpuI;pyB@clBatUbiU;2l|aY+ z^CeHOP0;z0r#B?%e96-vP0;z0rw4%!EQ9!xr*{GkkDo7j`VWA%5dQg+ryokR=S!ac z(*&I_dHNfPe)y87zX^04Pw^#BKb@fSB~L#G^lbR&OP>B;K!cwoBfjM6GT?1&WBHP& zD-v|R04#5;EQQjxly17qQH^+^v5``*)z zcp!NTy`>~^X2tE(UlS4AbO))Pd}?3QfdKDr@P0>QWo1LvI*)7bI`}!xKCf24j)osr p;hz)b&-{_qtRI^vep;3I(K-IbmQUxln9No>-@SL=I>=BU^gqbzG4%id literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabihf.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv7em-none-eabihf.a new file mode 100644 index 0000000000000000000000000000000000000000..cf91a7a59012c7d74c13c0c6b75f40928440d285 GIT binary patch literal 20480 zcmd^Hd6ZSfov!;{H}payG$0_L4WeQPnzt_ol~qw1#1$mQ=B?17yJ=rH+k_~=CFnTO zBGTw;_&&xp|&oud<+m;~bzGcj(RIL^4u_tpK?dv!1GVdmt|DZTfr z-(K~rx^?Tmdz-0qGNs(wlbVhW&yJ+pDkW5@wz+lt+}0Ke#ljJ-v$`qU-8Xx1?S|g$ z#$=&)R^R%*!mL6j+r75fv0h!WsPh!Zag-^JnxQI`QY%l?lKPm28EONi5A~l)l6r3r zjos!_F1>AN?2dhjn=JamSS_WFKvsKFP% zVTT=CJzVkq=FljQ?wdo69(vnQqsMlxWvhPs(Qi$k+bn*_s{g>si<%ZV8oAki(}L}i zk!?c_I~q=Py_j6Jdg8q~GSLCCs$lrcrRFgdhFZ$?@ zQP?h)VK^MMoG=1Mof>kMe+v~|swh?y1;B(4LY+QrAI@m!n2}@ZgCj?cpEUBG`4dMw z=Z;q@kamJ2l?v85r;X{I7#!K$yu&#R<}*}qB5tbnG`qE&+FmX7H_?^}n>ouC`veDXx4#!gY;F=Vc6KEHVd490nNP8&n5 z!|PQ*jM(V$Qyj0+1j@sZOsrRvTUa>)obhfLT1+BI{^Vxe1f{0L#N_DUXG$Gq zg{Wt{RAZAnoH*+RX|kFJE=#8i`W!d|5IBdY^KlA3jnkDl9H%Y^P<87_)D7SqsQWz5 z!Mg2atNO3N>(6ln_cb}go_8y8h)@Dw<>>~VzK)Z2x(5|F-3d^2x00y49p^yZ9XJPZ zsK8#<*np>SK=(0#s{1(!9K%=h+Xa%0gddL~E2-weh%4ylGk@`)|TUkHRb=q(_ zh&#wQ&1tv?_#4)jI}I-ZN1#W66;5L-@I=-xq>*V>m+N7~B1rlvEg+0WEoj(^`gcih zbQ*sE{59)0*&c3oJv9CSl2%-_fm?0qZLW005s)mRbeH(wr3DR3!P`jwozBRu!0)nt zkJIo2;IpjX?=<`eFj$ZJLr!BO@C4Q$)lphbE!SI4FIUxJ%TT|V^b=0YRT`<@^5t?> z1-^p%i0g5Bg3MQ?S+8=?RpayEwO}O+{E4(l*6UiRMoffcDW&g-)jO`$`QTkc{(tGl z$;iK_d#W0~0m*Zee&mdL1vq6m>aDn82WFvGAHk_a)-1;vriWmbquthD3GQQ*oM~_LbAJ4Uu1&yH73C{BI;EeAQ z7Da*S^%LuQSW})>p&d?W{L$h-TBR*nX9>)#YRL--mb0r^x^}RP_$+zfa#rwib3#W@ zi&vcV;nQ%$kkW@q$D@8Kc$1kN=3$DnoEJBW&W4*aUX^IYYH5Y!OSfOE;uJXDv_i9~ z!V>5-Y>z`;+Hlx&D2HbnORvMT4cp_8>jNBaK9s|i#?tF>m0{!F!zR03<{~50z4Be_zE*2_LEYxKBc z`5PHvOcWVPG;*ZoSdHX@hDIJCnx>IQmd#dhnS;i$USIaa=i&#Ah|h-=g-aqdPV#B! zk!G+T8BF5fxmrrvPxpF2k5+**!8x;_1-jY18k`keQguGKrj}iC zRTWnk!Gf_5r@Fq-zu>yspB{Ugs46CM_z4v za&d9?JO8Cu9liW@#ko6kxpvE>_=8v5b{Uma|Iy_PUyAE&c%2#naFbi7%u@kO-wUj`oQo`ezxq-E-yp|;#h_o`l~(#`A)k(tzrit#a#21vRjxFQ+nt>wCL%YC}q$Rp`lVF64=Y%s@fS%U!gg8)`tX z)Y*lL77PrkGfMeFsk?8DD)tVl(xBQHR-J|7pgN23)q+CbV4C*VDbG zuNOR3DhzDsf%Q7Is8m7-O`$!iyRWCaub{eCEsKIoxMZTME4!|LFq~W)j)rsDTr!i3 zB@4M!EVD?tBA-Dx+|`v^-#1uV-_uosSuPZh=W?NZCKL@tLZLLx%5t?K8d0S~c-RCF z$#^arN#8k$gdr2jcsQ0yrIM*= zC>P4*jY;8PlRSoe3rs?ZTqGGwXJg@FA&DwYv`po; zA@O-f%6bR-_1I^l>0G`Ljbt*3SU8`KvN>8--GqakFCxK-NHLyCrnBLgo-Q=mq&8-H zd}io&-}-*`Bc2GQi-k-kRVcQ~lDZbTS%FCL-ZzIugpovIz#$vg#)6R3@28=VO^rK9SExBPl%(Xrkw?b+MsC z1BHz+h-HiUOg}jH%yq-Cbr2Hd8yW zu`;Vle{V@cV>``t;)!k;ifSPO^j@PcZklYHU>^~mC*3&<^mWX1vItp8DJw>*`0$Z5J z0Nj-{YAe%cOc3=Jw!Hc-r&dBoc0hAIY9&?l(3{j(@yyoM#aq-vI%H+(_z~l|Tc2Z5 z)tfN>wrh4;=c8eq47cm#oAJE~Tnq*FL+W-Yo4wV8nqAq{gmhc=zCnGiTra4!XC&=u zuYT`wu}S?3?ztyB%WV^PeZR1pvPpdk0=;V-u6xGS{uHpxj&ZJA*Skpm^vo^d5UbguW2!^*K1(sSDKCHw7YVzK!DBn{YaANoljdD% z+v!!MJx*P)ethts$8Fa>Uiq9;Rc(u__Puc(wbbCHDfq2%x=BH}q2916EgIVtZ0V@4 zU!whNJg89~Hy^+aTX)&G)BmQhm#%a5KOFnF>0c%K@7C7W2@bg_Jm;X+YUv5C^z`b| zpW}rZN9Tb{sw4x0_qxb$yrjDQkjTGML;k+VudE^8h8K2>e_4(Ampe`X%i2NH<|?uK zpNp%v`x=q|wTAq9k-u3(zSB89aJWBiV^i>6vHQivRq_EjUfbyYJO=qe?S}jjk^i)Y z{o^A4aSiz|A?KWXdQ8LaT9YnNk3cVp;)9>0_>n}s;^Kxm2VY$9^yPrtrFXwjLt#hI zRrp|Q^_+ZJ3##erXixs8`{c)|`#k=S^U2%Q ztsZ&1Pd-as>ygj$$wTTAkDR;hN(ri{>hs8>6(MRtl~AAc$P+$!T6KEl+-g-yP|Z=F z_Q>Z{gs278$tvc_&&fXdd^N=*pYM||Qg?g&FY?J3tD8OY#Xk8Gb(KfH#3x^-ws_>r zeDX8ZT95oppZpxP!XxK*9hDMPE7U0-`HG4VwV+z1;vV@bpZv3`!;_!S`sAy9bk;}b zeDoS0-L1yMe_NTmOzlQ{Dzv}9{bfy7g7_7duekBQ-Yd6)^On$DNm{YKd>=?T_sXqU zPxj)OrJ_GV&G*oU>9?1Zb0ulTe@CG`q+NgGRK16up#CKGu6&Yu7RnX2q!5Ma=eKQ zNrWqnrwT3=3a{ULkmm;0=O11#c7FC3v^sj|G1wxKHpI!To~2 z5&XU2tAcL`z9Yzu3EQthtQjwk@I9+gtU`Q|~I7e`<;9|jZ1T%sK!Ct|O1h)u& zLGW_HD+O;5{I=ljf_Do3Sny%N#{{1c+%Ncw;2#Cw6$}R4{tg#BOmLFmQG&+_eo8PZ zm=ru&aDm_w!7~IuBUlvVddEC(6uemQO2O*|ZxZ~b;P(XY7ThEFh~U$L&kDXE_?qDB zg8wZz4C@fv(Im(Z^++Es*d}<4;PHYH!IK3S2zCmt66_Mp30@?4iQuJzR}0=uMBDUd ze`v>DLjQzVhfmQ&@85-fiHM8+&%%FKkoP0YJ!}aA(;zFhN5a%lOfY6T%5}Z%O zI^0Qw-U^}D22cxz zo8a#R-w=5d=1c%LiLpesPjII2=MiyVTO#~bLa!m>K6jDu|3UCd;eV4DQEHd)?-lw{ zBJPJz3IBPa|0wt|5% z-`*|!p9=jH5%=Hy!hcclE#VKtHN*B`SXE#??khxG*O*%RI&LFEID?2jAT|0rLsRv2 zG?$3$WHAxO%ZZrxD~XubtBIJ$Yl(2$PsIG(OvHTLM#TKvL2Og%S|aAvjl}6n-9p5? z*+razb%u!XzmJIV-Alwc?jwej{+XNOv!67^;{XwPevO#IJSHNK?-7wNZqAq=7WTVN zuz?5yONGW!MC1Wo(l~(#C3Hb!8xgrglQqsD!Wd1|h^Fa0p-CFi6rC?Nfq9!tMBWw( zE+!&ar{HoT@_3HmN+KF@f#7N)@|qW1OGM*(1pA4|^Pu2nVw+N11-B8A_sax#5Yd^d z1+OJy9Ig|*k%&(26ugCqarutmE+RU=TktL-#_1lx`-mZ>9u(Y5#JD{wxQ`f9>Pf+; zi5SOc1@{wEO1&U>fQWH@S@1RD9Hm|te2a*2{)-@nQgOZ;oIv_i8BfdubWPLff*yZ_ z(llJ^@n0--C$T~1JM1qYjd`$Em7y1Jt=7HYNW1N4;eAMClej+Br zJH!V3p$qjejwcgGU>zf3+^!{Jy!H|?PJCYH`0(>yj>}9U#-o#nap)l;|5p={_uWL~ z`$^(7%vU1vTNeZ(ul!n*`CLdu9xoswfBX{*=4~et`QqzO=II3@@}u`r$V&(M!hD=T zL>~Hy=)c|{q2H>bROsoLch=I5!shP$=8nO_=D`m0wNrJO{YJRDhIyY}UFv>xQ(fl1 zNUtt4?{+uUXtQZoEjhp4>Btwd8`gAXve^>jN1nYno%p?y3}Y_ z<@>Da5zIi;iolN_YFL`jj_gc#_Z8RI(6>Hi>gZcPSm-!)*}1a@1~a*JH4OO4RQ1q& zd9NkzsOYaSExK63z}7J3M+UWI-Yp`K8}y%NuSrr>s>%ZE6#&ix4smUvHr8(sK! zgnm6EqXKR(x(s*q`nL;>u=QF7)FGn4>>2fjs{W>_%EBE&T(2Q$hn7I5- z%kWTD*IIGu*Tj7QiL&G7MMfJI6PLe(*m2iF#<$&zPSA& zbG=pK@^>CPF2{>;%^O1#x5F3r7Ax*3@ontv{%(cL^a0g!e>rvSxH~}89$O<_OkDc1 z`@74E%fCc1{hf%49rs$u%v_;Eljp-+z4G|p2pQv=H=HJJGb(o6yR5j_u9f3{?91~l zkX4KOS6`lYL631K;9xOv-}dGCJ}d4-(WBifzPNXRS1qpogEebD-v>R~n>Vs1?yr1t z_gZnW4K4TgDJ0p>^IpiR#eLM(E9ZG1^cWXgSzS!rz0kAsyw8ez6f~(vyD#Ce<30_# zTHG(VdgZwLLDPOJ4i*!43+i^(ftM2~jdhud)vhzy{MnO9j?uN?PfNNGRaRV&B6 z5PEjp{Z`y#plkX&(--%3$g1^snlJ8OpvSn!;b1ZSJ<=EVfE9O!=+W+Obk^?g2jEqU z%jYcoU+!-m2-@S(Ll+bGJK)>>ea(u?&mv8K*P#y8a;y;`s>RK?dgZudp~twhaIl!T zd}C(EeaniA$DwlEmr%FkP6lCoKvZ5go_F=iaoZ$rh)O8N<~h{uxbInU`OeAo*YRDy zGit>BFW>mil(^=L0uy)0H@+MQ=7sBd%!+%9FD~En7#~n8_xA=@uiW31#KohcF2?4o z(6js7V8u;B)AW~r@(35@F`Zi@uKo*TYhEpsxM??RxvkIp`a8;si^tb;T)scC<961F z%jau|%Kcp~ap(Br?()T*V8uPrihG4G?n?N>V|}?mtPB681v~Db#5G@Rm^|}u#qB(| zS#jsWlgTr$DYz)-c`Jx&*U?m0uiW3uB<_6hSxnq1sM~R8SaBDK9_Lx7+mCXrtHmEg zxXqYiU1GZz<6tpy z{{?kBZpw;#n&{E4$=BcAHRAGuf~Xw#9*MgIK3GiL55TwM&b8upiXP*xbg#>DA0LF> zbUKn^{4I0!%5e`!++{w!)1ha_U2MfY1G@CbxLbX3`8!#)xFuiQ5$Hed&&0uE+Slic zyWEO>VaLtah`YemE644TxV+!8n7CZO?700_+zUmIai5fVg{m%t z@YibyAlt;U&o^H-!yos~yuYo+Ve

c$3D^&q%6Ob2dWPRJ5&w)Ea$pK|SmvW* z$8Cta^Otcyhr`5;`20PA2ai+fK#K9#;qy1j^49}hPqXX#rzfhb=jP(U&`UwV2H_@geKWMwl61n z|2w0xWP?k(ZTIXPYwpbd-nn!Czx%)c`~MhgO4xwAa%1{(?K+*AP99A1lIE{d&or$y zXiY}0jWgX={@)>Jp_U%S859=lSMi4cVla>*HW=tBBQ zXT}>!vVKhJhrbc&Cl1A@Rz;1HtaXqr9Oa`Z^+AyOEJpnYy_wLZA&nfNe}G?xNP|Ss zPZs>h(DK8!A<4s1rOxsq(I#J+CdC~uUYCpGGcarMPe{`*e#SZ{u?zJNRcwPleyWIP?Zjh`1QiG?iniITeI zplXof<0$o!RdJnGSj~OnVkFtn7A`qzw~W|xyTm2$iv85}F$!vLGE_|Jk|FJ=Rf%Y6 zZqHTR7a7Y$o6wgiiqcPrdlW|1c}!JU)##G+YGSl7bo4OrAcb;KtFx5erfg+fmC8k} zu2SbV8J=pi$Z*gaIao>7^+k#+BSwGZfFIZkAM{5W;ra}DpfVhgk#%K}`Smd95$Yf} z^n(l;=ppNAvc{QyGf37%sU|CV&`CCoNIzGSfgpF?L)Ot`^N4i3hxGG}$0+;=lL3u$ zG~1|^O;1hfetF*f+co6A=YQR}q`E9kMIZ!!Ry;IGkdXhVs~sU4Ze;KaA||NWc^Wv9 zz#TM0N+e~DU3~#p@y(DZhB}^b`=P;%Hao%tv-?qJ&VJWa54;7x2n#Qbv;ooRQs#x^m;^$@$>8E|rV#bg@X%EjHl0^+u z1*5X!zB%?sduI=6u>yt^g!<%=o+*Iw%ox%w`+`|RN?)OpaF5aOC=y|m3QraA?7|y) zB;R`WRRTHT4uimj zqFFE@+`7}{cdN4(Y>Rfyd*Gq-5_`@ThjiszPaOMZ zyL#uB+uJL4j(xlRkzIqHm5=SZwDv<7`LYQKJ3hY{!Q$6W;YXj)_-@v`2Cr|N9uR^06F8-;as3>|Do{pAzTx7U^wPWl&vE_Se$0tL?%KxQyT)9ZJ z|6J{u7$(kLQCm*}4yOR2zX!hbvY>i!T+WWV#c;v=N^#6e9&scTlnI899f7j!}1<#>L-E&q~6eL0kWc?=Y5 z-iJiKPqp3LXJ3CbTs-Vpkzm9bInYctcW>YJSyX`$$bUNjBCDR%CcFXWU$(guiXaIOD87@0rCnI50bpT*_B>T7L zsVS%8)|m7*t+>u$E&sWLs#Q|g7z%Db9h2T1qb3~G9cKB}DOQcQkntr`n!FpDyg^MK z%;2PEsgM3)@mc$ZGh)k;uw}UXEX+PIdl1H1hP8C|1(V_vhMKw!eTE5fxw-vYOgrf9 zI)6LfqCoaqXwdJlxC8lRw7pZFJujduqnC%e4j=x_<{o8%r$nnOeIcrOrCaK8*rEM% zD1Dwy)#+D9Sb1wy*EUFBLEs9(FzUCq|+rMGR{ z^-a1U&{*H#rklKh`l|i4w03QgWi7L&wrX!>Lv;&X;4bpI-P$4(L+cowc8ylIMqBia zZD{c$%RKjvl~2hX}`7z}zBYtZV8jAj>O z(OGm1qh$@O$>1t7z=anh9AE=2>o73u>I3d|7@c)IJn(j}%k0wYTn4kzZPHs@9#fH) z_4zy=y$QO|YW42@HU6qgfs)!rYpR6z>x=Xjok?$G z%&ghGrHQQuLlNY{HwY&QxyJA0&gPv2K;1sw7s$)-F(vm*E^k>2M zMeBOrM1ItHnkYm+M@YQbN~4%H%?f>tB6Q9vR+8tPVw${ALRzKsMCzDXLZqiNlr7l5 ztjn(Ki7BrsB?X4_m`v&H+sP(B*&HR8?-Ye%1Vc6iX(Vf`5*=#i&6qiEV2`XGDycaS+X= zx91zt8%X-88fCW;Dnv4NCPTkKWX*^*gtTEa+z*W}i=b(gP#%f&fC?Hv&ea;P-tavoAYD0TMc)Q(AAL1`sQhYS1{OFtBnRtCB2 zF=@}(l1d;3rH5=JZt46PF@f70%`JD0Ne}i=a6YO!6Y7#YP_V>keA~E0cS`@#skgR^ zj6tf*jN3gGHpv*`Q6u^E#9xV5FgN_;i&1@MN zXuY96-#dTOmJiz*s4`v;XBn2KS`k9F+4BJ9vX^nPajl6HQJhk zP(_7npT7Z?jULvakzdM2o(Sti3oG5_HnDDl$?G;7*ez<m0KA^WIQWXmu>UIz|Ku z`jWH{#YE`ji`0`~J$JU>Sez3STaV3m62UYy(n5#i8l7jwXX?#eVyB$}OMJPsZ9%J3 zDbY*Y9|v`h*1H`eAv=YXN-;O?Z%dr&H|4RtoY4;BWNC!H38lc>Jh*cMQE^t&U-*MP>9FJV`Bwu(sp(aSm6Ew(dwkHhklP; zo+&tO`T~1DjN5^NmZRdnc$dvaQWj*j%JG~huse{7oe$^&c6d!Ubo{dQwY(d){8Y$B zk$lLxbgXCTk%n&A*e5`!u*|?8j~_M2;rHlmX$pP^4$KYU0RYfc z@);E?Rq#;2nNSsX-7tOj2ErbVl-J2wRR}8 zbqfzt%PtZl9*2{fbnaf(9X9uss)tL#YZW!BUXp!4Q>UW8;%=KpX)x8cDWy-s_?Jsb z#9{a!7{h;?g&~S{#_NK#s;tHNB~;ltpyA@HO~a~8@3@D6m@2vi%TV$qNj>80oPWxSMoOxy#HCYudnjVoCXt!F{Z){m_dRK z2Cdt}=zWaOrQ_b!W|QxF_@UKp;#j)>cDf%q`Q57zq1TVuv-)jn7cqYiF&_dXhmEj? zvykfQ=Ds34_^eHktK|n{j)1 zY}or^L+v4`IkEYlsn~F9cbv$X#9}grPrR7;XNU;^H1ZuX1-?4|%cVU2p=#s%U&;%(khIP<7eV1y>=)f~0jc_2|;>P)Q%5 z?h9?2!q)vJUcO9%d@Ym|z$LoSBb8NDc)&1iaksedf|08L7#X8mXEIn^2CdI)g3B!d zFI!y!Pb_K+;kBL(%TQk~Y#PMcX{8A(dw7+ov9o<+fw1mH`D3Ddq(;kXPzEYN!FR;- zJhH=@<-H%!SJmj+LLzT4wD_tsON2(1eFJAUJ7B{}E9q`W=={pk^-+7_XK_%Yr)&_< z8D(H^IXWO=qwVwhof*JSLJ!;|I6d$o%*G~IscEQ33`<;1!V*75PGD*eo+*Tve-HI< z=rTRlW%~`;z5b*)7)Jz1`clV-ebbWuT}M)F^kXG(6W7_;Hd^Jd!-U?k9fnSLVPB8c zbYhPi13hq##Pfy^mPY6?D24gNx_m{4zBQzN--b79tczDdnOOha{+-6He@~5T=F}9y zoYlDS+IM?AMJ9IUc z^;q=$8n-2}b!6OYe~&MDI=&IVm6tyiF(!kUUd?) zSvFDKvsS7ymR`qX5U5)A4!e8V5pm97sf9C7TN_4|U3e=>gI5Xr&~+PUYJP-KnzreY zC25aF?*XNQQ<~HEX#09>bj__B{~=X38ZnkP~N@2)b97+wZ8xj z>&7A@WAS-e7D7QqU}y3;hLSkm+qR77?}_KnsT=3V%`l9Fd~rVF#@Q?;b^lBsF;(}^ z;Ul6fk7n^xnoJ*?;v*(yDAh;w2dZk=`hBz49`+HZtFSP+A#CO|yIdB7#mKOD0WNCm zO=58G^=EtVY1@NIS>o5<)aE(Y-_+pT>+i8Y=la_Q*b6c;hu%V2UrTTK@2R&qD!^tj z=^{jEn@z(y^=o^SI3<4u>_CHp}bo+H+p<`@dz|5D@AUf%Vabb zc^RMA!X$Xq+{I(7b7W@tF72)6w6~BMZMHF$5R-8ds6j}nY#a^O20_sRw1tl?%g-a~He^V9Z;JJ!WJ@r7$SF2E z!~Y{1F;8+?3(S8BJj2QF!p+}+OVq{0h>D8(%8L4ydN*5LT?;v&y)&`U>QWovIrl>T z$>6qFz;yFkyxN4lk;J5jnznUsCG574+7&Xq8!`xUo#zF?420=?dbxoOZOq(G>)ym7`c}B@~ z#-{SHt;}%0ggudld7K$<;Np&4yrG+mH$YYg;tkiZ^>+eW%4nMkp5P)zi3kOb8u1Z| zl%V6yI1Z^PKH%yWNn@QM9BH8AG!gaaOs$mQUfW2s5AK`f9 z;EXuLU&Gi1eS~9eJzp88M~))n`O&hWc0cwJxLJ)16O|)YGT%k0`3S zi@FiTBgMnvl3={xZ0qWg*21%*)ewo|LsA7d8O7C}(*q?#V%6#X!k8#GNMuii)t`lz zQFpk<>qivNm-IoLD)BcRs^ZoYq>U2tG|0uOeo3DNd2;RF-%#HWVEy181!k##Y`9I= zgESe;UX#mX(Ry@VP$+KjO2KZU9*~9ewkbP`yJ>kdOz0=hR%SB3>SkrTAC(i-6$t#v z(RQW$eNY}PD7f>ICS%-6o$AZ^xGx8h!2+2S0$0`zGXhtoc_>%v%<{2|H0UGL^=Mn8 zl9MYLf*AHm$Rc(?>!rG(^r|1nI3m?SX%aa%MMoI&$Hw-Q} ztM|A(W-Yi|T5M!M&O3?wY=54YmK4v7XE_4K-=4B3rsih6WoB8*@xB?a8wC zU9$Ek%hSBcykuq*4POL{b)(qMGotW!pgkCWlWEuUCT#F28<(2baH)C7(eoEh`3OzL zf{Hsx4%w(n*1shWM!6StaxWT9(~Xkm$;ckZ5Su?}dpOdfB#(2eEhTWnueOPvrElUa zzcZY27JqLPf6@nIhKr_xNK-S}G88!kd}ABbkdzM`YDK^1_7!g}>#FuvRJmDq3dUd*jKKn&e@cfB z2QrhJ&#a_tV)NOwC%#EARA(k#Pf@|9!xH#1DEGxWIuc+a_0~v(Bhm;v_8{oJXc}x2 z-&=8OEE$K5N^uM}8CVSFo}H0@{Wy`5D&|sBg6|Fccc9WS@)P@SB|o0~%MafK z>lmHUTx2qtEjpdqWYqKWLo9||=_<&T?gaUH9ptAR#fF?s!VM%mZJaWkN6{n2yrmQ%p#0zGk2X&oMDYP%xpVCvgmNL= z1K!*r)Z-i6UO0q$T!P;D3M*TDjcqfb6zB^QbfFaJxIY{)5K4i*JV6&qfsU0pZZDJq zT?;hKuTTnf9HYT>p%m!F3A#`UbSuzt|3WFyA4<@LQlS48&~g7lDbODW8pc5=1^OPK z;r@kEpnDT^p%m!VK*#+Hr9iJs(1lWoJ*IpKIDL5_@%0p6coSd1a358`39{T3IMvN(VEF=`z*(|n zUI;F^><3psEsjN3;9xC|UgA?#YG@0_BE&6{J{5LzlMYt$5_(H9SZCQL)3^LqQ(fIu zv)1F@Z9e2!7yv=d@znxu1UufjkQLdZfkHajfZsWsiCH>xY!7%@Z` z1EPsO;zWoei)dzG1d%~hM#6{^h0);PGjRls3J8xdAnhoQ+r00&->JIyrYbs*|K`BG z@A>v~zO&rZ_g3aCP8YL%=QW)XS`?0UREk}xb~ttSy`v+Pv~7p8xhc~>w5Zg#Z7{Pv zF}QGOcqqRxpU(7m55IrK+6yhqQl?m{Q&lLXj>WX3KB}Qp^;7z_k(DH=_xjkBJr3p2 zd&Z{hdu(iYznfQlxT2qN)vY;7~_~JM0bH`SX zReZlb*5=WDeXP+#?-^_K*e-S1svrIFN2bpmF23!m-|NbYnj1I+x!HT$^1YIgJ!1{~ z8df@9Os?8J@m?RBwCBi!mGh$IIVNJ5$(K@+4 z*xELIR_jCO&zxjkK3%Cm$_lnB6|A#XPad2ZY;A7dXHA58rwX>tMy0;n8fp!;p40r! z`i^F_vL1XAt0yZpejbSPnw!CI=vJcEOtr?cRrBh}WHdEn4mU>~WAM<)iV784#IcsO zR=j=Cno04*inegt$~wAXle*Er_Hj#R=;k#qnW+8XmAD$cfBRdR?EO;S?hql2Q~l#m+^K5Zoy-?-Gs}s>aqY;x0OWQDDHu}_u?L` z+e@~p|0ukE8&~jXlQr%KPQ}@7RN!M&{{(NJqzRoqj0;W=0aV?cBlot50Ej_YT2(*3mSfmdJ|@Lpwnt-2cFBiZB1AK9AQ0awd~YL{if#Kte@*RZMYG{ z=gC-YH9Q1-p7o7Z!_R;d(4#<))z}U^m-YA1$TX|h@i1WpBqNmO5k{jHH0(zG9@5*b z#(RN3Wc@a`hua+wjX#H^9m_Isr(1fLBb{&>Br7OAEdCE`LBl%mwv&Iq)w&ya59<$E z4fg_{W&O)m!+!#U^{9W%YHS3a!}=3CO3TV}y=6_gswS>S{W{W5SuHnfqElsv=Oc3xW1^GF>ft1^?Dn6KgM#r>R%DXG@{=vJhf~Y4 z>9hSca#6G?w6vclFsvR1oDR;^USUxbm{&i&Zh$p! ztI!V1o_dBjkXC6+)>#4zs#3ou_iR$yjP`%oyq+dp^OEAb zyy}=HpVu7MEai@XS^5>x*03gbaKW8 zh|L|#$@CQKV(wXz_BCD)=+TwnOtUV|Yk_X|X|T6?xUuPcaAzyK;@&2%u7w3-PouhC z= zSaI&mT<)MUDSqzNcAUSBz3SmkiUm`TdB(!@psS~IGt;R823oB~?{4Opa^r>Rq*IyB zb(yO1>o7UT*QrZKI`Z$M$@2w10T0Bh(#Bb=wPv`nU9z z26lCHW@GtmHWW+P9br2hS{Mp148_hmOQlB#7Y+1hx{IT#dy&cx7xQX#*HBiaOT&Zx zS+y;xF3At1cjj}%e0nsmmSwNq)((oKm>=CX0PC%4MX`twnnHV2|Ik4HP+s+3 zxjq6i?vU}`-ptmKQYg_EiiEP6Y$BbFCi2;2G`&JOBA-Dh)Z3dK9x4@w2YQPz%i6J6 zHf!h7cEk?bc8X?Yx!M*9tKum11*RQtwt#!_23zEeSMsWVAmA`y~1ijfS#0 zJ5sOGMRJT*na3UR##8c@=CS>a_ zl9gl``sR)~+Wz|hM z*tr4{91j;_=|n0Mit6b?lO1Y%dcbFfZVwHQuphCwohszh>14hT!!R)pBtCV{%#mXM zV0v_`Ze1>$C`1d%OePgg#qG3iU0Lq4MW;rjQ>jEGl!%8zm`Zjwnu#-*mQ^=lr_zaZ zDi=-Lxp*!U2`BYDpoyNluEmB9jpnz*Aet%U(z#SPn~BHlbXa!?5?=(UZ_5?vKb9?I z67hH}Zx`|@TdPBIvign!r)4spO2kqy2u1R#Tv+EAl4|PxP|wFR>1ZMsL5dQEY&gaa z? zSo-loBpS=cGaMR^&Z+(6jGt^co{S|D$y7L;OvEE@KaP&N0w*8m@N*Prh*q2j%wpM( zL!`4C>`*W3dS&fJ%X&N1tvFNY$J#fw5|{N>E#`U{b86*jryhqko@_kO`F3|3EP2A- zj;iyJd=52v?A@?lBjFWzH!}ow`1| z@Ld}ZCN~0cGU>vR(>%$Zbn58g89Kl23H)))7B1);+?kij)UPw+JV4-8Eyq=vTzo+% zry0J+E1!<|7K6tO{^5bM)y;s)VF-j;7Q!vf4-(2c6V>J6ZabyMHH}}_pc(_MYLYd@ znyRJ;XIL|>w^?(o`Ic&f8qe}|II&y1TPL)DHfMEI^*P>6BU>Ih&%J~_KmR^)`y+iO8d<0IqJ}R}ziVwF@O1(%3rBRd zNFVMOl@IaJ2p)r>NGzVr*r_lc{&)!BOc~9@qNwC~q%Wq6yB2X-E*dRn7wLt<6~vQ1 zygD0=5YARaLeJoOeGe|O>H_ukO~LnAbyj_AaDF%5SfEipY0i;$tf?v;ux&n@fxeD+Ac@!vs1fksliKA@Y7RulY($Vy>V4qG^Hun(p_JFk@mCwq(*t%{2p%D zx*Mjh`HRASV5_75hbe!V{>`HQ>)QG{!M2ma%T8*omY(BC*Ho8&8?XL3I$wEzm1JP> zUKRPl_gA+c6ZuDL$bTpDn`+4S;L`%*-%um|jg}R_wsg|8xmoP~=ep|c-Y@e1t|7lw z!=m3%<{FCu>u@{`&P`PW7Mcn$k+iTtZIVrdt(^#pZ7Q{}L_t?94Hp(Ze%RF*?v2>N7YFEoW@^+V$_ES~ZBcJM%&rowba{ao! ztP@nTRGUXWt1M$Bh_^+5@}$K3_9&?4sE>K<=lJaBsp~!Rc|Q4>YQ!VwL%mXhs!R2H zI#p1l}~<=TIG>n=&x1gyyicD_cF~@fT6oc={7pe7|3b zmr{E?^kV&M49a=VYgbDYPvE4T_MWe%i9XMH?P`U(*CSu0p7pf%A~jdyb0=w6>(zxG z+8NI-_+;T}5$yc1_(B4~ytay*FV2rd&`DY#CM^Mra=2yPb42@VSG7Q9~Y zZw2=YenRk&;9Y`;1s@drs^Gs09u<5>@VMaffH^S%PmDJX7#&!H8f&aEah@!HWbp2wo*v5G)FA7rajJCc#?; zZxj4`!OsdlDEP48*9DIWJ}dZ~;LC!q3jS7*`!Ms+B*>q;ke((uhX~!Xg^mlooQTD@ zPWV>~-A}~g8x=l(2t$7#68>F+Um`Xr^|;8N7Wz5CUlOq&{Z8cL5R3FQ!Lx~2+%Y2j zFD53HS}ODgkzXbJoX|Un*w=V|q8-l(qz?&xQSc}c``-76(0g9!*97bECWdnS%nQFp zQR)mL^ty#UPw;ZVYlzr4OGM~>Km_c ze5IZf{?CQ}6%qULABEpI9yG?Qg@|^ZCU_PRdMk){9&8Z)Cc(U5N#qBJ*tBmG{@sEP z3jawWo+Hl)|Af%55%FC4jqv%)7`9^~5&U_?Fve5(=L)@si098`!tWJ&Snx(7o=f{h zew)z$DEPSWkp>mO!v#}FuP+R-UQZYTy?#20&_z@9yhp0^d|yh$d|gF^@kS!%-zFmF z*JdK-Qy&pdM~IjgJBgSVdx)3^`-mM%9UyXii5Sm2i1U>?Ozc$Z0V2lX5hC(@gou0| zCEECXG7)(?PDEZ#5Yc}Y?i*Mx8XJfpuw*s15s?HmS>p^Ml+Z+t9Ym~mG)W_xqWg~~ zXhdk82ZYp^B*H0%P~%b}@^XRTDk6fd72HTfo-PyIL_{O57Tiok-g1I{L^N(daD<3F zmIQYaJCxcjxQB?m-XOS-h|b(1cz}pJe_Ze&5uH3Fcn1-A|BT>aB07Jc-~&XA!$X3P z5N)L%6+A-3xI7_vlo(a&X~APejMKA%7z#Zf4I&jPfIpkiWj%gqnx@eNJ$^}{7ZYK$ zO6ax32APkrznV10u}|a!#0fGVA>U0J^Ld}hZy~nHe1!ZEX^i7xk>5w0BJ&aQM@eHG zkBablnuu}i6MBHS0R0zwHxc8wPv~2S7{`M`A0lEL4-0)C5##uX z(2o)^j`|#l_4ZHfPaS@pNyNCkNo>ILfO;5*CBzBXCy2=V0V48!gor%9K}3G}voPj$ z0TKCJOGF+Ah{)e9MC9#0BJ%Y#ajsG?5Rsp{AP{+(M?^j@AR-U?oPhr8a{>B&hJ91;DiM<4V)(p}6CbT7MPU3Y$Ge{N@YDZjJSZ9bz^mznR0{Qgv3!};=DUFLjh zuP!rRkapDYYa-W@^MhS?E}z-9r8k|)6iKl^wY>2&mhO7GR4Vpoww3buy$sXgxER@% zDeW3Li8quU^zzb0{9MP&G91SdzBSiqg7a0sdNQ1^P}OB7QMLTKzjsylQ27*EU2alc zD+0fg*03ypP1JHH1^q*X;Trm`FZSI-!=-%p%Jr8o94)1@TWc8bmjTs7^J}3isQ$5$ zi!Kx~bTv%*8=P7)?}zK^p+!f&BUabpr{C%l{R<#Z(}%M)RQcJqx)c7criNq?63oI< znz(C_IIq+lO7V_ct~;F641LE9jD%+ByS|0vnxXId7LI9#zUx~!su}vOZ{dh$=)1m! z!GQk^P0`73_2Pzg#--!r=kzd8S|+ z*5${zvyQD?7i^85Vob)s_3IfK4X`ci@(S+I8`&##5{Sn`xh=-#Mey8j-TUS_dVSzi zhZpVm8)tXirQn&iqFRpo8Aq=icNJu`H@YV79nf>f9dX6QQN0}ZM%3MLH-g6Ftz1lh z-wO`(%5kp-&A29piMzwaLsji`#id{B(e647nmcYzWB^@E+>)bLj@t(*?eXZ<#l+<= z$xT}**yD=Z0@}po0J-Cih>SKYCho6Mard_b8RMESASUjc&~wM#=Zf0~eG`{xQ~eaEFg=Cd%G|0VOLxn-^y`6h5>Pp?-9tV#pU@F|Ci_UQRuPVI0EWo;_@F& zxX1SaSKPNllX|r4$K{TD40N@)y^dZv?s3qxpM#6V#Jvi2cicx@ap#I2?QCa#lw+L` z89)~^ulSD}-2Ht4Qrg3iPWZv@n1f4||ISDm%u`sURFi5r0rmU3L*yn5LcmuCPIH|N_o z_+H-lpg*|LhAuw zx#Dsyn(=LO`caN`i}<527Kn8j=jfH=eq8ich}^^tK+hd_hAZxc&^2-IK^-p2aryqE zT7PeM^vZERBXL)O&tl^K9qR759j>^mMUQ#<4(#1=@2e5_2}iFS_aV@~n%GVZf(e{W$ypMVbi@td*nx54M{SsebUXNvK6ku4U`n#tw1|G%%`$)Z$w`HQ&2K-;o C*LS@D literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.base-none-eabi-lto.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.base-none-eabi-lto.a new file mode 100644 index 0000000000000000000000000000000000000000..f62acafd374083db4a588cd102fd56abb083f910 GIT binary patch literal 14280 zcmcgz3v?6LnZ6^*lCb5G07GOWixH334X@E#!iGq;Nk~E)g#d9=5^MAV2R~$4ev#eo zNU|-5xIH3=w%!eUR!(S_Hjg?9?RrzXm25*?>ZVS%o8@HL9y^c(QlQSGU3NFy?tf=A zmi#JY+pLZ?cl6)K-246i{a<&it6)OjgWL1h>bDpzRQ5w>Zz=vh_exQElRNeGfn>IHgget32zcLpgM8dsCL2Dwf=0E2y zcwQxInUn_MZ$kQ^OZkyQ*`Sg&x@4Uk<$8jAk0n1&k^f0m6NWsbQy}zx_!fwCNCe}o zgs&{J_Na4Aa<^1vus=z3Dc0x7i?xy`JZ#YpQRR~bl_yk&BAZ-&Z@yu7@6O<;Zf*6l zc%RDoq{ufWf3b+Fy0e%1DPh>%rM|uF_JsZ~2KOJO&Wyphk5dT2bdh1r&Lx!RPNdtg zuD?jP9xlb7S9G69xOe;ZQ|tUuwuGRGBz+f>eokH8hor^EKE3>}i9Y8!xmUGHPD_HX zz5di%$1dWmI<^kRyI+maMkrUkN!|DZe29d+B@quEjE4@2J38XwpzLs&tP>4KO3xG2 zWu4~Il;&JS`<7cXIiO`*%4F?OyEER5ET*FQsJfKO#{}saXz8mH(fpU4&T}kbd_begwx-$HG`(a1?@IhJgpseDc%&Lk9`|(oR zJ7A`9%Sl;#jjX*R{#Y<>DT@bH@$h+C_RfU#S`uHUld={{c9@ohCZyj&1ox*|~u_3U}f1v9~uA>gY*Qu>6bJBAPizwi@TM6 zhYGsqOlj}KWph#b{V;UHD}g5>j&XZSUK2}F@QeSr(Xv&NBVRQj+jq5#({4?yYJ}+|L^xb z-M(I-c75mT#J3BJT~B|5IMZ3|`dvSf_d>C2@Ho-^n_}1dPZR#FC9X@)5PA2Mxc=z` zvHrdi*Gq2`{ztX0;8Iqny=@PH6%~#J1il zTh~ZmB`fRfkhSzTE8a!QYbx?%mNY6VwZrMs*9J5JI*)4>TQx4;HdeK*PrPlsqYsqF zV{)t>f}ll$;kctYBS31mS1N7tNr(@+4 zRrXWjiqo-*E^+zzbWxjI_84qutd?X}HXZ~O<(9RT$=Yt@!LaRYyjC7>R>wpA@y`Cp z#_QAM^-1!#De@{U_KXc^E)8hLx$6Z+b55rjjg+2aq;Dpw>|<5-e(pLnVmnr4>lK$D z8`%O6{UlocOL6(&h~m|{c(5iO3dX_*WgYH#SRD^14mg**r|O(r@0W(UYG=BS^7Sq4XE$84OVSE9xESrt;;OL9S4on(SQH0j}uCa zfc8=CIYx6?SNf}T=~oFYp0KWTnvw45j@iaX$_J~q0U)0YS6r$p?}eWueP{AvrSW!{ zj~r|0P=93qMHP89MZV)AKcd&B-*9R#P2F~Ws`OVdft|(WgRyO=Vyn7FY<*Ss@sWz5 zw0&#@)>tvV^Hj532D54g0BhpK|8|zV>Q-KxlulF1cWA7+f9E0_RpdpQgr6TxO0P_k zmt5oxdhOd+84WfIQ@35!mAjP|#5K0=2kGv^!FY498=D=Fy-o^j9mrxxyOXNwRTM7?8Fo@@ zBYj7YzFwVFmH8_4hRUxebkCfW`Ub0@{SlPE#HsELYT}F{noxB&t9$63ZrbE_E1VzX zyC)~pZUxiQu%*7vvpLkVd5gE6X*@vf+O_YCR9UFCCG4fz{Gpb*rbbG?*=*lTZ)&VN za4=loNtJocey>+=w$hY=Ht09$4V(1lFMOe*wee76Q+wlfZ&S$M(%I-`!c7fz-ups6 zf2gkUK&x%Hznkc$F_#4B!{DJUp z{Lm`+;ScTQ$A`gN>%+Ub>wSlIghJJRPwN5d?#4h9wU3{1z~t5YjCzmRPBVr;K(9BM z3_e;PFj)g8U%+mFCF7OXHP+WP`eE@_J>w6Ujb6rMV~j?#*$bV$2EWZ8Fa*2?o1bsk zYBYqJ@M^Yj@NAiZ!DRF>CcV*Yv3Y2_!ET^wJ!4|5CXd+!H-3z8hzWIW!N6>333<0* zbhhyDz|;L6o5yJIm~0lW)oAzltY$qE2>5(PD-5C68@){p!Mb{Xs5anl^!jTb`jQC` zWWs}3_(AkQ$!(*z9<&?H_JGZAH+qeXoi-YGv@!KzCUn3b2KNu09R&e_4;`h$YvnO( zRQ0uC*S=Ib4dz(&9M;gB9ZcXZyW8le;(?-y?Iglxhso|L_gdo9O3e^1o;E@gvU=?)=OnkL70`sSvL| z7QKC(elC4hikBz3;1;8>QIgu#g-(lTG3_EcDyIuA=mjMGNP~*I2sM(?RgMDVQjx15 z6^`g*Xkr)|Pl}*vf>0ex2Opo7dXohwH%&XS?Le!?tL115GD?0##~cNx=;b=}6Qr=9 zmy^cQt1R3NJggVA4RH@w#}W>7tu_ z&jl)8c?m0e<$Esj<3Tne>jd`^EKo-rv?tcTHNoQ}wo^p;iP*MdBcelK%rqCKG#4n% zB?ezFN3_F?W@11y#w$(Yb&x-B9FT0h;zX?cI2a!Bwq&dVj8I~P06Ie1Vq=P63F>X>i)d7Yo_q4^UslDN6W!94 zC9K#nTIeBq^Uy>m6;bF6zI7jKsuN;&l>-8(wNlB_s9Pm5O1mHEAF-pYUe`qA0TQWH zVs74Fk+7N{DpKt@*1{i#LgLj&*($tdZ&PD9)Kp&^n!RwnKBo$n@1;TGd1)U*8)?v8 z_8l;XE<&;I?)ZjY@kD;mT@XZWe&@f4(6cAJD@PfP&-qf`l1Zd$j@6(y2^3fnv5yV! zxm=NO^r(sr%MO!k#)v^36>ok#NP4J(<(t5X(z)VGhFy5S@z^*3o4mcp#arR`T}0G9 zeKLI=LK)?c;c`a`2RO9Xg;MsUcre}PbjrSDM-GPq^E`uHJQuqF&;{)9Gr~PTi+->4 zU8gn|vhzqW=3YISTzxFu561lx2o;tY_~Y>-M>+iNotEa{*WSK3fb9UF)$BDItUeQ5 z^hT41#`2?6d`=!yKldd0ph}ipF-hGviBddT=Lxj$?pHVVitS^S-z+Fj@uD>(M!DdP z6B9mHki6pFzXtE1O3g$iM5EDG^|$1gY4WAS>)g+_^AtD}yHwKMF#oku8R9U!hA})n z2Sb$VP2bN_>WW8${|!|!4rm;k-Z8E&LM(X&^{I=h<Z0)EaWRr$v%>Qy1+qQ-UM_z?tY-KFY6tf115vML zlF_~q(WIzSpzyp{2PH4d)f_R-?O$)OrOr2-4OS3iOa%_uK!Qysz1K$@19ZS+;GWgR zWMvpFD8oddn<#{2$5Lx=9<>rV-it^KU1N!(6D=wy$p&K4kWIEq1kP7>FYhQRdN)W4 zVAds`2UPwrjR6|za}ubDB~yur8yTf%4i)_Cs-!pxh?Uyjf%r@h>sm~97sqDc7O}y8 zL5_0EVB-gDEZ|R=Y&M(KW~9Be*T-WMxhXcJn;;j(=9{_LaC`TJ^M@P?Sh{#IA!dmQ z0Mko2yC}7U+sobdHmM9`>!EU$wtEDLYs3O9%wS>O^{b%6Z2i zq3&~P%HD?D36eHbYgc;lk-s z$JQA=aL9!@RmJH6oJ`{Mz#w@QU7#lWoUhByZygk~X+#*MJ65}XothE(26t9}d?fTs zLO))A5Jqh9Ru{dW%BY1C8MTm+eN_5G#hKeMAMuBw5c(370)O%TSl45WMl^3ZvGK;b zc|DXFeZblCJWe0@8a%UEWdCi{uhaNw8U;O736G$8t}5f<=^EdS8j}*BC&os(DMd>V%l~QR-Bm z^MkjBe=EI$E@#bNj_w%#R<2%M7{7OKhF{A9__bjCXuHW^Wh_REoiTd!bVirzZiXMR z(oL*f6u+-?_-!lr6Y3w!1zpt4rt_%CA>D%hlw`JtgU5ecMmiEUseo{H`kwa8m z=^NX5+1^XZQa!BZ?D}DQZ)D>qqS>x$#`bf*s;vl4It1JQ=pd&+e*>FWIpatL$;+r7 zyw({{e{q|?HwQNy_J(_&0Nk*@%E2|`sfs#z%H|x zqc>sK9(>bC7PCawFS?TT?FTfW0ZkUOIet;|<1X^xM1HdaGNbkK31FGEen7`IWet?`ZAxQPaGp&88rF$s3vCbh83s~9X7Dw690#&EE^JfM zT6bEzs7@>->@bZS-?DrA+$HAti?iay`=Fn&zD43hw9=8(aNVNb!syJ`TO1WIW2}tbXJTld#RsWTTP9{9$Qd7QVZB9c z3V~zH$8(_TZ%J>79{Ozc)|rRqZfe-O*?oO;y~SwHffD&+daK3XHcxK>4RADh0zSrP zH+Vf3Go->ZdP|qZabdkRwaGmt;5a`no~O6+_Rn2nc73z+TR8R-^p*tf*Y(^hdPX~z z)}-8u$;=wpLOEYIxB3F})(A8#D`s!NW3^b!emdZ{)0s6o=dCg7o}8V+%X@{*dj;80 zwUZ7)7Ry7RuyC}pO}6wB#9j%!j-1&4VZ2UspPCEi7hB^(wr5HUCvBPaEo^(*19KvH zh-ZKX>$6$xRYYrKJ~k|2YCpt*} zYk_masaVCVeADoTA;SGb)H6*;Q^AUo>S7mTQS9W(&4HMCg zr$rkeOU0+F%C6ALx09zvD#pa>Q^OlmqE#$Wd^M)|IJSno!F6w$P=2jq5OP?VznL@^ zx6hm~FJ8_@xjfd-sM8>4o~EX7OE|;?A#4iGF$>tCo2dsWGuixBkI%068T_DVyb!5^ zKSzE}K2i!P<%)hv(Fu(H*d3*>rf<3_<1LPO*cESu>79V--9uz#Z_s%a_^ce7 z&GK>_V{o!pk2u-m6 z-uXIt9Zh!;_;g2*D>vl2Mi1oXx@vRe3j6K9?0GiY0|!@`Lx~yR=?FgA0o?*kI9_M{ zcK%Fjl*@sI=bUI6;b_-XTN@4oZv#F%?X%K;Yrt$bd(2kM+lX?;e?nRP!Nq-RHTXSo7%RS@?*KihwTG^87+AqAaq@=uHXh~;n|(f$0ooTU4qB<5s{3%qAC zmpEFS9e8K$^K2i>4RaIrHqV2XMR6@0MP|>~_`|k=%VJ|fW?^9ETEO(tUVlN@QyJ1JO&8r^ai`v>ZkRbUYfcYADBl{%p;$Y z55uQFdp_j-_|M3P`8l1JMRU&nxy0aC(<=fDr<&&42L3$j2m~5@*0ix@Zb}Dl3O${z z1%`O_@Q#pK54>P3KA*+71J3@7X6(e=oKD70)YcEwX8FPAbZ*@H^kO;H8wHE!CVsN+ z&zMuK$k=|fuWz2w>kHsFCq*#_KQ6`U@tSB`AP_K_ z7`;Jn2K;nc{O0BE&1P{fzT@7D4ZKbIqK=Naw60Ym6;^CkHA(EDZ)PLz}Heqs>giOK>Lazc_D( ztIi+N`9CGDmFGTNT)WTRBCZ1zLfZkeXCyy$5!CmP&d}AX(p8SiA1`tADs*eAdsX_% z-K1)bw`=q?Ro&COblHcjs z)!y|BqoVDVYyWWv@+;uI0GP`%@i7|9H})m}8NPUaIByIXBdlxi2bb6Ya*jWg*Wim^ zB2qx3Wl-Y&_#@Qgd(L3u8~6zIxCFoU56HyRaP9%qa4FE2W_}B$K*zZyoPZEYfxb3F z7fOMS&);x+p%mzPpkc)#lmZ>+d@x-o1$udgE|db@0dzdRPzv-Kp%mzC8M;sk^v5!Ep%myW&_QI7 zPzv-upyBxor9l4{&~W}!C zlmh)HK*!?4ggvqy6pQeVWzJiNGq>%TH?{b}pLyGc zdtn1EaFSk&kJI^+UcP`H_%tqi{sgz&DGOIXEzWt@;-oOnlHyBUZVD|Y&w)KpE*#@r zP~H#CIzTgbFeJ7-_4REHn|+=Go8fioR=?i3nT8kN@$253X1@f#z(3MuUVrEQp$@-O VA24`r7OS1!38RAF$`CqUMIlKS> literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.base-none-eabi.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.base-none-eabi.a new file mode 100644 index 0000000000000000000000000000000000000000..c0cc96c4a440876c4b514f593aba2540390bccf2 GIT binary patch literal 18680 zcmd5^d7KvET9X!0YMQ#QKKIeG{4#sY0bw+X2qf%)e^2&JDj@v+|dz9CnJvjn&xcZ;H>hx4FlPY z>4EO7JyMuCI5b$8S+KKx-9t*LE9Wmg%d#xgoMNd?Ri%`AD5d!gaSffSpVG&N7m%dh z8;2%rb0~-2c4)$mCk_qW=;oEaQq|A8>OGA;)2#Hn&$@M=IMnO0ed5qLKHBU1jYEyT z_>DW<{?rrI*l!$a^XR^DsL4ZbJJjT{?Qz+vm;d~-X>*5*A9mI6bM=clE^s{h=IYze zxLSH-+o8rCjSCzvPG9vLRByU-?K#-vqqq6!y&n3FLpyx=@9^XwT2O8KdnnAGC4j?H z%L&amLh6vU{0>xfsiF8jBKipFqn-~+5sWbE|C6FM&iZg`dqc3bZSqmA51l@BoOS+W zbWO$zwkj12S&P~SrUqMET6S1RpoyI-*g6fBhHh)HHP|}4<&=hw7PP1Vd=iV=l^Q)A z#Az)p;5T+FQEQ=EQ^l%fQ9BvUEx2}C;*K$RN{y+iP+_b%*0R>Bw~t#>DL$gAEu6Lr z2f0vXoOsu%jqgTt$B*inqO)z8J5{OnqgAAx%+)Oyw5)=`1h3Abc4|#*PysPwmXnUQ zyhf8Lk3ce|K}{RW%2aSBJ7H*XBuVm*YSAeuH7zbCM|%U#or zW6+|&DywNc@Kn|>rjbdj*YPlBJ|x4G77#|G7Bp@}{d1%@T21!>zt8&ZZV#V!JT(0b zlJQs*0(ZKlcRA8AM?x~6(%s^Jw-z*>4c-4Qjs2JZOLkX&aZ*NKrD&k2UUQr0TYMJwF?Dmf^a2Fi+!QxizQ z0W>&6tuPzi{!4OEv?;W-AKpf+Rh+3-c%rqOQ`L%4eG(TsmPQy?oLtkAR|70()v$EzU>WsUIxXO}V}-d2DPBI( zhEu$4IPye@7l3yZ6Xh|@TFxsKMd$DI880zpu||xgzjXdu6{o;rlZ9qeg(a}mussfW zox)-N`#D@;EWHlTGi;ATUhHtV`TZQOHkMw87aBJ18%)`0GFJ?lCfmJE-5tY~Lr)V< zRq5ipyy}=H4`_~SK5${dEPX^Y(HZ_(%H>AFf79#Fog|kX(R$6N2`VQ;PC`l$PZ3uMI=mq>ASDJ&R! z64mvEe!1gnhj!(fC0s%!w*e?~5fvYw(yHzb{(|3_E36pvKJ7C8x5JG0`;EB(i}4d) z$4ai^co*J%s7OZ=(#eud^^VNB3^Y2(P^6Fnhspy z{bozVjHx-pvD)E`J{yyMbV$7gfs=PgnLR(pj|FMy!bOqA@C_Qi(fc4YcJ=g({DY8F zk)@uWdVJ&8v97kq=$rN!J%fgC^galUT|GS`{~-LoXlJh99$ee8bm>RV?&vIS7%AsE zHWo@FeM5sCk?usMJ3Mo+Z|%Br|CWxHIb%#1{5MiM8UsO*t}S^a(4 z?$U_ro~3d_rGgsSGMH0#d1#<7r#7V3xrKgvb0JSG;K_oTm%DUBAJl+gsq+e#o-tBZ z=alk=Qs3ZORU9a*Qdw<`sHKHsS)I%H>Wso*xlmH)53U~^+BB%<_4lnE8~{(13L_i( zVZC0>FO?8NQ^-g44fgj97F6$r%VHpt4w>xj&8{CVM^ft|u}ChPOWC=2s*p>^?fJ?P z`3xeF-rn5MV7WBZ-&=xNE}Tf@a^bukj)kM)aE4|Tx!Mqms?z&-*aQ!$L@pLh<>NR- zV)1O)?O~JJMC&+vG0t90I=vVHXJELmzfkHe76x+#xXHv4nPR$-iREH;CLD{+N7uVm z)DZjAmrDxC4v+NZVV_1j;_*l>AC48n#cWikL0N4RhD@dsk$5_tPNievTsW6ECWXUI z@)+_hFbOAf(NsK>jYo=w6sk1QGL_qs!`RvVy{vc#DFK~w#KHj2F|{Y$l#bhHaf)MeegjqlTqXnN%#2 zN=75GOf;N}XOj%3WwlM%C_80m@^L$yPv*0+Xj;z$n&`Rfy4cX5k-|n8#Iwb`ozFyb z*<>PYM|FcB@kN08hJ2C!6S-nGl}siI;bI{Z*6NTPuD+?rX_-!DQi%)JQ>X9gtU)MXbWh7_!_cKbtj>Y1+Oa_Bl$P^+p zt176$lCn!{{Z24M*`cBGNV#NlVB_gRDx1$l^3ehk&*>Rgkt@s#RobZV0M_Rw23EYc zx6Ea$n9qdssc<1xOk@(-gubB4WmQJ-Lb-+=I<>3~(cV-hn!&{wDHdbNEc1t?o{7zL zbI~}~Do(*@rcfw4CUy-IEUV?R&HNJiY!uTX63ygNg>XdjvunkPgq_Q0aKu?zBUsB4 z5g6IYd_GyZx+ty@(q*kLv}`UOP8W;Cc-)ReBYISMp~2ceE!myC4{RPBLBi2!&JHJ1 zu~<40&PF0}Hj*O6U9+?CS&JX2PvVDZHC=T+Zr$cOc^+F$N3==3=~mmMW;tr+Dpi+N z%r>d#u^VHzsavt#(097ATFNW^OS;BOWVY6FO|-8;8#g=tF!n9@w;)?io-jmm^Zhic z&i(Tx)Z~u%JMElT$em!yjdhBS!|Pxhn7I8e*Db-Qs&9e8d+S%R9nmYZS`CiewcAAv z1FXA&3+O*+U)72IMS65@%rj8cTLeC%Gy8zG*m26u_g=8gJ^nh)uHIbVb!dH$O6gp9 zFDs}AJ$jqecj1E@fODM?++v)75tLy)30%EDIiS0N>&jVRnY~GmQ`h?yJ`Ut&c;Zs@{gvU%4$z#B9vf(uEkNEL3}_c+Y>%UtZaAq_=EcfJ{ZJi>3TqQ zcLPGri{NDQO^mWmK=q7hcQ~U)wT(WzQ8nQy^f+sRHBn6tPO+w1$5_Xy8T_@{hJ)Mn z5H{u3*48m&L65;<3fkhK(HS0^TiW;2_uKpR{r>(|+8^()_2;+$TWM~+-Tm{|=JVI; zGvC=bh1Auk;Z5A1TE`MN);KKe!qqIjf1g#^r^jQs(?w#5WI7wh(vR(G#E#pkcs3D7 zrNCW#$u4b~#S3!QNGUfSO&@gJ2cDC`b%sjr{fiI@Ged6N3DE2k$9sPGF{AK#ri~jHG>+4<) zJN>xwuxzz-wj*6!Tlys4NN|WAxw1x&U<6+m`OYhA+aD77&2{8|68Uv?$stQpHs+sCkk9?+29#$uN^*2x@39n!dEMr<_`pvE?G9a^otkJ zlY}qJVV68(?wTfiS?0Prgg#Diy5J1KPC;3gx=t3lTTqspuBgy)L0Lw+($2gLAaAZ* z#Dzroy_5)lw-e#-8$|efod|#Ig1{-x{ycCR#|AWzO$+qkTN5H^rXDy|DXy%f;Zh^} zo%C$Md4dZB&lWsSkXI)4*9hhX2L!hYUM2W3!5al{6Wk?um*8%}F9|*>_;tbkg3k)R zAov5p9|`_c@K=Jr5#$Y@d5^)oBDM)m5#;h~Nx`{-O9ht;ULd%R2;U{4FBh8YJGS)d7UAD5^d2HE(no~< z4Z;5w{?7&fOl-tAA@IRG+lio$7fchezMU>|e)dE9?*vOktQ-6Ui1ybIaZz*MOZqmE z-z9v09z^}eiC8E16QTD%LjPFskAg?wc~1cAC_ZJ=deeoD3oa2{L&PF<2@(D_2z{;K zF2OGnu?{~s8_ZLhx`>~f!rw3SbHwA6`l0ZDA@uKw({T?Q4MbjJh@htuXCP1E zcME+Au@es)g}60x|yD*V@p@cX9F?}>Z@ z<`(ZK#}JY4iA3nl6nc)xR}gW(`Ka)VMCe^2^cInSf*4h5r||D4LhoLozasLdh`9ef zC;Zoh{xuQz!#@c>gr88%tDOjbClU9_sPIn_TrB)GLSqL|g|8iJ0fhiI~T$iI}Hrh?tk_h;TYgJQANo5i!5E5iy^35IdB* ziHLc!lZbinSt91aZepiWdx#j%hlv=ky+n-1eqvbZC#3Ap7f7SOULm3%4ieKi5z)So zU?UL(E@_QzM05sH*Eod;C8VmcgNXJcHI1D_7$X&pNI~}pLThA5_6xdJV-FGibEe=z zB7!XyTuwxPtrT2ML=qPXt|6lT@`CG#NUmRSn27!?3vMQMV0{zZMnwN^7u-QaV{Q<< ziHQEbMQ|q(joc;pSt9!X9>Lv2H2!|UJw%MhLxK+z!%96SxR;3W*(bQ47+30P!DomV zuLFWF5YtM%B#5EW^VHxJ()igojfinYs+vYhdOTsO={ZCgEfjhwu~FtJ>@OmXaa||! ze&QIJr;u+Yjd{L9JLJ{L&Uf?a$f>}dOy~I>s07zM2xH6he3WaX^d-H9 zA|l3hozVTnlhJ;mw-Pa~JA}T0h;iL1^e!UCb+^#>6EUt23;h@oLGy}!k{ z{R`U{QtBxp#_2c2M%)LehjHQW8jgqFCt@6KC5`_74gw?y=JJAAR9BSiG?3L^TI zpOmpbZziH2zeq&?Jxe@Jsh<b4xw~B0T<$jCH`JC@UP;y#J8#iz%bd>!YRk+^ zvQ4VCoNp4l^M&k&wY_#WTO!3|>uB?}aBV+z1^lR{u8mz!q~EjZ4z$bVQeSpMxqy#| z*r`sg!yB^YEyIWL2JHba&o1E`CNIly97lKoUne^mka}Y0ONiQ?LDPD6W2|gw2#?&a=#4Q6FYhKcP4L-fx z9m(*lPmwgM`V>uRnLg`NG^rW-tWVK|X6Um%MdO;G&-xUNX@)-QQ#7g>`s|z{n&F&T zjfOQNtl!raqq%f4l?l(xt=-VA1z5lS(y|Zh8~!R~0v`3=fi=z)EWf%uhBNC}!gaxt z=qbh|2qnLsky$Cep zniwW-*~LRu-Q$W&zoxzX{q2sM7a46>Ox$xEy-Gi?gN$);%hkoi<+s2l7Ygoo#T^UU z#68{@cUWY!VKH&1`r@)(jBDQHn79*taUXKUZG*mvOFMUaw}P(K&kc@VrM){qGcL9g zx|q21tf*#|ZfP=-f_rt!pZ@J=jiXQF0kD%_j z?|@e;?z4_wrM)50w8vIm7Zdl};Je%Vjw|j-(4-#i7UOWo9Rs3P+#W}-5_f{coe4gR zi8}{%cihknCl2pN`1w$Ydl%~NxYIxw9}rd6jh&8OC2ohr4O0ol*xZ7;JMI`)T)wj~ z?LFul-_AO5U-pgf$r9JR={0frJlP$0f-7#^6_?M6;iA&Fd{1C}fL&>C!nbauB`$ti z>0)g7Pg>k@r@7+te>Y&-`yF38`l5U2*@}7k6o$xc}sf zyIkUO9avMVlLQ&rkK;ETH&{_r!nQXtkP=ZjmGxOhaMi;3IoiyL>v?SZE0 z=U<=>7nSklbAwT!O)+s_0Ry7SeBLf`PZvcK_a)Ho@txy}dj@1CF4tps+#Bk|{idT= ziF=F0oew^XiTicb-Eq%!#XU>(xNiK&H=p?&WEA+OnD)Nlo6q-1+=ZfO;vVqL=cTT= zi=b=TdkpOHSBZ6how!_|@K00gmlA~9N zyAL$uF7w6ZKh1Q$G9tSu$X@4KSy-O&AZ~B zD|)ocz#e~>cke0czMV}q)C8x!+WE{3UI1HP$K?~`!AZ`(~VvMZtI zVypWRw+%md823UPChpZRFgEn@Hhv`hffXr6b_FVKe~;mYdJsDFcM%TbkI(PE@Y z)zM>}#mH{<`MU=<-M!$^-^DnLKfX7njk%A$h#wGq_hbrXJO)M2@PC6%`03{279Gki zfu6e^c{tYN37L(<#J$kxFOJRi0y>Zau`VC+`RjN2%R$5V+v6Lz%eYy0731$LR4`?R zjfi@9d|4?*uhBRE_CSx*{{B51aL88XQ0KM6V6_za~<6qyPW_ literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabi-lto.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabi-lto.a new file mode 100644 index 0000000000000000000000000000000000000000..1a5151522ce7d8929706dd441bc495c91e2343e5 GIT binary patch literal 18672 zcmd6P4SZ8on)kU$n}oL91Sln?X}IA-D^j@mPH2IorHG1SK*XwObMr;3ZAsfuT5z2t z{Yb^?21iGH*LSx?oMrsj=?tvPD6^Zi1uN6h$~tbx<@If`YGDu&9fz59oqf)|xy?sg zi>~~BlV5Ys&2!E@_niNIzRvTUTU9Yr@2p&#u|&N}YoOvEI(|xV=ZQy(Qkx94j%{Pl za8%W<@>TAtaWtB0R@N|8wS~1iYu$xz#!*#R?c2F>Cqk&CH1fVa8zB*t0#W!5JIt^vu3yW=pGldBO6q`k|if`>7KH(C;G@LJOeOEZ#Vaa%@1V z8gl@UbIL*q@)&8kFW@(t!Zs3ezw#+RGQZ*EPhAmB|jV?q4pe2Mnnz?QV&~X zh!W*>oyC2LBiU#j`Wl5%#$jQX)F3~JsZxsqofe&qjTVNEZiYFCpqv-9mr$EzK_)1Z z%?mn8?3*O`QKNZl_gF%ED#dj@;^IoNu`=Y{DBfKu+}#AD4;c=NcbAKIH-+|kLxzHo zR~GUO)8Y?@M4xowYsxUFcM0GuLa2?;Zx-j zgn7yj1SCO1`IfRr38>O)=`&GZaK>GtkP zL(0rd9d?BY8YKICV&Cv!OO=NS2^A1*H>n9~Hn1 z5>R^K?9}kLoNJSpbbjHD4lBQNEy;o%Ca=J0p$16-Q1~)- zNJ|a^|0fOUfjNCCL;7uJ0klXO(w_C|lp*c9E+gf^y10~z!ZMp^*{fR*-PWeK^XtuR6?cx@+jh&ge%G?w zx1HYc{EOQT*0{gkc5wHyEV=C`j}y<&&b1wUia61nYy0v5k^WD)ww`B+woh|y=MNI@ z)eCK7&k^ajEVTXWA!6C>3vE6BM5O2D+1@`woOm$LcJP-(+u=Ohv#$})zmaF#_bb9Z zo@ev_8*xISuss7t*IPt#1_KUNG`vIlx z+4Dr%Ii>BZ&xp27i)?@Xk|;aA$QJ&ZaFYeLU$hAN0U(5a4tW0qlv;^j(Lbv2WD{#T zN=>bOoh5#8bCbB?KwZ{HNcxG4{K8Lavr3e`(fl{N6&^aBZPt=EC|om8x~5aOX0WLf z6zpCJR-s(F9_uqbS!(JK z7CqUw3U2yUu;?9OQBPmi>s29dd8ppo;;R%l*+V{g$k!Fhee(|KMI^m!Bgewz2Nvll zMP7hePzCvCqRL*Y^0Z2ECZIes0tO}jJfZZ+H=BA&S3lcQG-z8In}|IG8oKGg=1pIO zr5FL_1Ikm3VqBH~el-7KLWu{g%D=>jwzjpH2K$P7O4k4&U-cG`l@@it&%VwR88Fk( zZWxaQTe12Bf$bm2$O{qjLmT-yy(D_tsvH|#Fg%+7J`7-EZc$Imnxidwt$n7>QuAP6 z@v*3RpbzF)Jh<^_okR?yssjMaL%IKXlDuG-eljAuL`grSv32{>M%K#64`>p8em){P zH$slt$Sd@cvlkczHl3pjE~xT9Qswun^5F@Ns}^~v|66ptbj>lL`NqhBin!Ioc`fMSD<)*f~=(auHP@T68n`Yp>W(p)6n6X~Dkt*%T%AHlO z*+?x3bnf5(_WCYafvZ@pDS14sdTu~e*|h=M??V~0tnv=8BE)0`!?LzIc{{z)PV4OU zEbC_(_K}e&Ef)$9Vj5~zRaZGy);FwN<*a6EcTk%)ZM%&ssNdD#b5f1&`i82VwUm0L z-n^17tgYHn>8oz03Y>bk)2Y@QX-Y$D)P-tIp;~{#4aK`^AFSQEyLPQ}XT7_jxz@?} zcGgrmZ?AW`>#J&a>@sa}S2Im+7Zh%$!EJTc?W(HB1rY9V*OfN-JT<<0U!&SuUA3dO z#$D^%sGdu4>;F_IUe)W%c#z-Hu&5sGDm&JE?8lh&?)|+ND)H z^k$mTcsy#gPN#9vYLCw7(YZWk4NMu&ysEaks@4sYH>w%8N3V4<4ilr*>h(^z*r{=w z+#Zd`sWG{^hP$+y`ki<-t5|qeO~9bjIvAZ=t2dY&v{_@;(6pM-F-Dz3uY(geM!24- zZ(fCgS=CVQT!qnD#lZu2cRNfDt;V4<8JtF~+2Jzk)r`mEa%qjwg<7q3?yT`vRlDme zJnmYjyW*Z7=x|3m+=+qfL=BY0Hfm#~Qv*be!_Bx|jDw-IWsOXAqp`-v)bDWnz-xxT z3hX!|v|$Js20nCbTb2R&>~PrS9c)0ZFcl#>OJ!YM=mS|=!HQl}8j+Eu zCawMwCnk?j+U%yVcu$Y`A$rR)*?a1~A9 z&TMRF^KoZE_n@Vtw;)_{L+936tva!#;0zH&lq49wf$Id1EFUyNT7fHqhwy*smT<-k z_?E*8beO;8i?POo^p)rhJ-u0_dDXRedLh0E07im=licu`~P+!%CysO z5n-#`Pk50w?G<{S3jGV(v_KB#q7WMUS3*;ii>$d>PfO}((Q*HK!9{6^Zb4U~n_AHo z0bM$jsg*?XamOYYq^0msG%Hv*+zYi~Aw7)V>0JnO|L2J4U&MZSM?mgxd*E0guY*|F zMHIjZ{v&R@k`6x?azFjSiY`oCcqKg_w+wtJ3gb53TKgk`yz#*5jzFH*F(RtAK1x{ZD10lW7sfAKemxy z^!NkfW^lj3Vl{<8+hToP?tQk;bd)GM)UxKuKEZ=v{1j(K6=x{L7=w@F0c9_v80uCG za7vcIt{GkjhzE-gwG=%IhDx}mtECu>R=5w_ZH7Wf59Pcx>k4R!gz#P3UL+_{yh|v@ z3G^Aw&1LaT1L4gX{R*f?8^BAfsBk>!^?{gaL2eD4=o>g9$dwv2gTrZLoI0c1Y0@!e zXkM#o_O_eFE4qZ2GQ3o#7uiuqB)S3}LFmOp&*coM@+-Udw~0oOEYNZ{@({?!EAchr zIp@)^?643m5w*?<+GS~4QQI9orA279(>4@1LL!+=$d3EoG)w*~S&{!>7dS9Zh5~Vf zlAqfwIN#d-TJUiG7^95%v%VzAKL=(_H0U{V8H}OT8lS&^%K2M+(`Uuzf0jU= z`9#rB@7D3+u%%s=tC_opT>K8vqq2qS9vLDXmdqa&g43n)hi3JL@q9UKEPze=okv@W z;P>l9&~DjZ@-+%NW*}jpNgea{)5x0*MabuuQ9=8lQ_qG2z_(J|i zR%Iew!zgROzG$Rt(UZOd;0TNXLt%b_KMp&xpT+LhOQHnqcJH1ZyxjnvQSa1hj4mA< z)LNZ`#=OJKzD^>{d+7f5|Khz-WCjFk4;I2w>o?sWxmsn=Y z7G_@Bi{hA&c2V+3r}eYV%+@Dt-qR1VVW@ zx;A26*F(rVt%`!P5NAT7I*Pn?(Sbm5525G@th<0c{dF8a8KDoBpXR0&z$tpYOC+hN zaDju`>}+;Uf{(2L_-KPuW7L@)IH7JKQ;$QtB-Q#i{d*{@pC{V~;>k3N_?ntyt9 z{@F;504&5{-?8-_u+B;^?rB5l(_k}>^`$Wu(3ufVXR zRPR?H!qPusY2Ji&C7=_I%Zpep=j1*Da(`lXqTJsCnDfsQ zw^`b*4F(kNS+NnudUhF_7Tv)14=$M6cwgx6?} zYjk?NPO^Bt{9W-HyGD3PfX}zK|6TAW$-ZRQd=HVsd6ArqE|1G-f=#Yz@TU5ZV1HOD z;ONkroi4Xl!!QP&+GW;qa@rloacciDy1*M<5aT;aiR|0v^au;TD(U{*BFHUq4Qw1Y zci6;{c1!-rWhF%&MB!J#WEV2ghcsn>0!Arjs}F^-M(blW8tcU1IuYx){66ltu)cSa zJ=y|u=k=Eu&VB8V0$$jMWMP`{9tF)DRx75(D#c}tVTHX#mj_%IgT|w0jAn;ghh1&( zU!rlWdg8wJrwMBfMPs)jj#Y~PQujy?S$Qd=&JIEQYRMU9`{Ewq!l4o~>oy9SU@?Nt z2%ge}pD19_!OkM*XM=Y=;V0s>%(@F0L)K4>unKR&Pi$L_{h~w#$JqmnXYYbUdtktG zOIoLCgHar)13I<`i=mus4{CRMC)op_Vg05z&}NUDVIYK~2S1R*ZZwYF)V^O->53|+ z)o-%{t6>;1USij3Yp0)I@>=aSxQ?ISG;1}K1GeZMRknvoSgXbPCULFit*@$K8XioQ zGrU%tsKN~7gm9O~k4X3|~OlZB8_D>rv zOVq(-_u+Y>+vN~tNLo`T#mc6#FQZDxfW_uFwSC#`Nm)t5dIM-MKa;_1)SF?3YOUMs z(!^|Y_oVry!~s>ST&h*y!oJ*pwa;*x`KhpDHog7a?Wvmd{D21Ya~mL|VRUK1Y8W8{ zqL29=GtDo$$`$<<^E**-wetfvYJx{I;rz+=e;1T-aontvh`aDs9JVDsx+is zpsn&DCP*Iw|E)aHe~ZNc*f<{>131e1ZwTUicV=A1{@WP#-{{-q{OUG##UF7UdqqOD z@2MagQTURrn#b#Y9vKPfiw zw+YW0$Nh90&^Y-YnbsSRwiGADd3tX=CMX=}y|E{_n1n4wpCgg0N9rAtR&72VzIDzlrb>D^J!5e(GoAN57_y13x)-?({YI>KQLAcj{BrKX%S0>VcbdCb!Yy zGOJx0Hz*V*tSG@Z%f3!hS^#0%%?GHg=iq^Ega`U$@A7m0bRW8(ATK}=E(>jzWsTT# z{0|}jou@Zvj`xs9dlr7#vk-~>1riYilVB57VlZj366J{^In@j#rv89BZ%u>U2bixU z2x7(qEo{s<2r=W>* z7~udOD-YN*`XR{Fvq3HW0$pk);<*t@2|V&kj=7;9Nt_v?*CnXd$br)+RN8$Ln;{w9)ABIB26z zXJW8332V3P3E!I{Cv*k7c5^Clo+w(}A1$8IKk|wb*KWb)Gr)~`v9(*knkf7Gzth^y zIuBy}Cz_XD<=V}bfHhv*q=hEsp%Ork=b=``apq(QjBy;slspuRG8UoOW2gs=X|=&) zFqt3|rDkZgn!|WBjxmbsV>TDZVa%)ju68tEhm%4=G|9h7v#uU7m*GsP^rXWt_*}GD39BY3O@_9I>kN{s2w{o`qn{iC> z;Zt$Mfd+@k?52%wH|=mRT9X+&YoLqf&%mqJwf)w$-|4f`@_4C{wM*dA*R(0P6*v!^vn}4wp#{ODHvVA|QVp z$2xUQ&hhN%TJLBA*4&zWWD?I##J@&D)2=bg9!}!b?->8;OyJeEaDFJHeH1Ml4k*Tm zSl$#E_0Qm#b!U$ta-=JJqlz52REe7ph-nIZGwh_%{`9*ywr!KN-CdsUj_3Tc8!6a< zEYu8R|IL6}?t}K=)QzWqm_KHPEo5wZTg9fgAss^*&Xn6*5{|+j4&$wKFlIPu zEC@9=iJJ#P55v5%Z>fv(1rCX#w^)1Ou4Nq6?usfW751#%Ny4D*Gc-8gHNyxjPA=|bhm>~aJ)B-@wd(Dm1RQmJtr=x@ql20!i%nR zMc45PFFB#9lKLC>w>BRZ=gr+!E^e&EyV9CE0RAPSe%Ox?P6s>i!=+!?CNe;WBI3un z+~#mnZu84n)~7f*w+VJRvLjK){T1^~`N(^KZ(aeusRh0n0lpakzUczKVHV85H`Wa<>xOChCg(>p@J;9U$v5|cT=6jq z>|-nqy%=nVO+0aB!|m4C$4afxgyj&+W;}k%?eFPl^N7Bb-91{^45zE8@c95tkIPKE zjI`V6(VO)Sy%GE6fjCsQ6u+&H_1n6)o$B89jkfTCq@%uBr zo9~tlzFXVN*dFpZj_3W@9}(h%^xtvT7S~Og<4BHsZJ&hs5kW`^+pyyMi@1$O-Qz-S zSZwe^a35n1riYIev3a3%c7Ks?D$qd*0v%9?K!Xu>PC{;7?eSFwdz2wzvhI`wq*9Q03g23-8#W$##WPa~w`F%r--@>P*HLGVvXTqJi{}glox5T~o_%*{l{a4=y?zg4rnXTZud0H@llb?ViCJ!5dW4B9eS^C%`vVyYh=)AJSH z?ut16oF9JW*3`A*gdcw8(P{ng6aV&o_~CaZV25*KzV_z;yNNtBh77iWa%x%?7N@LZ zroe5|axn=vHZARN>S&Y4ZUI+gz!k^s>heBsB=hb6KCZ#; zT`YS8^X%2+q&FvEi}xA(+8+$A&-MbOyxW1Z`>DK`r~@2Lz-vic@h~6ay~I!fEU3{q z8Cq}DYE60?Hu~$ZuVI}DOO?A(<^GmfmYljKShk(IS}bo*z!Lj!)5&-_q`(tpJig}U z;`XQ5wH3&CbyZEOjGOpZ8e)RZHUX3!dd6XP(PjrE+h`9ByKb?KW8yfc%K8UfEY9PN zdg3^9vVLaMw6cDtb6QzXfAjm0^~Ctl6ta$?n@ZsWA~0Yepe;)C2w6DK7H$Zi~4Q&LxV|y68<2X;vr`Bq(wK|S7$ETgQP0Od9k4?{~zq_`4Isx5P@@Wj5 zZ{kzF3E&5>Q5m%!NUFoDUy!47$9&m1epB8|E4WD*X2w{Et zT-qBpf_ed|G_4&nRY||(k%g9yEY;%m9Wr&v7E-p@+1h`cTHoF=XYOUcEVpFKJ+j5F z)(n&lNq&C@N{3e(y3#BR^mLf8!FxUM(qJ~&IsbB$E`X{mO8{31Z4?w4L^h}#|1I2A z*%rt+pu_1l85H{nw!;UwDg{?1W~(v;Y}G!lYAIJWi@S=edV#B2!Bu5)R|(mxPN6nD zLLE24+1yoJ)p_o!V(uy_cU2lUFM^%ddah~?cNJH)oUO9=M6wX7gGu2%4H|%{75T+- z?_R&4O=9vt?oWGpRyp+#e$hu6P1I|C$=8_&x(59jKc0Q8>wSOLL2_93sh|9n^ond& zK=y`Au964lzBPe9(9bAYJ{EF4>KO!c<`#ap?m7o4^nCheZo+f|&_PM>k%|16epUFET{&M?& z&QGph_=C&q@d@6{0Usw+;+Iu| z_```grLJ2xShxGw0EAV@Z32*XE zobHaj6~z_q*qbiw%M);bUGEim>pQngn=9Z7yt_8OpA=4EWnIq|P>c7sRp1R^ct;dI zR3&bgfwAy=A>uh(oH~yuaO0=YTSAg7B`-4ZGZqnt_z4>{WCJN&G$p>QpE!dq*~J&0 z66b>PXHXOK8MwLN+TGRFjWsJ>jvXuECFxymwRR;9ue;-yybF_GeV^iA4#i%2XaDsO Xev{s#aheQ9GhOK1v1=uEztR5yXTuH` literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabi.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabi.a new file mode 100644 index 0000000000000000000000000000000000000000..d017a15b7b61a5cd6b006561d34521470f79040e GIT binary patch literal 24408 zcmeHvYnW8kneN(E-O_Xe(hUeGYOAfb9cb!)Nieir6tO{23~JP-uF|n@Ru{JnDls~O z<3ux2$0$iOA(4!Znv6OoI+3W)XpD|Jj~R&}8P8}O=ENh$_83nz=DhFP-`c(Qrb;ts z&U1d91$)2iTi@kfx4qWhRlE9_1-VLL{imCci_VY7+Q(C5JlpQ(?Q?s3ED=w*CF`2= z{X_Gs>o*MMH)aOA2Xp;H^M;0pO7lv&e1G?_QtFDOy{9^kgPfZj)v3lMrHZHP^2UUQ zPIWD{KN>lWBJB>0P2c89uDoq*`u0c1hOf8FDi4m^=dHYRjPsjS%E|oUg>n6(V|_l~ zN5{?#$o|*|#+m~BP1|j5_2_u)17lNtwg<*0`s8h66MeotmaqENhrcpyZnw%KR{k!l zU(~Uo5*+?P1~DJbEBBPYV+|O7;D|O=lkRJ-8R-5&`v#ZQE@hW81S|y=C`d&;Fi(ye%N_@yQ3qw)^V2 zZEU-*9Sx_AxADMObHKLQXM13*C7^Hd>HmntHZmQ8!%?dUlW;VsF=y2`kkP4zVJ%e% zg@{3D&_}%()WVQJ!un+Yj}4tx=lChp8pBhj&OBnu{flO|I_Jz(DwK7?QqhI_4(XYtE8ntkwo=oNRMBZHJh$b%mbGx0;kP+`8m$g%R3UL1^ zABARiqnb0BnZr>s)1{%u5foWIr$tvmsUs8Oa+IHN;cT=_siQ55M%GK6g*nT)g0o(L z=crS(q*SjUA#^5BYj`>jr||PQ?ZDwU4F!N|xP(H(D9)jVKf^iPa3zaX*_?q-ruA%*^mr<-~DDo#4+gUBH0PJn8-gF?fdIENbU!8wdWh4wJV3j7le*ggqR z4Np_RF<~7~PUvTV(9dyddIhIus6vySiLJm>m~UH&c00{2t0_#QfJt*UgfFsSwln#9 zjat$4ugEv!+6;9%O>MxFnU6S=mI6nZ&p4AeYovX1%U0%3c7rxu4dEUZobEK;5Bw$b ztDL4+fs@dp&{}6=8}MZ2FQSvFR-YST(o$$fs4am;qgFI+MgH5AH#!sV0{(*eTkQz9 zxe+G*J2Y(=<nr*D^RwP<@Y*MwgSJ+{QXYTUBDNa|AEu= zGBDhT{EwW86M>&({t3-8`7|#-dAXNWhpt5aa>_q-CSR+O=99nVWmV|Q$WOWnr=PO$ zb*a|t9CS7D=O~+u#V_<5%BHj4&`LFFHZ&`!eOtWVcD>F++4U^{ovxgW{Cm2ks_ARc z{EXTUovFVD9ytN|Hr$|u<{{S_#pyy8o#SZlL-ON-YVC(`GYk4`tt+V3ozVP*+J0N> z3aa%vX#PO$sI7Gc)!NXcR2oO9|8Fco!nL5Bc&nO00sRjPUZzfj-HjUxH)&T`={U{WikGVs zIm}tb>(zD6j2rGXq??Jz?|~c3iWUzGmn!1QY-DrJX2_H zO;0Wf@SI=6)AfUAEZ~W{qMckooXFv{;u<1t_!I(>Qrd9DNywjuvN`M=_QR3RDlS(@ zx;NZD<2r*{tdm+uf9d*bQ=CG}O)YdWO_)Nxrq~ydixmP6d{n^I#?v40Y*XwD$Q2I( zH-A*XbB(7z;Q6K)yD6*eHkr$&Op~kpLG6y=@~Ni@FB0kEZ~DzKP43Yp)-2`fidp(Y zvE+aRW+~TPq5nsJJiC%yd&TOtfR#0RT!Vv^43QH_h7y&WqD!nwa*0MI4;M>Q$)h~C zwOqJiae_aVJ@L7m!y*=lVX<(LhsCD@7J4Lf<<@fPcN=;55^!_%cYFFUXEoP<>GtLR z2x!syD4FG~E@_3XHm?R}EjJ0>AKWFpP~0aZ)TQts_hB^G7y4yxsO>tG)wSG5tghvj zF!QV0$nM&2>k{20eci3)HseHSJ^g!rYkP8Wy9ow=&To!Z{$f11J9D`k$)xyqzqK2j zJ>jh7u7nGw5%Y{`4h}T+Xf9^VGlix&6aA~1>&i_GuB{*CdaUJYT~*xdWGn~4!0k@@ zyhEbtG1q;b)FqZP_d;>z&7I}E=pg5_gU;M4#raXc^SXnaFAX|#Cl%-Ye&@>%a=t$3 z%#GG{p1#v>Z4WlLTWhfOhVzKu9E1H6U1D86+>3*5{~~T2e0Tc3s!Ob{2Z!MTe|@QB~q4$i$i7+gPp`hs8R2AHq{%iDwowFKbK=>}yU zfrUb^+pHNka3)i3klP{?uM(z@L*rM^&gef5^%iXLq3d-D#?>nnGzNqEkCRP3KF&_) zz5X%w|G(dAkBjLaY6}Cop^Mvldq1NUNkl@nmp+wl^Y$LKhU4=u8gYg`KmBnDXGydLj{$q4iEMh z)P{^Yt2B_?Tq+VvxzUn3rEuwnewYDKq|Po~x_Gpz&a4zmmHwfNRe7+gDpj>Hs(MT1 zsyd7OYH?|(TB@jXhAtTz-ZZ368R)-wXb@$pQX1Vb0PjoG(nkKeF-+uvCScB)Ia28# z%#B{6Yga6!%ZYL(pU)<;sYp)O&eI2c(Wnt=R5l%trc<$KJR6G?68RL#w63-b8OObLZ8`0*_9BjU+%xRfPWz)$l9HQ}3wiwfW3{5Tbewde1`CKAhjH8RvFuv3{ie~xH?*` zG*;p)-PQ~pwu8qQXbO*)C3?};es@zh_ z#cZUQj+D~nWHy;k>cy^FRaH!kQniL3no`w{n2YIbEQ^IQS}w=k20&BKB?m67{R!+N zTpnWCQmM=~SF5=iF4*#*VEvNCd<>UtG?p!-OOdG5FIS5v8gZAlp;33&i)Q16WE4)h zRI!-yRz9k0P+H!45zH47kxaQCSX5teTm<2L@HEK`a*y6TG>QtxVuf5JnU2RZ z$w)pLO|X$vaU5_J^bZBNGp1ZBFwj5fF5JmnK3j}r^H_W$<%r&LQ30*~6GG^@9*>t| z(NZ}RNoM1*sGjQ*BG?9BEwC<{T0~3nYze)Wjz!W4rFS!<{-|1r4Qo-#XVUR9R?%n? z>vg%r4l!!=J{}|7CyCGC!QhX$`5hlabv~Z=%)H{rHX-*Ez1~3-K`ETN!^0YuugjF+6aGax|XPctu5^lDoy* zkachP_8}*?aPRBjT+;7Aq1*}Hgomx*WqzdQ=3>4LhPa2kTB@8=PojV~h`-P#W|hK9 zs=i`+z?}|1u*FU4F?<}NZ%5R*h##_vXb3Fw^(cy~vmw=fg0**1!+oISCgA?rYVZurl|^U(&_nH>V-p z6n+1v7I^uRy5DEFNxg&^yn#N;W#ldT1-erD()$ET_5J-&9v zyTzONtAV(i-{^KF?+n#6-7ma38`gbiFZwrP5_1!L%nV*tJ#P=Tti=!L5L`zph>v-J zV|@Da+c9| ze1xy$DqH4rv6(+wDa_XwITr#x*(0jE7>nR8*A(<6*Qn3o`A$Qqv9URPk<;KbP6?mT zjnCv!sercVYTK9B)DAce;l`QazngKTj`8cyIW^6;xMts((Ou6BQJTZwn4zl_Mi|;1 zQlm!Go5Pd48ynBiaW)=QDPNcm5Qeq8YR2+EiS~<^xb}aT{-@brEB5c!x7QsUal3HM zLABM|PrBOWwY5*j(!_nL?HiFb@;D# zoDi1LgQm^3;`jT@YuEdF(f`jn`kO?5ppJg0vpjTIkauEp`0vH<*~@G62lW3S`X`}3 zsNT>&F8UwW@&AeFAFiW+4tmbH=chH@U2oEb8bS1`7(ViGhTjRfBk-%sYPaY<(Z5(n z|3lF~T}S_f==apoKPUPJ>gaza`g`l>Ul#q}TvlTypdBx4ddf2DO+htY?t2VXEr*E^g^q-;r(x=zolXx~^HA~;=c?FQ|6jn#5KA-;) zwi@w|QpI**o>VSTY z`kYVCck#wkSgloO`}AwamB@wF`TFT-yzu<-tkz$s8h!nDVL-o5z3Gd;E}$={mwfs{ zKwnmSeEM=g-><&w)AtAT1M07Q`hkFcSpAt#KOE3kRMDq*AFqs2SZy#_jbVIcVW+U# zY>Vj6tpWLRwF2?mz0#E`<&%Tsd9`QBOjuo`cJL+_dEQ62q2wjpep2SJwBfuTNSV)7 zZCEewgyFdTBz2NcK2*PdLOoZ?Hby{w#^cRUZ-~7cf0p`ZpL~SkyAL)(?0mb)O;3D&7SpAJp z@6Puw*f4c5D3OgPvQvnhTtwMkyQYZD4+D_8WZUeTE;3)eLF$t2uuHx~?~->@x@4Q{ zYS(6}>sY}K!4m{K1!Y_6nk#a*plml?F_GOLhNv#tM!GUm{z*aE9=bj)a*yC5!6kyH z3N8~|F4*hN>k#^ZJ0X!KA=L9yBKU44g70x6_}(Cbk6p_5rQxDNXL0Vh$gT=~2Jdi- z%&rJwS>R4hySaj#x0Klw;wgfs39b<2e4(B%WE0m376k_dxl&R81;IZTyk78T!JUHN z6x=QNeZhwX9}|2^@CCuWg1;2}H^J8h-xPdXkT;O5*Cb3@;#9#|f*pcfC#a7ICIlA< z_6RN$TqBqhEC~(@UMjdn@G`-x1-TBB?`FYo3EnAqui(RiyiRHVq~K2l_X_@6@IM6K z6%2=5zX^he3LYVNwBU(?pAd`-rUe%YE*3mP@Jzwa3YG;cf*S=d7u+Fuli;m_Ul;t2 z;P(X|6ntFpdBGP2_X+M7d_(Ym2_Ay=nElo)$d}+LA12r?c)Z|Af+@kpf~N_t5zGme z1S^792!2uU2Enfh-XVCe;6DidSnz4Vmjw0e_Neb`BEK#8JHht_Ct|H-yJiX=A=n`p z6-){)7F;cOj^IUtgGBVI$pAvjY%HI^!ukknOAIs?a z;@2lC1i4f2WFqzlzSzn3oF#Hza1#-W9`9qR-%ebq)O8}?Ci*+2{63K%Ct{y@mI%MS zBJUUcqu_M3A%uPCC?f1m5;-f#Utm#RBDN_tOoZL%MZQ+>4#5YB*vIw|VfUQK`-oVq zUzhR&f*(rxv zcBLMZ@@GYUnRqPbos=IC`2%7H_8*KH>(xqxd=&8n)KkjiBKHtGm0B+4=MXVo=ZRbv z)ITujRO-u=u|MA?<+}vGC%8xS`-s@gUYGI%f*(rxG(6gey3v0`)N`)L`sW7N=NC(P zui$5iC?6rlFrHGrL*$!@xF5J(%I^~SVZj%ODf~P}^skHjuHYohY3}ET5mBFGi0Fso zMNWwRbRst8v!(nZBJA=aUn=@PC*pqK1}VRd2)l2He2?fKC*pqLSt;L3gxx-oeV0F6DnK@(+p2lzKwS zpB3CE<-a8^SL%H!Z^kuGc_y(J{YOMSc@Ig0<1$jARqppoT*q)J>2<4}2xTV` za|J`L*BcCtURQdEQ{+Bus!|A{uk&+>xQ^Emaow&bBIpPa*W+d)uD@+WTyNWn?HC^- zuA^IsxK3^-;yT$)>{RMLVwX}65$9r^Aa*PD6fvUomu;Mndnsf7y+Xu1+fU3W^%fEH zeb-hA!|^~n7W#!uhxV4T`nek$5eTqgHB=+_M8Uic%izZwLah!D`N8mAJ` zf9ML0vxqQ4(>1men-!kaTng$RL^S3)!5fGe zzZ(T_A)=8x1#c%}Ja-B1CZh3o3*JY>_}(x05HX_EBZ7N~81E+ppCTrddPeYhBF6tk z!M(%`u4lnlh?ozr3GOE@kmm;ATa+$8-{xYBR{K9&w4TbGQTi&^mS=)7Ugqf{)FVZgp4lJ^9@bYdQ@G{ zH&AIAA@zJaSL6$bn0M<%9w1JV>k{#{QpRT`g^{cAFQE zYwOI*JbWXlwuSe`T5UDn*umRuwRLo@r}JLls_V-4lInSzw|na8O|$Ch`Nmdvv6SC% zabGTR+XBRzn*YPHgz-%u^#*99C@x2_`_^3^RP z2bB%w2K{BZ3Vz(+FES-=AiSAdr$sW{_0$~hdOG)=q}q-4UhJx^hO7G;T5Yu%?t0Aj zYgDx(jK2|HTW=;zJqEt)SI5(PwN2~Y{_P(s57)7`UY_nA8m^YQPg{A;ywPf|a7i5p zzSmcqnlGVQr22OsmRzo2Ues~r>u~jS{&$FLQ;UtflUCb?Z!Xr>xG&>bRUH^E)G_5d zgtde4ExI}y{8pkHQ@olZZW+{Ab7|zO!yU!$cvf{(yJPws)n}YgoYBSl9Mxxiil=q4 zK1cOgpW-Q9tj|$>)~9$<7wdCWpYk&H$fVNQ$h^YE8@jau_YZ$+nuPrYTbP#;ieb^*yuR1M2 zhIymHmgh^@#&ps@$w$t%GddbzyVZ%GzvBPMl_F!yRM_^tx)`4gFv6p{m#X-HoOU~K z(1r))7ZBL4Uk}Pm9gy{SpLFd!UTn46-`E=7$6;slZnb#vQH#g>Z^+xct03dH#Y+gI z(_WnI_Fe#)^)?)a_eHA=S#_1g%ebb!cOYZ)7DY!NCd2#JuASH3_0W+Qw^TYY9@AHl zF?FGQoy9vDGVSPhoEy*U+Y!+LbTYiNT|1Ar3N8H)bkKwu%o|u^TqJ~D8PHa#f#f=uf3blk#;}tfvy(splj#NtEXT`UfkO2WO(~w zXZQ0X7Vpupq#gaX2%l5<9!XK^zU%h9`91v*}TtKyvM`Vw0By7_YLT3wRd8G_Z`@g_e2~_roH^r z1UB!B7H_B6(U0Fl+3o!RWwm%$yLMiC`FRKZ@hGN~;avecn|GhZ`w3W@_6{I#^G1QUbtP<@?dxpp3JJ7n@kL~ndp zADj0Lix*jscYk1fJL~ZNDlooth1a~fWq4l>jPE-ZFYf_p$NFA_3_^H)o2bKknQP~@ zHzT}wbk@o6Zb8Ow?*|rd8kV#p?>`0F+f#@4i9mao2(Nk5%<%3Bw6_7z_~hAv1CR3_ zFTXcL2(P`pb$GuL;9VuW3*gISc=-n@?DkHwcuy8P)?+ZhdoJSPV-7Ewc~uDTR)yER z8E1I=0=&~L-X26X{mg3$A-wi(g;47{I>xp0#`h}WU4(Kb!+Rw1c6;Yoyo<$-?TrW8 zd!59CN+;7^em@MA$9tpLEfqV%%kPtI-VTfRRM?vKhTxC?UK@8psMX&0U;~xMy9)yA zy$lDF;pO^i^Uk$+PZvA-{T2?G-!nE`)>4 z`v`;%29jjr@q22U_Z8t?8L;E`+BWY3i}y^}G9GygZalAV`8j2W#3Im+={(oY>*q;m z7yVaj?YJGkFSmJ@SiEP!mhtHKIq=}W$2%SIYK`wY*UsbR=b`jpgM-P`?*iD_yuB7L zK34U3dHvhG9d&q54e-ttUh`(B;awEqU1RZ{Yw>mk?qd^mc-vh&uf6+mji?Y#C52yX%9Ooo^1war_#c#C33 z-XDO}=B*;0i2=2DzrpvH@ZaOzEWBkJAsL^$U}W=dwRkTUJM!{nz?uu_NzS z;BWKZUWb?OQ^C&TW&7zrjDyMWUX5~__eP6%MC|Cd3x~~nUmf0CT|1BWA>pl{oXPOs zjJ(ae)8ZW!JM#V=9LQ_Z9>n9{Q8meA?}eQmZx`ZaV6+3r1{~yNylyxcABgIOuse5| zXEHjzr)Bai=U;*2Z@^75I=z0I||6V8HeHJcTL8JF=^r#*X*F zr`+%Q81M5qOuQL^c%AsrfcLT{nQSZU?05;>%&kKiu{wMDhI1KO0fp{k!gLk}4FrbO|FM)VFt$1Is z;@uY*w-Lm%lZnT_mk3i%ah+&~q4SclYeGd$p2}UYt6J@4JD3`fvD>=~^)vl^HT5{y z{`Ug)o7I7LurRkwGFZ7GEk(xeZ?TH2j=BD5tuYSpS~t(DO#*-3T^3N!@TLUo)x zfM7)r_10rOr*jX{)>9vI24^~RdYpPE0a~%5gHFf8^!C+QQt^{eWs+J>Tr9Sw95P1$Q}Tt#)wJ67#LW#!>>`fP+G2qC+el>1)G zc*&OeGnud{DsaQ!u;8Lq`bDX_zb&62i5~JsB)BHGq6-P~v|Vb^(?pl${>PD; zXFI(yJf261_wtDj)O6c3&ml*bp{j6K^X{q!BrL@%4%P&T0YuW-O2g}XF<@sIwlGA**)$>#g*WwwnX{HW3VKCfapq&Q=dPY}{Gk*qT+`8$zrC8 zZqAbMQ~GJNrls8L7l9@0jYQCq7m;4o9~9Xz68I~{eW!T|@$;plN_-dQjxZ{*ZNtut zAi*@icSM8@m9My~ke4!~H~Y#`hIDG7Bz0;ZxZ%OUsN&PN2bZJ_>CO^7B9+H8Qieq5-<~q07cMH7qzvisjdO|Q2X|`C zUJ)~9CGMLU(ic=k3QDJ>?d+JRhV+NdLJ)wYA>BPdrVL5HG$ZA~y`b0x>Wr6&(oY{L zOL=fBZp%*Pr3aq?Z~+5+M;4_ePY$FE>CP8T*)o)lr-46SVndy*@Md_J-RW>cR1E(b z#Q}NV+>PB`bFR7ZWLo*6N~>V`D_aiT+AhEIn@#Q2cSi4Nzj^C`bNTIC-`Rfn#jVfO z)8A};X7_S&uJyUciNjfW)@Pn1PPFD(zdAsq|6885_aM>!S)TRdX9)U+Mb@!riS(Nn zS^w7|V)^ZhtiAt6r03;Z&;61(@j$-yng1Z#kK|hq{)RaGdcJk;b=?XSwMV?)G=b8_o1-Y4k$71o0v6O|t+tY3dl zv~OH&{p(jm@4Cd|n1t{}(8=BCmX4RPM?q)^wJe z+WNc7yu#KNVbg&|@dYIPL?-#tE76L}6n&9`w?c9kna(r|nzv zpa`p7H)v-!e^*P;tqkT3&6P}aOGZg)11UW}DVelNw6cMMb1M0Ws-TZjxX4F}j|Yl} z%gsmmCC39LZT#Y)$?RP=;e$0oBUbl9qc`XV)o&B-DirRzln&kQ_6Dm(!N%O6=RmOa zfN$lelaf!Pl0Std6C~e07?O{L}8ZXPT*A7GBh`c3=GO`ZJW z{r#)qreFJuPxFg=`^B%-2HjObk2}y@BW$q+n{$KBJ;A)U?vQ?pq!+D{v2MxvQt7Bt zG6Azt78ab1DEcglcU1DTKE>H6EJ6hz6AD-ECR1TZAnKHf{W} zTZ$1-+^;xA$;VY#)jv!q@PJhXlaydfd%!f*U))>11_1fGuVk#exD&qicb&+9nFe>m zctm*R^BnMPJ1>(=ge4zXC0~$BBkx!gW1|a4Mhnit05;?m_XgG+4dl1=o4U%)L;WSk zBIdz>SE4o@E@y9dU( zA-LNe%zMo!y+}$XCZW#&!LKs4-$l0XaR(dS?RYr{-fLANv=q3}qu8J}CgKFMU zU+cKt<7o_TFUU2OvmlQ*g<+NIYzD7%T$YV~>tT5Dutj6f9X5oRm({__xtFh}$28U5=wmXe_HRWbq~#;f{2;69e0c8Yqcv)W#a4%kDI5O)gTSw;P>0d*v>wZkMsXneuF>o59kCziMo3 zyWBg0U#|H*9N2Cnm6kLybDVdL_G-8RAY;mjjNUjF@= zNa)=lALhvKr8c{@NBCe^_+xVOa+#qJg-tz_AtIHd~ko0aOgo<1{9J#23L^; z?##+`wg7kLr-w?rc-QUsU)Qx|PFsc0TNow$NGb9UU&nR=BP%Tct&mpe4C5jE6B+2q zcoE++w*WoQ-SVYa<00~EV#U!uaUj2L2cBM87;ar^EJs5XBJWD1Mf?TcYt!Dd@nxAd z@^?hHCD%*1kv8q$$@waD3~gMPs}+TdpmBH=G(~yHk|%yjeI41@ zhQ8*J<4#Rym%Uz}u(gm`y;_2xd9m)Uav$tB9VLnn1=j5E=RE)mq5SNq{H#(wM&aYQPtixo zhePr~R^bwFgH?n52;or4p+NCLShV)F zM%rQ0QI%+Z8Q6$1Og2aQi#nGO{`g*)uolw>_qCoyjPdr{_6{4J|cVQHTSxx~K-Fj27=m@{~blJ(w zyfC4hCp?Nq_$U#$v&68|Iw|?wwr$Dr{u{z&^0VL&>N`BS-f0(a(MwCYb z#T#XUT`>No0wH4X!_Y~;PQVX!<;sO3KS5{w8B@pM@OSH*xe$Yqehzin>qUOwToGV> zSGYXkIV`UDLzjg>9;Gzg?Xw}R;KT!&Pss=QJCZQ|D1ltP<$}5Hm4VW0f&d`}mCZkD9I!K3;#e|T|qQ3}6 z{>7!I8J<8%JOO~%OLJ8sfrSJGXBm}zHX|l|NivJ=VUABQ|LAV^j=5>sw#FXesgl#+ z9Po3yBWuH!b-hGxmqlLqKE$bzpiwEgW$^)DNiQMq^{t!0R{uJdpN!B4!%y?l3gHyJ z)*}#AS3AL2ZFRIdE`yJ$0Qg9QLu1sL?K-uKHo|G8hoAarW~z+&aMM-4XnFFXB22)uzm?D2FF{$)bWzSS~MNxSW-Hr1-V?#8ZiKe>04c zd!D$>vJS1^Cx?(9oMSz^9LkuyGwX6XBk#_7d-9{v!!xV5V_A1NoqD4~PiaWXZZMcw zzV^+=*Qy0B)q)xMdTTqD^*1xpKbe#m(k5U?+}d+R{QXiH=I@wFy))xsvoc#&qE#z+~o1~a9#tI3#d49$iY zk>etAX2k1p2Cp@l-xIIFtBe=8=d<8dI}Khy1H3@o^^`%au~TNP!C{W!6`2jM(Hz(4 z%y^w-@cP;J#cS*;;Uxk--_r5V{^ycy$({x9>{%<4mC+S(8BJJ|>zmxEHYBV+3>9#+ zYt0TPt<_MJL8k^^m6g-cIF8fXkCBC*$if)k*%ZjOb?&k9qOZ$BUzGCl%AA86#?75J zVYtIvaB_KHai^u|>%L?YGPYJTHl!*0Gc={qp6kULtsEbuj1hzD1dQGCN!)H>Z11G? zXfw>6(_cb3Z|-;$@WM7E1JjiC$ZKV>S~(+DDJEkKD{L(~U0}KxG%h`5G~3lWY-)r3 zLP)39>TulF{yf3gkhg^7aja78m&QkiB{e9s(Va=4I#HC`w&WOp(djZXV>a?y!5P8J z2%ZwRhCJt_nG74|XPHevc+eL{Aj$IEho_)qd{bs;( zOY+mSen|2V3ZUclUX#ZDE+ZhG4HO$-&VqKuT;siR1z!3kkZQ_PR>#j%=RHxWfG5Ex;7 zE70Rtq?>qmUlrYS;_jJccXr)GDNcc+_%_|tMDMyxHvtW>)7f24%4ya(>;^rAs$;q- z6vu9Q-85R{8s)IN+%LUMH>Gczd49>d3Hw5vZo*l@WgWNho>dG+59gHw>8~IYs<4oq zGe*l2b#Udqc%JC?T!=Cx`P50Vvgy{BQ3YhfV)L7RecA0w@ub1u02<8CWH1}`W|*N` zOPigV*xEdL+5A%CfU4Cl)#~rCzT9`E&v1tMsjy)-^ZL2lReRa<0~*YaHb8d6=+wfh zVT5dmK4yDlPuU*R^JrwXEAk!YccS`A=Lcrg6pv=Y`TmaI^D5amuJ|O9OhPs@^bub> zB5d^r9=7pKw!n|OgQjuDj=}RUfooWQzk*2%bdh1Ay1J>Rx~a9vLDkhYK(1zcG8Sr0 zVgvllX~+}l9A-0^WVD%9$83rOOr%q>->+i!Sg7EBpYDQB7klQ)#YsAERN~F*hlqbs z-IBCYg%^iE|0`yjb=}go+a|2)4BR6_wm_-$Pvok(QHUh_bPXy5Es=D>nt7-(lZWbL zpAw4=X`hmo+!4x89tHcYCDDG1#Q>N%9}@#O&e(4V;(R+Zu<5pL0^4u4TXQ+@Hg?5d za2<0+LbUIvJSL)mxAUy4nlA`<`mpz}j3~jMJ-jKQVTf(W7>L`jyrRLr>wEo6B(Npv3nXy%O5MZK zI_9KtSbB5uP@u#cDLn4Ke%QbAIPZFh4zXdP!jDMl`#nedO9uJ5NBdTWdHG%we^cQjMxHEF{4~JCkKRxo2Y#~e*wNh7?4jJ??s!tvKQ_*$ z>VcbdCfW$uI<-?ngF(zwgcQ{up`he22>Xcv$kQ-bI&s7a>S}i3AW#@~%q?CfOAzUl7e{pddl@XVi5| z+MX(guS5u9#>4#LFvN`g5HoIjXcz+UR_T9PGhb{3?*KS(k1cq2)ng0?hNXY&jkxg^ zgO+YcxhusJFuXHFEY1`v!|WwxxPp1u!&5xgo`E--tvd^czq{i+7Q2FpK`~dH4y@t$ zFT`VdV|a5L<}tz!JXYm%XAD4)sdxP*=~rm7jfm$)Y!F`>_%P9*_)!86;TZqeRE)ng zyNt@YnZU;O!=VLb#KOz$Ay5~wwXTiP6}N&Cg=YupYcQ@Mf7+6)C$x}ZRcn(Pz~gn$ zBxy9-U3Su_)0rr2OoH#WAg(_pQ@Voj-2!r)CyJDujFil3A9;m|zMH=_3f!0<^WA(@ zqU?V^-_0@~V*DpsmtCRnW=+5v`!;F8%koeOpvUu2tK&GcG6aip9LAJ96oWDrq1a>a z0LG-+;4+v@kcm=Lq*~2ltcqi-jO$}27sp~utr?@%#4zsRVhO!BK9dqlKvKh8o=ln$ zROl6g#oDXt3C`g`W{$H#CLu3X`QWm|m_j$^^?t@{o+YMmZ6eR!m4f3~$BU59!!d;f z_>#DlUE9AM#}per6-OLsu$#;@X{2e=Zl|;+Gd9*h7sYWTr{z`4+LM;G-<4M%x;ni2 z(D&h0tQWR`UU)t^&K1rs3*}V#auQu}M(3}J^J{`$a8a-^Wjb%1(+dd=uwKyF9hBB- zcbe4TLaDJ40r}%N)~P-@%d?|vJ);R&vp#wBGM=4^e??!L(Z{TOIEh!kXZ))xfmheU z`JtfpQM7!-Cm$nXc~fB2zk*>F%8nvQv?qImN-|zrD{MU=B$Z&BVIz(7rvGR|`&Lo= zkE+t?c+M|-mlAd`^ED&belwuJz0e+vy7BZ63dSt3os3CutC;jQh@1x<7|S*9JDhKwlcw-9D#}%!K57 zPJB^`2LuxoUSypsvMwg5DUPE>>fN=kZO<`b{=8i^czaq)Cw@eGU?m=a{RrLZunzoW z*;np(ymV5yiOp?BlX9DvVp*Rx$+=Bfm&3tC9rxduZ^Hkr_{KRq->^-vPSF@ldZW=~ z)@V#dgO=r+P!8lHiy$9)5Ae+~;2RI{%{cJQ2=Gl9_$IV)7QV5pcUjiY$TvCvV-~*Y z`XTw|9*`?8MuBaNWx*Hy9k7Wfu58%d8haV3<(se^V%dzxPucxF156&VIc0Z`7B zkh+axvjSv~-JkKj;_jAgu-)2!hSx(bYx}P~*d7VsgY;dTwZ(PQ<~Wk$UfW^_kh0>Y*Ma|QJ4oVQ{fI0*kjIfIma_efB zOUtM}z?W^__61QvDTEJ%c+1xa%Am9qdWM zDH4sDrd_b)0Pci*N;OQ+@2Y!;RQG;I+{<3MYPh$*a&>V3jUV`3CI1#Rlg#e}48O0B z@jEq*mVteQ&CL|%c)ioEf#A7XV|Ey6QqAZY)oi#^_YG0^eMj8;j$bw0(_j4|aKAN0 z&ur=VB`;+kBa>8pII_S+F{&n2x3hbA_A>q>&NMePrKZNPhF6np9vaue18}I#T8CZ@ z*i#0l)1a*cpC^ugsvREF^VObEbsT@z4!?9us_!^uhhKVQMmzk(Z+{3o{LTdIaBi%* z<5|FNDi4hzgKeO!x=?isQ~a1|aJ$T1Ou~&xOWPef(&TcvbUI3{QR@LWDvn!f-iO7_ z=WOvg89% z^7aHQvHdoaj8{PlJWkSJ&dDqoTukgOP$A37sr|9)2>@* zB*= zr&@SR%v@a^s{?!ucGy+#0u^AVjb?*7rbktAd{g;zDXT{tJduVtzA-&IGk>1_7XCc< zL-1!+!dirL$<2^U2J9#W#4clyP4VX___dS4ALj-ehO`@+ga8Xh%zEM;yZ|ab-nE=iGT0y|TQr&3DU|INLH%Hf%)k zW}tLwd_~ds1Zb{)0E|)j3tlBVNH*87<1=UeV*?13hngGoH&j*7KfM{0qs5?2=dVru335 z!zcTrELWB1n|EriNmb~}{@c8&(G9+wkFr}{zQ>olKj#3|;9K7ZD>?d&F*;Xr z^xJ@r`{zoIj%5<#z?B^RKA_?Lxss#PF*;Xr^g5v9{<)H)H^%5($LsAB@qt zlB0Wp4lIMXlB0J44UeBIIr>vT%YuKdcPI1 zz!q=?-c26gKMki4N%F7-)Z+b|)p)}r-T{aYwTauqU@Y9;pZFdHyj3K=VIh7By(J`t zQ}TdQUt<{{h!-+Jawc%dMi1j*tf@2Tk_k58DX}gGcLp^v8=0L8uEhh0nS8O6-F0=l z>Q_1K+gHI)2JEEO+Epa{_yhjQgQDagf|%w68 literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabihf.a b/bitbox02-bt/vendor/cortex-m/bin/thumbv8m.main-none-eabihf.a new file mode 100644 index 0000000000000000000000000000000000000000..223ff1df388e198bef9c760e63a65ede3e27df07 GIT binary patch literal 25524 zcmeHvdzf5Bopzn>8JJ8iB$JQ}2{1qiaU_$zUo^nv1|bAUAeg`clfIIXxzW>;%eMg{ zm(PJkh`WLaL4j3>D+`E-sAz(?O8{5mBWMuRxS(bqSON?ptEk`m*7?=xIw#%W_v}93 zUtd9=w|@1zymdQOb$U+cm<72?Vg1Ri$3^GIW9_vRsb$;UynStNk0leyl(t#dn(yhK zUtK@km*0@->+H+*^v~-b=r7GHS90a8qfz-UW=zh%VcRy%944~$Oq*&Y}j|6X;;diz zwu(CI*jMcPt41f%Z|9W%RQpVwZQHFMVB57{yekM_VmdtXdR0+V{F28Mi~a8W>4;6?zcI8GOeaItB^Rc z($kJ~{7%!Uk3ut}SH%n>M==F-q(CPkLd8mp_I)R75sIm%CX$_%tjsiQ55X4Xp` zz?|h=!BsENv(!Q@DdjHFt`IsK7+THC`M8Al;Bp;4j?+{CsHRIPG!5YzYWiDT!%bJQ zST%ndQJ=;qyt~yoK_5W|LAL``(_Ivr?!`6KbU&_Pd{k%` zbF9D*@qz7=0M+y~1$+)&$BPqs9uRr~mzI6Fv_cgc?~IuQT*!Ret7x~=I(8L>$rLbY z&V_I_3uZXuZ_=n0Ex$y*758RnuG7*6Jc;>;Gj1txkok-=ev?Mpw~pPy{7G)mmTMv0 z&w|sPmWP2qXMUyA@-lE7S`=F2jA;X&#Qeo{GS%vKBaB-L%^oPqXgL#Q8(98;GhqwxOUys) zw0s5l9P{6FT7Cu$HzWUDXUrJjN0|SaL zYSMOSo}#wL*1Ce4^ei-gqISsEx`LY2)S^@xpU~y5wzW;q*DJJy<#Q2q!_;5nIEUz| zagD2L-ip%uskzQ*t`n!w*HJv_ySThV{Vl%8pEZ%4F-m3e3Eg4*?{HOTn7eKUnZKcOo1v99Z0>U16o;fC5&$-JQr(XC?1rhTCUcr%;P^QVZ!X zU4LzgOK7>Ng)XKEQ)q=L_66i(hk(8B7jTvF^aniG6#D{l#YDhO?-y{b@$?70z!YOQ zW|iG0bJ>+?a*aQz-7#E#^)%s4CS82D-yGBAeqCbCQm)RJrQZ@u4oF~@a?KX{fAz<+ zE6KH6tX>INS)<1_JXpyPIgw;2QOOCq#Hu8hcvSKTu{4!D%5z)8g&!7k{ITqb&+Pyf zu|N!qg_{H{P7YY;kz+@8Z{t?jO?a%l#41q6<(m-C0%A3SDj9 z4bB>FGP*yw%Xp!<&q%1t;6d)GG}kx!H%l4IJ}_{*ls=y=(e#+>K2Pcr%b9zr zIP-95IWIcM`P`s0w_0)D>33dtkn?3hXYRz}yx;G9#X-(D1)aH3yUtU#`>pN4=5}oj zw%%|a^P6L^pVB4P?Zdr1==KwFR+=`PCQvqF`_y5hVCvm3 zyhVE#LA_MR>o24K|NU5hoJ{`&k=BLYT>mBQD^`5$%=WpJ;h}1weM6}-)HBfE9_>tK zJ0tV@doEdD?cLlyw~#Cq3ejXb(jJS%qVuA$dC}yDKBRI(ee-*J@|~3-)j3}k1}Y^r zw7I{aa@B#po`M?AsB=oaxlN@av6LGssfC5hhI?QJM3FkTblKvesye$;ELD2?FHz;b zs;X4ghNxOmDp%Dxt6wXnD6lKwuFsY+>RxEJ1+s-=|*D71w7 zsGk1bp8k^RzTm7l#FQ(hy1Vn24pyV-_0f2=kT0Zjg+#hk$Ru)0m8%LkM5Eo^g@OKR zWuUja0=GgWnJg3{#atvFiA5q=x_Npv9FM8W`$X7?2r`QL0b`fz?PkV5NJ-fA&%%!5Sd@dVL6|&kKnm}}PS>Mp09{YSeTPT*|v0N^d zh@$gZ9j&YH!oe<<(ZQ)$Ihjjm^U;K!E_B(bHspE(ZfJJ@z#!X^OhvNgQZAP%m6I4I z@<0--V6JrE}S0A{Qy9iurgfqvru#^xU;>HZ*9cv;hu@e7Tq_W@CkXDjCVebc3J? zFu;7cSZ4fWp`1^rQpr-JT*^kYIWz~GZ!B|KW>VR7G7E=jyp%1*bRR=g&%6ibrBptb zNEhSiqI9_sOR~Wm%RK?}XbhEK-#xT>sF3UJB}*w6k0%P*EC#cbEk)^8Gf@2%m8)D5 z41yub4-8a?s+AlEHjyc%ao0wRu@Wj?&@;}{E6fX3*`PM0`vPI&D2m1r3X3O3w7W02 z3Bd}bNF<%km-CTyB9Y1IfwL^?#b9+L2G_DkG*wPzGFZu?xkxnXix6BnbR8^z&Vzg= zTZ*JhrAR)Xi)XTWoJ{=STrh1Y=dfCPa~2b>kc$`d#Y_})DyloxvZ&Vv%#u=nF5g?~ z?kVI7>p20Eg>)j0TR&BfCz6E}mcoF|`^PDoIE7d$lT4>G*;p)-PQ~pwu8qPUAPi`hsq9Vw;D$!s#8)QerUs;Zb6rD`2NG^MH?F&ER>SQZOqv|Nt64S=SR zOAcI#LM(xOgv&!LTPl^==4v%p#|2v+6s%ven2+I>jmENtbSV;*`sM2JL?iCf)<5L# zdeLmWkc`49mns%h-pWUH9ZJhvFM|0(B9bYW%ZWrT8jI>Xj*B3?51uBOKJL+*`iD^A zSgeqXB-8PDCK<^`qX{;WDvks0f}Z{WcgB=U1$uk>+=V-t%V&#`Y#xhGq#V&(E-Ika ze?Y0ELtjOBFSt#7S(fILIm63s|D6YQ;TRRo-LvG(y>Syq4aKM)bCddv0*Jr z`Aj-q#wr>uV!bYx*da!(%7ep!FmV)RySvMSLxqa&h*Tb1e;EzPm(tl(RCk1E-_MoQ zsdO=x$i!oDtY5K`du(xCH>#uYwC6tKjN*~y6#S*9Hha`>^Y0o%{Z{SheEC8ruciE<8E>#9#ed4^5d|^xscyJ1kOgRFz@9E zRB}$e9a;CN`4Vz+c>Jgi$<5?06v`R&c|0rz7nqC0ut#l$Ax^LVB2~_*CsDwo=}hfr z)<>-2>c^%B+==*KwzyG+a9Y;~A+;6}>|?g=M)fHznwfMTjBumkoUQJK zuQ{{-P#4z@%Zuvs-GeT5A^4__247JcHLEaDfpU2y-|G_Hu~vf zhHf-Z4X2{WJb84vdHpoPKOFK=<60n|H6GD5aL=aax?PXHdqDTEy(N7H6P;UhNLPU? ztD2}gU3MkeDSoFzaHdxfA9Dwv+AYFAJj$a=5?SxjhhNa}8G>Kp;lb&8KUz@yN zdod;7S0AiDzgDs11?8aq|Fj(JkN@fTjQ1pNyC!uNa(IL5j}yidI9Ks;@XdmnufLO+ z?|t`>h~xAgjVDu?d;~`(Jc37aiCj97PbQEl@tcTBuCjSPSFZU(mBM_z8gTvK7Zix< zuIwVXYd-~jZ#L^|c)rsVYHn@~U+gqF%@e|NI`MZ6R4Sk?y4v>Tb+x@tQ@D9r_-lt> zrDOd1<4#?(&92!!hj%tILzLF=7Y^4|3L^~d4yjY4DXro0oz2Z>=r|h=s+2FxdkDkY zU32*Izl!$iOI`avP5JBWuNV7w8r$m*j<{X8`k>ls?MGbg^7`7R@v;U-=UZ3S=?o0s zYofpP%KHAJqW^RQ{U1etT?74AybMDAYZ~xh>o_4Svj&5R6SJbcfO``u@1O3gS zKhQwG-B})*8sr_*8vcg({o56F`U86W0bIA|N$3x%H}p@4{_zI>Pl^894fM}K&pEee za?5>BVo6H-`i5Ze{U51J4TOX z+n2hzz)NaUZ~n#PiDCR#vGnr3m1h#hA3GNL^gaRJW7P4!BAnE$6voau!Kb%(QnDSU zeviGUmhgt4mBOk`?epo|EG_*HS5Nu$`fpX9O;}A=5Bc=dJsmS)HB;U0)6Wd(k5bq8 z^yZH&u31c0hlEI@+f{A)xP2Ek1omKtE5t>8szofIgyr z=F{_8tCqqluAcDe<25C6VU<$%`ShuPKCAf7RxR;lTuWiKK)?4@D_Ky>A{SPtC?4}` z>6BU)xv*NKQa=5nfPSgs+h4V`w3bCKtd{8~xLV<|T2|}NP_O#xe?~xmmU_;oKP#YL zrM~0SuL|f_t9yKUzE4?8VYNox3ahDUiCwtzBiyBP~Y(B2Lk$vy3?n3pW}>CSPiS| zeEMOd(im2oRK=&?6wveevzEf@@|u8LSX~j2c}A|Ku)0Q_hW=~!iq29UJ~=oa{?4;x zCagZC?&TpHd7kszP%;_c22kd(wBdS)==t2&hV}Mk7}o5^sgh4VOus`!Jy+T`{Kp6U zTD-&6T%SB$P4LMx)i-hcuGt@@?n9iKe2ltT>gU#XwmQ#O-xJgwKK~B<&cpVfr%pvM z#&i86s>4_RxO&Pbr_@BBoK?T{@h?yhh|K4{HmoO6AKxN1EP6iowW+0w58<`;EK_k` z{m)RJ5I(N-ZR#xj3M}nid6l}+=f7H2eexRB>+8=8)c1V)i_|(_|EyEz`s!OyKNovc z1N>$6w$Hvt{nlsStDg7i2h?t#zM`)5>4))`QM>)_{m=m$CXR(hPCld#b{dhBk0{%B z2j1}4GQZ3~>X2=@V~WUpy$Y#Aw%ZPQm!U)6KkATew4+^{sg7d>XA8~|oGU2XUdM?d zcM8gO))5og{c(}%kZr0XBjq0vlrsH zmq?co>U|jz{I?Oo{{#{IuMxq|E)HSv;i5tx<5;`Mt_xj&_x?p@*M!bfiYEiwohZn8 zP8p#!E)+aX@JvC@FWQ|ixK6Mr*eAF}@DqanTks~qTLiZY-YvL8@FBr(3w}>P8XalI9D(tm=Ihb*d@43P`?s{csY?vf_;LQ z32qj=T<}`K>jZBR{6|5q=d9-gg5MV0Dfpz|GlF{se=YbQg6{~1LvFl71rHOPDR{Kt z34$LMj0>g(PZ3-!c!uEFf`21e7OV(v5WGV0I>DO-Zxj5y;5~v52|gnDgy0^*=LBC8 z+%Nc=;C~4og7umG*(%5%PEejI*e-ay;D-cLf{O)D6I?Br6D$c<1g{jlT5y}-9fEfW za^GP+z9aa!;M0OX71Te`fZZ!1za{v4!9NO)!P?7s(*$P<&K8UcCIuG@t`a;?@M6JU z!OH}P1+NzTwBXHxpBMaRBKrOtB7aZhXNmZ{Am#f-{v8pE8NSfg^>4xcr`th9d8goF zVhet$A^NoU2(Bh#Kf9O+yB?7@3vLtq5)q5_14P(;OXQ~oeA%&u}aOB^7$e!AkJ3mR4HF2^2NkCsHc<hno^`0+yvXq}o#QESNDeo0|GZE*7tEKz~ z!P}+$L1GN!DdkUz{1YP175k+8RgwQFI0pv6=salz*NGySqjHs_6ffh;zgqDSwd&yI+d@y6D6B(-_Yg?ha-}{h<;z80LtKIVTFO5zxLL|?B;s6ltCZg>^20=&)4nU^PYV7-%3l*1 zx2yiSBbETY{^1tX>s>n$%DF_$MNA>RPGLy(delY4`hu$K^#fFTeOODx{l1Pk754`b zK?jMrk2eu<-)<%1J{=*pEB(C0`|noDxZmz1;{Mt}oU7D>#15q%C7!6%E+XdpZXznT zhZs|8FOl<>i21pnm{IBtBIenT3~`>c5WD1jg>l#CD~xYD%TGo7iObM_BE}~} zT%nXcSE1kaxoRciA#wj`5^NztKsRfgNJM|4Ycx(L!U$cVv7LxHjHYXxON29;sxd-D zf1_y{(InmPYzo)!E@GQfsJcc}S&sv%s*zRXc&rv&OGG6u6kJEd_!I@#6H&Qd!9gO% zt17sO*p45_32r4~{H_rkA)+xi2yP={JU=6ND-n&{E_f#qiLHGrO)+1J?~av{AIrB z`G@(Y&-Xw*4_7Ls&-p-1EqxywoK6`JKeLD-xsM^EOZ9w2)3qK=)AJEk&@w3Xd|WH? zg+$ED^&$0%c7?iT$Ih^YKt zkzXQWUhWt9HR3F}kKz9wWz0+6-;nk5QoHmoWZl1*m%2Y8>;9ZA{Rdh1-yFG*A+KP6 z&sAzI5%PsZ%**v6_YzM;`$gVD#Jn64`37PH?H74F5%Y3~$oCO3FCP{8F(T&WZjpaL z#Ng}|`6VLe<$jT0BQ8MuMShRSbqr(7`i>)Zq5UGyA}&JvMLv;;`Ir%T0TJ_YnaC@M z%g}z2FC=0IxD5#&V}ck*;(4u zQ{2>9Ep4iHn)lc1>+ILN>Ra%YApPQFeYJU|uD%xU`r*yF`a1Wmy81fr9l`o)xbhXW zMv=`cTaEOl(T((cIj^%=$`4=Coy+Gdl-QLG+QAoJ>sPa(LceO($S2n*oPK>w4{xqo zt@PxFt0nw|g+uPvb#ORe-8^_uS%0q2UzV%j7c~ANQ{o1~>)#DpB$J_$+PqL#ziFHd zjXW8+kxnKu6d&jfB-b|-P41DXefv0)b-X6xD{_;Qrd+YuE z&i;XFsq?h6&YL$>%@rdEo{QWN; z)~_C4VXd#xzX$SFeW1|5lrNLk55iyBG|=GZI-R%ysyX83K8M-5eU0j?zQj|ySYM<1sxR@RF4otmzUoUnp^No3s;~MIkLzN6 zjq0m=iRof}jkvRD!%o`Q9QeVRMsMB3_?2L{E*v57GtZO%TmB`qN z6^;{LU5w8^zz$zkcGrS8B z(B|C+otZ1hdb}~$&gI zXswgsof6=E!{VI*OVeI{|82MTLFnr7{uvIi^V<6;?8s~0Kr+04K*nzGyB05w`yTJt zFmY_&UC`Cz{jzK4@$QBldGW}gli}sRY+>{A3m4jP-8dQ_+EKm-ADed%J{kdKbuBKhW8V&vw0_4yvK_j z{mu^XzJ{`T?Oht+eH(W4KLH;m!@DrRJKf@)D|YnzY+!ufLs>oEPX)%8-^0)!k9ay6 zUj7}=Zg0EA`(aqpj(*qUV~_7R2=#ckx^~|9^7|e7&%=kw@N(U;dFNWZcfcM$JeY8?|7X)~p z3GlA8cu%r;zZ~FQi+K3@#7m~1zYyT93a@!Xk^RSXdw_SX#oGnF>1WmB;%Tv0Ey3hBp^z z?|O^(RM?vKw!DiA6B|$G^uz<+XR8@Zu{kos3-{GB)p4 zi}!4a$A0>P8_(nA_oK7jP`-HlJHO344g*jBRbmUZPJA!G<{hzk&w&N)=r@93_}}B5 zf_U}D_X^j}YcIctrT=Ptm<;d#f}PE~&Em!DPabc7fOmES-eQ3FMBz1W*c#q-0p43J z-nABQIdHB^G~m6^we#A`@0Ho!3-DnwynO$`ZttBI@85_W{Wy>Czt^`*8t^_8XzvQ) zy$HTchL`_hoz1($;=NexbbaA(^R8~dyVAAu+RN|B>AwyiCd146*t`!~yg9L>- zyu}8*i(Na9w^w)zC}%RfT(523M=jo>*pc_AAhmg`h-YFz?d`w+=Gu9@{QjT*Wf~zF zpQm7F^X{^EFA+QXy$*kycPr$2_YuFphn>gEzcbLk2OlQGyAS0y?{16t<6=j@U*Ti( zZfn5HAO70Bw+e4B%9#xBkCC@|_gK7rVn<&7Gj}%coeg;Z#kKR=yF+*f5QE9^K8|vm zcdx}eD0bxi9zHhjgYc`@&wLKE+xw{SR#47lcppaI=G|xU4v8IkH^blN-PM41z_s(* zyIXk88|{YoQk2`g`z_uL7B9!g=H1hPH}BecynBUr6UvzkFV_Z}_YI48v)Hk{2jDfV@}WV|d$9Z{x!lci;;Uo)t|pS?*_cyj>@|e?w)wt@xODd>_;J zFvjmDyLQYo8QuIqyp}G+K^fy+g^!81P~w^AoRjcH$&ywWNMbyG#)+LN{{$Z1dG;~M z@V3CtZpX+XxBtm|Ek1^qe{VHDjPb=|@eg-0BgyFAM#he}&5HL)*qV5+1;*`F#Iuu$ z_X;vFpm)X((u-$8Hcmk7jr?0EOz ps5TJ|S0oT``ciN}$^QG46>lZxrBxj@f(L^LCOYGoeSaeI{|9yIOqT!v literal 0 HcmV?d00001 diff --git a/bitbox02-bt/vendor/cortex-m/build.rs b/bitbox02-bt/vendor/cortex-m/build.rs new file mode 100644 index 0000000..23ceeba --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/build.rs @@ -0,0 +1,54 @@ +use std::path::PathBuf; +use std::{env, fs}; + +fn main() { + let target = env::var("TARGET").unwrap(); + let host_triple = env::var("HOST").unwrap(); + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + let name = env::var("CARGO_PKG_NAME").unwrap(); + + if host_triple == target { + println!("cargo:rustc-cfg=native"); + } + + if target.starts_with("thumb") { + let suffix = if env::var_os("CARGO_FEATURE_LINKER_PLUGIN_LTO").is_some() { + "-lto" + } else { + "" + }; + + fs::copy( + format!("bin/{}{}.a", target, suffix), + out_dir.join(format!("lib{}.a", name)), + ) + .unwrap(); + + println!("cargo:rustc-link-lib=static={}", name); + println!("cargo:rustc-link-search={}", out_dir.display()); + } + + if target.starts_with("thumbv6m-") { + println!("cargo:rustc-cfg=cortex_m"); + println!("cargo:rustc-cfg=armv6m"); + } else if target.starts_with("thumbv7m-") { + println!("cargo:rustc-cfg=cortex_m"); + println!("cargo:rustc-cfg=armv7m"); + } else if target.starts_with("thumbv7em-") { + println!("cargo:rustc-cfg=cortex_m"); + println!("cargo:rustc-cfg=armv7m"); + println!("cargo:rustc-cfg=armv7em"); // (not currently used) + } else if target.starts_with("thumbv8m.base") { + println!("cargo:rustc-cfg=cortex_m"); + println!("cargo:rustc-cfg=armv8m"); + println!("cargo:rustc-cfg=armv8m_base"); + } else if target.starts_with("thumbv8m.main") { + println!("cargo:rustc-cfg=cortex_m"); + println!("cargo:rustc-cfg=armv8m"); + println!("cargo:rustc-cfg=armv8m_main"); + } + + if target.ends_with("-eabihf") { + println!("cargo:rustc-cfg=has_fpu"); + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/asm.rs b/bitbox02-bt/vendor/cortex-m/src/asm.rs new file mode 100644 index 0000000..4dc1ab0 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/asm.rs @@ -0,0 +1,209 @@ +//! Miscellaneous assembly instructions + +// When inline assembly is enabled, pull in the assembly routines here. `call_asm!` will invoke +// these routines. +#[cfg(feature = "inline-asm")] +#[path = "../asm/inline.rs"] +pub(crate) mod inline; + +/// Puts the processor in Debug state. Debuggers can pick this up as a "breakpoint". +/// +/// **NOTE** calling `bkpt` when the processor is not connected to a debugger will cause an +/// exception. +#[inline(always)] +pub fn bkpt() { + call_asm!(__bkpt()); +} + +/// Blocks the program for *at least* `cycles` CPU cycles. +/// +/// This is implemented in assembly so its execution time is independent of the optimization +/// level, however it is dependent on the specific architecture and core configuration. +/// +/// NOTE that the delay can take much longer if interrupts are serviced during its execution +/// and the execution time may vary with other factors. This delay is mainly useful for simple +/// timer-less initialization of peripherals if and only if accurate timing is not essential. In +/// any other case please use a more accurate method to produce a delay. +#[inline] +pub fn delay(cycles: u32) { + call_asm!(__delay(cycles: u32)); +} + +/// A no-operation. Useful to prevent delay loops from being optimized away. +#[inline] +pub fn nop() { + call_asm!(__nop()); +} + +/// Generate an Undefined Instruction exception. +/// +/// Can be used as a stable alternative to `core::intrinsics::abort`. +#[inline] +pub fn udf() -> ! { + call_asm!(__udf() -> !) +} + +/// Wait For Event +#[inline] +pub fn wfe() { + call_asm!(__wfe()) +} + +/// Wait For Interrupt +#[inline] +pub fn wfi() { + call_asm!(__wfi()) +} + +/// Send Event +#[inline] +pub fn sev() { + call_asm!(__sev()) +} + +/// Instruction Synchronization Barrier +/// +/// Flushes the pipeline in the processor, so that all instructions following the `ISB` are fetched +/// from cache or memory, after the instruction has been completed. +#[inline] +pub fn isb() { + call_asm!(__isb()) +} + +/// Data Synchronization Barrier +/// +/// Acts as a special kind of memory barrier. No instruction in program order after this instruction +/// can execute until this instruction completes. This instruction completes only when both: +/// +/// * any explicit memory access made before this instruction is complete +/// * all cache and branch predictor maintenance operations before this instruction complete +#[inline] +pub fn dsb() { + call_asm!(__dsb()) +} + +/// Data Memory Barrier +/// +/// Ensures that all explicit memory accesses that appear in program order before the `DMB` +/// instruction are observed before any explicit memory accesses that appear in program order +/// after the `DMB` instruction. +#[inline] +pub fn dmb() { + call_asm!(__dmb()) +} + +/// Test Target +/// +/// Queries the Security state and access permissions of a memory location. +/// Returns a Test Target Response Payload (cf section D1.2.215 of +/// Armv8-M Architecture Reference Manual). +#[inline] +#[cfg(armv8m)] +// The __tt function does not dereference the pointer received. +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn tt(addr: *mut u32) -> u32 { + let addr = addr as u32; + call_asm!(__tt(addr: u32) -> u32) +} + +/// Test Target Unprivileged +/// +/// Queries the Security state and access permissions of a memory location for an unprivileged +/// access to that location. +/// Returns a Test Target Response Payload (cf section D1.2.215 of +/// Armv8-M Architecture Reference Manual). +#[inline] +#[cfg(armv8m)] +// The __ttt function does not dereference the pointer received. +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn ttt(addr: *mut u32) -> u32 { + let addr = addr as u32; + call_asm!(__ttt(addr: u32) -> u32) +} + +/// Test Target Alternate Domain +/// +/// Queries the Security state and access permissions of a memory location for a Non-Secure access +/// to that location. This instruction is only valid when executing in Secure state and is +/// undefined if used from Non-Secure state. +/// Returns a Test Target Response Payload (cf section D1.2.215 of +/// Armv8-M Architecture Reference Manual). +#[inline] +#[cfg(armv8m)] +// The __tta function does not dereference the pointer received. +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn tta(addr: *mut u32) -> u32 { + let addr = addr as u32; + call_asm!(__tta(addr: u32) -> u32) +} + +/// Test Target Alternate Domain Unprivileged +/// +/// Queries the Security state and access permissions of a memory location for a Non-Secure and +/// unprivileged access to that location. This instruction is only valid when executing in Secure +/// state and is undefined if used from Non-Secure state. +/// Returns a Test Target Response Payload (cf section D1.2.215 of +/// Armv8-M Architecture Reference Manual). +#[inline] +#[cfg(armv8m)] +// The __ttat function does not dereference the pointer received. +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn ttat(addr: *mut u32) -> u32 { + let addr = addr as u32; + call_asm!(__ttat(addr: u32) -> u32) +} + +/// Branch and Exchange Non-secure +/// +/// See section C2.4.26 of Armv8-M Architecture Reference Manual for details. +/// Undefined if executed in Non-Secure state. +#[inline] +#[cfg(armv8m)] +pub unsafe fn bx_ns(addr: u32) { + call_asm!(__bxns(addr: u32)); +} + +/// Semihosting syscall. +/// +/// This method is used by cortex-m-semihosting to provide semihosting syscalls. +#[inline] +pub unsafe fn semihosting_syscall(nr: u32, arg: u32) -> u32 { + call_asm!(__sh_syscall(nr: u32, arg: u32) -> u32) +} + +/// Bootstrap. +/// +/// Clears CONTROL.SPSEL (setting the main stack to be the active stack), +/// updates the main stack pointer to the address in `msp`, then jumps +/// to the address in `rv`. +/// +/// # Safety +/// +/// `msp` and `rv` must point to valid stack memory and executable code, +/// respectively. +#[inline] +pub unsafe fn bootstrap(msp: *const u32, rv: *const u32) -> ! { + // Ensure thumb mode is set. + let rv = (rv as u32) | 1; + let msp = msp as u32; + call_asm!(__bootstrap(msp: u32, rv: u32) -> !); +} + +/// Bootload. +/// +/// Reads the initial stack pointer value and reset vector from +/// the provided vector table address, sets the active stack to +/// the main stack, sets the main stack pointer to the new initial +/// stack pointer, then jumps to the reset vector. +/// +/// # Safety +/// +/// The provided `vector_table` must point to a valid vector +/// table, with a valid stack pointer as the first word and +/// a valid reset vector as the second word. +#[inline] +pub unsafe fn bootload(vector_table: *const u32) -> ! { + let msp = core::ptr::read_volatile(vector_table); + let rv = core::ptr::read_volatile(vector_table.offset(1)); + bootstrap(msp as *const u32, rv as *const u32); +} diff --git a/bitbox02-bt/vendor/cortex-m/src/call_asm.rs b/bitbox02-bt/vendor/cortex-m/src/call_asm.rs new file mode 100644 index 0000000..295277f --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/call_asm.rs @@ -0,0 +1,24 @@ +/// An internal macro to invoke an assembly routine. +/// +/// Depending on whether the unstable `inline-asm` feature is enabled, this will either call into +/// the inline assembly implementation directly, or through the FFI shim (see `asm/lib.rs`). +macro_rules! call_asm { + ( $func:ident ( $($args:ident: $tys:ty),* ) $(-> $ret:ty)? ) => {{ + #[allow(unused_unsafe)] + unsafe { + match () { + #[cfg(feature = "inline-asm")] + () => crate::asm::inline::$func($($args),*), + + #[cfg(not(feature = "inline-asm"))] + () => { + extern "C" { + fn $func($($args: $tys),*) $(-> $ret)?; + } + + $func($($args),*) + }, + } + } + }}; +} diff --git a/bitbox02-bt/vendor/cortex-m/src/cmse.rs b/bitbox02-bt/vendor/cortex-m/src/cmse.rs new file mode 100644 index 0000000..36d7447 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/cmse.rs @@ -0,0 +1,238 @@ +//! Cortex-M Security Extensions +//! +//! This module provides several helper functions to support Armv8-M and Armv8.1-M Security +//! Extensions. +//! Most of this implementation is directly inspired by the "Armv8-M Security Extensions: +//! Requirements on Development Tools" document available here: +//! https://developer.arm.com/docs/ecm0359818/latest +//! +//! Please note that the TT instructions support as described part 4 of the document linked above is +//! not part of CMSE but is still present in this module. The TT instructions return the +//! configuration of the Memory Protection Unit at an address. +//! +//! # Notes +//! +//! * Non-Secure Unprivileged code will always read zeroes from TestTarget and should not use it. +//! * Non-Secure Privileged code can check current (AccessType::Current) and Non-Secure Unprivileged +//! accesses (AccessType::Unprivileged). +//! * Secure Unprivileged code can check Non-Secure Unprivileged accesses (AccessType::NonSecure). +//! * Secure Privileged code can check all access types. +//! +//! # Example +//! +//! ``` +//! use cortex_m::cmse::{TestTarget, AccessType}; +//! +//! // suspect_address was given by Non-Secure to a Secure function to write at it. +//! // But is it allowed to? +//! let suspect_address_test = TestTarget::check(0xDEADBEEF as *mut u32, +//! AccessType::NonSecureUnprivileged); +//! if suspect_address_test.ns_read_and_writable() { +//! // Non-Secure can not read or write this address! +//! } +//! ``` + +use crate::asm::{tt, tta, ttat, ttt}; +use bitfield::bitfield; + +/// Memory access behaviour: determine which privilege execution mode is used and which Memory +/// Protection Unit (MPU) is used. +#[derive(PartialEq, Copy, Clone, Debug)] +pub enum AccessType { + /// Access using current privilege level and reading from current security state MPU. + /// Uses the TT instruction. + Current, + /// Unprivileged access reading from current security state MPU. Uses the TTT instruction. + Unprivileged, + /// Access using current privilege level reading from Non-Secure MPU. Uses the TTA instruction. + /// Undefined if used from Non-Secure state. + NonSecure, + /// Unprivilege access reading from Non-Secure MPU. Uses the TTAT instruction. + /// Undefined if used from Non-Secure state. + NonSecureUnprivileged, +} + +/// Abstraction of TT instructions and helper functions to determine the security and privilege +/// attribute of a target address, accessed in different ways. +#[derive(PartialEq, Copy, Clone, Debug)] +pub struct TestTarget { + tt_resp: TtResp, + access_type: AccessType, +} + +bitfield! { + /// Test Target Response Payload + /// + /// Provides the response payload from a TT, TTA, TTT or TTAT instruction. + #[derive(PartialEq, Copy, Clone)] + struct TtResp(u32); + impl Debug; + mregion, _: 7, 0; + sregion, _: 15, 8; + mrvalid, _: 16; + srvalid, _: 17; + r, _: 18; + rw, _: 19; + nsr, _: 20; + nsrw, _: 21; + s, _: 22; + irvalid, _: 23; + iregion, _: 31, 24; +} + +impl TestTarget { + /// Creates a Test Target Response Payload by testing addr using access_type. + #[inline] + pub fn check(addr: *mut u32, access_type: AccessType) -> Self { + let tt_resp = match access_type { + AccessType::Current => TtResp(tt(addr)), + AccessType::Unprivileged => TtResp(ttt(addr)), + AccessType::NonSecure => TtResp(tta(addr)), + AccessType::NonSecureUnprivileged => TtResp(ttat(addr)), + }; + + TestTarget { + tt_resp, + access_type, + } + } + + /// Creates a Test Target Response Payload by testing the zone from addr to addr + size - 1 + /// using access_type. + /// Returns None if: + /// * the address zone overlaps SAU, IDAU or MPU region boundaries + /// * size is 0 + /// * addr + size - 1 overflows + #[inline] + pub fn check_range(addr: *mut u32, size: usize, access_type: AccessType) -> Option { + let begin: usize = addr as usize; + // Last address of the range (addr + size - 1). This also checks if size is 0. + let end: usize = begin.checked_add(size.checked_sub(1)?)?; + + // Regions are aligned at 32-byte boundaries. If the address range fits in one 32-byte + // address line, a single TT instruction suffices. This is the case when the following + // constraint holds. + let single_check: bool = (begin % 32).checked_add(size)? <= 32usize; + + let test_start = TestTarget::check(addr, access_type); + + if single_check { + Some(test_start) + } else { + let test_end = TestTarget::check(end as *mut u32, access_type); + // Check that the range does not cross SAU, IDAU or MPU region boundaries. + if test_start != test_end { + None + } else { + Some(test_start) + } + } + } + + /// Access type that was used for this test target. + #[inline] + pub fn access_type(self) -> AccessType { + self.access_type + } + + /// Get the raw u32 value returned by the TT instruction used. + #[inline] + pub fn as_u32(self) -> u32 { + self.tt_resp.0 + } + + /// Read accessibility of the target address. Only returns the MPU settings without checking + /// the Security state of the target. + /// For Unprivileged and NonSecureUnprivileged access types, returns the permissions for + /// unprivileged access, regardless of whether the current mode is privileged or unprivileged. + /// Returns false if the TT instruction was executed from an unprivileged mode + /// and the NonSecure access type was not specified. + /// Returns false if the address matches multiple MPU regions. + #[inline] + pub fn readable(self) -> bool { + self.tt_resp.r() + } + + /// Read and write accessibility of the target address. Only returns the MPU settings without + /// checking the Security state of the target. + /// For Unprivileged and NonSecureUnprivileged access types, returns the permissions for + /// unprivileged access, regardless of whether the current mode is privileged or unprivileged. + /// Returns false if the TT instruction was executed from an unprivileged mode + /// and the NonSecure access type was not specified. + /// Returns false if the address matches multiple MPU regions. + #[inline] + pub fn read_and_writable(self) -> bool { + self.tt_resp.rw() + } + + /// Indicate the MPU region number containing the target address. + /// Returns None if the value is not valid: + /// * the MPU is not implemented or MPU_CTRL.ENABLE is set to zero + /// * the register argument specified by the MREGION field does not match any enabled MPU regions + /// * the address matched multiple MPU regions + /// * the address specified by the SREGION field is exempt from the secure memory attribution + /// * the TT instruction was executed from an unprivileged mode and the A flag was not specified. + #[inline] + pub fn mpu_region(self) -> Option { + if self.tt_resp.srvalid() { + // Cast is safe as SREGION field is defined on 8 bits. + Some(self.tt_resp.sregion() as u8) + } else { + None + } + } + + /// Indicates the Security attribute of the target address. Independent of AccessType. + /// Always zero when the test target is done in the Non-Secure state. + #[inline] + pub fn secure(self) -> bool { + self.tt_resp.s() + } + + /// Non-Secure Read accessibility of the target address. + /// Same as readable() && !secure() + #[inline] + pub fn ns_readable(self) -> bool { + self.tt_resp.nsr() + } + + /// Non-Secure Read and Write accessibility of the target address. + /// Same as read_and_writable() && !secure() + #[inline] + pub fn ns_read_and_writable(self) -> bool { + self.tt_resp.nsrw() + } + + /// Indicate the IDAU region number containing the target address. Independent of AccessType. + /// Returns None if the value is not valid: + /// * the IDAU cannot provide a region number + /// * the address is exempt from security attribution + /// * the test target is done from Non-Secure state + #[inline] + pub fn idau_region(self) -> Option { + if self.tt_resp.irvalid() { + // Cast is safe as IREGION field is defined on 8 bits. + Some(self.tt_resp.iregion() as u8) + } else { + None + } + } + + /// Indicate the SAU region number containing the target address. Independent of AccessType. + /// Returns None if the value is not valid: + /// * SAU_CTRL.ENABLE is set to zero + /// * the register argument specified in the SREGION field does not match any enabled SAU regions + /// * the address specified matches multiple enabled SAU regions + /// * the address specified by the SREGION field is exempt from the secure memory attribution + /// * the TT instruction was executed from the Non-secure state or the Security Extension is not + /// implemented + #[inline] + pub fn sau_region(self) -> Option { + if self.tt_resp.srvalid() { + // Cast is safe as SREGION field is defined on 8 bits. + Some(self.tt_resp.sregion() as u8) + } else { + None + } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/critical_section.rs b/bitbox02-bt/vendor/cortex-m/src/critical_section.rs new file mode 100644 index 0000000..d33e90f --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/critical_section.rs @@ -0,0 +1,25 @@ +#[cfg(all(cortex_m, feature = "critical-section-single-core"))] +mod single_core_critical_section { + use critical_section::{set_impl, Impl, RawRestoreState}; + + use crate::interrupt; + use crate::register::primask; + + struct SingleCoreCriticalSection; + set_impl!(SingleCoreCriticalSection); + + unsafe impl Impl for SingleCoreCriticalSection { + unsafe fn acquire() -> RawRestoreState { + let was_active = primask::read().is_active(); + interrupt::disable(); + was_active + } + + unsafe fn release(was_active: RawRestoreState) { + // Only re-enable interrupts if they were enabled before the critical section. + if was_active { + interrupt::enable() + } + } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/delay.rs b/bitbox02-bt/vendor/cortex-m/src/delay.rs new file mode 100644 index 0000000..66a63bf --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/delay.rs @@ -0,0 +1,136 @@ +//! A delay driver based on SysTick. + +use crate::peripheral::{syst::SystClkSource, SYST}; +use embedded_hal::blocking::delay::{DelayMs, DelayUs}; + +/// System timer (SysTick) as a delay provider. +pub struct Delay { + syst: SYST, + frequency: u32, +} + +impl Delay { + /// Configures the system timer (SysTick) as a delay provider. + /// + /// `ahb_frequency` is a frequency of the AHB bus in Hz. + #[inline] + pub fn new(syst: SYST, ahb_frequency: u32) -> Self { + Self::with_source(syst, ahb_frequency, SystClkSource::Core) + } + + /// Configures the system timer (SysTick) as a delay provider + /// with a clock source. + /// + /// `frequency` is the frequency of your `clock_source` in Hz. + #[inline] + pub fn with_source(mut syst: SYST, frequency: u32, clock_source: SystClkSource) -> Self { + syst.set_clock_source(clock_source); + + Delay { syst, frequency } + } + + /// Releases the system timer (SysTick) resource. + #[inline] + pub fn free(self) -> SYST { + self.syst + } + + /// Delay using the Cortex-M systick for a certain duration, in µs. + #[allow(clippy::missing_inline_in_public_items)] + pub fn delay_us(&mut self, us: u32) { + let ticks = (u64::from(us)) * (u64::from(self.frequency)) / 1_000_000; + + let full_cycles = ticks >> 24; + if full_cycles > 0 { + self.syst.set_reload(0xffffff); + self.syst.clear_current(); + self.syst.enable_counter(); + + for _ in 0..full_cycles { + while !self.syst.has_wrapped() {} + } + } + + let ticks = (ticks & 0xffffff) as u32; + if ticks > 1 { + self.syst.set_reload(ticks - 1); + self.syst.clear_current(); + self.syst.enable_counter(); + + while !self.syst.has_wrapped() {} + } + + self.syst.disable_counter(); + } + + /// Delay using the Cortex-M systick for a certain duration, in ms. + #[inline] + pub fn delay_ms(&mut self, mut ms: u32) { + // 4294967 is the highest u32 value which you can multiply by 1000 without overflow + while ms > 4294967 { + self.delay_us(4294967000u32); + ms -= 4294967; + } + self.delay_us(ms * 1_000); + } +} + +impl DelayMs for Delay { + #[inline] + fn delay_ms(&mut self, ms: u32) { + Delay::delay_ms(self, ms); + } +} + +// This is a workaround to allow `delay_ms(42)` construction without specifying a type. +impl DelayMs for Delay { + #[inline(always)] + fn delay_ms(&mut self, ms: i32) { + assert!(ms >= 0); + Delay::delay_ms(self, ms as u32); + } +} + +impl DelayMs for Delay { + #[inline(always)] + fn delay_ms(&mut self, ms: u16) { + Delay::delay_ms(self, u32::from(ms)); + } +} + +impl DelayMs for Delay { + #[inline(always)] + fn delay_ms(&mut self, ms: u8) { + Delay::delay_ms(self, u32::from(ms)); + } +} + +impl DelayUs for Delay { + #[inline] + fn delay_us(&mut self, us: u32) { + Delay::delay_us(self, us); + } +} + +// This is a workaround to allow `delay_us(42)` construction without specifying a type. +impl DelayUs for Delay { + #[inline(always)] + fn delay_us(&mut self, us: i32) { + assert!(us >= 0); + Delay::delay_us(self, us as u32); + } +} + +impl DelayUs for Delay { + #[inline(always)] + fn delay_us(&mut self, us: u16) { + Delay::delay_us(self, u32::from(us)) + } +} + +impl DelayUs for Delay { + #[inline(always)] + fn delay_us(&mut self, us: u8) { + Delay::delay_us(self, u32::from(us)) + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/interrupt.rs b/bitbox02-bt/vendor/cortex-m/src/interrupt.rs new file mode 100644 index 0000000..0fd1284 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/interrupt.rs @@ -0,0 +1,73 @@ +//! Interrupts + +pub use bare_metal::{CriticalSection, Mutex, Nr}; + +/// Trait for enums of external interrupt numbers. +/// +/// This trait should be implemented by a peripheral access crate (PAC) +/// on its enum of available external interrupts for a specific device. +/// Each variant must convert to a u16 of its interrupt number, +/// which is its exception number - 16. +/// +/// # Safety +/// +/// This trait must only be implemented on enums of device interrupts. Each +/// enum variant must represent a distinct value (no duplicates are permitted), +/// and must always return the same value (do not change at runtime). +/// +/// These requirements ensure safe nesting of critical sections. +pub unsafe trait InterruptNumber: Copy { + /// Return the interrupt number associated with this variant. + /// + /// See trait documentation for safety requirements. + fn number(self) -> u16; +} + +/// Implement InterruptNumber for the old bare_metal::Nr trait. +/// This implementation is for backwards compatibility only and will be removed in cortex-m 0.8. +unsafe impl InterruptNumber for T { + #[inline] + fn number(self) -> u16 { + self.nr() as u16 + } +} + +/// Disables all interrupts +#[inline] +pub fn disable() { + call_asm!(__cpsid()); +} + +/// Enables all the interrupts +/// +/// # Safety +/// +/// - Do not call this function inside an `interrupt::free` critical section +#[inline] +pub unsafe fn enable() { + call_asm!(__cpsie()); +} + +/// Execute closure `f` in an interrupt-free context. +/// +/// This as also known as a "critical section". +#[inline] +pub fn free(f: F) -> R +where + F: FnOnce(&CriticalSection) -> R, +{ + let primask = crate::register::primask::read(); + + // disable interrupts + disable(); + + let r = f(unsafe { &CriticalSection::new() }); + + // If the interrupts were active before our `disable` call, then re-enable + // them. Otherwise, keep them disabled + if primask.is_active() { + unsafe { enable() } + } + + r +} diff --git a/bitbox02-bt/vendor/cortex-m/src/itm.rs b/bitbox02-bt/vendor/cortex-m/src/itm.rs new file mode 100644 index 0000000..72cb0d9 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/itm.rs @@ -0,0 +1,158 @@ +//! Instrumentation Trace Macrocell +//! +//! **NOTE** This module is only available on ARMv7-M and newer. + +use core::{fmt, ptr, slice}; + +use crate::peripheral::itm::Stim; + +// NOTE assumes that `bytes` is 32-bit aligned +unsafe fn write_words(stim: &mut Stim, bytes: &[u32]) { + let mut p = bytes.as_ptr(); + for _ in 0..bytes.len() { + while !stim.is_fifo_ready() {} + stim.write_u32(ptr::read(p)); + p = p.offset(1); + } +} + +/// Writes an aligned byte slice to the ITM. +/// +/// `buffer` must be 4-byte aligned. +unsafe fn write_aligned_impl(port: &mut Stim, buffer: &[u8]) { + let len = buffer.len(); + + if len == 0 { + return; + } + + let split = len & !0b11; + #[allow(clippy::cast_ptr_alignment)] + write_words( + port, + slice::from_raw_parts(buffer.as_ptr() as *const u32, split >> 2), + ); + + // 3 bytes or less left + let mut left = len & 0b11; + let mut ptr = buffer.as_ptr().add(split); + + // at least 2 bytes left + if left > 1 { + while !port.is_fifo_ready() {} + + #[allow(clippy::cast_ptr_alignment)] + port.write_u16(ptr::read(ptr as *const u16)); + + ptr = ptr.offset(2); + left -= 2; + } + + // final byte + if left == 1 { + while !port.is_fifo_ready() {} + port.write_u8(*ptr); + } +} + +struct Port<'p>(&'p mut Stim); + +impl<'p> fmt::Write for Port<'p> { + #[inline] + fn write_str(&mut self, s: &str) -> fmt::Result { + write_all(self.0, s.as_bytes()); + Ok(()) + } +} + +/// A wrapper type that aligns its contents on a 4-Byte boundary. +/// +/// ITM transfers are most efficient when the data is 4-Byte-aligned. This type provides an easy +/// way to accomplish and enforce such an alignment. +#[repr(align(4))] +pub struct Aligned(pub T); + +/// Writes `buffer` to an ITM port. +#[allow(clippy::missing_inline_in_public_items)] +pub fn write_all(port: &mut Stim, buffer: &[u8]) { + unsafe { + let mut len = buffer.len(); + let mut ptr = buffer.as_ptr(); + + if len == 0 { + return; + } + + // 0x01 OR 0x03 + if ptr as usize % 2 == 1 { + while !port.is_fifo_ready() {} + port.write_u8(*ptr); + + // 0x02 OR 0x04 + ptr = ptr.offset(1); + len -= 1; + } + + // 0x02 + if ptr as usize % 4 == 2 { + if len > 1 { + // at least 2 bytes + while !port.is_fifo_ready() {} + + // We checked the alignment above, so this is safe + #[allow(clippy::cast_ptr_alignment)] + port.write_u16(ptr::read(ptr as *const u16)); + + // 0x04 + ptr = ptr.offset(2); + len -= 2; + } else { + if len == 1 { + // last byte + while !port.is_fifo_ready() {} + port.write_u8(*ptr); + } + + return; + } + } + + // The remaining data is 4-byte aligned, but might not be a multiple of 4 bytes + write_aligned_impl(port, slice::from_raw_parts(ptr, len)); + } +} + +/// Writes a 4-byte aligned `buffer` to an ITM port. +/// +/// # Examples +/// +/// ```no_run +/// # use cortex_m::{itm::{self, Aligned}, peripheral::ITM}; +/// # let port = unsafe { &mut (*ITM::PTR).stim[0] }; +/// let mut buffer = Aligned([0; 14]); +/// +/// buffer.0.copy_from_slice(b"Hello, world!\n"); +/// +/// itm::write_aligned(port, &buffer); +/// +/// // Or equivalently +/// itm::write_aligned(port, &Aligned(*b"Hello, world!\n")); +/// ``` +#[allow(clippy::missing_inline_in_public_items)] +pub fn write_aligned(port: &mut Stim, buffer: &Aligned<[u8]>) { + unsafe { write_aligned_impl(port, &buffer.0) } +} + +/// Writes `fmt::Arguments` to the ITM `port` +#[inline] +pub fn write_fmt(port: &mut Stim, args: fmt::Arguments) { + use core::fmt::Write; + + Port(port).write_fmt(args).ok(); +} + +/// Writes a string to the ITM `port` +#[inline] +pub fn write_str(port: &mut Stim, string: &str) { + write_all(port, string.as_bytes()) +} diff --git a/bitbox02-bt/vendor/cortex-m/src/lib.rs b/bitbox02-bt/vendor/cortex-m/src/lib.rs new file mode 100644 index 0000000..044085e --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/lib.rs @@ -0,0 +1,112 @@ +//! Low level access to Cortex-M processors +//! +//! This crate provides: +//! +//! - Access to core peripherals like NVIC, SCB and SysTick. +//! - Access to core registers like CONTROL, MSP and PSR. +//! - Interrupt manipulation mechanisms +//! - Safe wrappers around Cortex-M specific instructions like `bkpt` +//! +//! # Optional features +//! +//! ## `inline-asm` +//! +//! When this feature is enabled the implementation of all the functions inside the `asm` and +//! `register` modules use inline assembly (`asm!`) instead of external assembly (FFI into separate +//! assembly files pre-compiled using `arm-none-eabi-gcc`). The advantages of enabling `inline-asm` +//! are: +//! +//! - Reduced overhead. FFI eliminates the possibility of inlining so all operations include a +//! function call overhead when `inline-asm` is not enabled. +//! +//! - Some of the `register` API only becomes available only when `inline-asm` is enabled. Check the +//! API docs for details. +//! +//! The disadvantage is that `inline-asm` requires a Rust version at least 1.59 to use the `asm!()` +//! macro. In the future 0.8 and above versions of `cortex-m`, this feature will always be enabled. +//! +//! ## `critical-section-single-core` +//! +//! This feature enables a [`critical-section`](https://github.com/rust-embedded/critical-section) +//! implementation suitable for single-core targets, based on disabling interrupts globally. +//! +//! It is **unsound** to enable it on multi-core targets or for code running in unprivileged mode, +//! and may cause functional problems in systems where some interrupts must be not be disabled +//! or critical sections are managed as part of an RTOS. In these cases, you should use +//! a target-specific implementation instead, typically provided by a HAL or RTOS crate. +//! +//! ## `cm7-r0p1` +//! +//! This feature enables workarounds for errata found on Cortex-M7 chips with revision r0p1. Some +//! functions in this crate only work correctly on those chips if this Cargo feature is enabled +//! (the functions are documented accordingly). +//! +//! ## `linker-plugin-lto` +//! +//! This feature links against prebuilt assembly blobs that are compatible with [Linker-Plugin LTO]. +//! This allows inlining assembly routines into the caller, even without the `inline-asm` feature, +//! and works on stable Rust (but note the drawbacks below!). +//! +//! If you want to use this feature, you need to be aware of a few things: +//! +//! - You need to make sure that `-Clinker-plugin-lto` is passed to rustc. Please refer to the +//! [Linker-Plugin LTO] documentation for details. +//! +//! - You have to use a Rust version whose LLVM version is compatible with the toolchain in +//! `asm-toolchain`. +//! +//! - Due to a [Rust bug][rust-lang/rust#75940] in compiler versions **before 1.49**, this option +//! does not work with optimization levels `s` and `z`. +//! +//! [Linker-Plugin LTO]: https://doc.rust-lang.org/stable/rustc/linker-plugin-lto.html +//! [rust-lang/rust#75940]: https://github.com/rust-lang/rust/issues/75940 +//! +//! # Minimum Supported Rust Version (MSRV) +//! +//! This crate is guaranteed to compile on stable Rust 1.38 and up. It *might* +//! compile with older versions but that may change in any new patch release. + +#![deny(missing_docs)] +#![no_std] +#![allow(clippy::identity_op)] +#![allow(clippy::missing_safety_doc)] +// Prevent clippy from complaining about empty match expression that are used for cfg gating. +#![allow(clippy::match_single_binding)] +// This makes clippy warn about public functions which are not #[inline]. +// +// Almost all functions in this crate result in trivial or even no assembly. +// These functions should be #[inline]. +// +// If you do add a function that's not supposed to be #[inline], you can add +// #[allow(clippy::missing_inline_in_public_items)] in front of it to add an +// exception to clippy's rules. +// +// This should be done in case of: +// - A function containing non-trivial logic (such as itm::write_all); or +// - A generated #[derive(Debug)] function (in which case the attribute needs +// to be applied to the struct). +#![deny(clippy::missing_inline_in_public_items)] +// Don't warn about feature(asm) being stable on Rust >= 1.59.0 +#![allow(stable_features)] + +extern crate bare_metal; +extern crate volatile_register; + +#[macro_use] +mod call_asm; +#[macro_use] +mod macros; + +pub mod asm; +#[cfg(armv8m)] +pub mod cmse; +mod critical_section; +pub mod delay; +pub mod interrupt; +#[cfg(all(not(armv6m), not(armv8m_base)))] +pub mod itm; +pub mod peripheral; +pub mod prelude; +pub mod register; + +pub use crate::peripheral::Peripherals; diff --git a/bitbox02-bt/vendor/cortex-m/src/macros.rs b/bitbox02-bt/vendor/cortex-m/src/macros.rs new file mode 100644 index 0000000..512c932 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/macros.rs @@ -0,0 +1,114 @@ +/// Macro for sending a formatted string through an ITM channel +#[macro_export] +macro_rules! iprint { + ($channel:expr, $s:expr) => { + $crate::itm::write_str($channel, $s); + }; + ($channel:expr, $($arg:tt)*) => { + $crate::itm::write_fmt($channel, format_args!($($arg)*)); + }; +} + +/// Macro for sending a formatted string through an ITM channel, with a newline. +#[macro_export] +macro_rules! iprintln { + ($channel:expr) => { + $crate::itm::write_str($channel, "\n"); + }; + ($channel:expr, $fmt:expr) => { + $crate::itm::write_str($channel, concat!($fmt, "\n")); + }; + ($channel:expr, $fmt:expr, $($arg:tt)*) => { + $crate::itm::write_fmt($channel, format_args!(concat!($fmt, "\n"), $($arg)*)); + }; +} + +/// Macro to create a mutable reference to a statically allocated value +/// +/// This macro returns a value with type `Option<&'static mut $ty>`. `Some($expr)` will be returned +/// the first time the macro is executed; further calls will return `None`. To avoid `unwrap`ping a +/// `None` variant the caller must ensure that the macro is called from a function that's executed +/// at most once in the whole lifetime of the program. +/// +/// # Notes +/// This macro is unsound on multi core systems. +/// +/// For debuggability, you can set an explicit name for a singleton. This name only shows up the +/// the debugger and is not referencable from other code. See example below. +/// +/// # Example +/// +/// ``` no_run +/// use cortex_m::singleton; +/// +/// fn main() { +/// // OK if `main` is executed only once +/// let x: &'static mut bool = singleton!(: bool = false).unwrap(); +/// +/// let y = alias(); +/// // BAD this second call to `alias` will definitively `panic!` +/// let y_alias = alias(); +/// } +/// +/// fn alias() -> &'static mut bool { +/// singleton!(: bool = false).unwrap() +/// } +/// +/// fn singleton_with_name() { +/// // A name only for debugging purposes +/// singleton!(FOO_BUFFER: [u8; 1024] = [0u8; 1024]); +/// } +/// ``` +#[macro_export] +macro_rules! singleton { + ($name:ident: $ty:ty = $expr:expr) => { + $crate::interrupt::free(|_| { + // this is a tuple of a MaybeUninit and a bool because using an Option here is + // problematic: Due to niche-optimization, an Option could end up producing a non-zero + // initializer value which would move the entire static from `.bss` into `.data`... + static mut $name: (::core::mem::MaybeUninit<$ty>, bool) = + (::core::mem::MaybeUninit::uninit(), false); + + #[allow(unsafe_code)] + let used = unsafe { $name.1 }; + if used { + None + } else { + let expr = $expr; + + #[allow(unsafe_code)] + unsafe { + $name.1 = true; + $name.0 = ::core::mem::MaybeUninit::new(expr); + Some(&mut *$name.0.as_mut_ptr()) + } + } + }) + }; + (: $ty:ty = $expr:expr) => { + $crate::singleton!(VAR: $ty = $expr) + }; +} + +/// ``` compile_fail +/// use cortex_m::singleton; +/// +/// fn foo() { +/// // check that the call to `uninitialized` requires unsafe +/// singleton!(: u8 = std::mem::uninitialized()); +/// } +/// ``` +#[allow(dead_code)] +const CFAIL: () = (); + +/// ``` +/// #![deny(unsafe_code)] +/// use cortex_m::singleton; +/// +/// fn foo() { +/// // check that calls to `singleton!` don't trip the `unsafe_code` lint +/// singleton!(: u8 = 0); +/// } +/// ``` +#[allow(dead_code)] +const CPASS: () = (); diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/ac.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/ac.rs new file mode 100644 index 0000000..1ac5be1 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/ac.rs @@ -0,0 +1,93 @@ +//! Cortex-M7 TCM and Cache access control. + +use volatile_register::RW; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Instruction Tightly-Coupled Memory Control Register + pub itcmcr: RW, + /// Data Tightly-Coupled Memory Control Register + pub dtcmcr: RW, + /// AHBP Control Register + pub ahbpcr: RW, + /// L1 Cache Control Register + pub cacr: RW, + /// AHB Slave Control Register + pub ahbscr: RW, + reserved0: u32, + /// Auxilary Bus Fault Status Register + pub abfsr: RW, +} + +/// ITCMCR and DTCMCR TCM enable bit. +pub const TCM_EN: u32 = 1; + +/// ITCMCR and DTCMCR TCM read-modify-write bit. +pub const TCM_RMW: u32 = 2; + +/// ITCMCR and DTCMCR TCM rety phase enable bit. +pub const TCM_RETEN: u32 = 4; + +/// ITCMCR and DTCMCR TCM size mask. +pub const TCM_SZ_MASK: u32 = 0x78; + +/// ITCMCR and DTCMCR TCM shift. +pub const TCM_SZ_SHIFT: usize = 3; + +/// AHBPCR AHBP enable bit. +pub const AHBPCR_EN: u32 = 1; + +/// AHBPCR AHBP size mask. +pub const AHBPCR_SZ_MASK: u32 = 0x0e; + +/// AHBPCR AHBP size shit. +pub const AHBPCR_SZ_SHIFT: usize = 1; + +/// CACR Shared cachedable-is-WT for data cache. +pub const CACR_SIWT: u32 = 1; + +/// CACR ECC in the instruction and data cache (disable). +pub const CACR_ECCDIS: u32 = 2; + +/// CACR Force Write-Through in the data cache. +pub const CACR_FORCEWT: u32 = 4; + +/// AHBSCR AHBS prioritization control mask. +pub const AHBSCR_CTL_MASK: u32 = 0x03; + +/// AHBSCR AHBS prioritization control shift. +pub const AHBSCR_CTL_SHIFT: usize = 0; + +/// AHBSCR Threshold execution prioity for AHBS traffic demotion, mask. +pub const AHBSCR_TPRI_MASK: u32 = 0x7fc; + +/// AHBSCR Threshold execution prioity for AHBS traffic demotion, shift. +pub const AHBSCR_TPRI_SHIFT: usize = 2; + +/// AHBSCR Failness counter initialization value, mask. +pub const AHBSCR_INITCOUNT_MASK: u32 = 0xf800; + +/// AHBSCR Failness counter initialization value, shift. +pub const AHBSCR_INITCOUNT_SHIFT: usize = 11; + +/// ABFSR Async fault on ITCM interface. +pub const ABFSR_ITCM: u32 = 1; + +/// ABFSR Async fault on DTCM interface. +pub const ABFSR_DTCM: u32 = 2; + +/// ABFSR Async fault on AHBP interface. +pub const ABFSR_AHBP: u32 = 4; + +/// ABFSR Async fault on AXIM interface. +pub const ABFSR_AXIM: u32 = 8; + +/// ABFSR Async fault on EPPB interface. +pub const ABFSR_EPPB: u32 = 16; + +/// ABFSR Indicates the type of fault on the AXIM interface, mask. +pub const ABFSR_AXIMTYPE_MASK: u32 = 0x300; + +/// ABFSR Indicates the type of fault on the AXIM interface, shift. +pub const ABFSR_AXIMTYPE_SHIFT: usize = 8; diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/cbp.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/cbp.rs new file mode 100644 index 0000000..5aee544 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/cbp.rs @@ -0,0 +1,138 @@ +//! Cache and branch predictor maintenance operations +//! +//! *NOTE* Not available on Armv6-M. + +use volatile_register::WO; + +use crate::peripheral::CBP; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// I-cache invalidate all to PoU + pub iciallu: WO, + reserved0: u32, + /// I-cache invalidate by MVA to PoU + pub icimvau: WO, + /// D-cache invalidate by MVA to PoC + pub dcimvac: WO, + /// D-cache invalidate by set-way + pub dcisw: WO, + /// D-cache clean by MVA to PoU + pub dccmvau: WO, + /// D-cache clean by MVA to PoC + pub dccmvac: WO, + /// D-cache clean by set-way + pub dccsw: WO, + /// D-cache clean and invalidate by MVA to PoC + pub dccimvac: WO, + /// D-cache clean and invalidate by set-way + pub dccisw: WO, + /// Branch predictor invalidate all + pub bpiall: WO, +} + +const CBP_SW_WAY_POS: u32 = 30; +const CBP_SW_WAY_MASK: u32 = 0x3 << CBP_SW_WAY_POS; +const CBP_SW_SET_POS: u32 = 5; +const CBP_SW_SET_MASK: u32 = 0x1FF << CBP_SW_SET_POS; + +impl CBP { + /// I-cache invalidate all to PoU + #[inline(always)] + pub fn iciallu(&mut self) { + unsafe { self.iciallu.write(0) }; + } + + /// I-cache invalidate by MVA to PoU + #[inline(always)] + pub fn icimvau(&mut self, mva: u32) { + unsafe { self.icimvau.write(mva) }; + } + + /// D-cache invalidate by MVA to PoC + #[inline(always)] + pub unsafe fn dcimvac(&mut self, mva: u32) { + self.dcimvac.write(mva); + } + + /// D-cache invalidate by set-way + /// + /// `set` is masked to be between 0 and 3, and `way` between 0 and 511. + #[inline(always)] + pub unsafe fn dcisw(&mut self, set: u16, way: u16) { + // The ARMv7-M Architecture Reference Manual, as of Revision E.b, says these set/way + // operations have a register data format which depends on the implementation's + // associativity and number of sets. Specifically the 'way' and 'set' fields have + // offsets 32-log2(ASSOCIATIVITY) and log2(LINELEN) respectively. + // + // However, in Cortex-M7 devices, these offsets are fixed at 30 and 5, as per the Cortex-M7 + // Generic User Guide section 4.8.3. Since no other ARMv7-M implementations except the + // Cortex-M7 have a DCACHE or ICACHE at all, it seems safe to do the same thing as the + // CMSIS-Core implementation and use fixed values. + self.dcisw.write( + ((u32::from(way) & (CBP_SW_WAY_MASK >> CBP_SW_WAY_POS)) << CBP_SW_WAY_POS) + | ((u32::from(set) & (CBP_SW_SET_MASK >> CBP_SW_SET_POS)) << CBP_SW_SET_POS), + ); + } + + /// D-cache clean by MVA to PoU + #[inline(always)] + pub fn dccmvau(&mut self, mva: u32) { + unsafe { + self.dccmvau.write(mva); + } + } + + /// D-cache clean by MVA to PoC + #[inline(always)] + pub fn dccmvac(&mut self, mva: u32) { + unsafe { + self.dccmvac.write(mva); + } + } + + /// D-cache clean by set-way + /// + /// `set` is masked to be between 0 and 3, and `way` between 0 and 511. + #[inline(always)] + pub fn dccsw(&mut self, set: u16, way: u16) { + // See comment for dcisw() about the format here + unsafe { + self.dccsw.write( + ((u32::from(way) & (CBP_SW_WAY_MASK >> CBP_SW_WAY_POS)) << CBP_SW_WAY_POS) + | ((u32::from(set) & (CBP_SW_SET_MASK >> CBP_SW_SET_POS)) << CBP_SW_SET_POS), + ); + } + } + + /// D-cache clean and invalidate by MVA to PoC + #[inline(always)] + pub fn dccimvac(&mut self, mva: u32) { + unsafe { + self.dccimvac.write(mva); + } + } + + /// D-cache clean and invalidate by set-way + /// + /// `set` is masked to be between 0 and 3, and `way` between 0 and 511. + #[inline(always)] + pub fn dccisw(&mut self, set: u16, way: u16) { + // See comment for dcisw() about the format here + unsafe { + self.dccisw.write( + ((u32::from(way) & (CBP_SW_WAY_MASK >> CBP_SW_WAY_POS)) << CBP_SW_WAY_POS) + | ((u32::from(set) & (CBP_SW_SET_MASK >> CBP_SW_SET_POS)) << CBP_SW_SET_POS), + ); + } + } + + /// Branch predictor invalidate all + #[inline(always)] + pub fn bpiall(&mut self) { + unsafe { + self.bpiall.write(0); + } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/cpuid.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/cpuid.rs new file mode 100644 index 0000000..db85566 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/cpuid.rs @@ -0,0 +1,140 @@ +//! CPUID + +use volatile_register::RO; +#[cfg(not(armv6m))] +use volatile_register::RW; + +#[cfg(not(armv6m))] +use crate::peripheral::CPUID; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// CPUID base + pub base: RO, + + _reserved0: [u32; 15], + + /// Processor Feature (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub pfr: [RO; 2], + #[cfg(armv6m)] + _reserved1: [u32; 2], + + /// Debug Feature (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub dfr: RO, + #[cfg(armv6m)] + _reserved2: u32, + + /// Auxiliary Feature (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub afr: RO, + #[cfg(armv6m)] + _reserved3: u32, + + /// Memory Model Feature (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub mmfr: [RO; 4], + #[cfg(armv6m)] + _reserved4: [u32; 4], + + /// Instruction Set Attribute (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub isar: [RO; 5], + #[cfg(armv6m)] + _reserved5: [u32; 5], + + _reserved6: u32, + + /// Cache Level ID (only present on Cortex-M7) + #[cfg(not(armv6m))] + pub clidr: RO, + + /// Cache Type (only present on Cortex-M7) + #[cfg(not(armv6m))] + pub ctr: RO, + + /// Cache Size ID (only present on Cortex-M7) + #[cfg(not(armv6m))] + pub ccsidr: RO, + + /// Cache Size Selection (only present on Cortex-M7) + #[cfg(not(armv6m))] + pub csselr: RW, +} + +/// Type of cache to select on CSSELR writes. +#[cfg(not(armv6m))] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum CsselrCacheType { + /// Select DCache or unified cache + DataOrUnified = 0, + /// Select ICache + Instruction = 1, +} + +#[cfg(not(armv6m))] +impl CPUID { + /// Selects the current CCSIDR + /// + /// * `level`: the required cache level minus 1, e.g. 0 for L1, 1 for L2 + /// * `ind`: select instruction cache or data/unified cache + /// + /// `level` is masked to be between 0 and 7. + #[inline] + pub fn select_cache(&mut self, level: u8, ind: CsselrCacheType) { + const CSSELR_IND_POS: u32 = 0; + const CSSELR_IND_MASK: u32 = 1 << CSSELR_IND_POS; + const CSSELR_LEVEL_POS: u32 = 1; + const CSSELR_LEVEL_MASK: u32 = 0x7 << CSSELR_LEVEL_POS; + + unsafe { + self.csselr.write( + ((u32::from(level) << CSSELR_LEVEL_POS) & CSSELR_LEVEL_MASK) + | (((ind as u32) << CSSELR_IND_POS) & CSSELR_IND_MASK), + ) + } + } + + /// Returns the number of sets and ways in the selected cache + #[inline] + pub fn cache_num_sets_ways(&mut self, level: u8, ind: CsselrCacheType) -> (u16, u16) { + const CCSIDR_NUMSETS_POS: u32 = 13; + const CCSIDR_NUMSETS_MASK: u32 = 0x7FFF << CCSIDR_NUMSETS_POS; + const CCSIDR_ASSOCIATIVITY_POS: u32 = 3; + const CCSIDR_ASSOCIATIVITY_MASK: u32 = 0x3FF << CCSIDR_ASSOCIATIVITY_POS; + + self.select_cache(level, ind); + crate::asm::dsb(); + let ccsidr = self.ccsidr.read(); + ( + (1 + ((ccsidr & CCSIDR_NUMSETS_MASK) >> CCSIDR_NUMSETS_POS)) as u16, + (1 + ((ccsidr & CCSIDR_ASSOCIATIVITY_MASK) >> CCSIDR_ASSOCIATIVITY_POS)) as u16, + ) + } + + /// Returns log2 of the number of words in the smallest cache line of all the data cache and + /// unified caches that are controlled by the processor. + /// + /// This is the `DminLine` field of the CTR register. + #[inline(always)] + pub fn cache_dminline() -> u32 { + const CTR_DMINLINE_POS: u32 = 16; + const CTR_DMINLINE_MASK: u32 = 0xF << CTR_DMINLINE_POS; + let ctr = unsafe { (*Self::PTR).ctr.read() }; + (ctr & CTR_DMINLINE_MASK) >> CTR_DMINLINE_POS + } + + /// Returns log2 of the number of words in the smallest cache line of all the instruction + /// caches that are controlled by the processor. + /// + /// This is the `IminLine` field of the CTR register. + #[inline(always)] + pub fn cache_iminline() -> u32 { + const CTR_IMINLINE_POS: u32 = 0; + const CTR_IMINLINE_MASK: u32 = 0xF << CTR_IMINLINE_POS; + let ctr = unsafe { (*Self::PTR).ctr.read() }; + (ctr & CTR_IMINLINE_MASK) >> CTR_IMINLINE_POS + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/dcb.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/dcb.rs new file mode 100644 index 0000000..4a63c88 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/dcb.rs @@ -0,0 +1,60 @@ +//! Debug Control Block + +use volatile_register::{RW, WO}; + +use crate::peripheral::DCB; +use core::ptr; + +const DCB_DEMCR_TRCENA: u32 = 1 << 24; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Debug Halting Control and Status + pub dhcsr: RW, + /// Debug Core Register Selector + pub dcrsr: WO, + /// Debug Core Register Data + pub dcrdr: RW, + /// Debug Exception and Monitor Control + pub demcr: RW, +} + +impl DCB { + /// Enables TRACE. This is for example required by the + /// `peripheral::DWT` cycle counter to work properly. + /// As by STM documentation, this flag is not reset on + /// soft-reset, only on power reset. + #[inline] + pub fn enable_trace(&mut self) { + // set bit 24 / TRCENA + unsafe { + self.demcr.modify(|w| w | DCB_DEMCR_TRCENA); + } + } + + /// Disables TRACE. See `DCB::enable_trace()` for more details + #[inline] + pub fn disable_trace(&mut self) { + // unset bit 24 / TRCENA + unsafe { + self.demcr.modify(|w| w & !DCB_DEMCR_TRCENA); + } + } + + /// Is there a debugger attached? (see note) + /// + /// Note: This function is [reported not to + /// work](http://web.archive.org/web/20180821191012/https://community.nxp.com/thread/424925#comment-782843) + /// on Cortex-M0 devices. Per the ARM v6-M Architecture Reference Manual, "Access to the DHCSR + /// from software running on the processor is IMPLEMENTATION DEFINED". Indeed, from the + /// [Cortex-M0+ r0p1 Technical Reference Manual](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0484c/BABJHEIG.html), "Note Software cannot access the debug registers." + #[inline] + pub fn is_debugger_attached() -> bool { + unsafe { + // do an 8-bit read of the 32-bit DHCSR register, and get the LSB + let value = ptr::read_volatile(Self::PTR as *const u8); + value & 0x1 == 1 + } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/dwt.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/dwt.rs new file mode 100644 index 0000000..58d91fd --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/dwt.rs @@ -0,0 +1,268 @@ +//! Data Watchpoint and Trace unit + +#[cfg(not(armv6m))] +use volatile_register::WO; +use volatile_register::{RO, RW}; + +use crate::peripheral::DWT; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Control + pub ctrl: RW, + /// Cycle Count + #[cfg(not(armv6m))] + pub cyccnt: RW, + /// CPI Count + #[cfg(not(armv6m))] + pub cpicnt: RW, + /// Exception Overhead Count + #[cfg(not(armv6m))] + pub exccnt: RW, + /// Sleep Count + #[cfg(not(armv6m))] + pub sleepcnt: RW, + /// LSU Count + #[cfg(not(armv6m))] + pub lsucnt: RW, + /// Folded-instruction Count + #[cfg(not(armv6m))] + pub foldcnt: RW, + /// Cortex-M0(+) does not have these parts + #[cfg(armv6m)] + reserved: [u32; 6], + /// Program Counter Sample + pub pcsr: RO, + /// Comparators + #[cfg(armv6m)] + pub c: [Comparator; 2], + #[cfg(not(armv6m))] + /// Comparators + pub c: [Comparator; 16], + #[cfg(not(armv6m))] + reserved: [u32; 932], + /// Lock Access + #[cfg(not(armv6m))] + pub lar: WO, + /// Lock Status + #[cfg(not(armv6m))] + pub lsr: RO, +} + +/// Comparator +#[repr(C)] +pub struct Comparator { + /// Comparator + pub comp: RW, + /// Comparator Mask + pub mask: RW, + /// Comparator Function + pub function: RW, + reserved: u32, +} + +// DWT CTRL register fields +const NUMCOMP_OFFSET: u32 = 28; +const NOTRCPKT: u32 = 1 << 27; +const NOEXTTRIG: u32 = 1 << 26; +const NOCYCCNT: u32 = 1 << 25; +const NOPRFCNT: u32 = 1 << 24; +const CYCCNTENA: u32 = 1 << 0; + +impl DWT { + /// Number of comparators implemented + /// + /// A value of zero indicates no comparator support. + #[inline] + pub fn num_comp() -> u8 { + // NOTE(unsafe) atomic read with no side effects + unsafe { ((*Self::PTR).ctrl.read() >> NUMCOMP_OFFSET) as u8 } + } + + /// Returns `true` if the the implementation supports sampling and exception tracing + #[cfg(not(armv6m))] + #[inline] + pub fn has_exception_trace() -> bool { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).ctrl.read() & NOTRCPKT == 0 } + } + + /// Returns `true` if the implementation includes external match signals + #[cfg(not(armv6m))] + #[inline] + pub fn has_external_match() -> bool { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).ctrl.read() & NOEXTTRIG == 0 } + } + + /// Returns `true` if the implementation supports a cycle counter + #[cfg(not(armv6m))] + #[inline] + pub fn has_cycle_counter() -> bool { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).ctrl.read() & NOCYCCNT == 0 } + } + + /// Returns `true` if the implementation the profiling counters + #[cfg(not(armv6m))] + #[inline] + pub fn has_profiling_counter() -> bool { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).ctrl.read() & NOPRFCNT == 0 } + } + + /// Enables the cycle counter + /// + /// The global trace enable ([`DCB::enable_trace`]) should be set before + /// enabling the cycle counter, the processor may ignore writes to the + /// cycle counter enable if the global trace is disabled + /// (implementation defined behaviour). + /// + /// [`DCB::enable_trace`]: crate::peripheral::DCB::enable_trace + #[cfg(not(armv6m))] + #[inline] + pub fn enable_cycle_counter(&mut self) { + unsafe { self.ctrl.modify(|r| r | CYCCNTENA) } + } + + /// Disables the cycle counter + #[cfg(not(armv6m))] + #[inline] + pub fn disable_cycle_counter(&mut self) { + unsafe { self.ctrl.modify(|r| r & !CYCCNTENA) } + } + + /// Returns `true` if the cycle counter is enabled + #[cfg(not(armv6m))] + #[inline] + pub fn cycle_counter_enabled() -> bool { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).ctrl.read() & CYCCNTENA != 0 } + } + + /// Returns the current clock cycle count + #[cfg(not(armv6m))] + #[inline] + #[deprecated( + since = "0.7.4", + note = "Use `cycle_count` which follows the C-GETTER convention" + )] + pub fn get_cycle_count() -> u32 { + Self::cycle_count() + } + + /// Returns the current clock cycle count + #[cfg(not(armv6m))] + #[inline] + pub fn cycle_count() -> u32 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).cyccnt.read() } + } + + /// Set the cycle count + #[cfg(not(armv6m))] + #[inline] + pub fn set_cycle_count(&mut self, count: u32) { + unsafe { self.cyccnt.write(count) } + } + + /// Removes the software lock on the DWT + /// + /// Some devices, like the STM32F7, software lock the DWT after a power cycle. + #[cfg(not(armv6m))] + #[inline] + pub fn unlock() { + // NOTE(unsafe) atomic write to a stateless, write-only register + unsafe { (*Self::PTR).lar.write(0xC5AC_CE55) } + } + + /// Get the CPI count + /// + /// Counts additional cycles required to execute multi-cycle instructions, + /// except those recorded by [`lsu_count`], and counts any instruction fetch + /// stalls. + /// + /// [`lsu_count`]: DWT::lsu_count + #[cfg(not(armv6m))] + #[inline] + pub fn cpi_count() -> u8 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).cpicnt.read() as u8 } + } + + /// Set the CPI count + #[cfg(not(armv6m))] + #[inline] + pub fn set_cpi_count(&mut self, count: u8) { + unsafe { self.cpicnt.write(count as u32) } + } + + /// Get the total cycles spent in exception processing + #[cfg(not(armv6m))] + #[inline] + pub fn exception_count() -> u8 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).exccnt.read() as u8 } + } + + /// Set the exception count + #[cfg(not(armv6m))] + #[inline] + pub fn set_exception_count(&mut self, count: u8) { + unsafe { self.exccnt.write(count as u32) } + } + + /// Get the total number of cycles that the processor is sleeping + /// + /// ARM recommends that this counter counts all cycles when the processor is sleeping, + /// regardless of whether a WFI or WFE instruction, or the sleep-on-exit functionality, + /// caused the entry to sleep mode. + /// However, all sleep features are implementation defined and therefore when + /// this counter counts is implementation defined. + #[cfg(not(armv6m))] + #[inline] + pub fn sleep_count() -> u8 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).sleepcnt.read() as u8 } + } + + /// Set the sleep count + #[cfg(not(armv6m))] + #[inline] + pub fn set_sleep_count(&mut self, count: u8) { + unsafe { self.sleepcnt.write(count as u32) } + } + + /// Get the additional cycles required to execute all load or store instructions + #[cfg(not(armv6m))] + #[inline] + pub fn lsu_count() -> u8 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).lsucnt.read() as u8 } + } + + /// Set the lsu count + #[cfg(not(armv6m))] + #[inline] + pub fn set_lsu_count(&mut self, count: u8) { + unsafe { self.lsucnt.write(count as u32) } + } + + /// Get the folded instruction count + /// + /// Increments on each instruction that takes 0 cycles. + #[cfg(not(armv6m))] + #[inline] + pub fn fold_count() -> u8 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).foldcnt.read() as u8 } + } + + /// Set the folded instruction count + #[cfg(not(armv6m))] + #[inline] + pub fn set_fold_count(&mut self, count: u8) { + unsafe { self.foldcnt.write(count as u32) } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/fpb.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/fpb.rs new file mode 100644 index 0000000..b86b8b2 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/fpb.rs @@ -0,0 +1,21 @@ +//! Flash Patch and Breakpoint unit +//! +//! *NOTE* Not available on Armv6-M. + +use volatile_register::{RO, RW, WO}; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Control + pub ctrl: RW, + /// Remap + pub remap: RW, + /// Comparator + pub comp: [RW; 127], + reserved: [u32; 875], + /// Lock Access + pub lar: WO, + /// Lock Status + pub lsr: RO, +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/fpu.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/fpu.rs new file mode 100644 index 0000000..9a047d8 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/fpu.rs @@ -0,0 +1,19 @@ +//! Floating Point Unit +//! +//! *NOTE* Available only on targets with a Floating Point Unit (FPU) extension. + +use volatile_register::{RO, RW}; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + reserved: u32, + /// Floating Point Context Control + pub fpccr: RW, + /// Floating Point Context Address + pub fpcar: RW, + /// Floating Point Default Status Control + pub fpdscr: RW, + /// Media and FP Feature + pub mvfr: [RO; 3], +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/icb.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/icb.rs new file mode 100644 index 0000000..e1de33b --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/icb.rs @@ -0,0 +1,32 @@ +//! Implementation Control Block + +#[cfg(any(armv7m, armv8m, native))] +use volatile_register::RO; +use volatile_register::RW; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Interrupt Controller Type Register + /// + /// The bottom four bits of this register give the number of implemented + /// interrupt lines, divided by 32. So a value of `0b0010` indicates 64 + /// interrupts. + #[cfg(any(armv7m, armv8m, native))] + pub ictr: RO, + + /// The ICTR is not defined in the ARMv6-M Architecture Reference manual, so + /// we replace it with this. + #[cfg(not(any(armv7m, armv8m, native)))] + _reserved: u32, + + /// Auxiliary Control Register + /// + /// This register is entirely implementation defined -- the standard gives + /// it an address, but does not define its role or contents. + pub actlr: RW, + + /// Coprocessor Power Control Register + #[cfg(armv8m)] + pub cppwr: RW, +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/itm.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/itm.rs new file mode 100644 index 0000000..c0d560f --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/itm.rs @@ -0,0 +1,71 @@ +//! Instrumentation Trace Macrocell +//! +//! *NOTE* Not available on Armv6-M and Armv8-M Baseline. + +use core::cell::UnsafeCell; +use core::ptr; + +use volatile_register::{RO, RW, WO}; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Stimulus Port + pub stim: [Stim; 256], + reserved0: [u32; 640], + /// Trace Enable + pub ter: [RW; 8], + reserved1: [u32; 8], + /// Trace Privilege + pub tpr: RW, + reserved2: [u32; 15], + /// Trace Control + pub tcr: RW, + reserved3: [u32; 75], + /// Lock Access + pub lar: WO, + /// Lock Status + pub lsr: RO, +} + +/// Stimulus Port +pub struct Stim { + register: UnsafeCell, +} + +impl Stim { + /// Writes an `u8` payload into the stimulus port + #[inline] + pub fn write_u8(&mut self, value: u8) { + unsafe { ptr::write_volatile(self.register.get() as *mut u8, value) } + } + + /// Writes an `u16` payload into the stimulus port + #[inline] + pub fn write_u16(&mut self, value: u16) { + unsafe { ptr::write_volatile(self.register.get() as *mut u16, value) } + } + + /// Writes an `u32` payload into the stimulus port + #[inline] + pub fn write_u32(&mut self, value: u32) { + unsafe { ptr::write_volatile(self.register.get(), value) } + } + + /// Returns `true` if the stimulus port is ready to accept more data + #[cfg(not(armv8m))] + #[inline] + pub fn is_fifo_ready(&self) -> bool { + unsafe { ptr::read_volatile(self.register.get()) & 0b1 == 1 } + } + + /// Returns `true` if the stimulus port is ready to accept more data + #[cfg(armv8m)] + #[inline] + pub fn is_fifo_ready(&self) -> bool { + // ARMv8-M adds a disabled bit; we indicate that we are ready to + // proceed with a stimulus write if the port is either ready (bit 0) or + // disabled (bit 1). + unsafe { ptr::read_volatile(self.register.get()) & 0b11 != 0 } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/mod.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/mod.rs new file mode 100644 index 0000000..d8fd2d4 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/mod.rs @@ -0,0 +1,685 @@ +//! Core peripherals. +//! +//! # API +//! +//! To use (most of) the peripheral API first you must get an *instance* of the peripheral. All the +//! core peripherals are modeled as singletons (there can only ever be, at most, one instance of any +//! one of them at any given point in time) and the only way to get an instance of them is through +//! the [`Peripherals::take`](struct.Peripherals.html#method.take) method. +//! +//! ``` no_run +//! # use cortex_m::peripheral::Peripherals; +//! let mut peripherals = Peripherals::take().unwrap(); +//! peripherals.DCB.enable_trace(); +//! ``` +//! +//! This method can only be successfully called *once* -- this is why the method returns an +//! `Option`. Subsequent calls to the method will result in a `None` value being returned. +//! +//! ``` no_run, should_panic +//! # use cortex_m::peripheral::Peripherals; +//! let ok = Peripherals::take().unwrap(); +//! let panics = Peripherals::take().unwrap(); +//! ``` +//! A part of the peripheral API doesn't require access to a peripheral instance. This part of the +//! API is provided as static methods on the peripheral types. One example is the +//! [`DWT::cycle_count`](struct.DWT.html#method.cycle_count) method. +//! +//! ``` no_run +//! # use cortex_m::peripheral::{DWT, Peripherals}; +//! { +//! let mut peripherals = Peripherals::take().unwrap(); +//! peripherals.DCB.enable_trace(); +//! peripherals.DWT.enable_cycle_counter(); +//! } // all the peripheral singletons are destroyed here +//! +//! // but this method can be called without a DWT instance +//! let cyccnt = DWT::cycle_count(); +//! ``` +//! +//! The singleton property can be *unsafely* bypassed using the `ptr` static method which is +//! available on all the peripheral types. This method is a useful building block for implementing +//! safe higher level abstractions. +//! +//! ``` no_run +//! # use cortex_m::peripheral::{DWT, Peripherals}; +//! { +//! let mut peripherals = Peripherals::take().unwrap(); +//! peripherals.DCB.enable_trace(); +//! peripherals.DWT.enable_cycle_counter(); +//! } // all the peripheral singletons are destroyed here +//! +//! // actually safe because this is an atomic read with no side effects +//! let cyccnt = unsafe { (*DWT::PTR).cyccnt.read() }; +//! ``` +//! +//! # References +//! +//! - ARMv7-M Architecture Reference Manual (Issue E.b) - Chapter B3 + +use core::marker::PhantomData; +use core::ops; + +use crate::interrupt; + +#[cfg(cm7)] +pub mod ac; +#[cfg(not(armv6m))] +pub mod cbp; +pub mod cpuid; +pub mod dcb; +pub mod dwt; +#[cfg(not(armv6m))] +pub mod fpb; +// NOTE(native) is for documentation purposes +#[cfg(any(has_fpu, native))] +pub mod fpu; +pub mod icb; +#[cfg(all(not(armv6m), not(armv8m_base)))] +pub mod itm; +pub mod mpu; +pub mod nvic; +#[cfg(armv8m)] +pub mod sau; +pub mod scb; +pub mod syst; +#[cfg(not(armv6m))] +pub mod tpiu; + +#[cfg(test)] +mod test; + +// NOTE the `PhantomData` used in the peripherals proxy is to make them `Send` but *not* `Sync` + +/// Core peripherals +#[allow(non_snake_case)] +#[allow(clippy::manual_non_exhaustive)] +pub struct Peripherals { + /// Cortex-M7 TCM and cache access control. + #[cfg(cm7)] + pub AC: AC, + + /// Cache and branch predictor maintenance operations. + /// Not available on Armv6-M. + pub CBP: CBP, + + /// CPUID + pub CPUID: CPUID, + + /// Debug Control Block + pub DCB: DCB, + + /// Data Watchpoint and Trace unit + pub DWT: DWT, + + /// Flash Patch and Breakpoint unit. + /// Not available on Armv6-M. + pub FPB: FPB, + + /// Floating Point Unit. + pub FPU: FPU, + + /// Implementation Control Block. + /// + /// The name is from the v8-M spec, but the block existed in earlier + /// revisions, without a name. + pub ICB: ICB, + + /// Instrumentation Trace Macrocell. + /// Not available on Armv6-M and Armv8-M Baseline. + pub ITM: ITM, + + /// Memory Protection Unit + pub MPU: MPU, + + /// Nested Vector Interrupt Controller + pub NVIC: NVIC, + + /// Security Attribution Unit + pub SAU: SAU, + + /// System Control Block + pub SCB: SCB, + + /// SysTick: System Timer + pub SYST: SYST, + + /// Trace Port Interface Unit. + /// Not available on Armv6-M. + pub TPIU: TPIU, + + // Private field making `Peripherals` non-exhaustive. We don't use `#[non_exhaustive]` so we + // can support older Rust versions. + _priv: (), +} + +// NOTE `no_mangle` is used here to prevent linking different minor versions of this crate as that +// would let you `take` the core peripherals more than once (one per minor version) +#[no_mangle] +static CORE_PERIPHERALS: () = (); + +/// Set to `true` when `take` or `steal` was called to make `Peripherals` a singleton. +static mut TAKEN: bool = false; + +impl Peripherals { + /// Returns all the core peripherals *once* + #[inline] + pub fn take() -> Option { + interrupt::free(|_| { + if unsafe { TAKEN } { + None + } else { + Some(unsafe { Peripherals::steal() }) + } + }) + } + + /// Unchecked version of `Peripherals::take` + #[inline] + pub unsafe fn steal() -> Self { + TAKEN = true; + + Peripherals { + #[cfg(cm7)] + AC: AC { + _marker: PhantomData, + }, + CBP: CBP { + _marker: PhantomData, + }, + CPUID: CPUID { + _marker: PhantomData, + }, + DCB: DCB { + _marker: PhantomData, + }, + DWT: DWT { + _marker: PhantomData, + }, + FPB: FPB { + _marker: PhantomData, + }, + FPU: FPU { + _marker: PhantomData, + }, + ICB: ICB { + _marker: PhantomData, + }, + ITM: ITM { + _marker: PhantomData, + }, + MPU: MPU { + _marker: PhantomData, + }, + NVIC: NVIC { + _marker: PhantomData, + }, + SAU: SAU { + _marker: PhantomData, + }, + SCB: SCB { + _marker: PhantomData, + }, + SYST: SYST { + _marker: PhantomData, + }, + TPIU: TPIU { + _marker: PhantomData, + }, + _priv: (), + } + } +} + +/// Access control +#[cfg(cm7)] +pub struct AC { + _marker: PhantomData<*const ()>, +} + +#[cfg(cm7)] +unsafe impl Send for AC {} + +#[cfg(cm7)] +impl AC { + /// Pointer to the register block + pub const PTR: *const self::ac::RegisterBlock = 0xE000_EF90 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const self::ac::RegisterBlock { + Self::PTR + } +} + +/// Cache and branch predictor maintenance operations +pub struct CBP { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for CBP {} + +#[cfg(not(armv6m))] +impl CBP { + #[inline(always)] + pub(crate) const unsafe fn new() -> Self { + CBP { + _marker: PhantomData, + } + } + + /// Pointer to the register block + pub const PTR: *const self::cbp::RegisterBlock = 0xE000_EF50 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const self::cbp::RegisterBlock { + Self::PTR + } +} + +#[cfg(not(armv6m))] +impl ops::Deref for CBP { + type Target = self::cbp::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// CPUID +pub struct CPUID { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for CPUID {} + +impl CPUID { + /// Pointer to the register block + pub const PTR: *const self::cpuid::RegisterBlock = 0xE000_ED00 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const self::cpuid::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for CPUID { + type Target = self::cpuid::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// Debug Control Block +pub struct DCB { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for DCB {} + +impl DCB { + /// Pointer to the register block + pub const PTR: *const dcb::RegisterBlock = 0xE000_EDF0 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const dcb::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for DCB { + type Target = self::dcb::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*DCB::PTR } + } +} + +/// Data Watchpoint and Trace unit +pub struct DWT { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for DWT {} + +impl DWT { + /// Pointer to the register block + pub const PTR: *const dwt::RegisterBlock = 0xE000_1000 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const dwt::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for DWT { + type Target = self::dwt::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// Flash Patch and Breakpoint unit +pub struct FPB { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for FPB {} + +#[cfg(not(armv6m))] +impl FPB { + /// Pointer to the register block + pub const PTR: *const fpb::RegisterBlock = 0xE000_2000 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const fpb::RegisterBlock { + Self::PTR + } +} + +#[cfg(not(armv6m))] +impl ops::Deref for FPB { + type Target = self::fpb::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// Floating Point Unit +pub struct FPU { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for FPU {} + +#[cfg(any(has_fpu, native))] +impl FPU { + /// Pointer to the register block + pub const PTR: *const fpu::RegisterBlock = 0xE000_EF30 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const fpu::RegisterBlock { + Self::PTR + } +} + +#[cfg(any(has_fpu, native))] +impl ops::Deref for FPU { + type Target = self::fpu::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// Implementation Control Block. +/// +/// This block contains implementation-defined registers like `ictr` and +/// `actlr`. It's called the "implementation control block" in the ARMv8-M +/// standard, but earlier standards contained the registers, just without a +/// name. +pub struct ICB { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for ICB {} + +impl ICB { + /// Pointer to the register block + pub const PTR: *mut icb::RegisterBlock = 0xE000_E004 as *mut _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *mut icb::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for ICB { + type Target = self::icb::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +impl ops::DerefMut for ICB { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { &mut *Self::PTR } + } +} + +/// Instrumentation Trace Macrocell +pub struct ITM { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for ITM {} + +#[cfg(all(not(armv6m), not(armv8m_base)))] +impl ITM { + /// Pointer to the register block + pub const PTR: *mut itm::RegisterBlock = 0xE000_0000 as *mut _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *mut itm::RegisterBlock { + Self::PTR + } +} + +#[cfg(all(not(armv6m), not(armv8m_base)))] +impl ops::Deref for ITM { + type Target = self::itm::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +#[cfg(all(not(armv6m), not(armv8m_base)))] +impl ops::DerefMut for ITM { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { &mut *Self::PTR } + } +} + +/// Memory Protection Unit +pub struct MPU { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for MPU {} + +impl MPU { + /// Pointer to the register block + pub const PTR: *const mpu::RegisterBlock = 0xE000_ED90 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const mpu::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for MPU { + type Target = self::mpu::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// Nested Vector Interrupt Controller +pub struct NVIC { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for NVIC {} + +impl NVIC { + /// Pointer to the register block + pub const PTR: *const nvic::RegisterBlock = 0xE000_E100 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const nvic::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for NVIC { + type Target = self::nvic::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// Security Attribution Unit +pub struct SAU { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for SAU {} + +#[cfg(armv8m)] +impl SAU { + /// Pointer to the register block + pub const PTR: *const sau::RegisterBlock = 0xE000_EDD0 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const sau::RegisterBlock { + Self::PTR + } +} + +#[cfg(armv8m)] +impl ops::Deref for SAU { + type Target = self::sau::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// System Control Block +pub struct SCB { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for SCB {} + +impl SCB { + /// Pointer to the register block + pub const PTR: *const scb::RegisterBlock = 0xE000_ED04 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const scb::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for SCB { + type Target = self::scb::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// SysTick: System Timer +pub struct SYST { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for SYST {} + +impl SYST { + /// Pointer to the register block + pub const PTR: *const syst::RegisterBlock = 0xE000_E010 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const syst::RegisterBlock { + Self::PTR + } +} + +impl ops::Deref for SYST { + type Target = self::syst::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} + +/// Trace Port Interface Unit +pub struct TPIU { + _marker: PhantomData<*const ()>, +} + +unsafe impl Send for TPIU {} + +#[cfg(not(armv6m))] +impl TPIU { + /// Pointer to the register block + pub const PTR: *const tpiu::RegisterBlock = 0xE004_0000 as *const _; + + /// Returns a pointer to the register block + #[inline(always)] + #[deprecated(since = "0.7.5", note = "Use the associated constant `PTR` instead")] + pub const fn ptr() -> *const tpiu::RegisterBlock { + Self::PTR + } +} + +#[cfg(not(armv6m))] +impl ops::Deref for TPIU { + type Target = self::tpiu::RegisterBlock; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/mpu.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/mpu.rs new file mode 100644 index 0000000..3a5f5b4 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/mpu.rs @@ -0,0 +1,65 @@ +//! Memory Protection Unit + +use volatile_register::{RO, RW}; + +/// Register block for ARMv7-M +#[cfg(not(armv8m))] +#[repr(C)] +pub struct RegisterBlock { + /// Type + pub _type: RO, + /// Control + pub ctrl: RW, + /// Region Number + pub rnr: RW, + /// Region Base Address + pub rbar: RW, + /// Region Attribute and Size + pub rasr: RW, + /// Alias 1 of RBAR + pub rbar_a1: RW, + /// Alias 1 of RASR + pub rasr_a1: RW, + /// Alias 2 of RBAR + pub rbar_a2: RW, + /// Alias 2 of RASR + pub rasr_a2: RW, + /// Alias 3 of RBAR + pub rbar_a3: RW, + /// Alias 3 of RASR + pub rasr_a3: RW, +} + +/// Register block for ARMv8-M +#[cfg(armv8m)] +#[repr(C)] +pub struct RegisterBlock { + /// Type + pub _type: RO, + /// Control + pub ctrl: RW, + /// Region Number + pub rnr: RW, + /// Region Base Address + pub rbar: RW, + /// Region Limit Address + pub rlar: RW, + /// Alias 1 of RBAR + pub rbar_a1: RW, + /// Alias 1 of RLAR + pub rlar_a1: RW, + /// Alias 2 of RBAR + pub rbar_a2: RW, + /// Alias 2 of RLAR + pub rlar_a2: RW, + /// Alias 3 of RBAR + pub rbar_a3: RW, + /// Alias 3 of RLAR + pub rlar_a3: RW, + + // Reserved word at offset 0xBC + _reserved: u32, + + /// Memory Attribute Indirection register 0 and 1 + pub mair: [RW; 2], +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/nvic.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/nvic.rs new file mode 100644 index 0000000..57fa94b --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/nvic.rs @@ -0,0 +1,265 @@ +//! Nested Vector Interrupt Controller + +use volatile_register::RW; +#[cfg(not(armv6m))] +use volatile_register::{RO, WO}; + +use crate::interrupt::InterruptNumber; +use crate::peripheral::NVIC; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Interrupt Set-Enable + pub iser: [RW; 16], + + _reserved0: [u32; 16], + + /// Interrupt Clear-Enable + pub icer: [RW; 16], + + _reserved1: [u32; 16], + + /// Interrupt Set-Pending + pub ispr: [RW; 16], + + _reserved2: [u32; 16], + + /// Interrupt Clear-Pending + pub icpr: [RW; 16], + + _reserved3: [u32; 16], + + /// Interrupt Active Bit (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub iabr: [RO; 16], + #[cfg(armv6m)] + _reserved4: [u32; 16], + + _reserved5: [u32; 48], + + /// Interrupt Priority + /// + /// On ARMv7-M, 124 word-sized registers are available. Each of those + /// contains of 4 interrupt priorities of 8 byte each.The architecture + /// specifically allows accessing those along byte boundaries, so they are + /// represented as 496 byte-sized registers, for convenience, and to allow + /// atomic priority updates. + /// + /// On ARMv6-M, the registers must only be accessed along word boundaries, + /// so convenient byte-sized representation wouldn't work on that + /// architecture. + #[cfg(not(armv6m))] + pub ipr: [RW; 496], + + /// Interrupt Priority + /// + /// On ARMv7-M, 124 word-sized registers are available. Each of those + /// contains of 4 interrupt priorities of 8 byte each.The architecture + /// specifically allows accessing those along byte boundaries, so they are + /// represented as 496 byte-sized registers, for convenience, and to allow + /// atomic priority updates. + /// + /// On ARMv6-M, the registers must only be accessed along word boundaries, + /// so convenient byte-sized representation wouldn't work on that + /// architecture. + #[cfg(armv6m)] + pub ipr: [RW; 8], + + #[cfg(not(armv6m))] + _reserved6: [u32; 580], + + /// Software Trigger Interrupt + #[cfg(not(armv6m))] + pub stir: WO, +} + +impl NVIC { + /// Request an IRQ in software + /// + /// Writing a value to the INTID field is the same as manually pending an interrupt by setting + /// the corresponding interrupt bit in an Interrupt Set Pending Register. This is similar to + /// [`NVIC::pend`]. + /// + /// This method is not available on ARMv6-M chips. + /// + /// [`NVIC::pend`]: #method.pend + #[cfg(not(armv6m))] + #[inline] + pub fn request(&mut self, interrupt: I) + where + I: InterruptNumber, + { + let nr = interrupt.number(); + + unsafe { + self.stir.write(u32::from(nr)); + } + } + + /// Disables `interrupt` + #[inline] + pub fn mask(interrupt: I) + where + I: InterruptNumber, + { + let nr = interrupt.number(); + // NOTE(unsafe) this is a write to a stateless register + unsafe { (*Self::PTR).icer[usize::from(nr / 32)].write(1 << (nr % 32)) } + } + + /// Enables `interrupt` + /// + /// This function is `unsafe` because it can break mask-based critical sections + #[inline] + pub unsafe fn unmask(interrupt: I) + where + I: InterruptNumber, + { + let nr = interrupt.number(); + // NOTE(ptr) this is a write to a stateless register + (*Self::PTR).iser[usize::from(nr / 32)].write(1 << (nr % 32)) + } + + /// Returns the NVIC priority of `interrupt` + /// + /// *NOTE* NVIC encodes priority in the highest bits of a byte so values like `1` and `2` map + /// to the same priority. Also for NVIC priorities, a lower value (e.g. `16`) has higher + /// priority (urgency) than a larger value (e.g. `32`). + #[inline] + pub fn get_priority(interrupt: I) -> u8 + where + I: InterruptNumber, + { + #[cfg(not(armv6m))] + { + let nr = interrupt.number(); + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).ipr[usize::from(nr)].read() } + } + + #[cfg(armv6m)] + { + // NOTE(unsafe) atomic read with no side effects + let ipr_n = unsafe { (*Self::PTR).ipr[Self::ipr_index(interrupt)].read() }; + let prio = (ipr_n >> Self::ipr_shift(interrupt)) & 0x0000_00ff; + prio as u8 + } + } + + /// Is `interrupt` active or pre-empted and stacked + #[cfg(not(armv6m))] + #[inline] + pub fn is_active(interrupt: I) -> bool + where + I: InterruptNumber, + { + let nr = interrupt.number(); + let mask = 1 << (nr % 32); + + // NOTE(unsafe) atomic read with no side effects + unsafe { ((*Self::PTR).iabr[usize::from(nr / 32)].read() & mask) == mask } + } + + /// Checks if `interrupt` is enabled + #[inline] + pub fn is_enabled(interrupt: I) -> bool + where + I: InterruptNumber, + { + let nr = interrupt.number(); + let mask = 1 << (nr % 32); + + // NOTE(unsafe) atomic read with no side effects + unsafe { ((*Self::PTR).iser[usize::from(nr / 32)].read() & mask) == mask } + } + + /// Checks if `interrupt` is pending + #[inline] + pub fn is_pending(interrupt: I) -> bool + where + I: InterruptNumber, + { + let nr = interrupt.number(); + let mask = 1 << (nr % 32); + + // NOTE(unsafe) atomic read with no side effects + unsafe { ((*Self::PTR).ispr[usize::from(nr / 32)].read() & mask) == mask } + } + + /// Forces `interrupt` into pending state + #[inline] + pub fn pend(interrupt: I) + where + I: InterruptNumber, + { + let nr = interrupt.number(); + + // NOTE(unsafe) atomic stateless write; ICPR doesn't store any state + unsafe { (*Self::PTR).ispr[usize::from(nr / 32)].write(1 << (nr % 32)) } + } + + /// Sets the "priority" of `interrupt` to `prio` + /// + /// *NOTE* See [`get_priority`](struct.NVIC.html#method.get_priority) method for an explanation + /// of how NVIC priorities work. + /// + /// On ARMv6-M, updating an interrupt priority requires a read-modify-write operation. On + /// ARMv7-M, the operation is performed in a single atomic write operation. + /// + /// # Unsafety + /// + /// Changing priority levels can break priority-based critical sections (see + /// [`register::basepri`](crate::register::basepri)) and compromise memory safety. + #[inline] + pub unsafe fn set_priority(&mut self, interrupt: I, prio: u8) + where + I: InterruptNumber, + { + #[cfg(not(armv6m))] + { + let nr = interrupt.number(); + self.ipr[usize::from(nr)].write(prio) + } + + #[cfg(armv6m)] + { + self.ipr[Self::ipr_index(interrupt)].modify(|value| { + let mask = 0x0000_00ff << Self::ipr_shift(interrupt); + let prio = u32::from(prio) << Self::ipr_shift(interrupt); + + (value & !mask) | prio + }) + } + } + + /// Clears `interrupt`'s pending state + #[inline] + pub fn unpend(interrupt: I) + where + I: InterruptNumber, + { + let nr = interrupt.number(); + + // NOTE(unsafe) atomic stateless write; ICPR doesn't store any state + unsafe { (*Self::PTR).icpr[usize::from(nr / 32)].write(1 << (nr % 32)) } + } + + #[cfg(armv6m)] + #[inline] + fn ipr_index(interrupt: I) -> usize + where + I: InterruptNumber, + { + usize::from(interrupt.number()) / 4 + } + + #[cfg(armv6m)] + #[inline] + fn ipr_shift(interrupt: I) -> usize + where + I: InterruptNumber, + { + (usize::from(interrupt.number()) % 4) * 8 + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/sau.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/sau.rs new file mode 100644 index 0000000..da91aca --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/sau.rs @@ -0,0 +1,243 @@ +//! Security Attribution Unit +//! +//! *NOTE* Available only on Armv8-M and Armv8.1-M, for the following Rust target triples: +//! * `thumbv8m.base-none-eabi` +//! * `thumbv8m.main-none-eabi` +//! * `thumbv8m.main-none-eabihf` +//! +//! For reference please check the section B8.3 of the Armv8-M Architecture Reference Manual. + +use crate::interrupt; +use crate::peripheral::SAU; +use bitfield::bitfield; +use volatile_register::{RO, RW}; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Control Register + pub ctrl: RW, + /// Type Register + pub _type: RO, + /// Region Number Register + pub rnr: RW, + /// Region Base Address Register + pub rbar: RW, + /// Region Limit Address Register + pub rlar: RW, + /// Secure Fault Status Register + pub sfsr: RO, + /// Secure Fault Address Register + pub sfar: RO, +} + +bitfield! { + /// Control Register description + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Ctrl(u32); + get_enable, set_enable: 0; + get_allns, set_allns: 1; +} + +bitfield! { + /// Type Register description + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Type(u32); + u8; + sregion, _: 7, 0; +} + +bitfield! { + /// Region Number Register description + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Rnr(u32); + u8; + get_region, set_region: 7, 0; +} + +bitfield! { + /// Region Base Address Register description + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Rbar(u32); + u32; + get_baddr, set_baddr: 31, 5; +} + +bitfield! { + /// Region Limit Address Register description + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Rlar(u32); + u32; + get_laddr, set_laddr: 31, 5; + get_nsc, set_nsc: 1; + get_enable, set_enable: 0; +} + +bitfield! { + /// Secure Fault Status Register description + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Sfsr(u32); + invep, _: 0; + invis, _: 1; + inver, _: 2; + auviol, _: 3; + invtran, _: 4; + lsperr, _: 5; + sfarvalid, _: 6; + lserr, _: 7; +} + +bitfield! { + /// Secure Fault Address Register description + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Sfar(u32); + u32; + address, _: 31, 0; +} + +/// Possible attribute of a SAU region. +#[derive(Debug)] +pub enum SauRegionAttribute { + /// SAU region is Secure + Secure, + /// SAU region is Non-Secure Callable + NonSecureCallable, + /// SAU region is Non-Secure + NonSecure, +} + +/// Description of a SAU region. +#[derive(Debug)] +pub struct SauRegion { + /// First address of the region, its 5 least significant bits must be set to zero. + pub base_address: u32, + /// Last address of the region, its 5 least significant bits must be set to one. + pub limit_address: u32, + /// Attribute of the region. + pub attribute: SauRegionAttribute, +} + +/// Possible error values returned by the SAU methods. +#[derive(Debug)] +pub enum SauError { + /// The region number parameter to set or get a region must be between 0 and + /// region_numbers() - 1. + RegionNumberTooBig, + /// Bits 0 to 4 of the base address of a SAU region must be set to zero. + WrongBaseAddress, + /// Bits 0 to 4 of the limit address of a SAU region must be set to one. + WrongLimitAddress, +} + +impl SAU { + /// Get the number of implemented SAU regions. + #[inline] + pub fn region_numbers(&self) -> u8 { + self._type.read().sregion() + } + + /// Enable the SAU. + #[inline] + pub fn enable(&mut self) { + unsafe { + self.ctrl.modify(|mut ctrl| { + ctrl.set_enable(true); + ctrl + }); + } + } + + /// Set a SAU region to a region number. + /// SAU regions must be 32 bytes aligned and their sizes must be a multiple of 32 bytes. It + /// means that the 5 least significant bits of the base address of a SAU region must be set to + /// zero and the 5 least significant bits of the limit address must be set to one. + /// The region number must be valid. + /// This function is executed under a critical section to prevent having inconsistent results. + #[inline] + pub fn set_region(&mut self, region_number: u8, region: SauRegion) -> Result<(), SauError> { + interrupt::free(|_| { + let base_address = region.base_address; + let limit_address = region.limit_address; + let attribute = region.attribute; + + if region_number >= self.region_numbers() { + Err(SauError::RegionNumberTooBig) + } else if base_address & 0x1F != 0 { + Err(SauError::WrongBaseAddress) + } else if limit_address & 0x1F != 0x1F { + Err(SauError::WrongLimitAddress) + } else { + // All fields of these registers are going to be modified so we don't need to read them + // before. + let mut rnr = Rnr(0); + let mut rbar = Rbar(0); + let mut rlar = Rlar(0); + + rnr.set_region(region_number); + rbar.set_baddr(base_address >> 5); + rlar.set_laddr(limit_address >> 5); + + match attribute { + SauRegionAttribute::Secure => { + rlar.set_nsc(false); + rlar.set_enable(false); + } + SauRegionAttribute::NonSecureCallable => { + rlar.set_nsc(true); + rlar.set_enable(true); + } + SauRegionAttribute::NonSecure => { + rlar.set_nsc(false); + rlar.set_enable(true); + } + } + + unsafe { + self.rnr.write(rnr); + self.rbar.write(rbar); + self.rlar.write(rlar); + } + + Ok(()) + } + }) + } + + /// Get a region from the SAU. + /// The region number must be valid. + /// This function is executed under a critical section to prevent having inconsistent results. + #[inline] + pub fn get_region(&mut self, region_number: u8) -> Result { + interrupt::free(|_| { + if region_number >= self.region_numbers() { + Err(SauError::RegionNumberTooBig) + } else { + unsafe { + self.rnr.write(Rnr(region_number.into())); + } + + let rbar = self.rbar.read(); + let rlar = self.rlar.read(); + + let attribute = match (rlar.get_enable(), rlar.get_nsc()) { + (false, _) => SauRegionAttribute::Secure, + (true, false) => SauRegionAttribute::NonSecure, + (true, true) => SauRegionAttribute::NonSecureCallable, + }; + + Ok(SauRegion { + base_address: rbar.get_baddr() << 5, + limit_address: (rlar.get_laddr() << 5) | 0x1F, + attribute, + }) + } + }) + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/scb.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/scb.rs new file mode 100644 index 0000000..f998b17 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/scb.rs @@ -0,0 +1,1109 @@ +//! System Control Block + +use core::ptr; + +use volatile_register::RW; + +#[cfg(not(armv6m))] +use super::cpuid::CsselrCacheType; +#[cfg(not(armv6m))] +use super::CBP; +#[cfg(not(armv6m))] +use super::CPUID; +use super::SCB; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Interrupt Control and State + pub icsr: RW, + + /// Vector Table Offset (not present on Cortex-M0 variants) + pub vtor: RW, + + /// Application Interrupt and Reset Control + pub aircr: RW, + + /// System Control + pub scr: RW, + + /// Configuration and Control + pub ccr: RW, + + /// System Handler Priority (word accessible only on Cortex-M0 variants) + /// + /// On ARMv7-M, `shpr[0]` points to SHPR1 + /// + /// On ARMv6-M, `shpr[0]` points to SHPR2 + #[cfg(not(armv6m))] + pub shpr: [RW; 12], + #[cfg(armv6m)] + _reserved1: u32, + /// System Handler Priority (word accessible only on Cortex-M0 variants) + /// + /// On ARMv7-M, `shpr[0]` points to SHPR1 + /// + /// On ARMv6-M, `shpr[0]` points to SHPR2 + #[cfg(armv6m)] + pub shpr: [RW; 2], + + /// System Handler Control and State + pub shcsr: RW, + + /// Configurable Fault Status (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub cfsr: RW, + #[cfg(armv6m)] + _reserved2: u32, + + /// HardFault Status (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub hfsr: RW, + #[cfg(armv6m)] + _reserved3: u32, + + /// Debug Fault Status (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub dfsr: RW, + #[cfg(armv6m)] + _reserved4: u32, + + /// MemManage Fault Address (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub mmfar: RW, + #[cfg(armv6m)] + _reserved5: u32, + + /// BusFault Address (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub bfar: RW, + #[cfg(armv6m)] + _reserved6: u32, + + /// Auxiliary Fault Status (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub afsr: RW, + #[cfg(armv6m)] + _reserved7: u32, + + _reserved8: [u32; 18], + + /// Coprocessor Access Control (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + pub cpacr: RW, + #[cfg(armv6m)] + _reserved9: u32, +} + +/// FPU access mode +#[cfg(has_fpu)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FpuAccessMode { + /// FPU is not accessible + Disabled, + /// FPU is accessible in Privileged and User mode + Enabled, + /// FPU is accessible in Privileged mode only + Privileged, +} + +#[cfg(has_fpu)] +mod fpu_consts { + pub const SCB_CPACR_FPU_MASK: u32 = 0b11_11 << 20; + pub const SCB_CPACR_FPU_ENABLE: u32 = 0b01_01 << 20; + pub const SCB_CPACR_FPU_USER: u32 = 0b10_10 << 20; +} + +#[cfg(has_fpu)] +use self::fpu_consts::*; + +#[cfg(has_fpu)] +impl SCB { + /// Shorthand for `set_fpu_access_mode(FpuAccessMode::Disabled)` + #[inline] + pub fn disable_fpu(&mut self) { + self.set_fpu_access_mode(FpuAccessMode::Disabled) + } + + /// Shorthand for `set_fpu_access_mode(FpuAccessMode::Enabled)` + #[inline] + pub fn enable_fpu(&mut self) { + self.set_fpu_access_mode(FpuAccessMode::Enabled) + } + + /// Gets FPU access mode + #[inline] + pub fn fpu_access_mode() -> FpuAccessMode { + // NOTE(unsafe) atomic read operation with no side effects + let cpacr = unsafe { (*Self::PTR).cpacr.read() }; + + if cpacr & SCB_CPACR_FPU_MASK == SCB_CPACR_FPU_ENABLE | SCB_CPACR_FPU_USER { + FpuAccessMode::Enabled + } else if cpacr & SCB_CPACR_FPU_MASK == SCB_CPACR_FPU_ENABLE { + FpuAccessMode::Privileged + } else { + FpuAccessMode::Disabled + } + } + + /// Sets FPU access mode + /// + /// *IMPORTANT* Any function that runs fully or partly with the FPU disabled must *not* take any + /// floating-point arguments or have any floating-point local variables. Because the compiler + /// might inline such a function into a caller that does have floating-point arguments or + /// variables, any such function must be also marked #[inline(never)]. + #[inline] + pub fn set_fpu_access_mode(&mut self, mode: FpuAccessMode) { + let mut cpacr = self.cpacr.read() & !SCB_CPACR_FPU_MASK; + match mode { + FpuAccessMode::Disabled => (), + FpuAccessMode::Privileged => cpacr |= SCB_CPACR_FPU_ENABLE, + FpuAccessMode::Enabled => cpacr |= SCB_CPACR_FPU_ENABLE | SCB_CPACR_FPU_USER, + } + unsafe { self.cpacr.write(cpacr) } + } +} + +impl SCB { + /// Returns the active exception number + #[inline] + pub fn vect_active() -> VectActive { + let icsr = unsafe { ptr::read(&(*SCB::PTR).icsr as *const _ as *const u32) }; + + match icsr as u8 { + 0 => VectActive::ThreadMode, + 2 => VectActive::Exception(Exception::NonMaskableInt), + 3 => VectActive::Exception(Exception::HardFault), + #[cfg(not(armv6m))] + 4 => VectActive::Exception(Exception::MemoryManagement), + #[cfg(not(armv6m))] + 5 => VectActive::Exception(Exception::BusFault), + #[cfg(not(armv6m))] + 6 => VectActive::Exception(Exception::UsageFault), + #[cfg(any(armv8m, native))] + 7 => VectActive::Exception(Exception::SecureFault), + 11 => VectActive::Exception(Exception::SVCall), + #[cfg(not(armv6m))] + 12 => VectActive::Exception(Exception::DebugMonitor), + 14 => VectActive::Exception(Exception::PendSV), + 15 => VectActive::Exception(Exception::SysTick), + irqn => VectActive::Interrupt { irqn: irqn - 16 }, + } + } +} + +/// Processor core exceptions (internal interrupts) +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "std", derive(PartialOrd, Hash))] +pub enum Exception { + /// Non maskable interrupt + NonMaskableInt, + + /// Hard fault interrupt + HardFault, + + /// Memory management interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + MemoryManagement, + + /// Bus fault interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + BusFault, + + /// Usage fault interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + UsageFault, + + /// Secure fault interrupt (only on ARMv8-M) + #[cfg(any(armv8m, native))] + SecureFault, + + /// SV call interrupt + SVCall, + + /// Debug monitor interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + DebugMonitor, + + /// Pend SV interrupt + PendSV, + + /// System Tick interrupt + SysTick, +} + +impl Exception { + /// Returns the IRQ number of this `Exception` + /// + /// The return value is always within the closed range `[-1, -14]` + #[inline] + pub fn irqn(self) -> i8 { + match self { + Exception::NonMaskableInt => -14, + Exception::HardFault => -13, + #[cfg(not(armv6m))] + Exception::MemoryManagement => -12, + #[cfg(not(armv6m))] + Exception::BusFault => -11, + #[cfg(not(armv6m))] + Exception::UsageFault => -10, + #[cfg(any(armv8m, native))] + Exception::SecureFault => -9, + Exception::SVCall => -5, + #[cfg(not(armv6m))] + Exception::DebugMonitor => -4, + Exception::PendSV => -2, + Exception::SysTick => -1, + } + } +} + +/// Active exception number +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "std", derive(PartialOrd, Hash))] +pub enum VectActive { + /// Thread mode + ThreadMode, + + /// Processor core exception (internal interrupts) + Exception(Exception), + + /// Device specific exception (external interrupts) + Interrupt { + /// Interrupt number. This number is always within half open range `[0, 240)` + irqn: u8, + }, +} + +impl VectActive { + /// Converts a `byte` into `VectActive` + #[inline] + pub fn from(vect_active: u8) -> Option { + Some(match vect_active { + 0 => VectActive::ThreadMode, + 2 => VectActive::Exception(Exception::NonMaskableInt), + 3 => VectActive::Exception(Exception::HardFault), + #[cfg(not(armv6m))] + 4 => VectActive::Exception(Exception::MemoryManagement), + #[cfg(not(armv6m))] + 5 => VectActive::Exception(Exception::BusFault), + #[cfg(not(armv6m))] + 6 => VectActive::Exception(Exception::UsageFault), + #[cfg(any(armv8m, native))] + 7 => VectActive::Exception(Exception::SecureFault), + 11 => VectActive::Exception(Exception::SVCall), + #[cfg(not(armv6m))] + 12 => VectActive::Exception(Exception::DebugMonitor), + 14 => VectActive::Exception(Exception::PendSV), + 15 => VectActive::Exception(Exception::SysTick), + irqn if irqn >= 16 => VectActive::Interrupt { irqn }, + _ => return None, + }) + } +} + +#[cfg(not(armv6m))] +mod scb_consts { + pub const SCB_CCR_IC_MASK: u32 = 1 << 17; + pub const SCB_CCR_DC_MASK: u32 = 1 << 16; +} + +#[cfg(not(armv6m))] +use self::scb_consts::*; + +#[cfg(not(armv6m))] +impl SCB { + /// Enables I-cache if currently disabled. + /// + /// This operation first invalidates the entire I-cache. + #[inline] + pub fn enable_icache(&mut self) { + // Don't do anything if I-cache is already enabled + if Self::icache_enabled() { + return; + } + + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = unsafe { CBP::new() }; + + // Invalidate I-cache + cbp.iciallu(); + + // Enable I-cache + extern "C" { + // see asm-v7m.s + fn __enable_icache(); + } + + // NOTE(unsafe): The asm routine manages exclusive access to the SCB + // registers and applies the proper barriers; it is technically safe on + // its own, and is only `unsafe` here because it's `extern "C"`. + unsafe { + __enable_icache(); + } + } + + /// Disables I-cache if currently enabled. + /// + /// This operation invalidates the entire I-cache after disabling. + #[inline] + pub fn disable_icache(&mut self) { + // Don't do anything if I-cache is already disabled + if !Self::icache_enabled() { + return; + } + + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = unsafe { CBP::new() }; + + // Disable I-cache + // NOTE(unsafe): We have synchronised access by &mut self + unsafe { self.ccr.modify(|r| r & !SCB_CCR_IC_MASK) }; + + // Invalidate I-cache + cbp.iciallu(); + + crate::asm::dsb(); + crate::asm::isb(); + } + + /// Returns whether the I-cache is currently enabled. + #[inline(always)] + pub fn icache_enabled() -> bool { + crate::asm::dsb(); + crate::asm::isb(); + + // NOTE(unsafe): atomic read with no side effects + unsafe { (*Self::PTR).ccr.read() & SCB_CCR_IC_MASK == SCB_CCR_IC_MASK } + } + + /// Invalidates the entire I-cache. + #[inline] + pub fn invalidate_icache(&mut self) { + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = unsafe { CBP::new() }; + + // Invalidate I-cache + cbp.iciallu(); + + crate::asm::dsb(); + crate::asm::isb(); + } + + /// Enables D-cache if currently disabled. + /// + /// This operation first invalidates the entire D-cache, ensuring it does + /// not contain stale values before being enabled. + #[inline] + pub fn enable_dcache(&mut self, cpuid: &mut CPUID) { + // Don't do anything if D-cache is already enabled + if Self::dcache_enabled() { + return; + } + + // Invalidate anything currently in the D-cache + unsafe { self.invalidate_dcache(cpuid) }; + + // Now turn on the D-cache + extern "C" { + // see asm-v7m.s + fn __enable_dcache(); + } + + // NOTE(unsafe): The asm routine manages exclusive access to the SCB + // registers and applies the proper barriers; it is technically safe on + // its own, and is only `unsafe` here because it's `extern "C"`. + unsafe { + __enable_dcache(); + } + } + + /// Disables D-cache if currently enabled. + /// + /// This operation subsequently cleans and invalidates the entire D-cache, + /// ensuring all contents are safely written back to main memory after disabling. + #[inline] + pub fn disable_dcache(&mut self, cpuid: &mut CPUID) { + // Don't do anything if D-cache is already disabled + if !Self::dcache_enabled() { + return; + } + + // Turn off the D-cache + // NOTE(unsafe): We have synchronised access by &mut self + unsafe { self.ccr.modify(|r| r & !SCB_CCR_DC_MASK) }; + + // Clean and invalidate whatever was left in it + self.clean_invalidate_dcache(cpuid); + } + + /// Returns whether the D-cache is currently enabled. + #[inline] + pub fn dcache_enabled() -> bool { + crate::asm::dsb(); + crate::asm::isb(); + + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).ccr.read() & SCB_CCR_DC_MASK == SCB_CCR_DC_MASK } + } + + /// Invalidates the entire D-cache. + /// + /// Note that calling this while the dcache is enabled will probably wipe out the + /// stack, depending on optimisations, therefore breaking returning to the call point. + /// + /// It's used immediately before enabling the dcache, but not exported publicly. + #[inline] + unsafe fn invalidate_dcache(&mut self, cpuid: &mut CPUID) { + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = CBP::new(); + + // Read number of sets and ways + let (sets, ways) = cpuid.cache_num_sets_ways(0, CsselrCacheType::DataOrUnified); + + // Invalidate entire D-cache + for set in 0..sets { + for way in 0..ways { + cbp.dcisw(set, way); + } + } + + crate::asm::dsb(); + crate::asm::isb(); + } + + /// Cleans the entire D-cache. + /// + /// This function causes everything in the D-cache to be written back to main memory, + /// overwriting whatever is already there. + #[inline] + pub fn clean_dcache(&mut self, cpuid: &mut CPUID) { + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = unsafe { CBP::new() }; + + // Read number of sets and ways + let (sets, ways) = cpuid.cache_num_sets_ways(0, CsselrCacheType::DataOrUnified); + + for set in 0..sets { + for way in 0..ways { + cbp.dccsw(set, way); + } + } + + crate::asm::dsb(); + crate::asm::isb(); + } + + /// Cleans and invalidates the entire D-cache. + /// + /// This function causes everything in the D-cache to be written back to main memory, + /// and then marks the entire D-cache as invalid, causing future reads to first fetch + /// from main memory. + #[inline] + pub fn clean_invalidate_dcache(&mut self, cpuid: &mut CPUID) { + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = unsafe { CBP::new() }; + + // Read number of sets and ways + let (sets, ways) = cpuid.cache_num_sets_ways(0, CsselrCacheType::DataOrUnified); + + for set in 0..sets { + for way in 0..ways { + cbp.dccisw(set, way); + } + } + + crate::asm::dsb(); + crate::asm::isb(); + } + + /// Invalidates D-cache by address. + /// + /// * `addr`: The address to invalidate, which must be cache-line aligned. + /// * `size`: Number of bytes to invalidate, which must be a multiple of the cache line size. + /// + /// Invalidates D-cache cache lines, starting from the first line containing `addr`, + /// finishing once at least `size` bytes have been invalidated. + /// + /// Invalidation causes the next read access to memory to be fetched from main memory instead + /// of the cache. + /// + /// # Cache Line Sizes + /// + /// Cache line sizes vary by core. For all Cortex-M7 cores, the cache line size is fixed + /// to 32 bytes, which means `addr` must be 32-byte aligned and `size` must be a multiple + /// of 32. At the time of writing, no other Cortex-M cores have data caches. + /// + /// If `addr` is not cache-line aligned, or `size` is not a multiple of the cache line size, + /// other data before or after the desired memory would also be invalidated, which can very + /// easily cause memory corruption and undefined behaviour. + /// + /// # Safety + /// + /// After invalidating, the next read of invalidated data will be from main memory. This may + /// cause recent writes to be lost, potentially including writes that initialized objects. + /// Therefore, this method may cause uninitialized memory or invalid values to be read, + /// resulting in undefined behaviour. You must ensure that main memory contains valid and + /// initialized values before invalidating. + /// + /// `addr` **must** be aligned to the size of the cache lines, and `size` **must** be a + /// multiple of the cache line size, otherwise this function will invalidate other memory, + /// easily leading to memory corruption and undefined behaviour. This precondition is checked + /// in debug builds using a `debug_assert!()`, but not checked in release builds to avoid + /// a runtime-dependent `panic!()` call. + #[inline] + pub unsafe fn invalidate_dcache_by_address(&mut self, addr: usize, size: usize) { + // No-op zero sized operations + if size == 0 { + return; + } + + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = CBP::new(); + + // dminline is log2(num words), so 2**dminline * 4 gives size in bytes + let dminline = CPUID::cache_dminline(); + let line_size = (1 << dminline) * 4; + + debug_assert!((addr & (line_size - 1)) == 0); + debug_assert!((size & (line_size - 1)) == 0); + + crate::asm::dsb(); + + // Find number of cache lines to invalidate + let num_lines = ((size - 1) / line_size) + 1; + + // Compute address of first cache line + let mask = 0xFFFF_FFFF - (line_size - 1); + let mut addr = addr & mask; + + for _ in 0..num_lines { + cbp.dcimvac(addr as u32); + addr += line_size; + } + + crate::asm::dsb(); + crate::asm::isb(); + } + + /// Invalidates an object from the D-cache. + /// + /// * `obj`: The object to invalidate. + /// + /// Invalidates D-cache starting from the first cache line containing `obj`, + /// continuing to invalidate cache lines until all of `obj` has been invalidated. + /// + /// Invalidation causes the next read access to memory to be fetched from main memory instead + /// of the cache. + /// + /// # Cache Line Sizes + /// + /// Cache line sizes vary by core. For all Cortex-M7 cores, the cache line size is fixed + /// to 32 bytes, which means `obj` must be 32-byte aligned, and its size must be a multiple + /// of 32 bytes. At the time of writing, no other Cortex-M cores have data caches. + /// + /// If `obj` is not cache-line aligned, or its size is not a multiple of the cache line size, + /// other data before or after the desired memory would also be invalidated, which can very + /// easily cause memory corruption and undefined behaviour. + /// + /// # Safety + /// + /// After invalidating, `obj` will be read from main memory on next access. This may cause + /// recent writes to `obj` to be lost, potentially including the write that initialized it. + /// Therefore, this method may cause uninitialized memory or invalid values to be read, + /// resulting in undefined behaviour. You must ensure that main memory contains a valid and + /// initialized value for T before invalidating `obj`. + /// + /// `obj` **must** be aligned to the size of the cache lines, and its size **must** be a + /// multiple of the cache line size, otherwise this function will invalidate other memory, + /// easily leading to memory corruption and undefined behaviour. This precondition is checked + /// in debug builds using a `debug_assert!()`, but not checked in release builds to avoid + /// a runtime-dependent `panic!()` call. + #[inline] + pub unsafe fn invalidate_dcache_by_ref(&mut self, obj: &mut T) { + self.invalidate_dcache_by_address(obj as *const T as usize, core::mem::size_of::()); + } + + /// Invalidates a slice from the D-cache. + /// + /// * `slice`: The slice to invalidate. + /// + /// Invalidates D-cache starting from the first cache line containing members of `slice`, + /// continuing to invalidate cache lines until all of `slice` has been invalidated. + /// + /// Invalidation causes the next read access to memory to be fetched from main memory instead + /// of the cache. + /// + /// # Cache Line Sizes + /// + /// Cache line sizes vary by core. For all Cortex-M7 cores, the cache line size is fixed + /// to 32 bytes, which means `slice` must be 32-byte aligned, and its size must be a multiple + /// of 32 bytes. At the time of writing, no other Cortex-M cores have data caches. + /// + /// If `slice` is not cache-line aligned, or its size is not a multiple of the cache line size, + /// other data before or after the desired memory would also be invalidated, which can very + /// easily cause memory corruption and undefined behaviour. + /// + /// # Safety + /// + /// After invalidating, `slice` will be read from main memory on next access. This may cause + /// recent writes to `slice` to be lost, potentially including the write that initialized it. + /// Therefore, this method may cause uninitialized memory or invalid values to be read, + /// resulting in undefined behaviour. You must ensure that main memory contains valid and + /// initialized values for T before invalidating `slice`. + /// + /// `slice` **must** be aligned to the size of the cache lines, and its size **must** be a + /// multiple of the cache line size, otherwise this function will invalidate other memory, + /// easily leading to memory corruption and undefined behaviour. This precondition is checked + /// in debug builds using a `debug_assert!()`, but not checked in release builds to avoid + /// a runtime-dependent `panic!()` call. + #[inline] + pub unsafe fn invalidate_dcache_by_slice(&mut self, slice: &mut [T]) { + self.invalidate_dcache_by_address( + slice.as_ptr() as usize, + slice.len() * core::mem::size_of::(), + ); + } + + /// Cleans D-cache by address. + /// + /// * `addr`: The address to start cleaning at. + /// * `size`: The number of bytes to clean. + /// + /// Cleans D-cache cache lines, starting from the first line containing `addr`, + /// finishing once at least `size` bytes have been invalidated. + /// + /// Cleaning the cache causes whatever data is present in the cache to be immediately written + /// to main memory, overwriting whatever was in main memory. + /// + /// # Cache Line Sizes + /// + /// Cache line sizes vary by core. For all Cortex-M7 cores, the cache line size is fixed + /// to 32 bytes, which means `addr` should generally be 32-byte aligned and `size` should be a + /// multiple of 32. At the time of writing, no other Cortex-M cores have data caches. + /// + /// If `addr` is not cache-line aligned, or `size` is not a multiple of the cache line size, + /// other data before or after the desired memory will also be cleaned. From the point of view + /// of the core executing this function, memory remains consistent, so this is not unsound, + /// but is worth knowing about. + #[inline] + pub fn clean_dcache_by_address(&mut self, addr: usize, size: usize) { + // No-op zero sized operations + if size == 0 { + return; + } + + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = unsafe { CBP::new() }; + + crate::asm::dsb(); + + let dminline = CPUID::cache_dminline(); + let line_size = (1 << dminline) * 4; + let num_lines = ((size - 1) / line_size) + 1; + + let mask = 0xFFFF_FFFF - (line_size - 1); + let mut addr = addr & mask; + + for _ in 0..num_lines { + cbp.dccmvac(addr as u32); + addr += line_size; + } + + crate::asm::dsb(); + crate::asm::isb(); + } + + /// Cleans an object from the D-cache. + /// + /// * `obj`: The object to clean. + /// + /// Cleans D-cache starting from the first cache line containing `obj`, + /// continuing to clean cache lines until all of `obj` has been cleaned. + /// + /// It is recommended that `obj` is both aligned to the cache line size and a multiple of + /// the cache line size long, otherwise surrounding data will also be cleaned. + /// + /// Cleaning the cache causes whatever data is present in the cache to be immediately written + /// to main memory, overwriting whatever was in main memory. + #[inline] + pub fn clean_dcache_by_ref(&mut self, obj: &T) { + self.clean_dcache_by_address(obj as *const T as usize, core::mem::size_of::()); + } + + /// Cleans a slice from D-cache. + /// + /// * `slice`: The slice to clean. + /// + /// Cleans D-cache starting from the first cache line containing members of `slice`, + /// continuing to clean cache lines until all of `slice` has been cleaned. + /// + /// It is recommended that `slice` is both aligned to the cache line size and a multiple of + /// the cache line size long, otherwise surrounding data will also be cleaned. + /// + /// Cleaning the cache causes whatever data is present in the cache to be immediately written + /// to main memory, overwriting whatever was in main memory. + #[inline] + pub fn clean_dcache_by_slice(&mut self, slice: &[T]) { + self.clean_dcache_by_address( + slice.as_ptr() as usize, + slice.len() * core::mem::size_of::(), + ); + } + + /// Cleans and invalidates D-cache by address. + /// + /// * `addr`: The address to clean and invalidate. + /// * `size`: The number of bytes to clean and invalidate. + /// + /// Cleans and invalidates D-cache starting from the first cache line containing `addr`, + /// finishing once at least `size` bytes have been cleaned and invalidated. + /// + /// It is recommended that `addr` is aligned to the cache line size and `size` is a multiple of + /// the cache line size, otherwise surrounding data will also be cleaned. + /// + /// Cleaning and invalidating causes data in the D-cache to be written back to main memory, + /// and then marks that data in the D-cache as invalid, causing future reads to first fetch + /// from main memory. + #[inline] + pub fn clean_invalidate_dcache_by_address(&mut self, addr: usize, size: usize) { + // No-op zero sized operations + if size == 0 { + return; + } + + // NOTE(unsafe): No races as all CBP registers are write-only and stateless + let mut cbp = unsafe { CBP::new() }; + + crate::asm::dsb(); + + // Cache lines are fixed to 32 bit on Cortex-M7 and not present in earlier Cortex-M + const LINESIZE: usize = 32; + let num_lines = ((size - 1) / LINESIZE) + 1; + + let mut addr = addr & 0xFFFF_FFE0; + + for _ in 0..num_lines { + cbp.dccimvac(addr as u32); + addr += LINESIZE; + } + + crate::asm::dsb(); + crate::asm::isb(); + } +} + +const SCB_SCR_SLEEPDEEP: u32 = 0x1 << 2; + +impl SCB { + /// Set the SLEEPDEEP bit in the SCR register + #[inline] + pub fn set_sleepdeep(&mut self) { + unsafe { + self.scr.modify(|scr| scr | SCB_SCR_SLEEPDEEP); + } + } + + /// Clear the SLEEPDEEP bit in the SCR register + #[inline] + pub fn clear_sleepdeep(&mut self) { + unsafe { + self.scr.modify(|scr| scr & !SCB_SCR_SLEEPDEEP); + } + } +} + +const SCB_SCR_SLEEPONEXIT: u32 = 0x1 << 1; + +impl SCB { + /// Set the SLEEPONEXIT bit in the SCR register + #[inline] + pub fn set_sleeponexit(&mut self) { + unsafe { + self.scr.modify(|scr| scr | SCB_SCR_SLEEPONEXIT); + } + } + + /// Clear the SLEEPONEXIT bit in the SCR register + #[inline] + pub fn clear_sleeponexit(&mut self) { + unsafe { + self.scr.modify(|scr| scr & !SCB_SCR_SLEEPONEXIT); + } + } +} + +const SCB_AIRCR_VECTKEY: u32 = 0x05FA << 16; +const SCB_AIRCR_PRIGROUP_MASK: u32 = 0x7 << 8; +const SCB_AIRCR_SYSRESETREQ: u32 = 1 << 2; + +impl SCB { + /// Initiate a system reset request to reset the MCU + #[inline] + pub fn sys_reset() -> ! { + crate::asm::dsb(); + unsafe { + (*Self::PTR).aircr.modify( + |r| { + SCB_AIRCR_VECTKEY | // otherwise the write is ignored + r & SCB_AIRCR_PRIGROUP_MASK | // keep priority group unchanged + SCB_AIRCR_SYSRESETREQ + }, // set the bit + ) + }; + crate::asm::dsb(); + loop { + // wait for the reset + crate::asm::nop(); // avoid rust-lang/rust#28728 + } + } +} + +const SCB_ICSR_PENDSVSET: u32 = 1 << 28; +const SCB_ICSR_PENDSVCLR: u32 = 1 << 27; + +const SCB_ICSR_PENDSTSET: u32 = 1 << 26; +const SCB_ICSR_PENDSTCLR: u32 = 1 << 25; + +impl SCB { + /// Set the PENDSVSET bit in the ICSR register which will pend the PendSV interrupt + #[inline] + pub fn set_pendsv() { + unsafe { + (*Self::PTR).icsr.write(SCB_ICSR_PENDSVSET); + } + } + + /// Check if PENDSVSET bit in the ICSR register is set meaning PendSV interrupt is pending + #[inline] + pub fn is_pendsv_pending() -> bool { + unsafe { (*Self::PTR).icsr.read() & SCB_ICSR_PENDSVSET == SCB_ICSR_PENDSVSET } + } + + /// Set the PENDSVCLR bit in the ICSR register which will clear a pending PendSV interrupt + #[inline] + pub fn clear_pendsv() { + unsafe { + (*Self::PTR).icsr.write(SCB_ICSR_PENDSVCLR); + } + } + + /// Set the PENDSTSET bit in the ICSR register which will pend a SysTick interrupt + #[inline] + pub fn set_pendst() { + unsafe { + (*Self::PTR).icsr.write(SCB_ICSR_PENDSTSET); + } + } + + /// Check if PENDSTSET bit in the ICSR register is set meaning SysTick interrupt is pending + #[inline] + pub fn is_pendst_pending() -> bool { + unsafe { (*Self::PTR).icsr.read() & SCB_ICSR_PENDSTSET == SCB_ICSR_PENDSTSET } + } + + /// Set the PENDSTCLR bit in the ICSR register which will clear a pending SysTick interrupt + #[inline] + pub fn clear_pendst() { + unsafe { + (*Self::PTR).icsr.write(SCB_ICSR_PENDSTCLR); + } + } +} + +/// System handlers, exceptions with configurable priority +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum SystemHandler { + // NonMaskableInt, // priority is fixed + // HardFault, // priority is fixed + /// Memory management interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + MemoryManagement = 4, + + /// Bus fault interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + BusFault = 5, + + /// Usage fault interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + UsageFault = 6, + + /// Secure fault interrupt (only on ARMv8-M) + #[cfg(any(armv8m, native))] + SecureFault = 7, + + /// SV call interrupt + SVCall = 11, + + /// Debug monitor interrupt (not present on Cortex-M0 variants) + #[cfg(not(armv6m))] + DebugMonitor = 12, + + /// Pend SV interrupt + PendSV = 14, + + /// System Tick interrupt + SysTick = 15, +} + +impl SCB { + /// Returns the hardware priority of `system_handler` + /// + /// *NOTE*: Hardware priority does not exactly match logical priority levels. See + /// [`NVIC.get_priority`](struct.NVIC.html#method.get_priority) for more details. + #[inline] + pub fn get_priority(system_handler: SystemHandler) -> u8 { + let index = system_handler as u8; + + #[cfg(not(armv6m))] + { + // NOTE(unsafe) atomic read with no side effects + + // NOTE(unsafe): Index is bounded to [4,15] by SystemHandler design. + // TODO: Review it after rust-lang/rust/issues/13926 will be fixed. + let priority_ref = unsafe { (*Self::PTR).shpr.get_unchecked(usize::from(index - 4)) }; + + priority_ref.read() + } + + #[cfg(armv6m)] + { + // NOTE(unsafe) atomic read with no side effects + + // NOTE(unsafe): Index is bounded to [11,15] by SystemHandler design. + // TODO: Review it after rust-lang/rust/issues/13926 will be fixed. + let priority_ref = unsafe { + (*Self::PTR) + .shpr + .get_unchecked(usize::from((index - 8) / 4)) + }; + + let shpr = priority_ref.read(); + let prio = (shpr >> (8 * (index % 4))) & 0x0000_00ff; + prio as u8 + } + } + + /// Sets the hardware priority of `system_handler` to `prio` + /// + /// *NOTE*: Hardware priority does not exactly match logical priority levels. See + /// [`NVIC.get_priority`](struct.NVIC.html#method.get_priority) for more details. + /// + /// On ARMv6-M, updating a system handler priority requires a read-modify-write operation. On + /// ARMv7-M, the operation is performed in a single, atomic write operation. + /// + /// # Unsafety + /// + /// Changing priority levels can break priority-based critical sections (see + /// [`register::basepri`](crate::register::basepri)) and compromise memory safety. + #[inline] + pub unsafe fn set_priority(&mut self, system_handler: SystemHandler, prio: u8) { + let index = system_handler as u8; + + #[cfg(not(armv6m))] + { + // NOTE(unsafe): Index is bounded to [4,15] by SystemHandler design. + // TODO: Review it after rust-lang/rust/issues/13926 will be fixed. + let priority_ref = (*Self::PTR).shpr.get_unchecked(usize::from(index - 4)); + + priority_ref.write(prio) + } + + #[cfg(armv6m)] + { + // NOTE(unsafe): Index is bounded to [11,15] by SystemHandler design. + // TODO: Review it after rust-lang/rust/issues/13926 will be fixed. + let priority_ref = (*Self::PTR) + .shpr + .get_unchecked(usize::from((index - 8) / 4)); + + priority_ref.modify(|value| { + let shift = 8 * (index % 4); + let mask = 0x0000_00ff << shift; + let prio = u32::from(prio) << shift; + + (value & !mask) | prio + }); + } + } + + /// Return the bit position of the exception enable bit in the SHCSR register + #[inline] + #[cfg(not(any(armv6m, armv8m_base)))] + fn shcsr_enable_shift(exception: Exception) -> Option { + match exception { + Exception::MemoryManagement => Some(16), + Exception::BusFault => Some(17), + Exception::UsageFault => Some(18), + #[cfg(armv8m_main)] + Exception::SecureFault => Some(19), + _ => None, + } + } + + /// Enable the exception + /// + /// If the exception is enabled, when the exception is triggered, the exception handler will be executed instead of the + /// HardFault handler. + /// This function is only allowed on the following exceptions: + /// * `MemoryManagement` + /// * `BusFault` + /// * `UsageFault` + /// * `SecureFault` (can only be enabled from Secure state) + /// + /// Calling this function with any other exception will do nothing. + #[inline] + #[cfg(not(any(armv6m, armv8m_base)))] + pub fn enable(&mut self, exception: Exception) { + if let Some(shift) = SCB::shcsr_enable_shift(exception) { + // The mutable reference to SCB makes sure that only this code is currently modifying + // the register. + unsafe { self.shcsr.modify(|value| value | (1 << shift)) } + } + } + + /// Disable the exception + /// + /// If the exception is disabled, when the exception is triggered, the HardFault handler will be executed instead of the + /// exception handler. + /// This function is only allowed on the following exceptions: + /// * `MemoryManagement` + /// * `BusFault` + /// * `UsageFault` + /// * `SecureFault` (can not be changed from Non-secure state) + /// + /// Calling this function with any other exception will do nothing. + #[inline] + #[cfg(not(any(armv6m, armv8m_base)))] + pub fn disable(&mut self, exception: Exception) { + if let Some(shift) = SCB::shcsr_enable_shift(exception) { + // The mutable reference to SCB makes sure that only this code is currently modifying + // the register. + unsafe { self.shcsr.modify(|value| value & !(1 << shift)) } + } + } + + /// Check if an exception is enabled + /// + /// This function is only allowed on the following exception: + /// * `MemoryManagement` + /// * `BusFault` + /// * `UsageFault` + /// * `SecureFault` (can not be read from Non-secure state) + /// + /// Calling this function with any other exception will read `false`. + #[inline] + #[cfg(not(any(armv6m, armv8m_base)))] + pub fn is_enabled(&self, exception: Exception) -> bool { + if let Some(shift) = SCB::shcsr_enable_shift(exception) { + (self.shcsr.read() & (1 << shift)) > 0 + } else { + false + } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/syst.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/syst.rs new file mode 100644 index 0000000..345acc2 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/syst.rs @@ -0,0 +1,185 @@ +//! SysTick: System Timer + +use volatile_register::{RO, RW}; + +use crate::peripheral::SYST; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Control and Status + pub csr: RW, + /// Reload Value + pub rvr: RW, + /// Current Value + pub cvr: RW, + /// Calibration Value + pub calib: RO, +} + +/// SysTick clock source +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SystClkSource { + /// Core-provided clock + Core, + /// External reference clock + External, +} + +const SYST_COUNTER_MASK: u32 = 0x00ff_ffff; + +const SYST_CSR_ENABLE: u32 = 1 << 0; +const SYST_CSR_TICKINT: u32 = 1 << 1; +const SYST_CSR_CLKSOURCE: u32 = 1 << 2; +const SYST_CSR_COUNTFLAG: u32 = 1 << 16; + +const SYST_CALIB_SKEW: u32 = 1 << 30; +const SYST_CALIB_NOREF: u32 = 1 << 31; + +impl SYST { + /// Clears current value to 0 + /// + /// After calling `clear_current()`, the next call to `has_wrapped()` will return `false`. + #[inline] + pub fn clear_current(&mut self) { + unsafe { self.cvr.write(0) } + } + + /// Disables counter + #[inline] + pub fn disable_counter(&mut self) { + unsafe { self.csr.modify(|v| v & !SYST_CSR_ENABLE) } + } + + /// Disables SysTick interrupt + #[inline] + pub fn disable_interrupt(&mut self) { + unsafe { self.csr.modify(|v| v & !SYST_CSR_TICKINT) } + } + + /// Enables counter + /// + /// *NOTE* The reference manual indicates that: + /// + /// "The SysTick counter reload and current value are undefined at reset, the correct + /// initialization sequence for the SysTick counter is: + /// + /// - Program reload value + /// - Clear current value + /// - Program Control and Status register" + /// + /// The sequence translates to `self.set_reload(x); self.clear_current(); self.enable_counter()` + #[inline] + pub fn enable_counter(&mut self) { + unsafe { self.csr.modify(|v| v | SYST_CSR_ENABLE) } + } + + /// Enables SysTick interrupt + #[inline] + pub fn enable_interrupt(&mut self) { + unsafe { self.csr.modify(|v| v | SYST_CSR_TICKINT) } + } + + /// Gets clock source + /// + /// *NOTE* This takes `&mut self` because the read operation is side effectful and can clear the + /// bit that indicates that the timer has wrapped (cf. `SYST.has_wrapped`) + #[inline] + pub fn get_clock_source(&mut self) -> SystClkSource { + // NOTE(unsafe) atomic read with no side effects + if self.csr.read() & SYST_CSR_CLKSOURCE != 0 { + SystClkSource::Core + } else { + SystClkSource::External + } + } + + /// Gets current value + #[inline] + pub fn get_current() -> u32 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).cvr.read() } + } + + /// Gets reload value + #[inline] + pub fn get_reload() -> u32 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).rvr.read() } + } + + /// Returns the reload value with which the counter would wrap once per 10 + /// ms + /// + /// Returns `0` if the value is not known (e.g. because the clock can + /// change dynamically). + #[inline] + pub fn get_ticks_per_10ms() -> u32 { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).calib.read() & SYST_COUNTER_MASK } + } + + /// Checks if an external reference clock is available + #[inline] + pub fn has_reference_clock() -> bool { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).calib.read() & SYST_CALIB_NOREF == 0 } + } + + /// Checks if the counter wrapped (underflowed) since the last check + /// + /// *NOTE* This takes `&mut self` because the read operation is side effectful and will clear + /// the bit of the read register. + #[inline] + pub fn has_wrapped(&mut self) -> bool { + self.csr.read() & SYST_CSR_COUNTFLAG != 0 + } + + /// Checks if counter is enabled + /// + /// *NOTE* This takes `&mut self` because the read operation is side effectful and can clear the + /// bit that indicates that the timer has wrapped (cf. `SYST.has_wrapped`) + #[inline] + pub fn is_counter_enabled(&mut self) -> bool { + self.csr.read() & SYST_CSR_ENABLE != 0 + } + + /// Checks if SysTick interrupt is enabled + /// + /// *NOTE* This takes `&mut self` because the read operation is side effectful and can clear the + /// bit that indicates that the timer has wrapped (cf. `SYST.has_wrapped`) + #[inline] + pub fn is_interrupt_enabled(&mut self) -> bool { + self.csr.read() & SYST_CSR_TICKINT != 0 + } + + /// Checks if the calibration value is precise + /// + /// Returns `false` if using the reload value returned by + /// `get_ticks_per_10ms()` may result in a period significantly deviating + /// from 10 ms. + #[inline] + pub fn is_precise() -> bool { + // NOTE(unsafe) atomic read with no side effects + unsafe { (*Self::PTR).calib.read() & SYST_CALIB_SKEW == 0 } + } + + /// Sets clock source + #[inline] + pub fn set_clock_source(&mut self, clk_source: SystClkSource) { + match clk_source { + SystClkSource::External => unsafe { self.csr.modify(|v| v & !SYST_CSR_CLKSOURCE) }, + SystClkSource::Core => unsafe { self.csr.modify(|v| v | SYST_CSR_CLKSOURCE) }, + } + } + + /// Sets reload value + /// + /// Valid values are between `1` and `0x00ffffff`. + /// + /// *NOTE* To make the timer wrap every `N` ticks set the reload value to `N - 1` + #[inline] + pub fn set_reload(&mut self, value: u32) { + unsafe { self.rvr.write(value) } + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/test.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/test.rs new file mode 100644 index 0000000..cab064a --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/test.rs @@ -0,0 +1,170 @@ +#[test] +fn cpuid() { + let cpuid = unsafe { &*crate::peripheral::CPUID::PTR }; + + assert_eq!(address(&cpuid.base), 0xE000_ED00); + assert_eq!(address(&cpuid.pfr), 0xE000_ED40); + assert_eq!(address(&cpuid.dfr), 0xE000_ED48); + assert_eq!(address(&cpuid.afr), 0xE000_ED4C); + assert_eq!(address(&cpuid.mmfr), 0xE000_ED50); + assert_eq!(address(&cpuid.isar), 0xE000_ED60); + assert_eq!(address(&cpuid.clidr), 0xE000_ED78); + assert_eq!(address(&cpuid.ctr), 0xE000_ED7C); + assert_eq!(address(&cpuid.ccsidr), 0xE000_ED80); + assert_eq!(address(&cpuid.csselr), 0xE000_ED84); +} + +#[test] +fn dcb() { + let dcb = unsafe { &*crate::peripheral::DCB::PTR }; + + assert_eq!(address(&dcb.dhcsr), 0xE000_EDF0); + assert_eq!(address(&dcb.dcrsr), 0xE000_EDF4); + assert_eq!(address(&dcb.dcrdr), 0xE000_EDF8); + assert_eq!(address(&dcb.demcr), 0xE000_EDFC); +} + +#[test] +fn dwt() { + let dwt = unsafe { &*crate::peripheral::DWT::PTR }; + + assert_eq!(address(&dwt.ctrl), 0xE000_1000); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.cyccnt), 0xE000_1004); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.cpicnt), 0xE000_1008); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.exccnt), 0xE000_100C); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.sleepcnt), 0xE000_1010); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.lsucnt), 0xE000_1014); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.foldcnt), 0xE000_1018); + assert_eq!(address(&dwt.pcsr), 0xE000_101C); + assert_eq!(address(&dwt.c[0].comp), 0xE000_1020); + assert_eq!(address(&dwt.c[0].mask), 0xE000_1024); + assert_eq!(address(&dwt.c[0].function), 0xE000_1028); + assert_eq!(address(&dwt.c[1].comp), 0xE000_1030); + assert_eq!(address(&dwt.c[1].mask), 0xE000_1034); + assert_eq!(address(&dwt.c[1].function), 0xE000_1038); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.lar), 0xE000_1FB0); + #[cfg(not(armv6m))] + assert_eq!(address(&dwt.lsr), 0xE000_1FB4); +} + +#[test] +fn fpb() { + let fpb = unsafe { &*crate::peripheral::FPB::PTR }; + + assert_eq!(address(&fpb.ctrl), 0xE000_2000); + assert_eq!(address(&fpb.remap), 0xE000_2004); + assert_eq!(address(&fpb.comp), 0xE000_2008); + assert_eq!(address(&fpb.comp[1]), 0xE000_200C); + assert_eq!(address(&fpb.lar), 0xE000_2FB0); + assert_eq!(address(&fpb.lsr), 0xE000_2FB4); +} + +#[test] +fn fpu() { + let fpu = unsafe { &*crate::peripheral::FPU::PTR }; + + assert_eq!(address(&fpu.fpccr), 0xE000_EF34); + assert_eq!(address(&fpu.fpcar), 0xE000_EF38); + assert_eq!(address(&fpu.fpdscr), 0xE000_EF3C); + assert_eq!(address(&fpu.mvfr), 0xE000_EF40); + assert_eq!(address(&fpu.mvfr[1]), 0xE000_EF44); + assert_eq!(address(&fpu.mvfr[2]), 0xE000_EF48); +} + +#[test] +fn itm() { + let itm = unsafe { &*crate::peripheral::ITM::PTR }; + + assert_eq!(address(&itm.stim), 0xE000_0000); + assert_eq!(address(&itm.ter), 0xE000_0E00); + assert_eq!(address(&itm.tpr), 0xE000_0E40); + assert_eq!(address(&itm.tcr), 0xE000_0E80); + assert_eq!(address(&itm.lar), 0xE000_0FB0); + assert_eq!(address(&itm.lsr), 0xE000_0FB4); +} + +#[test] +fn mpu() { + let mpu = unsafe { &*crate::peripheral::MPU::PTR }; + + assert_eq!(address(&mpu._type), 0xE000ED90); + assert_eq!(address(&mpu.ctrl), 0xE000ED94); + assert_eq!(address(&mpu.rnr), 0xE000ED98); + assert_eq!(address(&mpu.rbar), 0xE000ED9C); + assert_eq!(address(&mpu.rasr), 0xE000EDA0); + assert_eq!(address(&mpu.rbar_a1), 0xE000EDA4); + assert_eq!(address(&mpu.rasr_a1), 0xE000EDA8); + assert_eq!(address(&mpu.rbar_a2), 0xE000EDAC); + assert_eq!(address(&mpu.rasr_a2), 0xE000EDB0); + assert_eq!(address(&mpu.rbar_a3), 0xE000EDB4); + assert_eq!(address(&mpu.rasr_a3), 0xE000EDB8); +} + +#[test] +fn nvic() { + let nvic = unsafe { &*crate::peripheral::NVIC::PTR }; + + assert_eq!(address(&nvic.iser), 0xE000E100); + assert_eq!(address(&nvic.icer), 0xE000E180); + assert_eq!(address(&nvic.ispr), 0xE000E200); + assert_eq!(address(&nvic.icpr), 0xE000E280); + assert_eq!(address(&nvic.iabr), 0xE000E300); + assert_eq!(address(&nvic.ipr), 0xE000E400); + #[cfg(not(armv6m))] + assert_eq!(address(&nvic.stir), 0xE000EF00); +} + +#[test] +fn scb() { + let scb = unsafe { &*crate::peripheral::SCB::PTR }; + + assert_eq!(address(&scb.icsr), 0xE000_ED04); + assert_eq!(address(&scb.vtor), 0xE000_ED08); + assert_eq!(address(&scb.aircr), 0xE000_ED0C); + assert_eq!(address(&scb.scr), 0xE000_ED10); + assert_eq!(address(&scb.ccr), 0xE000_ED14); + assert_eq!(address(&scb.shpr), 0xE000_ED18); + assert_eq!(address(&scb.shcsr), 0xE000_ED24); + assert_eq!(address(&scb.cfsr), 0xE000_ED28); + assert_eq!(address(&scb.hfsr), 0xE000_ED2C); + assert_eq!(address(&scb.dfsr), 0xE000_ED30); + assert_eq!(address(&scb.mmfar), 0xE000_ED34); + assert_eq!(address(&scb.bfar), 0xE000_ED38); + assert_eq!(address(&scb.afsr), 0xE000_ED3C); + assert_eq!(address(&scb.cpacr), 0xE000_ED88); +} + +#[test] +fn syst() { + let syst = unsafe { &*crate::peripheral::SYST::PTR }; + + assert_eq!(address(&syst.csr), 0xE000_E010); + assert_eq!(address(&syst.rvr), 0xE000_E014); + assert_eq!(address(&syst.cvr), 0xE000_E018); + assert_eq!(address(&syst.calib), 0xE000_E01C); +} + +#[test] +fn tpiu() { + let tpiu = unsafe { &*crate::peripheral::TPIU::PTR }; + + assert_eq!(address(&tpiu.sspsr), 0xE004_0000); + assert_eq!(address(&tpiu.cspsr), 0xE004_0004); + assert_eq!(address(&tpiu.acpr), 0xE004_0010); + assert_eq!(address(&tpiu.sppr), 0xE004_00F0); + assert_eq!(address(&tpiu.ffcr), 0xE004_0304); + assert_eq!(address(&tpiu.lar), 0xE004_0FB0); + assert_eq!(address(&tpiu.lsr), 0xE004_0FB4); + assert_eq!(address(&tpiu._type), 0xE004_0FC8); +} + +fn address(r: *const T) -> usize { + r as usize +} diff --git a/bitbox02-bt/vendor/cortex-m/src/peripheral/tpiu.rs b/bitbox02-bt/vendor/cortex-m/src/peripheral/tpiu.rs new file mode 100644 index 0000000..11cb79e --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/peripheral/tpiu.rs @@ -0,0 +1,31 @@ +//! Trace Port Interface Unit; +//! +//! *NOTE* Not available on Armv6-M. + +use volatile_register::{RO, RW, WO}; + +/// Register block +#[repr(C)] +pub struct RegisterBlock { + /// Supported Parallel Port Sizes + pub sspsr: RO, + /// Current Parallel Port Size + pub cspsr: RW, + reserved0: [u32; 2], + /// Asynchronous Clock Prescaler + pub acpr: RW, + reserved1: [u32; 55], + /// Selected Pin Control + pub sppr: RW, + reserved2: [u32; 132], + /// Formatter and Flush Control + pub ffcr: RW, + reserved3: [u32; 810], + /// Lock Access + pub lar: WO, + /// Lock Status + pub lsr: RO, + reserved4: [u32; 4], + /// TPIU Type + pub _type: RO, +} diff --git a/bitbox02-bt/vendor/cortex-m/src/prelude.rs b/bitbox02-bt/vendor/cortex-m/src/prelude.rs new file mode 100644 index 0000000..bc47cc0 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/prelude.rs @@ -0,0 +1,3 @@ +//! Prelude + +pub use embedded_hal::prelude::*; diff --git a/bitbox02-bt/vendor/cortex-m/src/register/apsr.rs b/bitbox02-bt/vendor/cortex-m/src/register/apsr.rs new file mode 100644 index 0000000..e83435c --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/apsr.rs @@ -0,0 +1,54 @@ +//! Application Program Status Register + +/// Application Program Status Register +#[derive(Clone, Copy, Debug)] +pub struct Apsr { + bits: u32, +} + +impl Apsr { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(self) -> u32 { + self.bits + } + + /// DSP overflow and saturation flag + #[inline] + pub fn q(self) -> bool { + self.bits & (1 << 27) == (1 << 27) + } + + /// Overflow flag + #[inline] + pub fn v(self) -> bool { + self.bits & (1 << 28) == (1 << 28) + } + + /// Carry or borrow flag + #[inline] + pub fn c(self) -> bool { + self.bits & (1 << 29) == (1 << 29) + } + + /// Zero flag + #[inline] + pub fn z(self) -> bool { + self.bits & (1 << 30) == (1 << 30) + } + + /// Negative flag + #[inline] + pub fn n(self) -> bool { + self.bits & (1 << 31) == (1 << 31) + } +} + +/// Reads the CPU register +/// +/// **NOTE** This function is available if `cortex-m` is built with the `"inline-asm"` feature. +#[inline] +pub fn read() -> Apsr { + let bits: u32 = call_asm!(__apsr_r() -> u32); + Apsr { bits } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/basepri.rs b/bitbox02-bt/vendor/cortex-m/src/register/basepri.rs new file mode 100644 index 0000000..07084cd --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/basepri.rs @@ -0,0 +1,24 @@ +//! Base Priority Mask Register + +/// Reads the CPU register +#[inline] +pub fn read() -> u8 { + call_asm!(__basepri_r() -> u8) +} + +/// Writes to the CPU register +/// +/// **IMPORTANT** If you are using a Cortex-M7 device with revision r0p1 you MUST enable the +/// `cm7-r0p1` Cargo feature or this function WILL misbehave. +#[inline] +pub unsafe fn write(basepri: u8) { + #[cfg(feature = "cm7-r0p1")] + { + call_asm!(__basepri_w_cm7_r0p1(basepri: u8)); + } + + #[cfg(not(feature = "cm7-r0p1"))] + { + call_asm!(__basepri_w(basepri: u8)); + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/basepri_max.rs b/bitbox02-bt/vendor/cortex-m/src/register/basepri_max.rs new file mode 100644 index 0000000..cea3838 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/basepri_max.rs @@ -0,0 +1,21 @@ +//! Base Priority Mask Register (conditional write) + +/// Writes to BASEPRI *if* +/// +/// - `basepri != 0` AND `basepri::read() == 0`, OR +/// - `basepri != 0` AND `basepri < basepri::read()` +/// +/// **IMPORTANT** If you are using a Cortex-M7 device with revision r0p1 you MUST enable the +/// `cm7-r0p1` Cargo feature or this function WILL misbehave. +#[inline] +pub fn write(basepri: u8) { + #[cfg(feature = "cm7-r0p1")] + { + call_asm!(__basepri_max_cm7_r0p1(basepri: u8)); + } + + #[cfg(not(feature = "cm7-r0p1"))] + { + call_asm!(__basepri_max(basepri: u8)); + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/control.rs b/bitbox02-bt/vendor/cortex-m/src/register/control.rs new file mode 100644 index 0000000..a991625 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/control.rs @@ -0,0 +1,164 @@ +//! Control register + +/// Control register +#[derive(Clone, Copy, Debug)] +pub struct Control { + bits: u32, +} + +impl Control { + /// Creates a `Control` value from raw bits. + #[inline] + pub fn from_bits(bits: u32) -> Self { + Self { bits } + } + + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(self) -> u32 { + self.bits + } + + /// Thread mode privilege level + #[inline] + pub fn npriv(self) -> Npriv { + if self.bits & (1 << 0) == (1 << 0) { + Npriv::Unprivileged + } else { + Npriv::Privileged + } + } + + /// Sets the thread mode privilege level value (nPRIV). + #[inline] + pub fn set_npriv(&mut self, npriv: Npriv) { + let mask = 1 << 0; + match npriv { + Npriv::Unprivileged => self.bits |= mask, + Npriv::Privileged => self.bits &= !mask, + } + } + + /// Currently active stack pointer + #[inline] + pub fn spsel(self) -> Spsel { + if self.bits & (1 << 1) == (1 << 1) { + Spsel::Psp + } else { + Spsel::Msp + } + } + + /// Sets the SPSEL value. + #[inline] + pub fn set_spsel(&mut self, spsel: Spsel) { + let mask = 1 << 1; + match spsel { + Spsel::Psp => self.bits |= mask, + Spsel::Msp => self.bits &= !mask, + } + } + + /// Whether context floating-point is currently active + #[inline] + pub fn fpca(self) -> Fpca { + if self.bits & (1 << 2) == (1 << 2) { + Fpca::Active + } else { + Fpca::NotActive + } + } + + /// Sets the FPCA value. + #[inline] + pub fn set_fpca(&mut self, fpca: Fpca) { + let mask = 1 << 2; + match fpca { + Fpca::Active => self.bits |= mask, + Fpca::NotActive => self.bits &= !mask, + } + } +} + +/// Thread mode privilege level +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Npriv { + /// Privileged + Privileged, + /// Unprivileged + Unprivileged, +} + +impl Npriv { + /// Is in privileged thread mode? + #[inline] + pub fn is_privileged(self) -> bool { + self == Npriv::Privileged + } + + /// Is in unprivileged thread mode? + #[inline] + pub fn is_unprivileged(self) -> bool { + self == Npriv::Unprivileged + } +} + +/// Currently active stack pointer +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Spsel { + /// MSP is the current stack pointer + Msp, + /// PSP is the current stack pointer + Psp, +} + +impl Spsel { + /// Is MSP the current stack pointer? + #[inline] + pub fn is_msp(self) -> bool { + self == Spsel::Msp + } + + /// Is PSP the current stack pointer? + #[inline] + pub fn is_psp(self) -> bool { + self == Spsel::Psp + } +} + +/// Whether context floating-point is currently active +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Fpca { + /// Floating-point context active. + Active, + /// No floating-point context active + NotActive, +} + +impl Fpca { + /// Is a floating-point context active? + #[inline] + pub fn is_active(self) -> bool { + self == Fpca::Active + } + + /// Is a floating-point context not active? + #[inline] + pub fn is_not_active(self) -> bool { + self == Fpca::NotActive + } +} + +/// Reads the CPU register +#[inline] +pub fn read() -> Control { + let bits: u32 = call_asm!(__control_r() -> u32); + Control { bits } +} + +/// Writes to the CPU register. +#[inline] +pub unsafe fn write(control: Control) { + let control = control.bits(); + call_asm!(__control_w(control: u32)); +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/faultmask.rs b/bitbox02-bt/vendor/cortex-m/src/register/faultmask.rs new file mode 100644 index 0000000..e57fa28 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/faultmask.rs @@ -0,0 +1,35 @@ +//! Fault Mask Register + +/// All exceptions are ... +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Faultmask { + /// Active + Active, + /// Inactive, expect for NMI + Inactive, +} + +impl Faultmask { + /// All exceptions are active + #[inline] + pub fn is_active(self) -> bool { + self == Faultmask::Active + } + + /// All exceptions, except for NMI, are inactive + #[inline] + pub fn is_inactive(self) -> bool { + self == Faultmask::Inactive + } +} + +/// Reads the CPU register +#[inline] +pub fn read() -> Faultmask { + let r: u32 = call_asm!(__faultmask_r() -> u32); + if r & (1 << 0) == (1 << 0) { + Faultmask::Inactive + } else { + Faultmask::Active + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/fpscr.rs b/bitbox02-bt/vendor/cortex-m/src/register/fpscr.rs new file mode 100644 index 0000000..68692c7 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/fpscr.rs @@ -0,0 +1,305 @@ +//! Floating-point Status Control Register + +/// Floating-point Status Control Register +#[derive(Clone, Copy, Debug)] +pub struct Fpscr { + bits: u32, +} + +impl Fpscr { + /// Creates a `Fspcr` value from raw bits. + #[inline] + pub fn from_bits(bits: u32) -> Self { + Self { bits } + } + + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(self) -> u32 { + self.bits + } + + /// Read the Negative condition code flag + #[inline] + pub fn n(self) -> bool { + self.bits & (1 << 31) != 0 + } + + /// Sets the Negative condition code flag + #[inline] + pub fn set_n(&mut self, n: bool) { + let mask = 1 << 31; + match n { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Zero condition code flag + #[inline] + pub fn z(self) -> bool { + self.bits & (1 << 30) != 0 + } + + /// Sets the Zero condition code flag + #[inline] + pub fn set_z(&mut self, z: bool) { + let mask = 1 << 30; + match z { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Carry condition code flag + #[inline] + pub fn c(self) -> bool { + self.bits & (1 << 29) != 0 + } + + /// Sets the Carry condition code flag + #[inline] + pub fn set_c(&mut self, c: bool) { + let mask = 1 << 29; + match c { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Overflow condition code flag + #[inline] + pub fn v(self) -> bool { + self.bits & (1 << 28) != 0 + } + + /// Sets the Zero condition code flag + #[inline] + pub fn set_v(&mut self, v: bool) { + let mask = 1 << 28; + match v { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Alternative Half Precision bit + #[inline] + pub fn ahp(self) -> bool { + self.bits & (1 << 26) != 0 + } + + /// Sets the Alternative Half Precision bit + #[inline] + pub fn set_ahp(&mut self, ahp: bool) { + let mask = 1 << 26; + match ahp { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Default NaN mode bit + #[inline] + pub fn dn(self) -> bool { + self.bits & (1 << 25) != 0 + } + + /// Sets the Default NaN mode bit + #[inline] + pub fn set_dn(&mut self, dn: bool) { + let mask = 1 << 25; + match dn { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Flush to Zero mode bit + #[inline] + pub fn fz(self) -> bool { + self.bits & (1 << 24) != 0 + } + + /// Sets the Flush to Zero mode bit + #[inline] + pub fn set_fz(&mut self, fz: bool) { + let mask = 1 << 24; + match fz { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Rounding Mode control field + #[inline] + pub fn rmode(self) -> RMode { + match (self.bits & (3 << 22)) >> 22 { + 0 => RMode::Nearest, + 1 => RMode::PlusInfinity, + 2 => RMode::MinusInfinity, + _ => RMode::Zero, + } + } + + /// Sets the Rounding Mode control field + #[inline] + pub fn set_rmode(&mut self, rmode: RMode) { + let mask = 3 << 22; + match rmode { + RMode::Nearest => self.bits &= !mask, + RMode::PlusInfinity => self.bits = (self.bits & !mask) | (1 << 22), + RMode::MinusInfinity => self.bits = (self.bits & !mask) | (2 << 22), + RMode::Zero => self.bits |= mask, + } + } + + /// Read the Input Denormal cumulative exception bit + #[inline] + pub fn idc(self) -> bool { + self.bits & (1 << 7) != 0 + } + + /// Sets the Input Denormal cumulative exception bit + #[inline] + pub fn set_idc(&mut self, idc: bool) { + let mask = 1 << 7; + match idc { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Inexact cumulative exception bit + #[inline] + pub fn ixc(self) -> bool { + self.bits & (1 << 4) != 0 + } + + /// Sets the Inexact cumulative exception bit + #[inline] + pub fn set_ixc(&mut self, ixc: bool) { + let mask = 1 << 4; + match ixc { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Underflow cumulative exception bit + #[inline] + pub fn ufc(self) -> bool { + self.bits & (1 << 3) != 0 + } + + /// Sets the Underflow cumulative exception bit + #[inline] + pub fn set_ufc(&mut self, ufc: bool) { + let mask = 1 << 3; + match ufc { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Overflow cumulative exception bit + #[inline] + pub fn ofc(self) -> bool { + self.bits & (1 << 2) != 0 + } + + /// Sets the Overflow cumulative exception bit + #[inline] + pub fn set_ofc(&mut self, ofc: bool) { + let mask = 1 << 2; + match ofc { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Division by Zero cumulative exception bit + #[inline] + pub fn dzc(self) -> bool { + self.bits & (1 << 1) != 0 + } + + /// Sets the Division by Zero cumulative exception bit + #[inline] + pub fn set_dzc(&mut self, dzc: bool) { + let mask = 1 << 1; + match dzc { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } + + /// Read the Invalid Operation cumulative exception bit + #[inline] + pub fn ioc(self) -> bool { + self.bits & (1 << 0) != 0 + } + + /// Sets the Invalid Operation cumulative exception bit + #[inline] + pub fn set_ioc(&mut self, ioc: bool) { + let mask = 1 << 0; + match ioc { + true => self.bits |= mask, + false => self.bits &= !mask, + } + } +} + +/// Rounding mode +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RMode { + /// Round to Nearest (RN) mode. This is the reset value. + Nearest, + /// Round towards Plus Infinity (RP) mode. + PlusInfinity, + /// Round towards Minus Infinity (RM) mode. + MinusInfinity, + /// Round towards Zero (RZ) mode. + Zero, +} + +impl RMode { + /// Is Nearest the current rounding mode? + #[inline] + pub fn is_nearest(self) -> bool { + self == RMode::Nearest + } + + /// Is Plus Infinity the current rounding mode? + #[inline] + pub fn is_plus_infinity(self) -> bool { + self == RMode::PlusInfinity + } + + /// Is Minus Infinity the current rounding mode? + #[inline] + pub fn is_minus_infinity(self) -> bool { + self == RMode::MinusInfinity + } + + /// Is Zero the current rounding mode? + #[inline] + pub fn is_zero(self) -> bool { + self == RMode::Zero + } +} + +/// Read the FPSCR register +#[inline] +pub fn read() -> Fpscr { + let r: u32 = call_asm!(__fpscr_r() -> u32); + Fpscr::from_bits(r) +} + +/// Set the value of the FPSCR register +#[inline] +pub unsafe fn write(fpscr: Fpscr) { + let fpscr = fpscr.bits(); + call_asm!(__fpscr_w(fpscr: u32)); +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/lr.rs b/bitbox02-bt/vendor/cortex-m/src/register/lr.rs new file mode 100644 index 0000000..1aa546c --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/lr.rs @@ -0,0 +1,17 @@ +//! Link register + +/// Reads the CPU register +/// +/// **NOTE** This function is available if `cortex-m` is built with the `"inline-asm"` feature. +#[inline] +pub fn read() -> u32 { + call_asm!(__lr_r() -> u32) +} + +/// Writes `bits` to the CPU register +/// +/// **NOTE** This function is available if `cortex-m` is built with the `"inline-asm"` feature. +#[inline] +pub unsafe fn write(bits: u32) { + call_asm!(__lr_w(bits: u32)); +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/mod.rs b/bitbox02-bt/vendor/cortex-m/src/register/mod.rs new file mode 100644 index 0000000..48d157a --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/mod.rs @@ -0,0 +1,68 @@ +//! Processor core registers +//! +//! The following registers can only be accessed in PRIVILEGED mode: +//! +//! - BASEPRI +//! - CONTROL +//! - FAULTMASK +//! - MSP +//! - PRIMASK +//! +//! The rest of registers (see list below) can be accessed in either, PRIVILEGED +//! or UNPRIVILEGED, mode. +//! +//! - APSR +//! - LR +//! - PC +//! - PSP +//! +//! The following registers are NOT available on ARMv6-M devices +//! (`thumbv6m-none-eabi`): +//! +//! - BASEPRI +//! - FAULTMASK +//! +//! The following registers are only available for devices with an FPU: +//! +//! - FPSCR +//! +//! # References +//! +//! - Cortex-M* Devices Generic User Guide - Section 2.1.3 Core registers + +#[cfg(all(not(armv6m), not(armv8m_base)))] +pub mod basepri; + +#[cfg(all(not(armv6m), not(armv8m_base)))] +pub mod basepri_max; + +pub mod control; + +#[cfg(all(not(armv6m), not(armv8m_base)))] +pub mod faultmask; + +#[cfg(has_fpu)] +pub mod fpscr; + +pub mod msp; + +pub mod primask; + +pub mod psp; + +#[cfg(armv8m_main)] +pub mod msplim; + +#[cfg(armv8m_main)] +pub mod psplim; + +// Accessing these registers requires inline assembly because their contents are tied to the current +// stack frame +#[cfg(feature = "inline-asm")] +pub mod apsr; + +#[cfg(feature = "inline-asm")] +pub mod lr; + +#[cfg(feature = "inline-asm")] +pub mod pc; diff --git a/bitbox02-bt/vendor/cortex-m/src/register/msp.rs b/bitbox02-bt/vendor/cortex-m/src/register/msp.rs new file mode 100644 index 0000000..bccc2ae --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/msp.rs @@ -0,0 +1,32 @@ +//! Main Stack Pointer + +/// Reads the CPU register +#[inline] +pub fn read() -> u32 { + call_asm!(__msp_r() -> u32) +} + +/// Writes `bits` to the CPU register +#[inline] +#[deprecated = "calling this function invokes Undefined Behavior, consider asm::bootstrap as an alternative"] +pub unsafe fn write(bits: u32) { + call_asm!(__msp_w(bits: u32)); +} + +/// Reads the Non-Secure CPU register from Secure state. +/// +/// Executing this function in Non-Secure state will return zeroes. +#[cfg(armv8m)] +#[inline] +pub fn read_ns() -> u32 { + call_asm!(__msp_ns_r() -> u32) +} + +/// Writes `bits` to the Non-Secure CPU register from Secure state. +/// +/// Executing this function in Non-Secure state will be ignored. +#[cfg(armv8m)] +#[inline] +pub unsafe fn write_ns(bits: u32) { + call_asm!(__msp_ns_w(bits: u32)); +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/msplim.rs b/bitbox02-bt/vendor/cortex-m/src/register/msplim.rs new file mode 100644 index 0000000..ac6f9ed --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/msplim.rs @@ -0,0 +1,13 @@ +//! Main Stack Pointer Limit Register + +/// Reads the CPU register +#[inline] +pub fn read() -> u32 { + call_asm!(__msplim_r() -> u32) +} + +/// Writes `bits` to the CPU register +#[inline] +pub unsafe fn write(bits: u32) { + call_asm!(__msplim_w(bits: u32)) +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/pc.rs b/bitbox02-bt/vendor/cortex-m/src/register/pc.rs new file mode 100644 index 0000000..0b33629 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/pc.rs @@ -0,0 +1,17 @@ +//! Program counter + +/// Reads the CPU register +/// +/// **NOTE** This function is available if `cortex-m` is built with the `"inline-asm"` feature. +#[inline] +pub fn read() -> u32 { + call_asm!(__pc_r() -> u32) +} + +/// Writes `bits` to the CPU register +/// +/// **NOTE** This function is available if `cortex-m` is built with the `"inline-asm"` feature. +#[inline] +pub unsafe fn write(bits: u32) { + call_asm!(__pc_w(bits: u32)); +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/primask.rs b/bitbox02-bt/vendor/cortex-m/src/register/primask.rs new file mode 100644 index 0000000..842ca49 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/primask.rs @@ -0,0 +1,35 @@ +//! Priority mask register + +/// All exceptions with configurable priority are ... +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Primask { + /// Active + Active, + /// Inactive + Inactive, +} + +impl Primask { + /// All exceptions with configurable priority are active + #[inline] + pub fn is_active(self) -> bool { + self == Primask::Active + } + + /// All exceptions with configurable priority are inactive + #[inline] + pub fn is_inactive(self) -> bool { + self == Primask::Inactive + } +} + +/// Reads the CPU register +#[inline] +pub fn read() -> Primask { + let r: u32 = call_asm!(__primask_r() -> u32); + if r & (1 << 0) == (1 << 0) { + Primask::Inactive + } else { + Primask::Active + } +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/psp.rs b/bitbox02-bt/vendor/cortex-m/src/register/psp.rs new file mode 100644 index 0000000..0bca22c --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/psp.rs @@ -0,0 +1,13 @@ +//! Process Stack Pointer + +/// Reads the CPU register +#[inline] +pub fn read() -> u32 { + call_asm!(__psp_r() -> u32) +} + +/// Writes `bits` to the CPU register +#[inline] +pub unsafe fn write(bits: u32) { + call_asm!(__psp_w(bits: u32)) +} diff --git a/bitbox02-bt/vendor/cortex-m/src/register/psplim.rs b/bitbox02-bt/vendor/cortex-m/src/register/psplim.rs new file mode 100644 index 0000000..8ee1e94 --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/src/register/psplim.rs @@ -0,0 +1,13 @@ +//! Process Stack Pointer Limit Register + +/// Reads the CPU register +#[inline] +pub fn read() -> u32 { + call_asm!(__psplim_r() -> u32) +} + +/// Writes `bits` to the CPU register +#[inline] +pub unsafe fn write(bits: u32) { + call_asm!(__psplim_w(bits: u32)) +} diff --git a/bitbox02-bt/vendor/cortex-m/triagebot.toml b/bitbox02-bt/vendor/cortex-m/triagebot.toml new file mode 100644 index 0000000..fa0824a --- /dev/null +++ b/bitbox02-bt/vendor/cortex-m/triagebot.toml @@ -0,0 +1 @@ +[assign] diff --git a/bitbox02-bt/vendor/critical-section/.cargo-checksum.json b/bitbox02-bt/vendor/critical-section/.cargo-checksum.json new file mode 100644 index 0000000..d8c4a23 --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"3a56e288de253e6594c03a8ced0b1a0c78dc3616f8c53b751dea87184c0bad98","CODE_OF_CONDUCT.md":"8e25e95078b1a582086587adf8e1d907d43aacee6a072b8630d54a6289e5e0b9","Cargo.toml":"1dadae991b9ae6b61d2ab5c5ee8587d2f1469664f3dfaea9fdc5fba3a8416fe6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"fee6bdac4b917351332567b9fd5013c2ef3c847dd113fd6216cf28e96637a157","README.md":"5e6c551ffe891fd5b9a3b6196d8961bbd5e92b1c764999d7e426a83fd23ac623","docs/msrv.md":"690a70e9ed6764198e4a5c0933a4124fc382091754d8bafb82241483ae2d89b9","src/lib.rs":"9e3ffb87bcd725fc95e54484d2f2fd319fa8f47c2a6c508139aa209f129372f8","src/mutex.rs":"4c239da3d73a13689e5c09d248ea2cb5d2c5bff4c87ba73bd405a12c02e85b66","src/std.rs":"4f04dde8d9528d7b6676fc2ea929f9f095e34c613efee23ad1c9d63329eff8ca"},"package":"f64009896348fc5af4222e9cf7d7d82a95a256c634ebcf61c53e4ea461422242"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/critical-section/CHANGELOG.md b/bitbox02-bt/vendor/critical-section/CHANGELOG.md new file mode 100644 index 0000000..38628d7 --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/CHANGELOG.md @@ -0,0 +1,142 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +No unreleased changes yet + +## [v1.1.3] - 2024-08-22 + +- Added option to use a `usize` sized restore state + +## [v1.1.2] - 2023-08-09 + +- Clarified that `acquire()` must provide ordering guarantees +- Updated atomic-polyfill reference to point to portable-atomic instead +- Improved documentation for `Mutex` example +- Added list of some known implementations + +## [v1.1.1] - 2022-09-13 + +- On the `std` implementation, panicking inside the `critical_section::with()` closure no longer accidentally leaves the critical section locked (#26). + +## [v1.1.0] - 2022-08-17 + +- Added built-in critical section implementation using `std::sync::Mutex`, enabled by the `std` Cargo feature. +- MSRV changed to `1.54` when `std` feature is disabled, `1.63` when enabled. + +## [v1.0.0] - 2022-08-10 + +- Improved docs. + +## [v1.0.0-alpha.2] - 2022-07-28 + +- Change name of the `extern fn`s to avoid clash with critical-section 0.2. + +## [v1.0.0-alpha.1] - 2022-07-28 + +Breaking changes: + +- Removed all builtin impls. These are going to be provided by platform-support crates now. +- Renamed `custom_impl!` to `set_impl!`. +- RestoreState is now an opaque struct for the user, and a transparent `RawRestoreState` type alias for impl writers. +- RestoreState type is now configurable with Cargo features. Default is `()`. (previously it was fixed to `u8`.) +- Added own `CriticalSection` and `Mutex` types, instead of reexporting them from `bare_metal`. + +## [v0.2.8] - 2022-11-29 + +- Implemented critical-section by forwarding to version 1.1.1 + +Breaking changes: + +- `acquire` and `release` are only implemented if the restore-state used by + version 1.1.1 is an u8 or smaller. +- No default critical-section implementation is provided. + +Those breaking changes are necessary because versions <= 0.2.7 were unsound, and that +was impossible to fix without a breaking change. + +This version is meant to minimize that breaking change. However, all +users are encouraged to upgrade to critical-section 1.1. + +If you're seeing a linker error like `undefined symbol: _critical_section_1_0_acquire`, you're affected. To fix it: + +- If your target supports `std`: Add the `critical-section` dependency to `Cargo.toml` enabling the `std` feature. + + ```toml + [dependencies] + critical-section = { version = "1.1", features = ["std"]} + ``` + +- For single-core Cortex-M targets in privileged mode: + ```toml + [dependencies] + cortex-m = { version = "0.7.6", features = ["critical-section-single-core"]} + ``` + +- For single-hart RISC-V targets in privileged mode: + ```toml + [dependencies] + riscv = { version = "0.10", features = ["critical-section-single-hart"]} + ``` + +- For other targets: check if your HAL or architecture-support crate has a `critical-section 1.0` implementation available. Otherwise, [provide your own](https://github.com/rust-embedded/critical-section#providing-an-implementation). + + +## [v0.2.7] - 2022-04-08 + +- Add support for AVR targets. + +## [v0.2.6] - 2022-04-02 + +- Improved docs. + +## [v0.2.5] - 2021-11-02 + +- Fix `std` implementation to allow reentrant (nested) critical sections. This would previously deadlock. + +## [v0.2.4] - 2021-09-24 + +- Add support for 32bit RISC-V targets. + +## [v0.2.3] - 2021-09-13 + +- Use correct `#[vcfg]` for `wasm` targets. + +## [v0.2.2] - 2021-09-13 + +- Added support for `wasm` targets. + +## [v0.2.1] - 2021-05-11 + +- Added critical section implementation for `std`, based on a global Mutex. + +## [v0.2.0] - 2021-05-10 + +- Breaking change: use `CriticalSection<'_>` instead of `&CriticalSection<'_>` + +## v0.1.0 - 2021-05-10 + +- First release + +[Unreleased]: https://github.com/rust-embedded/critical-section/compare/v1.1.3...HEAD +[v1.1.2]: https://github.com/rust-embedded/critical-section/compare/v1.1.2...v1.1.3 +[v1.1.2]: https://github.com/rust-embedded/critical-section/compare/v1.1.1...v1.1.2 +[v1.1.1]: https://github.com/rust-embedded/critical-section/compare/v1.1.0...v1.1.1 +[v1.1.0]: https://github.com/rust-embedded/critical-section/compare/v1.0.0...v1.1.0 +[v1.0.0]: https://github.com/rust-embedded/critical-section/compare/v1.0.0-alpha.2...v1.0.0 +[v1.0.0-alpha.2]: https://github.com/rust-embedded/critical-section/compare/v1.0.0-alpha.1...v1.0.0-alpha.2 +[v1.0.0-alpha.1]: https://github.com/rust-embedded/critical-section/compare/v0.2.7...v1.0.0-alpha.1 +[v0.2.8]: https://github.com/rust-embedded/critical-section/compare/v0.2.7...v0.2.8 +[v0.2.7]: https://github.com/rust-embedded/critical-section/compare/v0.2.6...v0.2.7 +[v0.2.6]: https://github.com/rust-embedded/critical-section/compare/v0.2.5...v0.2.6 +[v0.2.5]: https://github.com/rust-embedded/critical-section/compare/v0.2.4...v0.2.5 +[v0.2.4]: https://github.com/rust-embedded/critical-section/compare/v0.2.3...v0.2.4 +[v0.2.3]: https://github.com/rust-embedded/critical-section/compare/v0.2.2...v0.2.3 +[v0.2.2]: https://github.com/rust-embedded/critical-section/compare/v0.2.1...v0.2.2 +[v0.2.1]: https://github.com/rust-embedded/critical-section/compare/v0.2.0...v0.2.1 +[v0.2.0]: https://github.com/rust-embedded/critical-section/compare/v0.1.0...v0.2.0 diff --git a/bitbox02-bt/vendor/critical-section/CODE_OF_CONDUCT.md b/bitbox02-bt/vendor/critical-section/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..bcefc6a --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/CODE_OF_CONDUCT.md @@ -0,0 +1,37 @@ +# The Rust Code of Conduct + +## Conduct + +**Contact**: [HAL team][team] + +* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. +* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. +* Please be kind and courteous. There's no need to be mean or rude. +* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. +* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. +* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. +* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [HAL team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. +* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. + +## Moderation + +These are the policies for upholding our community's standards of conduct. + +1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) +2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. +3. Moderators will first respond to such remarks with a warning. +4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off. +5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded. +6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology. +7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed. +8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others. + +In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. + +And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. + +The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org). + +*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* + +[team]: https://github.com/rust-embedded/wg#the-hal-team diff --git a/bitbox02-bt/vendor/critical-section/Cargo.toml b/bitbox02-bt/vendor/critical-section/Cargo.toml new file mode 100644 index 0000000..21e586e --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/Cargo.toml @@ -0,0 +1,43 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "critical-section" +version = "1.1.3" +build = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Cross-platform critical section" +readme = "README.md" +categories = [ + "embedded", + "no-std", + "concurrency", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-embedded/critical-section" + +[lib] +name = "critical_section" +path = "src/lib.rs" + +[features] +restore-state-bool = [] +restore-state-none = [] +restore-state-u16 = [] +restore-state-u32 = [] +restore-state-u64 = [] +restore-state-u8 = [] +restore-state-usize = [] +std = ["restore-state-bool"] diff --git a/bitbox02-bt/vendor/critical-section/LICENSE-APACHE b/bitbox02-bt/vendor/critical-section/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/critical-section/LICENSE-MIT b/bitbox02-bt/vendor/critical-section/LICENSE-MIT new file mode 100644 index 0000000..78bced9 --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2022 The critical-section authors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/critical-section/README.md b/bitbox02-bt/vendor/critical-section/README.md new file mode 100644 index 0000000..32f1678 --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/README.md @@ -0,0 +1,250 @@ +# critical-section +[![crates.io](https://img.shields.io/crates/d/critical-section.svg)](https://crates.io/crates/critical-section) +[![crates.io](https://img.shields.io/crates/v/critical-section.svg)](https://crates.io/crates/critical-section) +[![Documentation](https://docs.rs/critical-section/badge.svg)](https://docs.rs/critical-section) + +This project is developed and maintained by the [HAL team][team]. + +A critical section that works everywhere! + +When writing software for embedded systems, it's common to use a "critical section" +as a basic primitive to control concurrency. A critical section is essentially a +mutex global to the whole process, that can be acquired by only one thread at a time. +This can be used to protect data behind mutexes, to [emulate atomics](https://crates.io/crates/portable-atomic) in +targets that don't support them, etc. + +There's a wide range of possible implementations depending on the execution environment: +- For bare-metal single core, disabling interrupts in the current (only) core. +- For bare-metal multicore, disabling interrupts in the current core and acquiring a hardware spinlock to prevent other cores from entering a critical section concurrently. +- For bare-metal using a RTOS, using library functions for acquiring a critical section, often named "scheduler lock" or "kernel lock". +- For bare-metal running in non-privileged mode, calling some system call is usually needed. +- For `std` targets, acquiring a global `std::sync::Mutex`. + +Libraries often need to use critical sections, but there's no universal API for this in `core`. This leads +library authors to hard-code them for their target, or at best add some `cfg`s to support a few targets. +This doesn't scale since there are many targets out there, and in the general case it's impossible to know +which critical section implementation is needed from the Rust target alone. For example, the `thumbv7em-none-eabi` target +could be cases 1-4 from the above list. + +This crate solves the problem by providing this missing universal API. + +- It provides functions `acquire`, `release` and `with` that libraries can directly use. +- It provides a way for any crate to supply an implementation. This allows "target support" crates such as architecture crates (`cortex-m`, `riscv`), RTOS bindings, or HALs for multicore chips to supply the correct implementation so that all the crates in the dependency tree automatically use it. + +## Usage in `no-std` binaries. + +First, add a dependency on a crate providing a critical section implementation. Enable the `critical-section-*` Cargo feature if required by the crate. + +Implementations are typically provided by either architecture-support crates, HAL crates, and OS/RTOS bindings, including: + +* The [`cortex-m`] crate provides an implementation for all single-core Cortex-M microcontrollers via its `critical-section-single-core` feature +* The [`riscv`] crate provides an implementation for all single-hart RISC-V microcontrollers via its `critical-section-single-hart` feature +* The [`msp430`] crate provides an implementation for all MSP430 microcontrollers via its `critical-section-single-core` feature +* The [`rp2040-hal`] crate provides a multi-core-safe critical section for the RP2040 microcontroller via its `critical-section-impl` feature +* The [`avr-device`] crate provides an implementation for all AVR microcontrollers via its `critical-section-impl` feature +* The [`esp-hal-common`] crate provides an implementation for ESP32 microcontrollers which is used by the ESP HALs +* The [`embassy-rp`] crate provides a multi-core-safe critical section for the RP2040 microcontroller via its `critical-section-impl` feature +* The [`nrf-softdevice`] crate provides a critical section that's compatible with the nRF soft-device firmware via its `critical-section-impl` feature + +[`cortex-m`]: https://crates.io/crates/cortex-m +[`riscv`]: https://crates.io/crates/riscv +[`msp430`]: https://crates.io/crates/msp430 +[`rp2040-hal`]: https://crates.io/crates/rp2040-hal +[`avr-device`]: https://crates.io/crates/avr-device +[`esp-hal-common`]: https://crates.io/crates/esp-hal-common +[`embassy-rp`]: https://docs.embassy.dev/embassy-rp +[`nrf-softdevice`]: https://docs.embassy.dev/nrf-softdevice + +For example, for single-core Cortex-M targets, you can use: + +```toml +[dependencies] +cortex-m = { version = "0.7.6", features = ["critical-section-single-core"]} +``` + +Then you can use `critical_section::with()`. + +```rust +use core::cell::Cell; +use critical_section::Mutex; + +static MY_VALUE: Mutex> = Mutex::new(Cell::new(0)); + +critical_section::with(|cs| { + // This code runs within a critical section. + + // `cs` is a token that you can use to "prove" that to some API, + // for example to a `Mutex`: + MY_VALUE.borrow(cs).set(42); +}); + +# #[cfg(not(feature = "std"))] // needed for `cargo test --features std` +# mod no_std { +# struct MyCriticalSection; +# critical_section::set_impl!(MyCriticalSection); +# unsafe impl critical_section::Impl for MyCriticalSection { +# unsafe fn acquire() -> () {} +# unsafe fn release(token: ()) {} +# } +# } +``` + +## Usage in `std` binaries. + +Add the `critical-section` dependency to `Cargo.toml` enabling the `std` feature. This makes the `critical-section` crate itself +provide an implementation based on `std::sync::Mutex`, so you don't have to add any other dependency. + +```toml +[dependencies] +critical-section = { version = "1.1", features = ["std"]} +``` + +## Usage in libraries + +If you're writing a library intended to be portable across many targets, simply add a dependency on `critical-section` +and use `critical_section::free` and/or `Mutex` as usual. + +**Do not** add any dependency supplying a critical section implementation. Do not enable any `critical-section-*` Cargo feature. +This has to be done by the end user, enabling the correct implementation for their target. + +**Do not** enable any Cargo feature in `critical-section`. + +## Usage in `std` tests for `no-std` libraries. + +If you want to run `std`-using tests in otherwise `no-std` libraries, enable the `std` feature in `dev-dependencies` only. +This way the main target will use the `no-std` implementation chosen by the end-user's binary, and only the test targets +will use the `std` implementation. + +```toml +[dependencies] +critical-section = "1.1" + +[dev-dependencies] +critical-section = { version = "1.1", features = ["std"]} +``` + +## Providing an implementation + +Crates adding support for a particular architecture, chip or operating system should provide a critical section implementation. +It is **strongly recommended** to gate the implementation behind a feature, so the user can still use another implementation +if needed (having two implementations in the same binary will cause linking to fail). + +Add the dependency, and a `critical-section-*` feature to your `Cargo.toml`: + +```toml +[features] +# Enable critical section implementation that does "foo" +critical-section-foo = ["critical-section/restore-state-bool"] + +[dependencies] +critical-section = { version = "1.0", optional = true } +``` + +Then, provide the critical implementation like this: + +```rust +# #[cfg(not(feature = "std"))] // needed for `cargo test --features std` +# mod no_std { +// This is a type alias for the enabled `restore-state-*` feature. +// For example, it is `bool` if you enable `restore-state-bool`. +use critical_section::RawRestoreState; + +struct MyCriticalSection; +critical_section::set_impl!(MyCriticalSection); + +unsafe impl critical_section::Impl for MyCriticalSection { + unsafe fn acquire() -> RawRestoreState { + // TODO + } + + unsafe fn release(token: RawRestoreState) { + // TODO + } +} +# } +``` + +## Troubleshooting + +### Undefined reference errors + +If you get an error like these: + +```not_rust +undefined reference to `_critical_section_1_0_acquire' +undefined reference to `_critical_section_1_0_release' +``` + +it is because you (or a library) are using `critical_section::with` without providing a critical section implementation. +Make sure you're depending on a crate providing the implementation, and have enabled the `critical-section-*` feature in it if required. See the `Usage` section above. + +The error can also be caused by having the dependency but never `use`ing it. This can be fixed by adding a dummy `use`: + +```rust,ignore +use the_cs_impl_crate as _; +``` + +### Duplicate symbol errors + +If you get errors like these: + +```not_rust +error: symbol `_critical_section_1_0_acquire` is already defined +``` + +it is because you have two crates trying to provide a critical section implementation. You can only +have one implementation in a program. + +You can use `cargo tree --format '{p} {f}'` to view all dependencies and their enabled features. Make sure +that in the whole dependency tree, exactly one implementation is provided. + +Check for multiple versions of the same crate as well. For example, check the `critical-section-single-core` +feature is not enabled for both `cortex-m` 0.7 and 0.8. + +## Why not generics? + +An alternative solution would be to use a `CriticalSection` trait, and make all +code that needs acquiring the critical section generic over it. This has a few problems: + +- It would require passing it as a generic param to a very big amount of code, which +would be quite unergonomic. +- It's common to put `Mutex`es in `static` variables, and `static`s can't +be generic. +- It would allow mixing different critical section implementations in the same program, +which would be unsound. + +## Minimum Supported Rust Version (MSRV) + +This crate is guaranteed to compile on the following Rust versions: + +- If the `std` feature is not enabled: stable Rust 1.54 and up. +- If the `std` feature is enabled: stable Rust 1.63 and up. + +It might compile with older versions but that may change in any new patch release. + +See [here](docs/msrv.md) for details on how the MSRV may be upgraded. + +## License + +This work is licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. + +## Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +## Code of Conduct + +Contribution to this crate is organized under the terms of the [Rust Code of +Conduct][CoC], the maintainer of this crate, the [HAL team][team], promises +to intervene to uphold that code of conduct. + +[CoC]: CODE_OF_CONDUCT.md +[team]: https://github.com/rust-embedded/wg#the-hal-team diff --git a/bitbox02-bt/vendor/critical-section/docs/msrv.md b/bitbox02-bt/vendor/critical-section/docs/msrv.md new file mode 100644 index 0000000..ec0056a --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/docs/msrv.md @@ -0,0 +1,30 @@ +# Minimum Supported Rust Version (MSRV) + +This crate is guaranteed to compile on all stable Rust versions going back to +the version stated as MSRV in the README. It *might* compile with even older versions but +that may change in any new patch release. + +## How the MSRV will be upgraded + +For `critical-section`, we do not consider upgrading the MSRV a strictly breaking change as defined by +[SemVer](https://semver.org). + +We follow these rules when upgrading it: + +- We will not update the MSRV on any patch release: \_.\_.*Z*. +- We may upgrade the MSRV on any *major* or *minor* release: *X*.*Y*.\_. +- We may upgrade the MSRV in any preliminary version release (e.g. an `-alpha` release) as + these serve as preparation for the final release. +- MSRV upgrades will be clearly stated in the changelog. + +This applies both to `0._._` releases as well as `>=1._._` releases. + +For example: + +For a given `x.y.z` release, we may upgrade the MSRV on `x` and `y` releases but not on `z` releases. + +If your MSRV upgrade policy differs from this, you are advised to specify the +`critical-section` dependency in your `Cargo.toml` accordingly. + +See the [Rust Embedded Working Group MSRV RFC](https://github.com/rust-embedded/wg/blob/master/rfcs/0523-msrv-2020.md) +for more background information and reasoning. diff --git a/bitbox02-bt/vendor/critical-section/src/lib.rs b/bitbox02-bt/vendor/critical-section/src/lib.rs new file mode 100644 index 0000000..94d9ae7 --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/src/lib.rs @@ -0,0 +1,299 @@ +#![cfg_attr(not(feature = "std"), no_std)] +#![doc = include_str!("../README.md")] + +mod mutex; +#[cfg(feature = "std")] +mod std; + +use core::marker::PhantomData; + +pub use self::mutex::Mutex; + +/// Critical section token. +/// +/// An instance of this type indicates that the current thread is executing code within a critical +/// section. +#[derive(Clone, Copy, Debug)] +pub struct CriticalSection<'cs> { + _private: PhantomData<&'cs ()>, +} + +impl<'cs> CriticalSection<'cs> { + /// Creates a critical section token. + /// + /// This method is meant to be used to create safe abstractions rather than being directly used + /// in applications. + /// + /// # Safety + /// + /// This must only be called when the current thread is in a critical section. The caller must + /// ensure that the returned instance will not live beyond the end of the critical section. + /// + /// The caller must use adequate fences to prevent the compiler from moving the + /// instructions inside the critical section to the outside of it. Sequentially consistent fences are + /// suggested immediately after entry and immediately before exit from the critical section. + /// + /// Note that the lifetime `'cs` of the returned instance is unconstrained. User code must not + /// be able to influence the lifetime picked for this type, since that might cause it to be + /// inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + CriticalSection { + _private: PhantomData, + } + } +} + +#[cfg(any( + all(feature = "restore-state-none", feature = "restore-state-bool"), + all(feature = "restore-state-none", feature = "restore-state-u8"), + all(feature = "restore-state-none", feature = "restore-state-u16"), + all(feature = "restore-state-none", feature = "restore-state-u32"), + all(feature = "restore-state-none", feature = "restore-state-u64"), + all(feature = "restore-state-bool", feature = "restore-state-u8"), + all(feature = "restore-state-bool", feature = "restore-state-u16"), + all(feature = "restore-state-bool", feature = "restore-state-u32"), + all(feature = "restore-state-bool", feature = "restore-state-u64"), + all(feature = "restore-state-bool", feature = "restore-state-usize"), + all(feature = "restore-state-u8", feature = "restore-state-u16"), + all(feature = "restore-state-u8", feature = "restore-state-u32"), + all(feature = "restore-state-u8", feature = "restore-state-u64"), + all(feature = "restore-state-u8", feature = "restore-state-usize"), + all(feature = "restore-state-u16", feature = "restore-state-u32"), + all(feature = "restore-state-u16", feature = "restore-state-u64"), + all(feature = "restore-state-u16", feature = "restore-state-usize"), + all(feature = "restore-state-u32", feature = "restore-state-u64"), + all(feature = "restore-state-u32", feature = "restore-state-usize"), + all(feature = "restore-state-u64", feature = "restore-state-usize"), +))] +compile_error!("You must set at most one of these Cargo features: restore-state-none, restore-state-bool, restore-state-u8, restore-state-u16, restore-state-u32, restore-state-u64, restore-state-usize"); + +#[cfg(not(any( + feature = "restore-state-bool", + feature = "restore-state-u8", + feature = "restore-state-u16", + feature = "restore-state-u32", + feature = "restore-state-u64", + feature = "restore-state-usize" +)))] +type RawRestoreStateInner = (); + +#[cfg(feature = "restore-state-bool")] +type RawRestoreStateInner = bool; + +#[cfg(feature = "restore-state-u8")] +type RawRestoreStateInner = u8; + +#[cfg(feature = "restore-state-u16")] +type RawRestoreStateInner = u16; + +#[cfg(feature = "restore-state-u32")] +type RawRestoreStateInner = u32; + +#[cfg(feature = "restore-state-u64")] +type RawRestoreStateInner = u64; + +#[cfg(feature = "restore-state-usize")] +type RawRestoreStateInner = usize; + +// We have RawRestoreStateInner and RawRestoreState so that we don't have to copypaste the docs 5 times. +// In the docs this shows as `pub type RawRestoreState = u8` or whatever the selected type is, because +// the "inner" type alias is private. + +/// Raw, transparent "restore state". +/// +/// This type changes based on which Cargo feature is selected, out of +/// - `restore-state-none` (default, makes the type be `()`) +/// - `restore-state-bool` +/// - `restore-state-u8` +/// - `restore-state-u16` +/// - `restore-state-u32` +/// - `restore-state-u64` +/// - `restore-state-usize` +/// +/// See [`RestoreState`]. +/// +/// User code uses [`RestoreState`] opaquely, critical section implementations +/// use [`RawRestoreState`] so that they can use the inner value. +pub type RawRestoreState = RawRestoreStateInner; + +/// Opaque "restore state". +/// +/// Implementations use this to "carry over" information between acquiring and releasing +/// a critical section. For example, when nesting two critical sections of an +/// implementation that disables interrupts globally, acquiring the inner one won't disable +/// the interrupts since they're already disabled. The impl would use the restore state to "tell" +/// the corresponding release that it does *not* have to reenable interrupts yet, only the +/// outer release should do so. +/// +/// User code uses [`RestoreState`] opaquely, critical section implementations +/// use [`RawRestoreState`] so that they can use the inner value. +#[derive(Clone, Copy, Debug)] +pub struct RestoreState(RawRestoreState); + +impl RestoreState { + /// Create an invalid, dummy `RestoreState`. + /// + /// This can be useful to avoid `Option` when storing a `RestoreState` in a + /// struct field, or a `static`. + /// + /// Note that due to the safety contract of [`acquire`]/[`release`], you must not pass + /// a `RestoreState` obtained from this method to [`release`]. + pub const fn invalid() -> Self { + #[cfg(not(any( + feature = "restore-state-bool", + feature = "restore-state-u8", + feature = "restore-state-u16", + feature = "restore-state-u32", + feature = "restore-state-u64" + )))] + return Self(()); + + #[cfg(feature = "restore-state-bool")] + return Self(false); + + #[cfg(feature = "restore-state-u8")] + return Self(0); + + #[cfg(feature = "restore-state-u16")] + return Self(0); + + #[cfg(feature = "restore-state-u32")] + return Self(0); + + #[cfg(feature = "restore-state-u64")] + return Self(0); + } +} + +/// Acquire a critical section in the current thread. +/// +/// This function is extremely low level. Strongly prefer using [`with`] instead. +/// +/// Nesting critical sections is allowed. The inner critical sections +/// are mostly no-ops since they're already protected by the outer one. +/// +/// # Safety +/// +/// - Each `acquire` call must be paired with exactly one `release` call in the same thread. +/// - `acquire` returns a "restore state" that you must pass to the corresponding `release` call. +/// - `acquire`/`release` pairs must be "properly nested", ie it's not OK to do `a=acquire(); b=acquire(); release(a); release(b);`. +/// - It is UB to call `release` if the critical section is not acquired in the current thread. +/// - It is UB to call `release` with a "restore state" that does not come from the corresponding `acquire` call. +/// - It must provide ordering guarantees at least equivalent to a [`core::sync::atomic::Ordering::Acquire`] +/// on a memory location shared by all critical sections, on which the `release` call will do a +/// [`core::sync::atomic::Ordering::Release`] operation. +#[inline(always)] +pub unsafe fn acquire() -> RestoreState { + extern "Rust" { + fn _critical_section_1_0_acquire() -> RawRestoreState; + } + + #[allow(clippy::unit_arg)] + RestoreState(_critical_section_1_0_acquire()) +} + +/// Release the critical section. +/// +/// This function is extremely low level. Strongly prefer using [`with`] instead. +/// +/// # Safety +/// +/// See [`acquire`] for the safety contract description. +#[inline(always)] +pub unsafe fn release(restore_state: RestoreState) { + extern "Rust" { + fn _critical_section_1_0_release(restore_state: RawRestoreState); + } + + #[allow(clippy::unit_arg)] + _critical_section_1_0_release(restore_state.0) +} + +/// Execute closure `f` in a critical section. +/// +/// Nesting critical sections is allowed. The inner critical sections +/// are mostly no-ops since they're already protected by the outer one. +/// +/// # Panics +/// +/// This function panics if the given closure `f` panics. In this case +/// the critical section is released before unwinding. +#[inline] +pub fn with(f: impl FnOnce(CriticalSection) -> R) -> R { + // Helper for making sure `release` is called even if `f` panics. + struct Guard { + state: RestoreState, + } + + impl Drop for Guard { + #[inline(always)] + fn drop(&mut self) { + unsafe { release(self.state) } + } + } + + let state = unsafe { acquire() }; + let _guard = Guard { state }; + + unsafe { f(CriticalSection::new()) } +} + +/// Methods required for a critical section implementation. +/// +/// This trait is not intended to be used except when implementing a critical section. +/// +/// # Safety +/// +/// Implementations must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. +pub unsafe trait Impl { + /// Acquire the critical section. + /// + /// # Safety + /// + /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. + unsafe fn acquire() -> RawRestoreState; + + /// Release the critical section. + /// + /// # Safety + /// + /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. + unsafe fn release(restore_state: RawRestoreState); +} + +/// Set the critical section implementation. +/// +/// # Example +/// +/// ``` +/// # #[cfg(not(feature = "std"))] // needed for `cargo test --features std` +/// # mod no_std { +/// use critical_section::RawRestoreState; +/// +/// struct MyCriticalSection; +/// critical_section::set_impl!(MyCriticalSection); +/// +/// unsafe impl critical_section::Impl for MyCriticalSection { +/// unsafe fn acquire() -> RawRestoreState { +/// // ... +/// } +/// +/// unsafe fn release(restore_state: RawRestoreState) { +/// // ... +/// } +/// } +/// # } +#[macro_export] +macro_rules! set_impl { + ($t: ty) => { + #[no_mangle] + unsafe fn _critical_section_1_0_acquire() -> $crate::RawRestoreState { + <$t as $crate::Impl>::acquire() + } + #[no_mangle] + unsafe fn _critical_section_1_0_release(restore_state: $crate::RawRestoreState) { + <$t as $crate::Impl>::release(restore_state) + } + }; +} diff --git a/bitbox02-bt/vendor/critical-section/src/mutex.rs b/bitbox02-bt/vendor/critical-section/src/mutex.rs new file mode 100644 index 0000000..c9ea6ff --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/src/mutex.rs @@ -0,0 +1,200 @@ +use super::CriticalSection; +use core::cell::{Ref, RefCell, RefMut, UnsafeCell}; + +/// A mutex based on critical sections. +/// +/// # Example +/// +/// ```no_run +/// # use critical_section::Mutex; +/// # use std::cell::Cell; +/// +/// static FOO: Mutex> = Mutex::new(Cell::new(42)); +/// +/// fn main() { +/// critical_section::with(|cs| { +/// FOO.borrow(cs).set(43); +/// }); +/// } +/// +/// fn interrupt_handler() { +/// let _x = critical_section::with(|cs| FOO.borrow(cs).get()); +/// } +/// ``` +/// +/// +/// # Design +/// +/// [`std::sync::Mutex`] has two purposes. It converts types that are [`Send`] +/// but not [`Sync`] into types that are both; and it provides +/// [interior mutability]. `critical_section::Mutex`, on the other hand, only adds +/// `Sync`. It does *not* provide interior mutability. +/// +/// This was a conscious design choice. It is possible to create multiple +/// [`CriticalSection`] tokens, either by nesting critical sections or `Copy`ing +/// an existing token. As a result, it would not be sound for [`Mutex::borrow`] +/// to return `&mut T`, because there would be nothing to prevent calling +/// `borrow` multiple times to create aliased `&mut T` references. +/// +/// The solution is to include a runtime check to ensure that each resource is +/// borrowed only once. This is what `std::sync::Mutex` does. However, this is +/// a runtime cost that may not be required in all circumstances. For instance, +/// `Mutex>` never needs to create `&mut T` or equivalent. +/// +/// If `&mut T` is needed, the simplest solution is to use `Mutex>`, +/// which is the closest analogy to `std::sync::Mutex`. [`RefCell`] inserts the +/// exact runtime check necessary to guarantee that the `&mut T` reference is +/// unique. +/// +/// To reduce verbosity when using `Mutex>`, we reimplement some of +/// `RefCell`'s methods on it directly. +/// +/// ```no_run +/// # use critical_section::Mutex; +/// # use std::cell::RefCell; +/// +/// static FOO: Mutex> = Mutex::new(RefCell::new(42)); +/// +/// fn main() { +/// critical_section::with(|cs| { +/// // Instead of calling this +/// let _ = FOO.borrow(cs).take(); +/// // Call this +/// let _ = FOO.take(cs); +/// // `RefCell::borrow` and `RefCell::borrow_mut` are renamed to +/// // `borrow_ref` and `borrow_ref_mut` to avoid name collisions +/// let _: &mut i32 = &mut *FOO.borrow_ref_mut(cs); +/// }) +/// } +/// ``` +/// +/// [`std::sync::Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html +/// [interior mutability]: https://doc.rust-lang.org/reference/interior-mutability.html +#[derive(Debug)] +pub struct Mutex { + inner: UnsafeCell, +} + +impl Mutex { + /// Creates a new mutex. + #[inline] + pub const fn new(value: T) -> Self { + Mutex { + inner: UnsafeCell::new(value), + } + } + + /// Gets a mutable reference to the contained value when the mutex is already uniquely borrowed. + /// + /// This does not require locking or a critical section since it takes `&mut self`, which + /// guarantees unique ownership already. Care must be taken when using this method to + /// **unsafely** access `static mut` variables, appropriate fences must be used to prevent + /// unwanted optimizations. + #[inline] + pub fn get_mut(&mut self) -> &mut T { + unsafe { &mut *self.inner.get() } + } + + /// Unwraps the contained value, consuming the mutex. + #[inline] + pub fn into_inner(self) -> T { + self.inner.into_inner() + } + + /// Borrows the data for the duration of the critical section. + #[inline] + pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T { + unsafe { &*self.inner.get() } + } +} + +impl Mutex> { + /// Borrow the data and call [`RefCell::replace`] + /// + /// This is equivalent to `self.borrow(cs).replace(t)` + /// + /// # Panics + /// + /// This call could panic. See the documentation for [`RefCell::replace`] + /// for more details. + #[inline] + #[track_caller] + pub fn replace<'cs>(&'cs self, cs: CriticalSection<'cs>, t: T) -> T { + self.borrow(cs).replace(t) + } + + /// Borrow the data and call [`RefCell::replace_with`] + /// + /// This is equivalent to `self.borrow(cs).replace_with(f)` + /// + /// # Panics + /// + /// This call could panic. See the documentation for + /// [`RefCell::replace_with`] for more details. + #[inline] + #[track_caller] + pub fn replace_with<'cs, F>(&'cs self, cs: CriticalSection<'cs>, f: F) -> T + where + F: FnOnce(&mut T) -> T, + { + self.borrow(cs).replace_with(f) + } + + /// Borrow the data and call [`RefCell::borrow`] + /// + /// This is equivalent to `self.borrow(cs).borrow()` + /// + /// # Panics + /// + /// This call could panic. See the documentation for [`RefCell::borrow`] + /// for more details. + #[inline] + #[track_caller] + pub fn borrow_ref<'cs>(&'cs self, cs: CriticalSection<'cs>) -> Ref<'cs, T> { + self.borrow(cs).borrow() + } + + /// Borrow the data and call [`RefCell::borrow_mut`] + /// + /// This is equivalent to `self.borrow(cs).borrow_mut()` + /// + /// # Panics + /// + /// This call could panic. See the documentation for [`RefCell::borrow_mut`] + /// for more details. + #[inline] + #[track_caller] + pub fn borrow_ref_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, T> { + self.borrow(cs).borrow_mut() + } +} + +impl Mutex> { + /// Borrow the data and call [`RefCell::take`] + /// + /// This is equivalent to `self.borrow(cs).take()` + /// + /// # Panics + /// + /// This call could panic. See the documentation for [`RefCell::take`] + /// for more details. + #[inline] + #[track_caller] + pub fn take<'cs>(&'cs self, cs: CriticalSection<'cs>) -> T { + self.borrow(cs).take() + } +} + +// NOTE A `Mutex` can be used as a channel so the protected data must be `Send` +// to prevent sending non-Sendable stuff (e.g. access tokens) across different +// threads. +unsafe impl Sync for Mutex where T: Send {} + +/// ``` compile_fail +/// fn bad(cs: critical_section::CriticalSection) -> &u32 { +/// let x = critical_section::Mutex::new(42u32); +/// x.borrow(cs) +/// } +/// ``` +#[cfg(doctest)] +const BorrowMustNotOutliveMutexTest: () = (); diff --git a/bitbox02-bt/vendor/critical-section/src/std.rs b/bitbox02-bt/vendor/critical-section/src/std.rs new file mode 100644 index 0000000..40df429 --- /dev/null +++ b/bitbox02-bt/vendor/critical-section/src/std.rs @@ -0,0 +1,80 @@ +use std::cell::Cell; +use std::mem::MaybeUninit; +use std::sync::{Mutex, MutexGuard}; + +static GLOBAL_MUTEX: Mutex<()> = Mutex::new(()); + +// This is initialized if a thread has acquired the CS, uninitialized otherwise. +static mut GLOBAL_GUARD: MaybeUninit> = MaybeUninit::uninit(); + +std::thread_local!(static IS_LOCKED: Cell = Cell::new(false)); + +struct StdCriticalSection; +crate::set_impl!(StdCriticalSection); + +unsafe impl crate::Impl for StdCriticalSection { + unsafe fn acquire() -> bool { + // Allow reentrancy by checking thread local state + IS_LOCKED.with(|l| { + if l.get() { + // CS already acquired in the current thread. + return true; + } + + // Note: it is fine to set this flag *before* acquiring the mutex because it's thread local. + // No other thread can see its value, there's no potential for races. + // This way, we hold the mutex for slightly less time. + l.set(true); + + // Not acquired in the current thread, acquire it. + let guard = match GLOBAL_MUTEX.lock() { + Ok(guard) => guard, + Err(err) => { + // Ignore poison on the global mutex in case a panic occurred + // while the mutex was held. + err.into_inner() + } + }; + GLOBAL_GUARD.write(guard); + + false + }) + } + + unsafe fn release(nested_cs: bool) { + if !nested_cs { + // SAFETY: As per the acquire/release safety contract, release can only be called + // if the critical section is acquired in the current thread, + // in which case we know the GLOBAL_GUARD is initialized. + GLOBAL_GUARD.assume_init_drop(); + + // Note: it is fine to clear this flag *after* releasing the mutex because it's thread local. + // No other thread can see its value, there's no potential for races. + // This way, we hold the mutex for slightly less time. + IS_LOCKED.with(|l| l.set(false)); + } + } +} + +#[cfg(test)] +mod tests { + use std::thread; + + use crate as critical_section; + + #[cfg(feature = "std")] + #[test] + #[should_panic(expected = "Not a PoisonError!")] + fn reusable_after_panic() { + let _ = thread::spawn(|| { + critical_section::with(|_| { + panic!("Boom!"); + }) + }) + .join(); + + critical_section::with(|_| { + panic!("Not a PoisonError!"); + }) + } +} diff --git a/bitbox02-bt/vendor/cty/.cargo-checksum.json b/bitbox02-bt/vendor/cty/.cargo-checksum.json new file mode 100644 index 0000000..902714f --- /dev/null +++ b/bitbox02-bt/vendor/cty/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"077c738b5f2c05d66a12209edaabca887091db727d61164a7a414da23d8bf08f","Cargo.toml":"94a517ea6c7dad4634a9a2bd356f3a8035927e7ff8367bd5a975b4db4ccf8e6e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"035e70219855119df4273b3c5b97543ae82e0dd60c520416e759107c602f651b","README.md":"19687c50697e6abc991e4c35e6d674db56bd5e5ae0d5b833440718f8f154a74d","ci/install.sh":"9b34273d9e79ec59f63d5e3e7aea27b0db66194667f9730a21158740fa1b99f1","ci/script.sh":"54962430ca4d3528e5c0d44ff590b1504be13147db5cbe8bb82f1358528ef5f3","src/lib.rs":"33a38ce6df718fb0191f34ff2cefdcbd3ad9d93f0c4073b78eaf937c07fb7614"},"package":"b365fabc795046672053e29c954733ec3b05e4be654ab130fe8f1f94d7051f35"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/cty/CHANGELOG.md b/bitbox02-bt/vendor/cty/CHANGELOG.md new file mode 100644 index 0000000..26845fb --- /dev/null +++ b/bitbox02-bt/vendor/cty/CHANGELOG.md @@ -0,0 +1,73 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to $[Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.2.2] - 2021-10-09 + +### Fixed + +- fixed `c_char` on ARM64 macOS + +## [v0.2.1] - 2019-11-16 + +### Added + +- Support for the `xtensa`, `riscv32` and `riscv64` architectures + +## [v0.2.0] - 2019-02-06 + +### Changed + +- [breaking-change] `cty::c_void` is now a type alias of `core::ffi::c_void`. + +## [v0.1.5] - 2017-05-29 + +### Added + +- More types like `int32_t` + +## [v0.1.4] - 2017-05-29 + +### Added + +- Support for the `msp430` architecture. + +### Fixed + +- [breaking-change] The type definitions of `c_long` and `c_ulong`. + +## [v0.1.3] - 2017-05-29 - YANKED + +### Added + +- Support for the `nvptx` and `nvptx64` architectures. + +## [v0.1.2] - 2017-05-29 - YANKED + +### Fixed + +- [breaking-change] The type definitions of `c_int` and `c_uint`. + +## [v0.1.1] - 2017-05-29 - YANKED + +### Fixed + +- [breaking-change] The type definitions of `c_long`, `c_ulong` and + `c_longlong`. + +## v0.1.0 - 2017-05-24 - YANKED + +- Initial release + +[Unreleased]: https://github.com/japaric/cty/compare/v0.2.2...HEAD +[v0.2.2]: https://github.com/japaric/cty/compare/v0.2.1...v0.2.2 +[v0.2.1]: https://github.com/japaric/cty/compare/v0.2.0...v0.2.1 +[v0.2.0]: https://github.com/japaric/cty/compare/v0.1.5...v0.2.0 +[v0.1.5]: https://github.com/japaric/cty/compare/v0.1.4...v0.1.5 +[v0.1.4]: https://github.com/japaric/cty/compare/v0.1.3...v0.1.4 +[v0.1.3]: https://github.com/japaric/cty/compare/v0.1.2...v0.1.3 +[v0.1.2]: https://github.com/japaric/cty/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/japaric/cty/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/cty/Cargo.toml b/bitbox02-bt/vendor/cty/Cargo.toml new file mode 100644 index 0000000..d93a01a --- /dev/null +++ b/bitbox02-bt/vendor/cty/Cargo.toml @@ -0,0 +1,21 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "cty" +version = "0.2.2" +authors = ["Jorge Aparicio "] +description = "Type aliases to C types like c_int for use with bindgen" +documentation = "https://docs.rs/cty" +keywords = ["c", "types", "bindgen", "ffi"] +categories = ["embedded", "external-ffi-bindings", "no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/japaric/cty" diff --git a/bitbox02-bt/vendor/cty/LICENSE-APACHE b/bitbox02-bt/vendor/cty/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/cty/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/cty/LICENSE-MIT b/bitbox02-bt/vendor/cty/LICENSE-MIT new file mode 100644 index 0000000..a128ba4 --- /dev/null +++ b/bitbox02-bt/vendor/cty/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017 Jorge Aparicio + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/cty/README.md b/bitbox02-bt/vendor/cty/README.md new file mode 100644 index 0000000..f5d09bd --- /dev/null +++ b/bitbox02-bt/vendor/cty/README.md @@ -0,0 +1,22 @@ +[![crates.io](https://img.shields.io/crates/v/cty.svg)](https://crates.io/crates/cty) +[![crates.io](https://img.shields.io/crates/d/cty.svg)](https://crates.io/crates/cty) + +# `cty` + +> Type aliases to C types like c_int for use with bindgen + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bitbox02-bt/vendor/cty/ci/install.sh b/bitbox02-bt/vendor/cty/ci/install.sh new file mode 100644 index 0000000..58ed3c9 --- /dev/null +++ b/bitbox02-bt/vendor/cty/ci/install.sh @@ -0,0 +1,7 @@ +set -ex + +main() { + return +} + +main diff --git a/bitbox02-bt/vendor/cty/ci/script.sh b/bitbox02-bt/vendor/cty/ci/script.sh new file mode 100644 index 0000000..46ac0c2 --- /dev/null +++ b/bitbox02-bt/vendor/cty/ci/script.sh @@ -0,0 +1,10 @@ +set -ex + +main() { + for target in $(rustup target list | grep linux-gnu | cut -d' ' -f1); do + rustup target add $target || continue + cargo check --target $target + done +} + +main diff --git a/bitbox02-bt/vendor/cty/src/lib.rs b/bitbox02-bt/vendor/cty/src/lib.rs new file mode 100644 index 0000000..971c9cb --- /dev/null +++ b/bitbox02-bt/vendor/cty/src/lib.rs @@ -0,0 +1,136 @@ +//! Type aliases to C types like c_int for use with bindgen +//! +//! # MSRV +//! +//! This crate is guaranteed to compile on stable Rust 1.30.0 and up. It *might* compile with older +//! versions but that may change in any new patch release. + +#![allow(non_camel_case_types)] +#![deny(warnings)] +#![no_std] + +// AD = Architecture dependent +pub use ad::*; +// OD = OS dependent +pub use od::*; +// PWD = Pointer Width Dependent +pub use pwd::*; + +#[cfg(any(all(target_arch = "aarch64", not(target_os = "macos")), + target_arch = "arm", + target_arch = "asmjs", + target_arch = "wasm32", + target_arch = "wasm64", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "s390x", + target_arch = "riscv32", + target_arch = "riscv64"))] +mod ad { + pub type c_char = ::c_uchar; + + pub type c_int = i32; + pub type c_uint = u32; +} + +// TODO: Once https://github.com/rust-lang/rfcs/pull/2992 lands, +// this should be extended to cover `aarch64-apple-ios-macabi`. +#[cfg(all(target_arch = "aarch64", target_os = "macos"))] +mod ad { + pub type c_char = ::c_schar; + + pub type c_int = i32; + pub type c_uint = u32; +} + +#[cfg(any(target_arch = "mips", + target_arch = "mips64", + target_arch = "sparc64", + target_arch = "x86", + target_arch = "x86_64", + target_arch = "nvptx", + target_arch = "nvptx64", + target_arch = "xtensa"))] +mod ad { + pub type c_char = ::c_schar; + + pub type c_int = i32; + pub type c_uint = u32; +} + +#[cfg(target_arch = "msp430")] +mod ad { + pub type c_char = ::c_uchar; + + pub type c_int = i16; + pub type c_uint = u16; +} + +// NOTE c_{,u}long definitions come from libc v0.2.3 +#[cfg(not(any(windows, + target_os = "redox", + target_os = "solaris")))] +mod od { + #[cfg(any(target_pointer_width = "16", + target_pointer_width = "32"))] + pub type c_long = i32; + #[cfg(any(target_pointer_width = "16", + target_pointer_width = "32"))] + pub type c_ulong = u32; + + #[cfg(target_pointer_width = "64")] + pub type c_long = i64; + #[cfg(target_pointer_width = "64")] + pub type c_ulong = u64; +} + +#[cfg(windows)] +mod od { + pub type c_long = i32; + pub type c_ulong = u32; +} + +#[cfg(any(target_os = "redox", + target_os = "solaris"))] +mod od { + pub type c_long = i64; + pub type c_ulong = u64; +} + +#[cfg(target_pointer_width = "32")] +mod pwd {} + +#[cfg(target_pointer_width = "64")] +mod pwd {} + +pub type int8_t = i8; +pub type int16_t = i16; +pub type int32_t = i32; +pub type int64_t = i64; + +pub type uint8_t = u8; +pub type uint16_t = u16; +pub type uint32_t = u32; +pub type uint64_t = u64; + +pub type c_schar = i8; +pub type c_short = i16; +pub type c_longlong = i64; + +pub type c_uchar = u8; +pub type c_ushort = u16; +pub type c_ulonglong = u64; + +pub type c_float = f32; +pub type c_double = f64; + +pub type intmax_t = i64; +pub type uintmax_t = u64; + +pub type size_t = usize; +pub type ptrdiff_t = isize; +pub type intptr_t = isize; +pub type uintptr_t = usize; +pub type ssize_t = isize; + +pub type c_void = core::ffi::c_void; diff --git a/bitbox02-bt/vendor/da14531/.cargo-checksum.json b/bitbox02-bt/vendor/da14531/.cargo-checksum.json new file mode 100644 index 0000000..37cee2a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b8684f03ea959810d658217b619197ad6b8655a5bc7a9b5a8c30a88c9f8d3081","README.md":"adc7f86b7c0d90adf2435a2bb4c871021f1a0da3931face808f58e9c98f64973","src/adplldig.rs":"11bcc8393b7b3ee2b662ac20ecdc7ddd45e89ebcdfd2a21a2a46fe98508e803b","src/adplldig/adpll_acc_ctrl_reg.rs":"6b47d85883839f8fe3ab7ed40d5dbe04905ab8080d96646cae2f3ce790857d01","src/adplldig/adpll_ana_ctrl_reg.rs":"9bef0878782989386d2f10c8cc4f936b70d1b625e1d540f6a9259ec79ec67626","src/adplldig/adpll_anatst_ctrl_reg.rs":"fac5a09388a5b9dea1aa86739162ba8032a8c4737e2415813011ca1792985afe","src/adplldig/adpll_anatst_rd_reg.rs":"35ec91c8e78d0d82261d7c634b8db16527c7523ba0dfcdbcfb9624c7b7cfa6a4","src/adplldig/adpll_attr_ctrl_reg.rs":"a95625f61094fa5d2692ac884cbb9c80bf0f779446f1fc3042f3af0f450509a7","src/adplldig/adpll_cn_ctrl_reg.rs":"e75a4c5bb655038fa0592074a566c4199daac7ebde84835c2e52224d8ef5b504","src/adplldig/adpll_dco_rd_reg.rs":"6b02e18f30f0b6626d2e5d301b2e22a090dac48e3225eb8d049cc094b7e54534","src/adplldig/adpll_dcoamp_cal_ctrl_reg.rs":"d53f912cd92792f7af1a45d30b8294a5e82eb68c8d5cfc4cc9db095c76f7d0c1","src/adplldig/adpll_div_ctrl_reg.rs":"69d04ddc6bf55cf53b372a0b07abd29fce37eda8b77f8fc83297d14c5cd43bfe","src/adplldig/adpll_fif_ctrl1_reg.rs":"e38f501713af64f39bfc14377b66620797f851508040a0ae482a86142f22433c","src/adplldig/adpll_fif_ctrl2_reg.rs":"10a969e11f02ed6111d9d5f6c339594d03903d169f86b95458954982adf3298e","src/adplldig/adpll_freqmeas_rd_reg.rs":"9fdd924f03701ee37936d3ae76192f60ec071c522375203bdb7a7345509fc619","src/adplldig/adpll_fsm_ctrl_reg.rs":"0e53e8be9397271eaef266e71f546b4d158e199a2e67390b122919c6ba329362","src/adplldig/adpll_init_ctrl_reg.rs":"f705bb0a1c9d92de4c25a737c3405243b55df3ba3025c13aaf55e1d54b04a3bd","src/adplldig/adpll_kdco_cal_ctrl1_reg.rs":"e04195b3abedf8ffbbab799fe4b539761a777f66987272b82d8f6af32eaed8d2","src/adplldig/adpll_kdco_cal_ctrl2_reg.rs":"f334e6882e29344d9089162cfe556e7802cc5c0021e4e4d23dadb78c646c1ed4","src/adplldig/adpll_kdco_rd_reg.rs":"71ea09215ada5828789101f8a46edf4b970987d886dc5a4c348b70e6925e1df3","src/adplldig/adpll_kdtc_rd_reg.rs":"26389a6ff3a32cb0d2b128359c2c121c3345cda00173537725829cf78f5ab33d","src/adplldig/adpll_kdtctdc_cal_ctrl1_reg.rs":"9b49e602ad1a47d96eb9767840067c9c5fc164da17199fffa0f91466a40a7059","src/adplldig/adpll_kdtctdc_cal_ctrl2_reg.rs":"6a50fe129d3c07d88f6b07e59ed6b238b2231adddcd8a807ac62f6520427dbd9","src/adplldig/adpll_lf_ctrl1_reg.rs":"cffdd615686cfb886e5caf43032108f850d1c38aad542f23561d0f4d64165d8d","src/adplldig/adpll_lf_ctrl2_reg.rs":"6dd0538fd56d0b8752ed549a50abcff5c0f6aa6a3973bae513cbf8d690197637","src/adplldig/adpll_misc_ctrl_reg.rs":"0f879d8e13eab7b59475828f451900d4ed38c3e24aa7b0ca346131059bed5231","src/adplldig/adpll_mon_ctrl_reg.rs":"5a60ec606df6a8c13a2ef58c6cbe09235e9cef476de0ebc34b20e86abf6faae2","src/adplldig/adpll_overrule_ctrl1_reg.rs":"b331e52f1fc89d6a50c817b6afbcfe565e1615ab78cd911fc5af8d052983e6c8","src/adplldig/adpll_overrule_ctrl2_reg.rs":"7d3809678a98a6417a5b5cf5886d23dd5b29fbb3d6d72e0f6018776162f40235","src/adplldig/adpll_overrule_ctrl3_reg.rs":"b8890f71af6f41261c1a6073b12730360ebabc9498cfefe589c4b60a4a0f18f6","src/adplldig/adpll_pllfcwdt_rd_reg.rs":"c763a9343a777efb8b3b5bd5a92974742695c8b791185541c5f7a7ddaf913b5a","src/adplldig/adpll_rfpt_ctrl_reg.rs":"8d8f61c7223ed65133b5cb811bc53de3bc0947ec224cbcd820c03e292bf9654d","src/adplldig/adpll_sdmod_ctrl_reg.rs":"deefc9763b3f2ea7d1f9b82ad37b21b052a279a9b238618b934ed0ec91b4284d","src/adplldig/adpll_tunestate_rd_reg.rs":"d1c41cc6299a9cea6d63aca90baee5607783e4feff7e153ab085c4c6d7466840","src/adplldig/adpll_txmod_ctrl_reg.rs":"88892485cee79bd66f2080cddd7b543140b7f5b46267b4bcd2c97e19a5d84f79","src/anamisc.rs":"82ff26a9a8cde9595faf184adf6f6afdb7a976cdedf88ab5aca233b1e99dfb8a","src/anamisc/clk_ref_cnt_reg.rs":"220aee394c40ab0472c9f947f7d75fdc6ec7205c44aa7aeb9e415233a82d4abb","src/anamisc/clk_ref_sel_reg.rs":"50ba522ed97ff2efe4fcbe02818dac722bd3641997562a35f4932a2bbb72f153","src/anamisc/clk_ref_val_h_reg.rs":"ff80c4149474a4af7224f910ba505d4e36b546d219451ceae97e017bd616511e","src/anamisc/clk_ref_val_l_reg.rs":"a1303c1bf63b642563412681756e0eebf95a859867feaf199cff5f47eacbd492","src/ble.rs":"cac65312280adb8e61f3b5c180005a7f65ebcaf8e80ff4c218a78f969e414442","src/ble/ble_actscanstat_reg.rs":"e322c3c97fb61e11a566b8872b1e867f18a119fc324263befdc632cdfc91ff29","src/ble/ble_advchmap_reg.rs":"c1e9e732b1f45ea1b2693a07cb69e0cac80558a90bf9bf54eb641b8829388788","src/ble/ble_advtim_reg.rs":"026f317db7a883e39e2d1746a3828eaccbfa6bf5e0e43323998fc74c65ae9e30","src/ble/ble_aescntl_reg.rs":"e46887b3e20f46cdfb4454fab031b00c205cde5a552bd127d2146ecdd5d17293","src/ble/ble_aeskey127_96_reg.rs":"06f2e3fd43e293a13ce05b92b1ad478af67b9a9820cf65b8c412eea3d5fb35e7","src/ble/ble_aeskey31_0_reg.rs":"6067241703bf15a278ca7b7ae8e2e5190669a3ed897ca714110e362a9d5f6c42","src/ble/ble_aeskey63_32_reg.rs":"d9b9760f30539a6016e740f9bc031d546657f3a50133b5118bdbb5dcd475b3c2","src/ble/ble_aeskey95_64_reg.rs":"088880f640990420c2f425cb03d8eea5de971f473a417952ad73dd99247147cb","src/ble/ble_aesptr_reg.rs":"36391ab2c2f3576940b0a2149adc2931913b4ef29cf302d40a3b69a652eafde1","src/ble/ble_basetimecnt_reg.rs":"cb132d573982771c3b35339cf9004333acab99d0891c86dd6f5041f23030d907","src/ble/ble_basetimecntcorr_reg.rs":"07b016ba65bbd6b627a0e3244f3bf2e14bf0c4d225a1a6a3db2ab9bc09020b39","src/ble/ble_bdaddrl_reg.rs":"b9a6d86eb07d1de05811962b10e841b3632cc134072ace3a8446162230a95ce4","src/ble/ble_bdaddru_reg.rs":"fc09422631a15c49ccf4462a09640ac9fa71d72281ac44768f62cca754bb18d7","src/ble/ble_blemprio0_reg.rs":"32e5d0691a9d9ce65729da3c35b1f8812667f708462402291056d04a40fadaeb","src/ble/ble_blemprio1_reg.rs":"4e5cd8471fe936ebbb8eae6978b89e1e4411ff6e79f452db3f5b1fa0171cc969","src/ble/ble_cntl2_reg.rs":"e3e9017b6ac35e87befbd30a7ed1ff27931c7dbe074df95d76cad60d3e714622","src/ble/ble_coexifcntl0_reg.rs":"8e41b2092d97831d726e310fe2b22ec471056f4bfc501382819e4d0da953be4b","src/ble/ble_coexifcntl1_reg.rs":"6b3765469bff903ca36043a1d44f0b3883ce68604fd805ffbf05ee29eff3a551","src/ble/ble_currentrxdescptr_reg.rs":"4261bed22144ea7493b79ff933b67a49e7b740a31708941c1b64a8af31f255b3","src/ble/ble_debugaddmax_reg.rs":"4a3c0c4285689afa8b74d21dd67c0ccf925952e49b4fda778fb32d4f4e5268b3","src/ble/ble_debugaddmin_reg.rs":"c5f9bf7f1c1f783fa17984da4611e044883b05834acc5497c0c6c8cba3286ab1","src/ble/ble_deepslcntl_reg.rs":"755224e2110eddb27bfe54b932f88c67eeee63f27dcb727995a49f5c14f28723","src/ble/ble_deepslstat_reg.rs":"fe4ec7f6624e6d3a4c33c5244cdd912c3ea0926552c48c922bd1604695cd700a","src/ble/ble_deepslwkup_reg.rs":"ad385c3bbbc170c89fada502fda899c61219c925a9d31d99665af02ab789c63b","src/ble/ble_diagcntl2_reg.rs":"f0395e0fa267fe2f75c5ac66dbb0dc4f5ad10b8286fe7644433bdb738812e592","src/ble/ble_diagcntl3_reg.rs":"bf187619b61bb0ed60923500f19f721c9f89ad9ca7c6b4935bedb2dfacf82834","src/ble/ble_diagcntl_reg.rs":"bacbc997a128ee619e5705dd4f48f2d75cfd3f7118d4456917ac727399f4fee4","src/ble/ble_diagstat_reg.rs":"717b4e7ba2d31c45a6ecad8f7885c4c17001efb1d3fe35a0786e9355ad65ae64","src/ble/ble_em_base_reg.rs":"3d7e37c35cde4cca533d7e741b9ad7f575b08d8ec438019f3e6b7fdfafbda605","src/ble/ble_enbpreset_reg.rs":"115304ec62bf51dcaca9c59f463a7f384b4bbaef4a2b6785cdaf82e7d9f7f930","src/ble/ble_errortypestat_reg.rs":"57dd22896000b11a1266c4425b414171fed60760686e254ea6489a31b7e6477a","src/ble/ble_finecntcorr_reg.rs":"ff60eab33c140fdfc8ee39036479ccc475acf2f00cf2b6dc58d3b0bc74536169","src/ble/ble_finetimecnt_reg.rs":"4ef3b9e025d8fae3042d1f42ad406c47fff401e618d731d21645bcee0f798b46","src/ble/ble_finetimtgt_reg.rs":"ee6c14191fe6ba2355fd0a012590a5b45b1cf43490945d39251022854b7efba2","src/ble/ble_grosstimtgt_reg.rs":"b2c8b285ff807002206651f74033c063cb061e560101582e2b8de6f19acf0cf5","src/ble/ble_intack_reg.rs":"62f1b360e8ca3f0421f97eba7f1feb6aee261fedfa1b0b52072c50321f323079","src/ble/ble_intcntl_reg.rs":"4bdd20bdef25085ea71c2ede8e95f152d67f0ff0b2b0ae539c170f89f860feb2","src/ble/ble_intrawstat_reg.rs":"579a8eb44ade077e0cfee43a2a9d8fa7d25b1d0af051bc68c5e129c3858e40e8","src/ble/ble_intstat_reg.rs":"3b297e5a30f0fd9e47bd8aefc1a5de28e1ef384a6da136925a8a7dea71db5ac6","src/ble/ble_radiocntl0_reg.rs":"1c6896b7621a129a0800f0dfe26591ceb4dedf8b8a4663ef8f785870157d256a","src/ble/ble_radiocntl1_reg.rs":"9aa8a5e9c0cf7b01800006ad01be3d5f619f0ea844e7be4b788f12d4ee8a004f","src/ble/ble_radiocntl2_reg.rs":"9ac4ca0be6354a829f218ac645073085545f170c11217fba981ef1355f686de8","src/ble/ble_radiocntl3_reg.rs":"53dd388f46e81b3ccf93af33890e9cb2f9f425b31e1da7e3509e3544afaaf8df","src/ble/ble_radiopwrupdn_reg.rs":"e47fa9b2b35f83cde7b616365163f6ad147f367b17fddaa697bd41f263d80750","src/ble/ble_rftestcntl_reg.rs":"057513aae5feedf05d1c2595bd9e1c16f1e9b7b8cb5e6077ba9d9f7ce881243d","src/ble/ble_rftestrxstat_reg.rs":"be72af5ff3e635fb9280131f5fa662b83aa1de8c211b47af997a631ff1fe44f6","src/ble/ble_rftesttxstat_reg.rs":"3e63b3cb55480f1a5684a0f8edf86172498836eb3fbe7e44fc9ce83d8a2958bb","src/ble/ble_rwblecntl_reg.rs":"71d35290253e075f02aaba5a7af006bf9f3b6ae17bc6f2dc737e8d1d56819e1d","src/ble/ble_rwbleconf_reg.rs":"407b42835aefcfc998de166dbbb57ee8f4fc8d4319bc704dbf4857c23d2a41a0","src/ble/ble_rxmicval_reg.rs":"63ecb29ea8920bbd811c263c730e2c3cc16c3c3b79acbfdab622b747ed96fe01","src/ble/ble_sampleclk_reg.rs":"6c8fe1ddade3a68042c00af42275dd465150899dfa939f82a98c6f47ec5ce230","src/ble/ble_swprofiling_reg.rs":"ee9a6711125abf46d02564ebc22fcb9433a16e0aa8d606dbabded5b2e96a3389","src/ble/ble_timgencntl_reg.rs":"a4ddd7eb77dedc0f666564247abfc70c9092b32509ca2dee8ee47e6f300547cc","src/ble/ble_txmicval_reg.rs":"51e3d298f5e2948f671afe045022de6bafff6508826f46c7ee1177318628b250","src/ble/ble_version_reg.rs":"b40826d5733b09e3100236b6f472c85f4e0b2bc801cae2a4500bb41ff5c5737f","src/ble/ble_wlnbdev_reg.rs":"95af346340a2cc88eb1546f4073d2295755d0e2e77217596a1515b1aa599a01c","src/ble/ble_wlprivaddptr_reg.rs":"acd72bf1335f8342d58b497a14231e34051ab777a87e799a4319cda1516e1885","src/ble/ble_wlpubaddptr_reg.rs":"565167067be1d90dd49e86a6354531d20c6399d2435da3d8edab0bc924299b24","src/chip_version.rs":"26aa8c09422761bce121a135696d2b8fbc48490d4995aa94d7629ba7839f6332","src/chip_version/chip_id1_reg.rs":"b56900a482e8221599c5583e65680ca47ec1f351c3b644f0d0079f4c62b22c67","src/chip_version/chip_id2_reg.rs":"efb760ccca2a3d274f9844bfad23df3b254693cb6274d6943dd48527f5bb7b6e","src/chip_version/chip_id3_reg.rs":"567216abca426ca85f18a19671fb0fdbca657695a48597d7cf1d4b9eae9a8cbc","src/chip_version/chip_id4_reg.rs":"c2869c828aa2f291bc34bea41a3f45262d1340e6c94a325115e4d1455b0c49eb","src/chip_version/chip_revision_reg.rs":"e26256a9a3739b15ad238f9475b305327a0e059e8b66ea32c623851f1ae3e056","src/chip_version/chip_swc_reg.rs":"7058560cb803d63dea687d2aed5a9e77d0d5b2e7a8802fda1ec58667066cb684","src/chip_version/chip_test1_reg.rs":"2d6b0d51104c98e0b1e6465c01f655975f7030d5033917116f87b62af89318be","src/chip_version/chip_test2_reg.rs":"bb60d59a8c929259548830f6b7153c94ab192f117e79c61402edb8e32553c236","src/crg_aon.rs":"3386bd08e93280d35781f17b1e2ff7ff9bfb9500a86be862852ae28ea934a12c","src/crg_aon/gp_data_reg.rs":"2ff0ac0736631562a6fe1cdcdcb1fb87369991e527dc1fe3dc07171932e5fe35","src/crg_aon/hibern_ctrl_reg.rs":"d4ef5d99c6b3a4c58ef89303acfb1cc6212f702280cf5481db1020c13fa2b1d9","src/crg_aon/hwr_ctrl_reg.rs":"9c0f11d9107f5536c7361581b9b9f8df1a392623b3f95446d8466c9e67f3ba29","src/crg_aon/pad_latch_reg.rs":"e507aff259d4e530ceb1b5839ff3a38496bb025d9547bc8a6b6dcbd39aaf2a33","src/crg_aon/power_aon_ctrl_reg.rs":"b7f7d9ee2f295c5b74e5a4029c6c27516d810a999cfc2b09d084c00ddc5d09eb","src/crg_aon/ram_lpmx_reg.rs":"fc522d6be5fc919d74ffe52550671631db49dd162d599f30bd84fef89478bb96","src/crg_aon/reset_stat_reg.rs":"96de40b6ddb169ae585d777803962bdec18222032e7749abb99a84edf2386ea1","src/crg_aon/test_vdd_reg.rs":"65b0e244aacdee37f83233c112afc3d714968163ec11a4ea5be6732c9a995991","src/crg_tim.rs":"a4b00167e0c012b653030a44dd6fe1ce62a12b0e6cd2ac44acbd14591493a835","src/crg_tim/clk_rtcdiv_reg.rs":"5e1e0d37516c989e7ea53a04645cf9ae707cd2853de0965526b1c7c85e8596aa","src/crg_top.rs":"8ec8e1473c156dc42ef9e6df202559a9448d5c4a31fc42d61cb9b13b030fa07a","src/crg_top/ana_status_reg.rs":"08660643322739d04fceb588b33771942ad95c9aa5674976f213cc268e68bdea","src/crg_top/bandgap_reg.rs":"c6644b3bf192361a255cc377033b695bb75f4a292fc2bcc44bbb9bcedc66e746","src/crg_top/clk_amba_reg.rs":"14ccd8afc67617fd25791f1522eb66b10f80366e2793464d4fd992c1bc7c9be7","src/crg_top/clk_ctrl_reg.rs":"776964a587c877483191b386c8732dedcf42e47faeaa951e6245782f005d8ad5","src/crg_top/clk_freq_trim_reg.rs":"a45bdea2010c04fe84a64d2f5e65ee345f6421bfd54eadb95c735b0beac1f4b5","src/crg_top/clk_per_reg.rs":"eea80da792c70b75365047283b9bf242790dbd52a9c88d30d67caebacd538084","src/crg_top/clk_radio_reg.rs":"52473f682203dcb06368709b6a85f6ca8b605a69ed7b51680aa92ec0b8803f39","src/crg_top/clk_rc32k_reg.rs":"d413cf1777ade959ff8c446e321f278f2ae89201912af892b5c73a2dce91c70c","src/crg_top/clk_rc32m_reg.rs":"b935a983390a08baf134b2e18e504068090aca90bff84cd8007edb4182f0e945","src/crg_top/clk_rcx_reg.rs":"2a335bea53307592ba1dacecdf720e9a04703a14bd85edb4368b0e585ac53b8f","src/crg_top/clk_xtal32k_reg.rs":"ed55438b73689c738f6f52d0093499c18836469f070872060636b05f5d3eb6ac","src/crg_top/pmu_ctrl_reg.rs":"9b0d5aefab73cfbee06078cf5f3032118adf0c974a562cb802132288e64d3bd8","src/crg_top/pmu_sleep_reg.rs":"100ac3a58b8fe589f6952eb69f16c47fd6f45bb2aa560c8f94c430784ac438ee","src/crg_top/por_pin_reg.rs":"14973fe3ea1af25481a8dddfa8d0911872ecbc8b2d9dd56477039144d129ec02","src/crg_top/por_timer_reg.rs":"44b589f0663d447410fe14a71888867f49190e3b627243a30e6f26b5c18da718","src/crg_top/power_ctrl_reg.rs":"1f8d131ef4841ac7a1d43634baab4e2d0d8df9249f4d60b8a0e234adadfa48bd","src/crg_top/power_level_reg.rs":"920c1b29f69dc81d1bb16e3c0a50addaa01bf596bda86cc5d72dd7792f7d750a","src/crg_top/ram_pwr_ctrl_reg.rs":"0cf9f3fba203ecc6f95a110dd197763d60264ca945c3694188d3b925b4b82f59","src/crg_top/sys_ctrl_reg.rs":"ffc8a2b3960127ad648ff2a26aa4ab3ff73e52aa90fe95dbc6a8e483d7bebe9b","src/crg_top/sys_stat_reg.rs":"45b128cbde4135872cc403e4ed238b5ecfedc82be9504207cee02bb2df3ffa34","src/crg_top/trim_ctrl_reg.rs":"3ea67eab7bdab6b09c47e8161b93e1c9b08ab22aa35b3ef820aa6464a08811c8","src/crg_top/xtal32m_ctrl0_reg.rs":"42047277e87ea096280f44d40fc1643173e66fff95d5c4841ef83dc091f6cc7e","src/crg_top/xtal32m_start_reg.rs":"a6f64a671898f5f83d28a1eac8edab6fed609b61b35419b3b7ae339f3cf1f99d","src/crg_top/xtal32m_trstat_reg.rs":"39c1b5957760e9b14ceeeae0fca8b282eda676b4d3631e9fd2757a7867ece740","src/crg_top/xtalrdy_ctrl_reg.rs":"6977f72988723b3f7028daaf35798d00ce960e6666d940a8543c3cc5206bbccc","src/crg_top/xtalrdy_stat_reg.rs":"382681f805a28d40a960922de7165d37bfc9da82ab65ba84a4ec4b6c99c6f7d5","src/generic.rs":"5266ff29623fb1a3c0243a8743f1c4ece18ed108ea60450bc9b8815396e19634","src/gpadc.rs":"67baac208ec25e0469ef6b3454a8f0ca283e8b0875f3fddeef89192d27f242f8","src/gpadc/gp_adc_clear_int_reg.rs":"2d2b98a80ad7f76e9d9929756ecb768ea3f6327588782754ae2e4c466a7d5acf","src/gpadc/gp_adc_ctrl2_reg.rs":"905d2c801366681a93239a81dda95cac2fb091ed263e3bdeed064e9baf196b41","src/gpadc/gp_adc_ctrl3_reg.rs":"b6176db3b5621ad5ef5b5647408586368ae08b9645dacde12f5323cbb72b7b27","src/gpadc/gp_adc_ctrl_reg.rs":"27b590548226cfcef550b402a9487524b05b8e9f02c5f9104b1407305fa3c2e2","src/gpadc/gp_adc_offn_reg.rs":"34834ed65a5862715d98e31227f2c76a4ff637c6c9a140e857e31b3fa29d18e2","src/gpadc/gp_adc_offp_reg.rs":"f50fceff900e8ce0edba8b83257d68e0ba5f07b3c5c831bac204d981e96de1b0","src/gpadc/gp_adc_param_dif_reg.rs":"552c6d54f9a365a1d9bec57ff7d6edc0cc094a884103ae430011920a3eefce03","src/gpadc/gp_adc_param_se_reg.rs":"94c737f9d7f06966f5ffea2fe13ef1dfbb9ec2988725c8c91882d19411579714","src/gpadc/gp_adc_result_reg.rs":"0463b1e90fe995b42203c99579c4c17d4e3c040e25445f7ae47e9a9ac5bd0440","src/gpadc/gp_adc_sel_reg.rs":"498b691d82598c69d2a7fedf06828ec2a70e40553d63da36a7ef207dff6a9ff2","src/gpadc/gp_adc_trim_reg.rs":"5c68942ac14a0f3a9f4e1c6b0dae3a500ef4b1c1d72382f29677a51a7755308e","src/gpio.rs":"8a187eaa168d0d51f0507ec9e2874fc35892394b90269e7edc13c24464602e09","src/gpio/bist_ctrl_reg.rs":"7aa0ab0e5d192cc955f0cd50519942521a85620880fa62173534758834ed26e2","src/gpio/p0_data_reg.rs":"a74a1fef9c34f2b998daba44fe8803e76d8d4e27193131dcd498a95f13432a09","src/gpio/p0_mode_reg.rs":"d35cfb61e772422a73128e761e9b38ef0ae965d1a7f715d7cca6058b3b9d48cd","src/gpio/p0_reset_data_reg.rs":"d5bf0fc77c2b0bcc1b8d91f8c6f026da2b35b46780be9f789b896927a9ab2478","src/gpio/p0_set_data_reg.rs":"2ff99471ff94a6bc118487314697cd94cef74d2041895a457645ee658beda009","src/gpio/pad_weak_ctrl_reg.rs":"6f8e19419c5baedf8ffeceb4464355944351a7f378b50d1f3707a96b526b1d81","src/gpio/rombist_resulth_reg.rs":"758f4be24bccd53bd96de8b10fd53ca6a677b58ab883d2a0329eebcbfd65de3f","src/gpio/rombist_resultl_reg.rs":"fbd26800324e3c5c6ebb2086b2a8a78fd8a7129a6dc07c17fd2211f7100102e3","src/gpio/scan_observe_reg.rs":"1162dd9dd1fd0fbfe18de22e96f8aaf803eabfa8d2e6bbea8e7e9f1d42960043","src/gpio/test_ctrl2_reg.rs":"761f8e15714fc11bddb0e43072e835bf7e7bd4adec978f7d5e5854c46039c845","src/gpio/test_ctrl3_reg.rs":"61f2a29d3a3764a9952e5cc34b4fd23b09c54b2ee127aea7460c3ea34efa7e4e","src/gpio/test_ctrl4_reg.rs":"bc210308b2d56cf537e9c682c2f1899e3ff70c5e67290aaee2026ba365c074af","src/gpio/test_ctrl_reg.rs":"fd6edc6e7da783e5ffaf14c58566984ffb3207539d7244e4f04a85db8f7b1f79","src/gpio/xtal32m_testctrl0_reg.rs":"4ad27c8130f9dedde4e7773d2c094bf294d5d5aa77b64e3da2b78d715c902c66","src/gpio/xtal32m_testctrl1_reg.rs":"8fdfe0673a712f88da56b826306feec052c4ff7f5e449254c674486899c264dc","src/gpreg.rs":"53f4c3ba03d2fefd0aec12224a2154567df974d90cd07ad4c464adaccadfc770","src/gpreg/ble_timer_reg.rs":"3298fbd32585d2af37efaaa3c9b77b4041281b7b8d5a81064792f23ad0da92de","src/gpreg/debug_reg.rs":"1a42d7c0d607a530e2934bb58549ff93690140befaaff7080c154e1387900447","src/gpreg/gp_control_reg.rs":"7e117a6bae62130fc051dea93a2317d53517d9d87e7eba6fa88aa1d2d49ece81","src/gpreg/gp_status_reg.rs":"5633f96b689ce03520d15befc52589be4538dd87521dc3ac90cfe1430ee9c5f9","src/gpreg/mem_ctrl_reg.rs":"e7a066fadb364f780af61ad15859b2149f58877f59ff4a5c6203697a9538b5c4","src/gpreg/reset_freeze_reg.rs":"9b4ab69df8bcfe36787a72658968af88823be71409a24ff883f716c82926feae","src/gpreg/set_freeze_reg.rs":"f0e726fb16db77d9c62ddc267f121709799184e4eb979d45dd9a37167388c93e","src/i2c.rs":"ecdeddba983a1fdf4b14544c30463f17f8c1b2bc39c67617910b2fca7bdcbb38","src/i2c/i2c_ack_general_call_reg.rs":"84d6a2e8be7fad7fd320c6da1184f8cc078765b1858564edbd440cf951512736","src/i2c/i2c_clr_activity_reg.rs":"3e8fd12ea1e371060ce44ef035c670703db7d24fc63b1acf06d626afe900eda4","src/i2c/i2c_clr_gen_call_reg.rs":"eded42ea68e2dc0d0ad5ba0a39d5790d5c8c556e548918c14bacd4c6f6705035","src/i2c/i2c_clr_intr_reg.rs":"b4b42840d7340fe637fa548fa567f2360e731a053c2d853b583c9d449e856259","src/i2c/i2c_clr_rd_req_reg.rs":"412b76d1d66c0d907c45ad69b979c9c3f80cd4241c388cb4eec4142d611612a4","src/i2c/i2c_clr_rx_done_reg.rs":"49a0dc9ec11e420a66c661cb2c8f869e9e0e7e9e23f587872586ac8f1e3d893f","src/i2c/i2c_clr_rx_over_reg.rs":"7dad8dbb10699073b8e0b95693d09851260c22288b63a7d0c8b431f51b8988b6","src/i2c/i2c_clr_rx_under_reg.rs":"89c4d66baebe9ec6a3d31eb497ad33e83d3327a155e5d12e67a9d4ebdf51e080","src/i2c/i2c_clr_start_det_reg.rs":"bf9547bf8a0b68022fed937f6fb7fc17555e2ef40b9f16ba91d49b1accab414f","src/i2c/i2c_clr_stop_det_reg.rs":"61e770010ee6ddf1557913546a81b2f0942a62bb01e7ea2785ca273801314b63","src/i2c/i2c_clr_tx_abrt_reg.rs":"40e266805c22dd2e43d73ef3d2787a096fd09645726d992c2e918d0f504632b6","src/i2c/i2c_clr_tx_over_reg.rs":"309fd9541fa91d04c09bbf0bbe8d6bf0c755a26c0bee78335ace360aec319a6e","src/i2c/i2c_comp2_version.rs":"a98be996c2e9ded6b7734dd98d905cff3b2b7e65f35a2150a0c43ebea64a801e","src/i2c/i2c_comp_param1_reg.rs":"b934028393971dc43124aef344470b21e83f1a0f27700532ffaa8ebde65568cb","src/i2c/i2c_comp_param2_reg.rs":"b95337bf6a65f4e038c1742571f049f12ab48d3d7b3c56dfb354670baffcae3a","src/i2c/i2c_comp_type2_reg.rs":"d4785d1721e6bab83ca3f49d49941415ada3914c4e1b9e057837fd9129619a2a","src/i2c/i2c_comp_type_reg.rs":"e41bdcf2e68c3da909a992edd2958b2005c2943980beef11e49651ec6ac759e3","src/i2c/i2c_comp_version_reg.rs":"610d8ef91f309bc702b4ffd4aec5f68c26b40a93eabd9b6f2070833685d06900","src/i2c/i2c_con_reg.rs":"c1a8b727338b37eda419c61393b8695c373f592d8e35d6bdb9855be4f7ee4409","src/i2c/i2c_data_cmd_reg.rs":"281bfeacca166defca0e80b3a0cbb70dfcfb7f03cb3bd39dec0b2b1d1c03dd1a","src/i2c/i2c_dma_cr_reg.rs":"3c109bd9e0329a30eb5ae78de56b11493df78fdb87b48b6a046cae5287c0db9f","src/i2c/i2c_dma_rdlr_reg.rs":"a8b217b84d75ec358f33f056eae6d65eb958039481180cd53f0d9e8ad32c2bf7","src/i2c/i2c_dma_tdlr_reg.rs":"3e0fed86032ab5ba3705bbbf5641499e82b276a6c3ca8cb19b849872087a4119","src/i2c/i2c_enable_reg.rs":"7f68fb114e4cece1e25f496f01924e98e94dc6774c8b93579d18cb2acc19471f","src/i2c/i2c_enable_status_reg.rs":"083a5791f8df8f4bdde493af978920953a68462de03e8a7df4fd5989fbddd3e7","src/i2c/i2c_fs_scl_hcnt_reg.rs":"bb20d95a5f3248b04e513e166314ef635956f57afdcf4c5fe10b0f9b4d9d8003","src/i2c/i2c_fs_scl_lcnt_reg.rs":"6387d1382953186b72356a13364d5d84c5ee782c8abb5a206a2150c04a094200","src/i2c/i2c_ic_fs_spklen_reg.rs":"47f521ad53f28138fd76e32a821473c550b502617c30f567d799aa2f52788f8c","src/i2c/i2c_intr_mask_reg.rs":"054c4e091453ffe104ad0d1eefe8054e640c86d34f43c66a6afc0018cbb258d2","src/i2c/i2c_intr_stat_reg.rs":"e3457e9df7a0f2c052498f84199b869bf709ba5f6f22a4f639834bc69abc84d0","src/i2c/i2c_raw_intr_stat_reg.rs":"4045e223eec6a1ece355e343203622ae80b597d29a2e94d61bfd4fdb27d3ee39","src/i2c/i2c_rx_tl_reg.rs":"280ac566e1b3ed3a771403d6d5d7ddbb0704c0321ac52523d37bd68034fad5df","src/i2c/i2c_rxflr_reg.rs":"c802ea94c81911877a47b3c039d7259745d280a422a2a4ce688e2c797406e1d7","src/i2c/i2c_sar_reg.rs":"6ccc44be4cff55dade3826ad29181f00f8c180e2906b8c7520061cefb26d8791","src/i2c/i2c_sda_hold_reg.rs":"e6fa225e84fc0b6d3b81d7a52f756e50375c7fd942fc398d0b6687188d70f7ab","src/i2c/i2c_sda_setup_reg.rs":"39d87ebf18bae5d332f0fcd1250bdc9c0614172d762d43c5ed16f11ca59738de","src/i2c/i2c_ss_scl_hcnt_reg.rs":"1b8683d6b23565ce34fb8026d9bf049e830be8732ed67f048a0586cd1555d9a8","src/i2c/i2c_ss_scl_lcnt_reg.rs":"d8afbcb3f68214039b1853afa55af46cb42512d7601c4b76b7f67233adab38bb","src/i2c/i2c_status_reg.rs":"594d623ce8c6ad1978c47cfef912aa7a68304fdeab51b557186ec47e4f092f8e","src/i2c/i2c_tar_reg.rs":"9f7cca3617674810b780407b85b62892bd2e6a0ee3b85c9137fd3878917ceae8","src/i2c/i2c_tx_abrt_source_reg.rs":"0aba8d0d6cea933921bc1942e925e636b479f5f6e5e91eaedfe3c2c57cdd1d83","src/i2c/i2c_tx_tl_reg.rs":"72990ac442190d98c62b1af3eef6ea304c64338c67385b3af08cd52878d96d74","src/i2c/i2c_txflr_reg.rs":"258b3e9574770312339a0c388f0c90a46961eca121998bf958bba6f5c96bd7cc","src/kbrd.rs":"0b7f7ce456decf8fc43fb11e5ba866b0720ec4684583f5ed9b682536d490ceef","src/kbrd/gpio_debounce_reg.rs":"6eff6cf4e7c971c3f5c6272ff94ff4ebc9f5b9abdb5a6f5f49f6f133d80263e5","src/kbrd/gpio_int_level_ctrl_reg.rs":"29802543e036424cd2a81133318550f7b05584b6afa733274e7cdb0c7a4841df","src/kbrd/gpio_irq0_in_sel_reg.rs":"a99969be2becda39bd0526be6002e1e5f9b64bbf2761c9bec9fab1ca733d8a07","src/kbrd/gpio_irq1_in_sel_reg.rs":"e1a74792128c6025a6c6e0c7265758f6b2f780bd195a37170a06fafeef151fb6","src/kbrd/gpio_irq2_in_sel_reg.rs":"bef846bd8f397109b15f113caa0a4d04810ace3fa877b7be2f2fc17cd06adc2b","src/kbrd/gpio_irq3_in_sel_reg.rs":"ad9c67fd7c2a100177a34d722c984523d36b41991352cc68eeaba4ff2913afb8","src/kbrd/gpio_irq4_in_sel_reg.rs":"34e4cb0de6aa957755d7a68172fec5b7b02691b7d853dc8ac8e2e823982139f3","src/kbrd/gpio_reset_irq_reg.rs":"179284aaf76d52835e97cd9c11ebb50572a2d1baa9787904630486c03015f53d","src/kbrd/kbrd_ctrl_reg.rs":"e2d2bac652888f09c3b8fe2722eef41fa9936b3c0c3dc7ea217372413971ec6d","src/kbrd/kbrd_irq_in_sel0_reg.rs":"e0ca94e5890da72c80c8edf61e60636eab33235fded6c079c998169b831005f2","src/lib.rs":"3fd3fa737b307c6082d143105579a9f0a49e9a9b945968f259a04c3279167edb","src/mbist_sram12.rs":"5aa8e9584df73eb52ea6635c0b1e22d92fc9dd39aac9c35e316917b25c94e18e","src/mbist_sram12/mbist_sram12_addr_reg.rs":"87a5856880c739d6c523be9698f2c8393b5cedc63c760341e6868092ab20b4d9","src/mbist_sram12/mbist_sram12_rd_lsb_reg.rs":"2f391aa35f474aeb184350dc39f0992652f89b2bf50404da0e2a42f01016d4ae","src/mbist_sram12/mbist_sram12_rd_msb_reg.rs":"5834f388d06323ceea7effe9796ba8c32b63e614145ff75345b3d65edce81974","src/mbist_sram12/mbist_sram12_state_reg.rs":"1a6a91a8db17c636806acd145f8b7edf19228581ac5b45e9ee496797156209d8","src/mbist_sram3.rs":"cadf4d9c7961eedd9cadf6660f1730301cca2357b3e07ec4a9962958fd021375","src/mbist_sram3/mbist_sram3_addr_reg.rs":"96ae10f7ab4d1d1985d2f43068e281c3648d2e3daf087b21fad17afcb7d84ae1","src/mbist_sram3/mbist_sram3_rd_lsb_reg.rs":"dfe2c0baceaabd7892f91431e6c0e1d73f1c24a97eb043c4661d083ab69e3323","src/mbist_sram3/mbist_sram3_rd_msb_reg.rs":"85e7c2f860a91a5e983fc0e97bb67785819cc09faa5a04a91b20acde20d22862","src/mbist_sram3/mbist_sram3_state_reg.rs":"69d5906b9ffba5f631d9c5e3c6ea760dae63e85bfdd6e8b2676351fa564f6247","src/otpc.rs":"18963b24cecb341e417a8c61fb5efbf19c5d722c26f8f03452d5505e357f43a5","src/otpc/otpc_ahbadr_reg.rs":"f3dcbf8cbbdfa1036c123dd4e122efa1d556e7acc46ab179d4ad5645e957b1a9","src/otpc/otpc_celadr_reg.rs":"f26304972ce75d3c8fd981b08f98b290dd2249dc24fbcf59b784b2b436e8d5ac","src/otpc/otpc_mode_reg.rs":"a99a587473cee2f18e9dab60956d68284ebb049e825ef2cef3d0125ed870e8ea","src/otpc/otpc_nwords_reg.rs":"a94f1851a4373eabf56aba962f11a9b29e144ac08662885b32b011dfa50c2838","src/otpc/otpc_paddr_reg.rs":"f4826068b3eb175447048ad52a3a57eed4a3eb619acf32d07b690d97e28de739","src/otpc/otpc_pword_reg.rs":"a3d16738d4c7e78c55c7e9a4d6fb113f113c58ef194997bfc36271485851f371","src/otpc/otpc_stat_reg.rs":"5e77f30320898cbfb4752710dcc02c5ab5f821fedc1ea050c3a3974bd4ae83d2","src/otpc/otpc_tim1_reg.rs":"f513634b4ec5c508b3dc7a63340a9e9bcdbd8adef2a08e7da0cf45014d73f29f","src/otpc/otpc_tim2_reg.rs":"c4ffb70aa739c9587942085a5644eb1d0e49921257db9c7e59d5280a8f986767","src/patch.rs":"e16049a3b1e959b1f253e708114126c193fe6e48217dc7ffd40057e3c8e1dfb1","src/patch/patch_addr0_reg.rs":"650566b1490135662710727e357afbcdc2811e6f28273cabadac9e67db340913","src/patch/patch_addr10_reg.rs":"13f0952be9166a147f0c6bbc60852a889f806acbb8bd0785e4ef7c6113bb73a1","src/patch/patch_addr11_reg.rs":"442a73e85f065f537d6c9898179fb91df43060ea6ff89110e292ff192306f283","src/patch/patch_addr12_reg.rs":"4222be8771354b141ce3d6eee5943e90be7ab6e17d29a185eb2f21a1a68b5c1e","src/patch/patch_addr13_reg.rs":"494b63101b8038f83055e7c506066623d3c58e247edbae34071cce0ec2e20d8a","src/patch/patch_addr14_reg.rs":"1d7fa3a3d5a9fa7a9ef9861414d6b159d257fb71d80752fe6eca64c45b34f668","src/patch/patch_addr15_reg.rs":"d044aa0802485fcd9b1675c245181a0de0b9b821767e8e9f2968b4e6b1be8190","src/patch/patch_addr16_reg.rs":"621917a9138a48d802bc7ee27a08e8139a1635259008a0614c42096d1ca984a3","src/patch/patch_addr17_reg.rs":"38d0a2a5cf560d58078cc949b31b946ecad4ed5f30adabedf142cba5cc6a5ff1","src/patch/patch_addr18_reg.rs":"a743654b5137ee836f6e9c675366cec6e6482a2693390a244202e053d5243b74","src/patch/patch_addr19_reg.rs":"a1ae00575531c98a522c0b2c995e9b20741436161729d60655947bff8df880e5","src/patch/patch_addr1_reg.rs":"fe5f1ac44d7a1a314d820376c9b0bec606d1937dff03ed79f83fa79c296148fd","src/patch/patch_addr20_reg.rs":"7f082b707e435040f93265f7db3242a16178d7ba6147c586ea3aba70dda780ee","src/patch/patch_addr21_reg.rs":"040fe737bffe64c8a9b43787e137715a60c8a2af59fa9306093189594affebbc","src/patch/patch_addr2_reg.rs":"c1bbe09382fe7697c9c8dbf834c1eaa4a8162548d55af73d44c15c7bf0b27ac1","src/patch/patch_addr3_reg.rs":"50e5f23031a906f230479b2f31a2d1048d01a7eebe5debef6a48ac41cae10298","src/patch/patch_addr4_reg.rs":"2575845867d500ad98256dabbaa2996ad19502466f35e1b4c7a60f0ef737cfc5","src/patch/patch_addr5_reg.rs":"c07dfaa2174b889ebe7c462a8e8a7b8b1055249313c2c56a2763029cdd73d84e","src/patch/patch_addr6_reg.rs":"323a29ac51bc271ba6e6526b65cb1a13f9e0be93eb4fd28474ff5d362bd4640a","src/patch/patch_addr7_reg.rs":"27a3a983f0099272849bd52a6f58bdd0e2b30a28eef99bf67b04190993c93a19","src/patch/patch_addr8_reg.rs":"714cc5a3117d86465c2384f9223aba248887500545e55573549e17d84fe3c00c","src/patch/patch_addr9_reg.rs":"aaa452546e434e06c788f5faeb7a08e4d0dad4a934c541c86f8ba1e32cd65518","src/patch/patch_data20_reg.rs":"f3b561e19622257af313fbb1219d624db90ac5368d903ea168bfcc1c4f9e4614","src/patch/patch_data21_reg.rs":"3ec95ce21c8ca2af6fd207dcaacc4c1a589842227054a779916ea9921666ecff","src/patch/patch_valid_reg.rs":"611bd72c75f85fdd51165c41dcc3fd163999b9625e618a5eea16cc552d2f58ee","src/quadec.rs":"ebb65cff753cc511d941aaa08d33d500c162cb554efc4a508ad2b371e4827a75","src/quadec/qdec_clockdiv_reg.rs":"e92bb4c677439b834cb9e29c7045d51e52825312ef667e5784acc7deeb663a5f","src/quadec/qdec_ctrl2_reg.rs":"188eeeddf9ac6e83ef4ee4014a9ccbf662848aa408a9a23e39c43ea2844c598f","src/quadec/qdec_ctrl_reg.rs":"82970b97307d0603608f40fda80a4f9327dd2fc8d86ae605a8f3f4306a90ea45","src/quadec/qdec_event_cnt_reg.rs":"80559e5607b59489ebb2205650cc5af405765c2d317d30c50093aa293b526b54","src/quadec/qdec_xcnt_reg.rs":"32460cbe4249444c768f1a8d9e2afa994dcf5424f615d93291b511980a395062","src/quadec/qdec_ycnt_reg.rs":"ee927be246f9658061cf4e1a26e2e290f106223364051a531ab99b72e5e9609c","src/quadec/qdec_zcnt_reg.rs":"1617f436bc53367646770cac19796e13f9ba49401879449976f680ed43b168bf","src/rfcu.rs":"41e378826e217b3406c35ba7395af92a6c66fd69546e2e44a207d4955c7c5de8","src/rfcu/rf_adc_ctrl1_reg.rs":"e0c4d3bca24c8b704ed29b26371507352f49b738a80a4c704189153cefb733ac","src/rfcu/rf_adc_ctrl2_reg.rs":"5a016645b0924553639845c981492bf63da96539059821966b54f8520b73f935","src/rfcu/rf_adc_ctrl3_reg.rs":"22afcd1edcbedb4b5b5084f5d446308fb29f39aacda785fa4b9470bd1c9d6343","src/rfcu/rf_adci_dc_offset_reg.rs":"a459f1cbb3c615490eac8a9142c742305533ddc53c2aaa774e9d3ad4430cb946","src/rfcu/rf_adcq_dc_offset_reg.rs":"a56f932cacd99c4fe6ddf523df2e3dab3e30a91b5b436ba606e6b116a455e8af","src/rfcu/rf_adplldig_ctrl_reg.rs":"bf2df5f3d74ffacbee3dbe3008853ae947afc6525a9c43a1e37b6caa7c1e1c97","src/rfcu/rf_adplldig_rfmon_ctrl_reg.rs":"b8bb0efebf15f6c4eb14556e286a484bb8e89e5eb48f233b95330ce3011a6273","src/rfcu/rf_agc_ext_lut_reg.rs":"1a0825c91de09eaab89cb59eb69016c8af1d970de3a2d5998140037b458a33d6","src/rfcu/rf_attr_reg.rs":"1566432901965632074356474bebd41b13385b5d3037ad7c9e1621a0a9e3d865","src/rfcu/rf_cal_ctrl_reg.rs":"86fe5d7c3309180b437aca253db5a1869b67da7722324b2110bc32cf48d8da3a","src/rfcu/rf_calstate_reg.rs":"4481f55a968f6b8fa113660a7f8c99e62c86fdca7360dc6f9bbc58e7dc0a9d17","src/rfcu/rf_diagirq_ctrl_reg.rs":"07acc19280f22aa3221b37adc6e2144a54da366bbd33b4e0932b578631dc41b6","src/rfcu/rf_diagirq_stat_reg.rs":"9deeeb855bd52f88c25127d81973a79a0ec952047483903097d71a0bec55d7f1","src/rfcu/rf_iff_ctrl_reg.rs":"0edd4f3bc6b600664d2749c5f9abf35b9011ec958bab1fcc3323aa0f4964e94e","src/rfcu/rf_io_ctrl_reg.rs":"cae5d0e8d1334de32d108c228df1444535341f054798df89b6a24b1923335d9e","src/rfcu/rf_irq_ctrl_reg.rs":"6c6b2c5c19ba259f7fd3ccee7f4caea6012207a22a743fbce3c55be1a1bf76db","src/rfcu/rf_ldo_ctrl_reg.rs":"eab2e8f324b2209b21440bb83e57aea11bd6119efdba6c9488a455c0ae86f5f1","src/rfcu/rf_ldo_status_reg.rs":"cd2f99637e146cf0494a23fda3b384ac3eb14890273f8b7c9f68d98ce3add50a","src/rfcu/rf_ldo_vref_sel_reg.rs":"0e42ecd2e46da974321d6ada041616e7c119f94efc22fa299a7c418e1660b0db","src/rfcu/rf_lna_ctrl1_reg.rs":"3d6b4857b28c3ac1bb00546e6935a33d08cba359270ebbc4f1f2eb9c583b0eea","src/rfcu/rf_lna_ctrl2_reg.rs":"568451310ab763701eb0923c07857578fe79af656c4330bdf37d8b81cc4ab31a","src/rfcu/rf_lna_ctrl3_reg.rs":"5142e62311cb63e49bf3f0c396607f51c89d8acf6e2e872b205a1d0f650172e9","src/rfcu/rf_mixer_ctrl1_reg.rs":"f5fe0e4c4f357ab836b8e67972cb5ce02b5349185bdc53f6bc51979d11934f21","src/rfcu/rf_mixer_ctrl2_reg.rs":"a031f0346986cf88936b8ead7dda187a5df9cde815d8d4f394953f03ad17baa0","src/rfcu/rf_overrule_reg.rs":"b7c740e7106e94aa180b1419038816aa0e55a0b074700ced4675530d267d8bb9","src/rfcu/rf_pa_ctrl_reg.rs":"e5ced4e22626a09e20d4d86336b2fd966c05f6e81c13ed2eef2b1888ab566b1a","src/rfcu/rf_radio_init_reg.rs":"e03bc681abf237ceb930f9665d386cb0bf53d204701b975156a51a1e3b9917bc","src/rfcu/rf_rfcu_ctrl_reg.rs":"f23b2d179fd15447087e7b59f57ed6300a264f01d65d964f0c1732e8ce06443f","src/rfcu/rf_scan_feedback_reg.rs":"8467e81d46dd8f0d897573c1fb3a330b383f0d708725c0ee772b9467b648f2c6","src/rfcu/rf_spare_reg.rs":"c8100e2e36690c970ffa4e498db0a829a2a0eee0059e21671b575f6a53b34f31","src/rfcu_power.rs":"f12918f5f1b33aa63a1fb08927f983993b2e9baa067c29097c79f9e9b67e4b4a","src/rfcu_power/rf_always_en1_reg.rs":"7d87c19d8260c76e3469c91460856cc0cccf3408254901f8cf135f43f5f1b70f","src/rfcu_power/rf_always_en2_reg.rs":"5e63a33bc10c14cc9899a6be1bbc84f6ffe286f75c0581f714915f222ecf307b","src/rfcu_power/rf_cntrl_timer_10_reg.rs":"650107feeb618c052417598d2afeb9fc24c79eb57555a086295fd2cbf52e2163","src/rfcu_power/rf_cntrl_timer_11_reg.rs":"54501f9efc9ae38ac59d787b0c15c9eddae2787cd41841d7b229c9f903793e4b","src/rfcu_power/rf_cntrl_timer_12_reg.rs":"30c257779f78929a6ba60f4812779d8f14bd200e4b135c051b68fcc6b6b582dd","src/rfcu_power/rf_cntrl_timer_13_reg.rs":"7ad6ae50fa28055abbc302b8608c083d335cd6f772460ea7eb6520babe309e53","src/rfcu_power/rf_cntrl_timer_14_reg.rs":"3c95d57da2359e9a500a542506b24cad4a9eb5b23b278d1146635b42ba06f093","src/rfcu_power/rf_cntrl_timer_15_reg.rs":"28599f9cdfd011866c66eb59424abfcf94528d4073a8c6797079db4ded827bad","src/rfcu_power/rf_cntrl_timer_16_reg.rs":"38aeaa8e5b6be1a00bc24e67b0da3d78e04c5babe6e09543c8b1fcab41f66f9f","src/rfcu_power/rf_cntrl_timer_17_reg.rs":"24dd71c30d4da9594743cf56a9766374570e7adca548c8d83b625bad837d4c1b","src/rfcu_power/rf_cntrl_timer_18_reg.rs":"bb323a62c21cffb770742852d87ceda0570ea730d9494ae2771a2eed6df9523a","src/rfcu_power/rf_cntrl_timer_19_reg.rs":"af769cf38ec3ddc9f20c6c96e6cc916333d1ab515872e1252244f1e00955a422","src/rfcu_power/rf_cntrl_timer_1_reg.rs":"e0f8b6e6c695d43d1cf9f13bdbe426fe1a2b9a1e24580604fd75a8c1ac809083","src/rfcu_power/rf_cntrl_timer_20_reg.rs":"56f15e27c2310ff2cbf2a5afc73b61398ca8e698167e139bdda2ed90500befb1","src/rfcu_power/rf_cntrl_timer_21_reg.rs":"4621015f49bcc2837f682d39d8135bc6ca50f0653f182702958f5d8cff778f62","src/rfcu_power/rf_cntrl_timer_22_reg.rs":"0bb56ff1df0e46a59473855fd2a596e353ebdda3e2cef654b06ca333d4205688","src/rfcu_power/rf_cntrl_timer_23_reg.rs":"864ed90f48b7ac703d5548f087fde68eca941da0aeac2ae91b1df1d878ef554c","src/rfcu_power/rf_cntrl_timer_24_reg.rs":"634e73a2ad37b05c5e8e4ce569c2c0b9c364abdc11cef8b1cc3a1f14997bd94b","src/rfcu_power/rf_cntrl_timer_25_reg.rs":"6d2fd2e7c7906972c48ab5100ff3782e11c5897a9639c97a06b1d257f8c24cc3","src/rfcu_power/rf_cntrl_timer_26_reg.rs":"908424de000eb9421a246a9bcf09d63a6eefc0a9d823e1c9c04414fff0fbc036","src/rfcu_power/rf_cntrl_timer_27_reg.rs":"bc7192beb120f3918e482db19521ee37defc59843e901f793e539394e8ccc772","src/rfcu_power/rf_cntrl_timer_28_reg.rs":"22a9879d2ce7a485ecfb28c70395388fbf5c43cc0b7ba6e591b233b823ef09af","src/rfcu_power/rf_cntrl_timer_29_reg.rs":"cad1925720cc7f8fce2c5763551e71993f72fd4c95b3a72c3a5ecf84c37b60e0","src/rfcu_power/rf_cntrl_timer_2_reg.rs":"1a57b8d67681198ccb0270c7f0acf08f30437d2e435580092c5e03b85c4d035e","src/rfcu_power/rf_cntrl_timer_30_reg.rs":"fd76806a4fc8246c4db2bf7cfc7e67d0767d5f4ebc96bfd9d46a4442393f2d65","src/rfcu_power/rf_cntrl_timer_31_reg.rs":"0886e2f3a39440489a576c10771ffddcc51a8ff50856657dc550663fd4085bd5","src/rfcu_power/rf_cntrl_timer_3_reg.rs":"f04e10edeb7563d10b8248a7550d787c2a537a04b230e030bddc142df5b6a630","src/rfcu_power/rf_cntrl_timer_4_reg.rs":"08ae6b8aff900a19ab92e108bea43271bb3e746e44ad24313bc35a9cc42cfb9e","src/rfcu_power/rf_cntrl_timer_5_reg.rs":"1a26fc796b48e6b3dc4d409842043b2aed2217e827b2a26054aae617a44dbf20","src/rfcu_power/rf_cntrl_timer_6_reg.rs":"f68b1d540e9befbc705627bea8d08a52ea447db239ec520eb7e8094fc0cd3010","src/rfcu_power/rf_cntrl_timer_7_reg.rs":"2e0aee505c9d6bbd971d5f9d6dd35a57b3fa63cc72562b9393b3115bb6b0ae90","src/rfcu_power/rf_cntrl_timer_8_reg.rs":"8c555d32ca6b23b72885990087f58e21792da119cb75b07532f99aa6000aaa9d","src/rfcu_power/rf_cntrl_timer_9_reg.rs":"70c585d4765660f69c8a11cbec009574eb5415a8c82b3f7a6f1a2c9f4a373d66","src/rfcu_power/rf_enable_config0_reg.rs":"6bd095e45a20b79cd3c1ab27b368d35290749043cc674550bf56afcb65d63286","src/rfcu_power/rf_enable_config10_reg.rs":"4cde53a79010230801f692340826ebe3bd050b735e023f2489243ea84ba62ae0","src/rfcu_power/rf_enable_config11_reg.rs":"26626f1409db7d1058e8c75d2abb866b965eea6388ec999fe85886d4bcd94dcc","src/rfcu_power/rf_enable_config12_reg.rs":"7a4ac982777118430b97d28f1d844d9eb5198c4396f9e091e9751b236785af92","src/rfcu_power/rf_enable_config13_reg.rs":"c8e2ccb534f9d75674f36deb67c3c12bf2c658b3f5b9cad5480cfa8aa92da73a","src/rfcu_power/rf_enable_config14_reg.rs":"509b26e340d4c943fdc5600885dca762e43351349eaa0145f251d13d0b0a2f05","src/rfcu_power/rf_enable_config15_reg.rs":"1ab69456f692ecfcd0e8a6f8c279ecd5a7d7ed58321618606ef51676cd6befd3","src/rfcu_power/rf_enable_config16_reg.rs":"316fb6fa807319c261f3927c71344a3d5d387815054deee777e6dec505ab8a69","src/rfcu_power/rf_enable_config17_reg.rs":"71fea86b7c004beeb95002b3236f9cdb22b5c04e9fa093ff8f05507e143f0f18","src/rfcu_power/rf_enable_config18_reg.rs":"59d430021527d7c7b0ab3bc3f1b3f10dfbd2ade9be2d561ac49e29d9c15c690c","src/rfcu_power/rf_enable_config19_reg.rs":"141a8350131c66e1c63630f025948b508802b855b284b9a550b4f1a76080c634","src/rfcu_power/rf_enable_config1_reg.rs":"345262e1204752768533763c45e8c724af725b41edab71713cd3b189adc1f96b","src/rfcu_power/rf_enable_config20_reg.rs":"8aabe0a9d3656cb275de126ee8a94dc7cabc075fb814534a11c94672a71283cd","src/rfcu_power/rf_enable_config21_reg.rs":"65753f1b792ee8f263c734b83ed04aa9c23a8a60efc0b29fafa1811eeb662394","src/rfcu_power/rf_enable_config22_reg.rs":"c5c19381e45053cbf370417b9c7fbde5e8adfa6a3dcc86a811764b58eb28739f","src/rfcu_power/rf_enable_config23_reg.rs":"525f65825daf07460d2c13aedc8cdbede25754cadf43d9ad84a46b6e0585800b","src/rfcu_power/rf_enable_config24_reg.rs":"414d430b5dc2477823bd7c159b53171414eb25a79df0dd15dac852e96579a4c5","src/rfcu_power/rf_enable_config25_reg.rs":"4a980e8c1af19e66f1a0eed7af085fb2e48a1bd26661ed9ad80da4aab5287c1c","src/rfcu_power/rf_enable_config26_reg.rs":"9557c9535747dd170b2fc36b57fef9563ac024dddfb93549b1a0024647d178ec","src/rfcu_power/rf_enable_config27_reg.rs":"86d2ebb2055f6a1e7ba7bde0998d3e11d27ea655c9f8ca0c6325cbbae04addf4","src/rfcu_power/rf_enable_config28_reg.rs":"fdc0383c466853adb693efdedc97d4c60b7f3239b0fcfd2e218e2b80a9680ac7","src/rfcu_power/rf_enable_config29_reg.rs":"db203e2928b120a48040d3873d3cae47a48d86b9e8ba8d21c6bca042d12249ce","src/rfcu_power/rf_enable_config2_reg.rs":"e591fd42a0a4ba9c7b17aabf16206e981a21dd57e1903eea5f53e8628d04d17b","src/rfcu_power/rf_enable_config30_reg.rs":"b857a0764f9eff86306fb178665535948e85ffa9c7ad2391664fb380fe5341b2","src/rfcu_power/rf_enable_config31_reg.rs":"bd66c9e1e498dc1ae573f18acd608d1419e1e7d83272e5c21791ff403196a065","src/rfcu_power/rf_enable_config32_reg.rs":"3a1890188f1567443dbcf752ee568db7e6c99c2e682516ea4364fc8684c67f4c","src/rfcu_power/rf_enable_config33_reg.rs":"c33054f084652fc9dad354255f4af6d0e2931b829d126dba5283969c9af140e0","src/rfcu_power/rf_enable_config34_reg.rs":"802e42c1f670228d2fbf6563d644023723fa17a737002cdc937bbee9b7c7487c","src/rfcu_power/rf_enable_config35_reg.rs":"4f5390f1d33d9c20dc652c3e7665b61efcbc31748a80c41753b1ade9d0f7d6c5","src/rfcu_power/rf_enable_config36_reg.rs":"3d59b19bfcf2500044d41d17f0a77f6985001a67e9713b5ca3286c11a0f5195b","src/rfcu_power/rf_enable_config37_reg.rs":"1930a022d3f74fb1ad74f7bd84a87b876a6e3a7a8d0faa20b689d548892c4e88","src/rfcu_power/rf_enable_config38_reg.rs":"cc45cd5a25184ed0bdfab8360d8ddf8919f67632d330b2c048c4ffc141a8b30c","src/rfcu_power/rf_enable_config39_reg.rs":"492fc22901a16bb290c4a8b39bcaf2bc3cfca65048da9a7eb1b843a99504c75e","src/rfcu_power/rf_enable_config3_reg.rs":"8c015aa006b77e79090b7577265b563301967b5bd184d119a6aaa25281756377","src/rfcu_power/rf_enable_config40_reg.rs":"46ee710788d910abb88f0a64ff9ed4f15cc9639db2ac1c7dcfc1a200fa5660e3","src/rfcu_power/rf_enable_config41_reg.rs":"a307cf2f5ac765a76a42e8c57fbde4b11e678277d740bf027a8752f2533057ca","src/rfcu_power/rf_enable_config42_reg.rs":"5404c5a7d610e4c2ba8309ae6f1fed6c4bd99ebbba72bc3bbb55fb6d87eafc70","src/rfcu_power/rf_enable_config43_reg.rs":"451de2a422d4116e8686f59d79bfd3dd7592e7049587da640ffe62ace56eba39","src/rfcu_power/rf_enable_config44_reg.rs":"f25a9b08e097b6bb64896538d591c98de14863e94a0c110474da413729edbfbb","src/rfcu_power/rf_enable_config45_reg.rs":"0a28fa7738d0a9627411fd30093307d9b8ef3b1732d5ca21f78cbd1adbd960d6","src/rfcu_power/rf_enable_config46_reg.rs":"bdda9ec4631290ddbe39fdd7b5a2e0b7719c5644988f1a14fd36412b59e89c1d","src/rfcu_power/rf_enable_config4_reg.rs":"27f2ab1e83c629ffb7a07340b8fab62df0610166c38b9ffa3433032203f55d10","src/rfcu_power/rf_enable_config5_reg.rs":"35a8f0546540ba6a49cfb8edbe614d26947b63633753a3b5222a22b711629a1f","src/rfcu_power/rf_enable_config6_reg.rs":"fc2edf7f33a2d31ba12a8573384a2d8a5e29b39b75168814a77e1786d0e33788","src/rfcu_power/rf_enable_config7_reg.rs":"6b82789edb139dc3426d2c59b721935bc7ad4a851223f4f5a590dd048efdb248","src/rfcu_power/rf_enable_config8_reg.rs":"d9318903cab55cd47e730d098796ea471ee2e7ce9558c18a84bcb9c0b1ec9966","src/rfcu_power/rf_enable_config9_reg.rs":"e6ee4d6a8e35363087a7688b466c6d926bd7292899e29679e7de371d879033bd","src/rfcu_power/rf_port_en_reg.rs":"d8af85c0450d5936d9a854801a32b30dc0d0991cd02d0e22bba90e31da881bad","src/rfcu_power/rf_port_pol_reg.rs":"1e6484ce7d049a840aaa2ca10fc212cd9796c260d12327ce2439bb7b6b52f035","src/rfmon.rs":"b614363894a99e999ed94eec2fa71ba2b7205162c3b2876c21b82eeea27050a0","src/rfmon/rfmon_addr_reg.rs":"1261f193396a69f5d60592a3e44efe4f21d7a6479ea1040a15fee18777097197","src/rfmon/rfmon_crv_addr_reg.rs":"06c2dd26ff930df966392921468eb0c206f35af228c7ac9013445612e4c98d76","src/rfmon/rfmon_crv_len_reg.rs":"52056cb2fbae61e11f4035322f7a3e97d90c1f81e50315be8102866f80daa934","src/rfmon/rfmon_ctrl_reg.rs":"af339465df9ea03b32b80b2c92c5c9b5c8bf40fda4badf42d577ed97c370f419","src/rfmon/rfmon_len_reg.rs":"f34b024ad83919bb40d35ceb23d5b57afa9b96e98c28f2493b2b26cb32f916a9","src/rfmon/rfmon_stat_reg.rs":"9e74f70fcc5cee86d7417c8678a90d1a229e8a77759b2462442d02c40470d946","src/rtc.rs":"6f78820bbbc7f3751ae707997d96d0ac2c8a3e9fe9eaa5a8f31176a3a38f31cf","src/rtc/rtc_alarm_enable_reg.rs":"f977f20aaf564831f1b30bd60669245378e7cf865cf09e8b3a65c8531c78a7c5","src/rtc/rtc_calendar_alarm_reg.rs":"d7002878b713e8a0354fecb10f2902ace909d4501063e5323b0aa4fc83529305","src/rtc/rtc_calendar_reg.rs":"2cb3bf8b94595babd99cd9088e0e3917945d990db409f44c81ae233aa4e8f452","src/rtc/rtc_control_reg.rs":"b64450692c19bcd89bc2bca426b26382db08a5c563d72047fb20f07bdd34f14e","src/rtc/rtc_event_flags_reg.rs":"ca0f4faa688a4be709c27f9772d41d0ecdefc1dec536d4d4e9ea58badcac776a","src/rtc/rtc_hour_mode_reg.rs":"979b977c2fac70e422a3a62eb75cc520843965c73440cec8189b013f2d8a4294","src/rtc/rtc_interrupt_disable_reg.rs":"c370fbc8419a48982b69c939aec61e52e78785ff6531ea9e23ecbd6427150ab7","src/rtc/rtc_interrupt_enable_reg.rs":"69c08ad4da45038f9e43da148e11964ac9110ab1a113d840fb6217088a856b02","src/rtc/rtc_interrupt_mask_reg.rs":"350b7aa7180b0e4960769cdbf31b7008ee5d09329cbdb102e38003638794f59d","src/rtc/rtc_keep_rtc_reg.rs":"1052be4a2a5aeaf4f45cda94f2747861d0d0b62d54aab79924f67d80e065ba78","src/rtc/rtc_status_reg.rs":"cd8d55001c9921d2806927d9b7bedf9421e8b6e4a0a01b1bdebc0625fc894e17","src/rtc/rtc_time_alarm_reg.rs":"0e0825cb6602a3447de1257c07703fd8622fc0a4525ded749b829c51a0a6639a","src/rtc/rtc_time_reg.rs":"563e2f4ff25fc3ad65a2d748614f47559101c556e6ea33d42d27bc3ed8380ffc","src/spi.rs":"7bf033393bd38dabbec8b9130b2f92c6cc2de50331387a6fdbda05031b1d7bd4","src/spi/spi_clock_reg.rs":"870fc19ed9bd9ac9fc2120f2a4d84532c41ba54c2d40c2b8e0279769270beedc","src/spi/spi_config_reg.rs":"baebb6fc5834d1cc8b9411480695f67d16b2bb0b7418dd6bf5191b25d26036d2","src/spi/spi_cs_config_reg.rs":"68e1a65d402a0748050f5382f38c645dbb4952ac9812ae2491bae8cbc981f661","src/spi/spi_ctrl_reg.rs":"6020f1aae0715d4ee15aad016ac2a5dc8764c471900acaf73019d183579de2fb","src/spi/spi_fifo_config_reg.rs":"1f8457a771cfad96b78a3b6da440a9fd2800bd0fda9dfd348c7c6de0ff330192","src/spi/spi_fifo_high_reg.rs":"d3f2dc95187d0d32a9fa381a7ab78a3b25e5c9285019d14ccab4afff6845c541","src/spi/spi_fifo_read_reg.rs":"f747703935ec9e06eebae96efce73a6c986e653367538a02a8fdc4ec1169e324","src/spi/spi_fifo_status_reg.rs":"2b38ae0012b3c490f738bbf6958cede2a8d77e80a34a7f63556803705e7cc80c","src/spi/spi_fifo_write_reg.rs":"5c17c37662964948437dd0b80d8d29f5ec1f722bccabde8f238ba0f71f241cb1","src/spi/spi_irq_mask_reg.rs":"e5dd4c672af97fa54a0ce706f94774beff3d8ed57adcfec4814561e9dffaff31","src/spi/spi_status_reg.rs":"31ffc9a0cb9df98e53c31443ad0321d2c0c5c825202b50963312f678ad1cebda","src/spi/spi_txbuffer_force_h_reg.rs":"d074a32e46e0520b9b95f786a8f1b7bde12c9048faa8dec80a883df152c2f27f","src/spi/spi_txbuffer_force_l_reg.rs":"381ba89ee3e7a4cc4b4d55e54a5363ddeff62d69ca8872fb1b4751f41fcbc881","src/sys_tick.rs":"a84e0aa9390acaef3eadb676bcb253b65e5c9c8ce044eb29cd4301c6b4799b3d","src/sys_tick/calib.rs":"46f23350466a8a35b1fe0659724e80111936961c92a824e9259c3bee6afe849f","src/sys_tick/ctrl.rs":"cc4960ad376f7ab1d688ef44da231ff37a36b573efbd6154bc7231c238189698","src/sys_tick/load.rs":"5602549b2e77df1e4208de5f13e1aeea5c75454838c7ebcc889c0d4c9766decf","src/sys_tick/val.rs":"81d9ab97fbdd6139f87319829ce4da4d3b19c86d6fcde634c768463bf2fe386e","src/sys_wdog.rs":"9c1cf3426a2a0b048ecac62a6e1f4c3cc39f3d8a9d21025e1943168cc9a9558e","src/sys_wdog/watchdog_ctrl_reg.rs":"b26aca3a8552bb7f59b7137f4f5ddde5b55dde0fa524ca1f54d7b26833b2f7e1","src/sys_wdog/watchdog_reg.rs":"58b0d0e79ff3e19cac8563bd5c0d1d1e2d47f78d734c37160e995db4db7ae428","src/timer0.rs":"9188cc39f28238bb76966b2e5351d19c266eac0bca30e1908a5575bee351d110","src/timer0/pwm2_end_cycle.rs":"5458d622526da740010e617d87923c4afc30a2f75ddd5bdc645b16dfd5073bc9","src/timer0/pwm2_start_cycle.rs":"132bb062588e09532b29d4d48b2a473aa536c2136539465c41cd3cee893ceee9","src/timer0/pwm3_end_cycle.rs":"13a94fd3df69ba28410264409f446a285432ec9276d878be0a2a02da5a5fa359","src/timer0/pwm3_start_cycle.rs":"023b7a48ac4f1076e6570ae1f146359735d7d5ecf59f76a4eafb9dd73cccb13c","src/timer0/pwm4_end_cycle.rs":"8944d9f371b6a4cf2e677f3017700e861eeaa40ed075152c349ba6cf461ba07f","src/timer0/pwm4_start_cycle.rs":"9d63629337eb3cdaaf43736487640645679e1eaeb8ad5ea61c19915b9e5a881a","src/timer0/pwm5_end_cycle.rs":"54b43351a6cf42fe9a1283d813a5aa297fa85a3432fcb6b026db956a086045fb","src/timer0/pwm5_start_cycle.rs":"8ce1dac7e88b5aabb3940d5db7f58c6ef7b638e251b4cab885e66ed7da3f43a4","src/timer0/pwm6_end_cycle.rs":"004433be3a129152b07c0fb233c30ee01ef28141e211d461da2a8eca1bf52be1","src/timer0/pwm6_start_cycle.rs":"e6d3201460d164f88e936e9251c4b3af1ba9d5265532556bf807b7bb1372729a","src/timer0/pwm7_end_cycle.rs":"a945021ecfe11eebf0e870577c2ecedb38eb751b164a4c237bd033292a9cf255","src/timer0/pwm7_start_cycle.rs":"33ad1d92f03b6e55ef57e792c603751e5635850dcd70bef17e92dc3273e5ab57","src/timer0/timer0_ctrl_reg.rs":"e5fce45a11136a3130e42047f31402786fa46f0421a63a7fbef5af7f70a9d901","src/timer0/timer0_on_reg.rs":"b3e82db63df8693886468a5884a6e8112ab7bd26dc8fba160199f1b299b1e1a7","src/timer0/timer0_reload_m_reg.rs":"569940d15ea4e851fdea76a0627229537c30b8e3d062c48c7a2e8ad5b41ed552","src/timer0/timer0_reload_n_reg.rs":"85c827620132211e5ef9054dda3f436e9711adb61610f99fae7f13ca10fef939","src/timer0/triple_pwm_ctrl_reg.rs":"074fec2df3e03fc6e53fb7da89bd7a9f144b24fb9fa805310f1af4277f362324","src/timer0/triple_pwm_frequency.rs":"eb93c8015d375c3c0ea961a76e115a7fbcb19854e69d36b8a053c1ae2d144cc7","src/timer1.rs":"ddabc8b81ffec03f726c31991a97fd7379dea9bce41283ab785d85f45138fa4b","src/timer1/timer1_capcnt1_value_reg.rs":"898129048d481365e9042ab81b3b894ff17770494da29770fef502fc9aa36b19","src/timer1/timer1_capcnt2_value_reg.rs":"07a21ec0ce8e933bc30aa367b04826920061064a0aea21487ee00443c463c712","src/timer1/timer1_capture_reg.rs":"100318b4130805699440cd57867169978ea466d238d28cebaf5579b88534a34b","src/timer1/timer1_clr_event_reg.rs":"78e984f7efe7f0190a830588565734bfef3a73832042761c09acdec8faf01bad","src/timer1/timer1_ctrl_reg.rs":"c9f06947f426151f38aa9dea23cccd513b6bae185f7888bf6915940e5955b09d","src/timer1/timer1_status_reg.rs":"ac12d6d3eb9c67c1b85085c78b08252d05ff4bc0c6447a29dd66df0262239c96","src/uart.rs":"329978ad5163cc8b7c38010b92a102d17fca6763420218300d656dfb445429a7","src/uart/uart_ctr_high_reg.rs":"410d968615297068559b91e81a0b13f60b1b468d28fa477795605bf4ccd66b81","src/uart/uart_ctr_reg.rs":"8d18dcab10e6d9b59969ad9f1eb54c8a8b6fcdca6d17cfa71343b1de63a27966","src/uart/uart_dlf_reg.rs":"021481fb4910b3061c96afa3902c5fdedfc1e29791ff4c5d4266a3d125f3b723","src/uart/uart_dmasa_reg.rs":"692128de21e314538970cc1887df8cd16a7e39291ab8ae0f0893214af29b0224","src/uart/uart_far_reg.rs":"02295d63fd234c5070f4a730fc41a1283efdf3d8abbabccc05bc718be6c78ea9","src/uart/uart_htx_reg.rs":"1f88a99a8824c5b8fb6865cfc878d2a0025861528778326e176dc760f415f526","src/uart/uart_ier_dlh_reg.rs":"e13047353fd6d005b2025daa5ab48945ae39ac3190fda0195368345c10ee5504","src/uart/uart_iir_fcr_reg.rs":"b58d28cb0a43bdd77a496a29ebec8c18a25235229c123b129bb66c42a789dff4","src/uart/uart_lcr_reg.rs":"3d1c5c0e2286940d203767415813964856e7402b664d27d1378bfdb619dfd9ce","src/uart/uart_lsr_reg.rs":"3d47657f4615358a9d7b64bafcd09c59c64335abd7d8ca5850b36b1d31594825","src/uart/uart_mcr_reg.rs":"7f0f1c41de71a7a8ddb54290e2ab5238c7bc5639203c37044294ebb654561db9","src/uart/uart_msr_reg.rs":"e9a5156767e9ce487ecc4ddacf228343c4a046c81ef7fdabe30e25086ae73aec","src/uart/uart_rbr_thr_dll_reg.rs":"8e3f543bb71216bc5c05a65d9d079a90c734315f71835b9f53c71af1fd2e5d3d","src/uart/uart_rfl_reg.rs":"d370ba193a6b8479d1e109721da700c89e2e6296d417b5e24ce3e579e1b65c19","src/uart/uart_sbcr_reg.rs":"6da7fbddfac2b45fbf660a71ed2c38309d4bdd6abb70cf574daacdf4ab804068","src/uart/uart_scr_reg.rs":"00bfa1ad0be32caf82dff7f113d53d7d3e47dd0248fa2a939b5956f7682bd976","src/uart/uart_sdmam_reg.rs":"684e2ac397b9ee83607d9f504236e5ded4e3a2ddb2cd48e783d577d6942ce331","src/uart/uart_sfe_reg.rs":"73adf820bf91fea86f652c66087a90b5b6f7d8dcd6499252141513864376b4d7","src/uart/uart_srbr_sthr0_reg.rs":"cfe0ab24bae5b1e35601829a6ce7af47869b5bc8153a477824e441777484ad67","src/uart/uart_srbr_sthr10_reg.rs":"22c2445c3fdd86f09eae5285ca2e4e543c9553aa41ecf02cd44793c4cc442b51","src/uart/uart_srbr_sthr11_reg.rs":"1fd5a483b22de530b46a3efb7852410b54f81f1bedff9668337674fd59526faf","src/uart/uart_srbr_sthr12_reg.rs":"3689bdf455e991a9308e8b37fe700ab27341a94e46b6789b5afcc49e08d456bb","src/uart/uart_srbr_sthr13_reg.rs":"a4f882edeabfffd437f91b32f498f6ee4acd8b56a8b9e638caa2acf0464c7ef3","src/uart/uart_srbr_sthr14_reg.rs":"66e8b222dfb2be8a26ecbb6fb5e6d130dec313867370a7127ce4ec6af935e38b","src/uart/uart_srbr_sthr15_reg.rs":"9ba258568a7bec34b0b8995224842c8ae43872870c5c8f6b809a36e7b83cd362","src/uart/uart_srbr_sthr1_reg.rs":"41051bb3886e47b89a047aac82a0691c11183189ab0833f8371bb5138dd3e4dc","src/uart/uart_srbr_sthr2_reg.rs":"b55dee44a29ff25427e4470e0971c455b40d71a9f6e743a14a480b5dd1b2f28f","src/uart/uart_srbr_sthr3_reg.rs":"588404625b46e2b691ff08aee166a81d8fffc79f2d1cfe4cbd337b52cb80e343","src/uart/uart_srbr_sthr4_reg.rs":"37eed0489cbb46b59e60777df20e7b5390b262f8ea025a093955cfcbdfb5ac95","src/uart/uart_srbr_sthr5_reg.rs":"80e1d3220a3ccb8639d1c8fd8fa0761bd062bcaaa5df047e68ea4cd51aca5225","src/uart/uart_srbr_sthr6_reg.rs":"1c349f022c5b89ea946a14eb232df04b2eed25413cb7f241e0c2ad38b68eade5","src/uart/uart_srbr_sthr7_reg.rs":"8738357dcd2cadcda0d43376ef4223accb5c424f478c3c544006c604038501a4","src/uart/uart_srbr_sthr8_reg.rs":"173d0fb8da1c416963ed81a41e02b956fd0792d80286450b5b68c49a7754a67f","src/uart/uart_srbr_sthr9_reg.rs":"2dd2d66523cf5336ef169b7fc789e3f3272a34333ed23b1e502002a4505dba72","src/uart/uart_srr_reg.rs":"c6d8ca49984c68065495e3108c3aab1e4a74bf7fde9abfca4e50dc677be2d6e2","src/uart/uart_srt_reg.rs":"d3fe4068c2bc82fde38f4fb4a063243280fae1798298649723de3da342f90324","src/uart/uart_srts_reg.rs":"ff3335598bd67bad1486b43c59bf68c75fe47cfe9c1091d6551dcdf3811f4013","src/uart/uart_stet_reg.rs":"8baf6737449af6fecbdc7420c9b9cb69a1f800544b6c42bae0b19775987b1c15","src/uart/uart_tfl_reg.rs":"53b83dfecc7a4f45a095978b2fcb6a07ccf9cdd271d596ff7b4ac1837985cc7a","src/uart/uart_ucv_high_reg.rs":"e729fcede163acb8ccf7e7168ae2d615d7fe0d8dfcf61b97f00710d53e972388","src/uart/uart_ucv_reg.rs":"dc74a237c4abce3442845ffc57e59e004845cf14b79e477c3dd32ef8f2ac6d1d","src/uart/uart_usr_reg.rs":"a84ba3dad7d53bda0ca699b9df9bf071fce0fd2c42de49679344cc04b3aacdbf","src/uart2.rs":"0236f0a1a45a496513956bf1f68ee28c56bc4571fea84da273714dab499108fa","src/uart2/uart2_ctr_high_reg.rs":"261657e7ab49fdc4c072e7e4f41a702856b558b37cdc1ec74295715283bc1425","src/uart2/uart2_ctr_reg.rs":"9caf08403a8a5a7148f135c5feb4dd50473bbe65368b9261179c8005c3ffc136","src/uart2/uart2_dlf_reg.rs":"91ded9937bb1afeddf869e6f3d4589b0def0f2a68f60be81aa9a73e2fd93d094","src/uart2/uart2_dmasa_reg.rs":"90d263fa2881f09c0991ad71bdab948e18319ab297532f068c420f2bbff39bd5","src/uart2/uart2_far_reg.rs":"91bfee45c6326a26e29ccd93c774bbb4696029768458558723e4fd32b161c18a","src/uart2/uart2_htx_reg.rs":"a7e1956577e5ed6306b173cd89c36e70355c57975027c8900723e05ba37aca2c","src/uart2/uart2_ier_dlh_reg.rs":"81e191fa4a62d31f8f96c00e2067cafd669a5416eb0ba74cd64a2a98df23a2fd","src/uart2/uart2_iir_fcr_reg.rs":"0f38c3421c083d6725e1b728e4e921407e2c5c9eb581cc0a2c687c8cf6149b1e","src/uart2/uart2_lcr_reg.rs":"6882c54f0875c444e2a25310ec9d7e1fb7fd51b7bfe00a9182fef3cc76c9c0eb","src/uart2/uart2_lsr_reg.rs":"25e568ca51f5bce6ec48c37c8d352c06af096308aba214348d86da9bf1a205c0","src/uart2/uart2_mcr_reg.rs":"8e742080a1d728fddf410b97847472d9437f7e0b5694d4c3967c2d83d4e1e951","src/uart2/uart2_rbr_thr_dll_reg.rs":"20097523cf6e44af3ec78ad7fe91089ea2853e8ca9a68f0eee36ea6b7ae83768","src/uart2/uart2_rfl_reg.rs":"9e1d851093dc7870e1c93e813902651fc802c165de224353bce43939fe4f5f6c","src/uart2/uart2_sbcr_reg.rs":"b24f4509b83deea951d941a2faf954cb3b28015379187e50ecf48d8ba4dca6d5","src/uart2/uart2_scr_reg.rs":"d8f3a3f2a88abdf768833ea40a104ee91a5c8e63f4c9b9e6a5553de9b01dedcb","src/uart2/uart2_sdmam_reg.rs":"83fa72c5804055b9b345f957e4ce3a79905058f9bc213163bd8701f7ed49ce91","src/uart2/uart2_sfe_reg.rs":"e731dd40b9546b289993492beba83fc2d621d00f088a0db4e9acd4d7fcd601fe","src/uart2/uart2_srbr_sthr0_reg.rs":"1fecdeee9dae9f2c135f3ae48de435bcaf3158d91174057b059f1262286067b1","src/uart2/uart2_srbr_sthr10_reg.rs":"ffe6eab842ed0a9d8fe8a72f92f2b8ac99d8e3bda920acc43b45a8d09a727019","src/uart2/uart2_srbr_sthr11_reg.rs":"38e5af6e7f3a649c8871a428ad910d1e2b0e155f208d98672a776934a1b01fa3","src/uart2/uart2_srbr_sthr12_reg.rs":"304f6f7e60e50f0f38991d0d1dc058860e441efeee02e5a217eb807e78935ef2","src/uart2/uart2_srbr_sthr13_reg.rs":"169c5fbb349c24b438b14242a8724dc6aeaf44ea61e3651bef3acfee322e490d","src/uart2/uart2_srbr_sthr14_reg.rs":"cf70ff60b5123547e82c0ccda9252f1dd2463227db246af58700a777af2e1f13","src/uart2/uart2_srbr_sthr15_reg.rs":"e910c696cf975f74227701cff477b0e07e81ed28dd287f44a3e0b2b861117c56","src/uart2/uart2_srbr_sthr1_reg.rs":"f28a46e761f70d0b15e04b19f8e4cac9cf37008847f415a093976c6ef2abeb76","src/uart2/uart2_srbr_sthr2_reg.rs":"1256501cb5a069af38167b2812ac834319fe4ccae905e971ff318b2c7f368b2a","src/uart2/uart2_srbr_sthr3_reg.rs":"b5037beb9f8fe4926271d23eda3cb2c49dc405c459ba074ad29d74ecf9cf9ab5","src/uart2/uart2_srbr_sthr4_reg.rs":"54cc6ec28241945d807ffcc1875ad798321ea6cb6315c8f6e54461fd76a5fb2c","src/uart2/uart2_srbr_sthr5_reg.rs":"04668c7b4dbed2448b253f53bf5786d65492d8a95899e24032e96f8e2bc4cf39","src/uart2/uart2_srbr_sthr6_reg.rs":"37357b397cfec8066eb038d47000c0a77ca4d71958f189a44641276daa017b8c","src/uart2/uart2_srbr_sthr7_reg.rs":"d0c4679585904546606db31b657fde901c11948e02132209af73f7c137262584","src/uart2/uart2_srbr_sthr8_reg.rs":"d4d69f9ab17a4fb79ff93848eee2b80c824a195a83cdc19c6937fd7fb83bead0","src/uart2/uart2_srbr_sthr9_reg.rs":"a8dee51c37f1678bc5613d9d89bf9d7e8004f4dd84d7f9203fa454fd88b4837c","src/uart2/uart2_srr_reg.rs":"fc43ffd7df571d29bbd54667267877d9577052d194af47d54e21e7512e379e33","src/uart2/uart2_srt_reg.rs":"cc49cad3aa8077b047b6edccafa05b8e1691117d28e39f1d7c23ffc0bb41df6d","src/uart2/uart2_stet_reg.rs":"57dea6643013e22a18d9d4e2689b0cfd0018807b88f0697113ae16326b38fce2","src/uart2/uart2_tfl_reg.rs":"44e9bdd924ff83d058e397a2d31013615ef0564659fa6578ba5b51eaa9ffee54","src/uart2/uart2_ucv_high_reg.rs":"fe5f52fdd7121caccdb59a72cc9b7f90780f3b35bd8161284908925773f33588","src/uart2/uart2_ucv_reg.rs":"57fd4fab3038cdcc03e396944aa971df219b66bea387c7f92fd423445b613ac9","src/uart2/uart2_usr_reg.rs":"016dc4cb8080ce7d2a65bf8bd130b2b60e2b5401552e8301a6626133e9f9a531","src/wkup.rs":"e9404aa25d5547724ec57fffd6e9700e777afca9a91f09688134da88dd054ece","src/wkup/wkup2_pol_gpio_reg.rs":"3973f7e46ffe04b74ceaf10e07cb3728d93ddfd41be7e8707f91472cfe04ebba","src/wkup/wkup2_select_gpio_reg.rs":"c7f1b45a40ef80753a8d04216730e3dc78481018e48bfe5e89b003385f88eb69","src/wkup/wkup_compare_reg.rs":"9c11911f166c5218ec266f25c68155367c0403d585d63072e8e47786bb04ac6c","src/wkup/wkup_counter_reg.rs":"ae9e8d7cf878dbde52e09f56756b27fd9694782185614711ea190bf82225ca78","src/wkup/wkup_ctrl_reg.rs":"46978c67727e4caec664584d9f9399d3a694adcd99465dd2a224f5a87b78b803","src/wkup/wkup_irq_status_reg.rs":"a2f51797138e5efd37aa35d8cdb9dec6cd2ba4c1e32ee8bf99721797349fdd22","src/wkup/wkup_pol_gpio_reg.rs":"69f61f396220a010412aeb63c15185d8ea062cccb54beb281ac835c9a2fdbbfa","src/wkup/wkup_select_gpio_reg.rs":"0b25e91fc8217e6f3f04b8c1eb0eb66f4312602fa7bc901f717c1a6efb093777","update.sh":"104ef7c51c299d12c4a5993c0ddcefe0339426a0acc69aa62d966c87e167a936"},"package":"84c2c298c1f776661aca4e6bc2d6fc27bdd3b19ad89e897b9930d84bf6c50377"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/da14531/Cargo.toml b/bitbox02-bt/vendor/da14531/Cargo.toml new file mode 100644 index 0000000..cd8b840 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/Cargo.toml @@ -0,0 +1,49 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "da14531" +version = "0.2.1" +description = "Peripheral access crate for the DA14531 microcontroller" +documentation = "https://docs.rs/da14531" +readme = "README.md" +keywords = [ + "cortex-m", + "svd2rust", + "embedded", + "da14531", + "no_std", +] +categories = [ + "embedded", + "hardware-support", + "no-std", +] +license = "MIT" +repository = "https://github.com/rapitag/da14531" +resolver = "2" + +[package.metadata.docs.rs] +targets = ["thumbv6m-none-eabi"] + +[dependencies.cortex-m] +version = "0.7" + +[dependencies.cortex-m-rt] +version = "0.7" +optional = true + +[dependencies.vcell] +version = "0.1" + +[features] +rt = ["cortex-m-rt/device"] diff --git a/bitbox02-bt/vendor/da14531/README.md b/bitbox02-bt/vendor/da14531/README.md new file mode 100644 index 0000000..8d9dc58 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/README.md @@ -0,0 +1,11 @@ +# DA14531 Peripheral Access Crate + +[![Crates.io](https://img.shields.io/crates/d/da14531.svg)](https://crates.io/crates/da14531) +[![Crates.io](https://img.shields.io/crates/v/da14531.svg)](https://crates.io/crates/da14531) +[![Released API docs](https://docs.rs/da14531/badge.svg)](https://docs.rs/da14531) + +This repository provides a Rust peripheral access crates or "PAC" for the Dialog DA14531 +microcontroller, providing a safe API to that device's peripherals using +[svd2rust]. + +[svd2rust]: https://github.com/rust-embedded/svd2rust diff --git a/bitbox02-bt/vendor/da14531/src/adplldig.rs b/bitbox02-bt/vendor/da14531/src/adplldig.rs new file mode 100644 index 0000000..cf371bf --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig.rs @@ -0,0 +1,214 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - "] + pub adpll_attr_ctrl_reg: crate::Reg, + #[doc = "0x04 - "] + pub adpll_cn_ctrl_reg: crate::Reg, + #[doc = "0x08 - "] + pub adpll_fif_ctrl1_reg: crate::Reg, + #[doc = "0x0c - "] + pub adpll_fif_ctrl2_reg: crate::Reg, + #[doc = "0x10 - "] + pub adpll_kdco_cal_ctrl1_reg: + crate::Reg, + #[doc = "0x14 - "] + pub adpll_kdco_cal_ctrl2_reg: + crate::Reg, + #[doc = "0x18 - "] + pub adpll_kdtctdc_cal_ctrl1_reg: + crate::Reg, + #[doc = "0x1c - "] + pub adpll_kdtctdc_cal_ctrl2_reg: + crate::Reg, + #[doc = "0x20 - "] + pub adpll_dcoamp_cal_ctrl_reg: + crate::Reg, + #[doc = "0x24 - "] + pub adpll_txmod_ctrl_reg: crate::Reg, + #[doc = "0x28 - "] + pub adpll_sdmod_ctrl_reg: crate::Reg, + #[doc = "0x2c - "] + pub adpll_lf_ctrl1_reg: crate::Reg, + #[doc = "0x30 - "] + pub adpll_lf_ctrl2_reg: crate::Reg, + #[doc = "0x34 - "] + pub adpll_ana_ctrl_reg: crate::Reg, + #[doc = "0x38 - "] + pub adpll_div_ctrl_reg: crate::Reg, + #[doc = "0x3c - "] + pub adpll_init_ctrl_reg: crate::Reg, + #[doc = "0x40 - "] + pub adpll_fsm_ctrl_reg: crate::Reg, + #[doc = "0x44 - "] + pub adpll_mon_ctrl_reg: crate::Reg, + #[doc = "0x48 - "] + pub adpll_misc_ctrl_reg: crate::Reg, + _reserved19: [u8; 0x04], + #[doc = "0x50 - "] + pub adpll_overrule_ctrl1_reg: + crate::Reg, + #[doc = "0x54 - "] + pub adpll_overrule_ctrl2_reg: + crate::Reg, + #[doc = "0x58 - "] + pub adpll_overrule_ctrl3_reg: + crate::Reg, + #[doc = "0x5c - "] + pub adpll_rfpt_ctrl_reg: crate::Reg, + #[doc = "0x60 - "] + pub adpll_anatst_ctrl_reg: crate::Reg, + #[doc = "0x64 - "] + pub adpll_acc_ctrl_reg: crate::Reg, + _reserved25: [u8; 0x14], + #[doc = "0x7c - "] + pub adpll_freqmeas_rd_reg: crate::Reg, + #[doc = "0x80 - "] + pub adpll_dco_rd_reg: crate::Reg, + #[doc = "0x84 - "] + pub adpll_kdco_rd_reg: crate::Reg, + #[doc = "0x88 - "] + pub adpll_kdtc_rd_reg: crate::Reg, + #[doc = "0x8c - "] + pub adpll_tunestate_rd_reg: crate::Reg, + #[doc = "0x90 - "] + pub adpll_pllfcwdt_rd_reg: crate::Reg, + #[doc = "0x94 - "] + pub adpll_anatst_rd_reg: crate::Reg, +} +#[doc = "ADPLL_ACC_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_ACC_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_acc_ctrl_reg; +#[doc = "ADPLL_ANATST_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_ANATST_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_anatst_ctrl_reg; +#[doc = "ADPLL_ANATST_RD_REG register accessor: an alias for `Reg`"] +pub type ADPLL_ANATST_RD_REG = crate::Reg; +#[doc = ""] +pub mod adpll_anatst_rd_reg; +#[doc = "ADPLL_ANA_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_ANA_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_ana_ctrl_reg; +#[doc = "ADPLL_ATTR_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_ATTR_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_attr_ctrl_reg; +#[doc = "ADPLL_CN_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_CN_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_cn_ctrl_reg; +#[doc = "ADPLL_DCOAMP_CAL_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_DCOAMP_CAL_CTRL_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_dcoamp_cal_ctrl_reg; +#[doc = "ADPLL_DCO_RD_REG register accessor: an alias for `Reg`"] +pub type ADPLL_DCO_RD_REG = crate::Reg; +#[doc = ""] +pub mod adpll_dco_rd_reg; +#[doc = "ADPLL_DIV_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_DIV_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_div_ctrl_reg; +#[doc = "ADPLL_FIF_CTRL1_REG register accessor: an alias for `Reg`"] +pub type ADPLL_FIF_CTRL1_REG = crate::Reg; +#[doc = ""] +pub mod adpll_fif_ctrl1_reg; +#[doc = "ADPLL_FIF_CTRL2_REG register accessor: an alias for `Reg`"] +pub type ADPLL_FIF_CTRL2_REG = crate::Reg; +#[doc = ""] +pub mod adpll_fif_ctrl2_reg; +#[doc = "ADPLL_FREQMEAS_RD_REG register accessor: an alias for `Reg`"] +pub type ADPLL_FREQMEAS_RD_REG = crate::Reg; +#[doc = ""] +pub mod adpll_freqmeas_rd_reg; +#[doc = "ADPLL_FSM_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_FSM_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_fsm_ctrl_reg; +#[doc = "ADPLL_INIT_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_INIT_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_init_ctrl_reg; +#[doc = "ADPLL_KDCO_CAL_CTRL1_REG register accessor: an alias for `Reg`"] +pub type ADPLL_KDCO_CAL_CTRL1_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_kdco_cal_ctrl1_reg; +#[doc = "ADPLL_KDCO_CAL_CTRL2_REG register accessor: an alias for `Reg`"] +pub type ADPLL_KDCO_CAL_CTRL2_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_kdco_cal_ctrl2_reg; +#[doc = "ADPLL_KDCO_RD_REG register accessor: an alias for `Reg`"] +pub type ADPLL_KDCO_RD_REG = crate::Reg; +#[doc = ""] +pub mod adpll_kdco_rd_reg; +#[doc = "ADPLL_KDTCTDC_CAL_CTRL1_REG register accessor: an alias for `Reg`"] +pub type ADPLL_KDTCTDC_CAL_CTRL1_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_kdtctdc_cal_ctrl1_reg; +#[doc = "ADPLL_KDTCTDC_CAL_CTRL2_REG register accessor: an alias for `Reg`"] +pub type ADPLL_KDTCTDC_CAL_CTRL2_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_kdtctdc_cal_ctrl2_reg; +#[doc = "ADPLL_KDTC_RD_REG register accessor: an alias for `Reg`"] +pub type ADPLL_KDTC_RD_REG = crate::Reg; +#[doc = ""] +pub mod adpll_kdtc_rd_reg; +#[doc = "ADPLL_LF_CTRL1_REG register accessor: an alias for `Reg`"] +pub type ADPLL_LF_CTRL1_REG = crate::Reg; +#[doc = ""] +pub mod adpll_lf_ctrl1_reg; +#[doc = "ADPLL_LF_CTRL2_REG register accessor: an alias for `Reg`"] +pub type ADPLL_LF_CTRL2_REG = crate::Reg; +#[doc = ""] +pub mod adpll_lf_ctrl2_reg; +#[doc = "ADPLL_MISC_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_MISC_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_misc_ctrl_reg; +#[doc = "ADPLL_MON_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_MON_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_mon_ctrl_reg; +#[doc = "ADPLL_OVERRULE_CTRL1_REG register accessor: an alias for `Reg`"] +pub type ADPLL_OVERRULE_CTRL1_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_overrule_ctrl1_reg; +#[doc = "ADPLL_OVERRULE_CTRL2_REG register accessor: an alias for `Reg`"] +pub type ADPLL_OVERRULE_CTRL2_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_overrule_ctrl2_reg; +#[doc = "ADPLL_OVERRULE_CTRL3_REG register accessor: an alias for `Reg`"] +pub type ADPLL_OVERRULE_CTRL3_REG = + crate::Reg; +#[doc = ""] +pub mod adpll_overrule_ctrl3_reg; +#[doc = "ADPLL_PLLFCWDT_RD_REG register accessor: an alias for `Reg`"] +pub type ADPLL_PLLFCWDT_RD_REG = crate::Reg; +#[doc = ""] +pub mod adpll_pllfcwdt_rd_reg; +#[doc = "ADPLL_RFPT_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_RFPT_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_rfpt_ctrl_reg; +#[doc = "ADPLL_SDMOD_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_SDMOD_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_sdmod_ctrl_reg; +#[doc = "ADPLL_TUNESTATE_RD_REG register accessor: an alias for `Reg`"] +pub type ADPLL_TUNESTATE_RD_REG = crate::Reg; +#[doc = ""] +pub mod adpll_tunestate_rd_reg; +#[doc = "ADPLL_TXMOD_CTRL_REG register accessor: an alias for `Reg`"] +pub type ADPLL_TXMOD_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod adpll_txmod_ctrl_reg; diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_acc_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_acc_ctrl_reg.rs new file mode 100644 index 0000000..74a7c32 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_acc_ctrl_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `ADPLL_ACC_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_ACC_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `EN_CMF_AVG` reader - "] +pub struct EN_CMF_AVG_R(crate::FieldReader); +impl EN_CMF_AVG_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EN_CMF_AVG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EN_CMF_AVG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EN_CMF_AVG` writer - "] +pub struct EN_CMF_AVG_W<'a> { + w: &'a mut W, +} +impl<'a> EN_CMF_AVG_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `CLIP_MOD_TUNE_0_TX` reader - "] +pub struct CLIP_MOD_TUNE_0_TX_R(crate::FieldReader); +impl CLIP_MOD_TUNE_0_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CLIP_MOD_TUNE_0_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLIP_MOD_TUNE_0_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CLIP_MOD_TUNE_0_TX` writer - "] +pub struct CLIP_MOD_TUNE_0_TX_W<'a> { + w: &'a mut W, +} +impl<'a> CLIP_MOD_TUNE_0_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1fff << 16)) | ((value as u32 & 0x1fff) << 16); + self.w + } +} +#[doc = "Field `CLIP_MOD_TUNE_0_RX` reader - "] +pub struct CLIP_MOD_TUNE_0_RX_R(crate::FieldReader); +impl CLIP_MOD_TUNE_0_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CLIP_MOD_TUNE_0_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLIP_MOD_TUNE_0_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CLIP_MOD_TUNE_0_RX` writer - "] +pub struct CLIP_MOD_TUNE_0_RX_W<'a> { + w: &'a mut W, +} +impl<'a> CLIP_MOD_TUNE_0_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1fff) | (value as u32 & 0x1fff); + self.w + } +} +impl R { + #[doc = "Bit 31"] + #[inline(always)] + pub fn en_cmf_avg(&self) -> EN_CMF_AVG_R { + EN_CMF_AVG_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bits 16:28"] + #[inline(always)] + pub fn clip_mod_tune_0_tx(&self) -> CLIP_MOD_TUNE_0_TX_R { + CLIP_MOD_TUNE_0_TX_R::new(((self.bits >> 16) & 0x1fff) as u16) + } + #[doc = "Bits 0:12"] + #[inline(always)] + pub fn clip_mod_tune_0_rx(&self) -> CLIP_MOD_TUNE_0_RX_R { + CLIP_MOD_TUNE_0_RX_R::new((self.bits & 0x1fff) as u16) + } +} +impl W { + #[doc = "Bit 31"] + #[inline(always)] + pub fn en_cmf_avg(&mut self) -> EN_CMF_AVG_W { + EN_CMF_AVG_W { w: self } + } + #[doc = "Bits 16:28"] + #[inline(always)] + pub fn clip_mod_tune_0_tx(&mut self) -> CLIP_MOD_TUNE_0_TX_W { + CLIP_MOD_TUNE_0_TX_W { w: self } + } + #[doc = "Bits 0:12"] + #[inline(always)] + pub fn clip_mod_tune_0_rx(&mut self) -> CLIP_MOD_TUNE_0_RX_W { + CLIP_MOD_TUNE_0_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_acc_ctrl_reg](index.html) module"] +pub struct ADPLL_ACC_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_ACC_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_acc_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_ACC_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_acc_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_ACC_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_ACC_CTRL_REG to value 0x7fff_ffff"] +impl crate::Resettable for ADPLL_ACC_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7fff_ffff + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_ana_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_ana_ctrl_reg.rs new file mode 100644 index 0000000..e2be3e9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_ana_ctrl_reg.rs @@ -0,0 +1,637 @@ +#[doc = "Register `ADPLL_ANA_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_ANA_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DTC_LDO_DMY` reader - "] +pub struct DTC_LDO_DMY_R(crate::FieldReader); +impl DTC_LDO_DMY_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DTC_LDO_DMY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DTC_LDO_DMY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DTC_LDO_DMY` writer - "] +pub struct DTC_LDO_DMY_W<'a> { + w: &'a mut W, +} +impl<'a> DTC_LDO_DMY_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 27)) | ((value as u32 & 3) << 27); + self.w + } +} +#[doc = "Field `VPASETTLE` reader - "] +pub struct VPASETTLE_R(crate::FieldReader); +impl VPASETTLE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + VPASETTLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for VPASETTLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `VPASETTLE` writer - "] +pub struct VPASETTLE_W<'a> { + w: &'a mut W, +} +impl<'a> VPASETTLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 24)) | ((value as u32 & 3) << 24); + self.w + } +} +#[doc = "Field `TDC_OFFSET` reader - "] +pub struct TDC_OFFSET_R(crate::FieldReader); +impl TDC_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TDC_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TDC_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TDC_OFFSET` writer - "] +pub struct TDC_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> TDC_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 16)) | ((value as u32 & 0x3f) << 16); + self.w + } +} +#[doc = "Field `DTC_EN` reader - "] +pub struct DTC_EN_R(crate::FieldReader); +impl DTC_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DTC_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DTC_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DTC_EN` writer - "] +pub struct DTC_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DTC_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `DTCOFFSET` reader - "] +pub struct DTCOFFSET_R(crate::FieldReader); +impl DTCOFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DTCOFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DTCOFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DTCOFFSET` writer - "] +pub struct DTCOFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> DTCOFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 8)) | ((value as u32 & 0x7f) << 8); + self.w + } +} +#[doc = "Field `TGLDETEN` reader - "] +pub struct TGLDETEN_R(crate::FieldReader); +impl TGLDETEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TGLDETEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TGLDETEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TGLDETEN` writer - "] +pub struct TGLDETEN_W<'a> { + w: &'a mut W, +} +impl<'a> TGLDETEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `EN_CKDCOMOD` reader - "] +pub struct EN_CKDCOMOD_R(crate::FieldReader); +impl EN_CKDCOMOD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EN_CKDCOMOD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EN_CKDCOMOD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EN_CKDCOMOD` writer - "] +pub struct EN_CKDCOMOD_W<'a> { + w: &'a mut W, +} +impl<'a> EN_CKDCOMOD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `INV_CKDCOMOD` reader - "] +pub struct INV_CKDCOMOD_R(crate::FieldReader); +impl INV_CKDCOMOD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INV_CKDCOMOD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INV_CKDCOMOD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INV_CKDCOMOD` writer - "] +pub struct INV_CKDCOMOD_W<'a> { + w: &'a mut W, +} +impl<'a> INV_CKDCOMOD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `INV_CKPHV` reader - "] +pub struct INV_CKPHV_R(crate::FieldReader); +impl INV_CKPHV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INV_CKPHV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INV_CKPHV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INV_CKPHV` writer - "] +pub struct INV_CKPHV_W<'a> { + w: &'a mut W, +} +impl<'a> INV_CKPHV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `INV_CKTDC` reader - "] +pub struct INV_CKTDC_R(crate::FieldReader); +impl INV_CKTDC_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INV_CKTDC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INV_CKTDC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INV_CKTDC` writer - "] +pub struct INV_CKTDC_W<'a> { + w: &'a mut W, +} +impl<'a> INV_CKTDC_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `TDC_INV` reader - "] +pub struct TDC_INV_R(crate::FieldReader); +impl TDC_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TDC_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TDC_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TDC_INV` writer - "] +pub struct TDC_INV_W<'a> { + w: &'a mut W, +} +impl<'a> TDC_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `TDC_CKVIN_EN` reader - "] +pub struct TDC_CKVIN_EN_R(crate::FieldReader); +impl TDC_CKVIN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TDC_CKVIN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TDC_CKVIN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TDC_CKVIN_EN` writer - "] +pub struct TDC_CKVIN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TDC_CKVIN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `TDC_DTCIN_EN` reader - "] +pub struct TDC_DTCIN_EN_R(crate::FieldReader); +impl TDC_DTCIN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TDC_DTCIN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TDC_DTCIN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TDC_DTCIN_EN` writer - "] +pub struct TDC_DTCIN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TDC_DTCIN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bits 27:28"] + #[inline(always)] + pub fn dtc_ldo_dmy(&self) -> DTC_LDO_DMY_R { + DTC_LDO_DMY_R::new(((self.bits >> 27) & 3) as u8) + } + #[doc = "Bits 24:25"] + #[inline(always)] + pub fn vpasettle(&self) -> VPASETTLE_R { + VPASETTLE_R::new(((self.bits >> 24) & 3) as u8) + } + #[doc = "Bits 16:21"] + #[inline(always)] + pub fn tdc_offset(&self) -> TDC_OFFSET_R { + TDC_OFFSET_R::new(((self.bits >> 16) & 0x3f) as u8) + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn dtc_en(&self) -> DTC_EN_R { + DTC_EN_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bits 8:14"] + #[inline(always)] + pub fn dtcoffset(&self) -> DTCOFFSET_R { + DTCOFFSET_R::new(((self.bits >> 8) & 0x7f) as u8) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn tgldeten(&self) -> TGLDETEN_R { + TGLDETEN_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn en_ckdcomod(&self) -> EN_CKDCOMOD_R { + EN_CKDCOMOD_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn inv_ckdcomod(&self) -> INV_CKDCOMOD_R { + INV_CKDCOMOD_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn inv_ckphv(&self) -> INV_CKPHV_R { + INV_CKPHV_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn inv_cktdc(&self) -> INV_CKTDC_R { + INV_CKTDC_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn tdc_inv(&self) -> TDC_INV_R { + TDC_INV_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn tdc_ckvin_en(&self) -> TDC_CKVIN_EN_R { + TDC_CKVIN_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn tdc_dtcin_en(&self) -> TDC_DTCIN_EN_R { + TDC_DTCIN_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 27:28"] + #[inline(always)] + pub fn dtc_ldo_dmy(&mut self) -> DTC_LDO_DMY_W { + DTC_LDO_DMY_W { w: self } + } + #[doc = "Bits 24:25"] + #[inline(always)] + pub fn vpasettle(&mut self) -> VPASETTLE_W { + VPASETTLE_W { w: self } + } + #[doc = "Bits 16:21"] + #[inline(always)] + pub fn tdc_offset(&mut self) -> TDC_OFFSET_W { + TDC_OFFSET_W { w: self } + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn dtc_en(&mut self) -> DTC_EN_W { + DTC_EN_W { w: self } + } + #[doc = "Bits 8:14"] + #[inline(always)] + pub fn dtcoffset(&mut self) -> DTCOFFSET_W { + DTCOFFSET_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn tgldeten(&mut self) -> TGLDETEN_W { + TGLDETEN_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn en_ckdcomod(&mut self) -> EN_CKDCOMOD_W { + EN_CKDCOMOD_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn inv_ckdcomod(&mut self) -> INV_CKDCOMOD_W { + INV_CKDCOMOD_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn inv_ckphv(&mut self) -> INV_CKPHV_W { + INV_CKPHV_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn inv_cktdc(&mut self) -> INV_CKTDC_W { + INV_CKTDC_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn tdc_inv(&mut self) -> TDC_INV_W { + TDC_INV_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn tdc_ckvin_en(&mut self) -> TDC_CKVIN_EN_W { + TDC_CKVIN_EN_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn tdc_dtcin_en(&mut self) -> TDC_DTCIN_EN_W { + TDC_DTCIN_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_ana_ctrl_reg](index.html) module"] +pub struct ADPLL_ANA_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_ANA_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_ana_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_ANA_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_ana_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_ANA_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_ANA_CTRL_REG to value 0x0215_807b"] +impl crate::Resettable for ADPLL_ANA_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0215_807b + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_ctrl_reg.rs new file mode 100644 index 0000000..bb7c581 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_ctrl_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `ADPLL_ANATST_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_ANATST_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ANATSTSPARE` reader - "] +pub struct ANATSTSPARE_R(crate::FieldReader); +impl ANATSTSPARE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ANATSTSPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ANATSTSPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ANATSTSPARE` writer - "] +pub struct ANATSTSPARE_W<'a> { + w: &'a mut W, +} +impl<'a> ANATSTSPARE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xffff << 16)) | ((value as u32 & 0xffff) << 16); + self.w + } +} +#[doc = "Field `ANATSTEN` reader - "] +pub struct ANATSTEN_R(crate::FieldReader); +impl ANATSTEN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ANATSTEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ANATSTEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ANATSTEN` writer - "] +pub struct ANATSTEN_W<'a> { + w: &'a mut W, +} +impl<'a> ANATSTEN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bits 16:31"] + #[inline(always)] + pub fn anatstspare(&self) -> ANATSTSPARE_R { + ANATSTSPARE_R::new(((self.bits >> 16) & 0xffff) as u16) + } + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn anatsten(&self) -> ANATSTEN_R { + ANATSTEN_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bits 16:31"] + #[inline(always)] + pub fn anatstspare(&mut self) -> ANATSTSPARE_W { + ANATSTSPARE_W { w: self } + } + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn anatsten(&mut self) -> ANATSTEN_W { + ANATSTEN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_anatst_ctrl_reg](index.html) module"] +pub struct ADPLL_ANATST_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_ANATST_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_anatst_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_ANATST_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_anatst_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_ANATST_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_ANATST_CTRL_REG to value 0"] +impl crate::Resettable for ADPLL_ANATST_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_rd_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_rd_reg.rs new file mode 100644 index 0000000..edadc5d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_anatst_rd_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `ADPLL_ANATST_RD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_ANATST_RD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ANATSTSPARE_IN` reader - "] +pub struct ANATSTSPARE_IN_R(crate::FieldReader); +impl ANATSTSPARE_IN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ANATSTSPARE_IN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ANATSTSPARE_IN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn anatstspare_in(&self) -> ANATSTSPARE_IN_R { + ANATSTSPARE_IN_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_anatst_rd_reg](index.html) module"] +pub struct ADPLL_ANATST_RD_REG_SPEC; +impl crate::RegisterSpec for ADPLL_ANATST_RD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_anatst_rd_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_ANATST_RD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_anatst_rd_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_ANATST_RD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_ANATST_RD_REG to value 0"] +impl crate::Resettable for ADPLL_ANATST_RD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_attr_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_attr_ctrl_reg.rs new file mode 100644 index 0000000..c7902c0 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_attr_ctrl_reg.rs @@ -0,0 +1,160 @@ +#[doc = "Register `ADPLL_ATTR_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_ATTR_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PWR_MODE_TX` reader - "] +pub struct PWR_MODE_TX_R(crate::FieldReader); +impl PWR_MODE_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PWR_MODE_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PWR_MODE_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PWR_MODE_TX` writer - "] +pub struct PWR_MODE_TX_W<'a> { + w: &'a mut W, +} +impl<'a> PWR_MODE_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `PWR_MODE_RX` reader - "] +pub struct PWR_MODE_RX_R(crate::FieldReader); +impl PWR_MODE_RX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PWR_MODE_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PWR_MODE_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PWR_MODE_RX` writer - "] +pub struct PWR_MODE_RX_W<'a> { + w: &'a mut W, +} +impl<'a> PWR_MODE_RX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1"] + #[inline(always)] + pub fn pwr_mode_tx(&self) -> PWR_MODE_TX_R { + PWR_MODE_TX_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn pwr_mode_rx(&self) -> PWR_MODE_RX_R { + PWR_MODE_RX_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1"] + #[inline(always)] + pub fn pwr_mode_tx(&mut self) -> PWR_MODE_TX_W { + PWR_MODE_TX_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn pwr_mode_rx(&mut self) -> PWR_MODE_RX_W { + PWR_MODE_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_attr_ctrl_reg](index.html) module"] +pub struct ADPLL_ATTR_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_ATTR_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_attr_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_ATTR_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_attr_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_ATTR_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_ATTR_CTRL_REG to value 0x03"] +impl crate::Resettable for ADPLL_ATTR_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x03 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_cn_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_cn_ctrl_reg.rs new file mode 100644 index 0000000..5c58242 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_cn_ctrl_reg.rs @@ -0,0 +1,234 @@ +#[doc = "Register `ADPLL_CN_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_CN_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CH0` reader - "] +pub struct CH0_R(crate::FieldReader); +impl CH0_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CH0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CH0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CH0` writer - "] +pub struct CH0_W<'a> { + w: &'a mut W, +} +impl<'a> CH0_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1fff << 16)) | ((value as u32 & 0x1fff) << 16); + self.w + } +} +#[doc = "Field `SGN` reader - "] +pub struct SGN_R(crate::FieldReader); +impl SGN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SGN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SGN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SGN` writer - "] +pub struct SGN_W<'a> { + w: &'a mut W, +} +impl<'a> SGN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `CS` reader - "] +pub struct CS_R(crate::FieldReader); +impl CS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CS` writer - "] +pub struct CS_W<'a> { + w: &'a mut W, +} +impl<'a> CS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `CN` reader - "] +pub struct CN_R(crate::FieldReader); +impl CN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CN` writer - "] +pub struct CN_W<'a> { + w: &'a mut W, +} +impl<'a> CN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x7f) | (value as u32 & 0x7f); + self.w + } +} +impl R { + #[doc = "Bits 16:28"] + #[inline(always)] + pub fn ch0(&self) -> CH0_R { + CH0_R::new(((self.bits >> 16) & 0x1fff) as u16) + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn sgn(&self) -> SGN_R { + SGN_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn cs(&self) -> CS_R { + CS_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 0:6"] + #[inline(always)] + pub fn cn(&self) -> CN_R { + CN_R::new((self.bits & 0x7f) as u8) + } +} +impl W { + #[doc = "Bits 16:28"] + #[inline(always)] + pub fn ch0(&mut self) -> CH0_W { + CH0_W { w: self } + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn sgn(&mut self) -> SGN_W { + SGN_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn cs(&mut self) -> CS_W { + CS_W { w: self } + } + #[doc = "Bits 0:6"] + #[inline(always)] + pub fn cn(&mut self) -> CN_W { + CN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_cn_ctrl_reg](index.html) module"] +pub struct ADPLL_CN_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_CN_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_cn_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_CN_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_cn_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_CN_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_CN_CTRL_REG to value 0x0962_0100"] +impl crate::Resettable for ADPLL_CN_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0962_0100 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_dco_rd_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_dco_rd_reg.rs new file mode 100644 index 0000000..4d17bfc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_dco_rd_reg.rs @@ -0,0 +1,166 @@ +#[doc = "Register `ADPLL_DCO_RD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_DCO_RD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DCOAMP` reader - "] +pub struct DCOAMP_R(crate::FieldReader); +impl DCOAMP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOAMP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOAMP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOMOD` reader - "] +pub struct DCOMOD_R(crate::FieldReader); +impl DCOMOD_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + DCOMOD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOMOD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOFINE` reader - "] +pub struct DCOFINE_R(crate::FieldReader); +impl DCOFINE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOFINE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOFINE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOMEDIUM` reader - "] +pub struct DCOMEDIUM_R(crate::FieldReader); +impl DCOMEDIUM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOMEDIUM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOMEDIUM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOCOARSE` reader - "] +pub struct DCOCOARSE_R(crate::FieldReader); +impl DCOCOARSE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOCOARSE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOCOARSE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 26:29"] + #[inline(always)] + pub fn dcoamp(&self) -> DCOAMP_R { + DCOAMP_R::new(((self.bits >> 26) & 0x0f) as u8) + } + #[doc = "Bits 13:25"] + #[inline(always)] + pub fn dcomod(&self) -> DCOMOD_R { + DCOMOD_R::new(((self.bits >> 13) & 0x1fff) as u16) + } + #[doc = "Bits 7:12"] + #[inline(always)] + pub fn dcofine(&self) -> DCOFINE_R { + DCOFINE_R::new(((self.bits >> 7) & 0x3f) as u8) + } + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn dcomedium(&self) -> DCOMEDIUM_R { + DCOMEDIUM_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn dcocoarse(&self) -> DCOCOARSE_R { + DCOCOARSE_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_dco_rd_reg](index.html) module"] +pub struct ADPLL_DCO_RD_REG_SPEC; +impl crate::RegisterSpec for ADPLL_DCO_RD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_dco_rd_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_DCO_RD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_dco_rd_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_DCO_RD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_DCO_RD_REG to value 0x1c00_0007"] +impl crate::Resettable for ADPLL_DCO_RD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x1c00_0007 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_dcoamp_cal_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_dcoamp_cal_ctrl_reg.rs new file mode 100644 index 0000000..a4ed784 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_dcoamp_cal_ctrl_reg.rs @@ -0,0 +1,382 @@ +#[doc = "Register `ADPLL_DCOAMP_CAL_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_DCOAMP_CAL_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DCOAMPIC_LP_TX` reader - "] +pub struct DCOAMPIC_LP_TX_R(crate::FieldReader); +impl DCOAMPIC_LP_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOAMPIC_LP_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOAMPIC_LP_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOAMPIC_LP_TX` writer - "] +pub struct DCOAMPIC_LP_TX_W<'a> { + w: &'a mut W, +} +impl<'a> DCOAMPIC_LP_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 28)) | ((value as u32 & 0x0f) << 28); + self.w + } +} +#[doc = "Field `DCOAMPIC_LP_RX` reader - "] +pub struct DCOAMPIC_LP_RX_R(crate::FieldReader); +impl DCOAMPIC_LP_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOAMPIC_LP_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOAMPIC_LP_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOAMPIC_LP_RX` writer - "] +pub struct DCOAMPIC_LP_RX_W<'a> { + w: &'a mut W, +} +impl<'a> DCOAMPIC_LP_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 24)) | ((value as u32 & 0x0f) << 24); + self.w + } +} +#[doc = "Field `DCOAMPIC_HP_TX` reader - "] +pub struct DCOAMPIC_HP_TX_R(crate::FieldReader); +impl DCOAMPIC_HP_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOAMPIC_HP_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOAMPIC_HP_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOAMPIC_HP_TX` writer - "] +pub struct DCOAMPIC_HP_TX_W<'a> { + w: &'a mut W, +} +impl<'a> DCOAMPIC_HP_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 20)) | ((value as u32 & 0x0f) << 20); + self.w + } +} +#[doc = "Field `DCOAMPIC_HP_RX` reader - "] +pub struct DCOAMPIC_HP_RX_R(crate::FieldReader); +impl DCOAMPIC_HP_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOAMPIC_HP_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOAMPIC_HP_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOAMPIC_HP_RX` writer - "] +pub struct DCOAMPIC_HP_RX_W<'a> { + w: &'a mut W, +} +impl<'a> DCOAMPIC_HP_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); + self.w + } +} +#[doc = "Field `DCOAMPTM` reader - "] +pub struct DCOAMPTM_R(crate::FieldReader); +impl DCOAMPTM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DCOAMPTM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOAMPTM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOAMPTM` writer - "] +pub struct DCOAMPTM_W<'a> { + w: &'a mut W, +} +impl<'a> DCOAMPTM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `AMPCALEN` reader - "] +pub struct AMPCALEN_R(crate::FieldReader); +impl AMPCALEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + AMPCALEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AMPCALEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AMPCALEN` writer - "] +pub struct AMPCALEN_W<'a> { + w: &'a mut W, +} +impl<'a> AMPCALEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `KMEDIUM` reader - "] +pub struct KMEDIUM_R(crate::FieldReader); +impl KMEDIUM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KMEDIUM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KMEDIUM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KMEDIUM` writer - "] +pub struct KMEDIUM_W<'a> { + w: &'a mut W, +} +impl<'a> KMEDIUM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 3)) | ((value as u32 & 7) << 3); + self.w + } +} +#[doc = "Field `KCOARSE` reader - "] +pub struct KCOARSE_R(crate::FieldReader); +impl KCOARSE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KCOARSE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KCOARSE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KCOARSE` writer - "] +pub struct KCOARSE_W<'a> { + w: &'a mut W, +} +impl<'a> KCOARSE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bits 28:31"] + #[inline(always)] + pub fn dcoampic_lp_tx(&self) -> DCOAMPIC_LP_TX_R { + DCOAMPIC_LP_TX_R::new(((self.bits >> 28) & 0x0f) as u8) + } + #[doc = "Bits 24:27"] + #[inline(always)] + pub fn dcoampic_lp_rx(&self) -> DCOAMPIC_LP_RX_R { + DCOAMPIC_LP_RX_R::new(((self.bits >> 24) & 0x0f) as u8) + } + #[doc = "Bits 20:23"] + #[inline(always)] + pub fn dcoampic_hp_tx(&self) -> DCOAMPIC_HP_TX_R { + DCOAMPIC_HP_TX_R::new(((self.bits >> 20) & 0x0f) as u8) + } + #[doc = "Bits 16:19"] + #[inline(always)] + pub fn dcoampic_hp_rx(&self) -> DCOAMPIC_HP_RX_R { + DCOAMPIC_HP_RX_R::new(((self.bits >> 16) & 0x0f) as u8) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn dcoamptm(&self) -> DCOAMPTM_R { + DCOAMPTM_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ampcalen(&self) -> AMPCALEN_R { + AMPCALEN_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn kmedium(&self) -> KMEDIUM_R { + KMEDIUM_R::new(((self.bits >> 3) & 7) as u8) + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn kcoarse(&self) -> KCOARSE_R { + KCOARSE_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 28:31"] + #[inline(always)] + pub fn dcoampic_lp_tx(&mut self) -> DCOAMPIC_LP_TX_W { + DCOAMPIC_LP_TX_W { w: self } + } + #[doc = "Bits 24:27"] + #[inline(always)] + pub fn dcoampic_lp_rx(&mut self) -> DCOAMPIC_LP_RX_W { + DCOAMPIC_LP_RX_W { w: self } + } + #[doc = "Bits 20:23"] + #[inline(always)] + pub fn dcoampic_hp_tx(&mut self) -> DCOAMPIC_HP_TX_W { + DCOAMPIC_HP_TX_W { w: self } + } + #[doc = "Bits 16:19"] + #[inline(always)] + pub fn dcoampic_hp_rx(&mut self) -> DCOAMPIC_HP_RX_W { + DCOAMPIC_HP_RX_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn dcoamptm(&mut self) -> DCOAMPTM_W { + DCOAMPTM_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ampcalen(&mut self) -> AMPCALEN_W { + AMPCALEN_W { w: self } + } + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn kmedium(&mut self) -> KMEDIUM_W { + KMEDIUM_W { w: self } + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn kcoarse(&mut self) -> KCOARSE_W { + KCOARSE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_dcoamp_cal_ctrl_reg](index.html) module"] +pub struct ADPLL_DCOAMP_CAL_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_DCOAMP_CAL_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_dcoamp_cal_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_DCOAMP_CAL_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_dcoamp_cal_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_DCOAMP_CAL_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_DCOAMP_CAL_CTRL_REG to value 0x7777_0011"] +impl crate::Resettable for ADPLL_DCOAMP_CAL_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7777_0011 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_div_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_div_ctrl_reg.rs new file mode 100644 index 0000000..3cd73e3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_div_ctrl_reg.rs @@ -0,0 +1,281 @@ +#[doc = "Register `ADPLL_DIV_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_DIV_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TXDIV_TRIM` reader - "] +pub struct TXDIV_TRIM_R(crate::FieldReader); +impl TXDIV_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TXDIV_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXDIV_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXDIV_TRIM` writer - "] +pub struct TXDIV_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> TXDIV_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 17)) | ((value as u32 & 0x01ff) << 17); + self.w + } +} +#[doc = "Field `RXDIV_TRIM` reader - "] +pub struct RXDIV_TRIM_R(crate::FieldReader); +impl RXDIV_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RXDIV_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXDIV_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXDIV_TRIM` writer - "] +pub struct RXDIV_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> RXDIV_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 8)) | ((value as u32 & 0x01ff) << 8); + self.w + } +} +#[doc = "Field `RXDIV_FB_EN_TX` reader - "] +pub struct RXDIV_FB_EN_TX_R(crate::FieldReader); +impl RXDIV_FB_EN_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXDIV_FB_EN_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXDIV_FB_EN_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXDIV_FB_EN_TX` writer - "] +pub struct RXDIV_FB_EN_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RXDIV_FB_EN_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RXDIV_FB_EN_RX` reader - "] +pub struct RXDIV_FB_EN_RX_R(crate::FieldReader); +impl RXDIV_FB_EN_RX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXDIV_FB_EN_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXDIV_FB_EN_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXDIV_FB_EN_RX` writer - "] +pub struct RXDIV_FB_EN_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RXDIV_FB_EN_RX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `FBDIV_EN` reader - "] +pub struct FBDIV_EN_R(crate::FieldReader); +impl FBDIV_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FBDIV_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FBDIV_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FBDIV_EN` writer - "] +pub struct FBDIV_EN_W<'a> { + w: &'a mut W, +} +impl<'a> FBDIV_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bits 17:25"] + #[inline(always)] + pub fn txdiv_trim(&self) -> TXDIV_TRIM_R { + TXDIV_TRIM_R::new(((self.bits >> 17) & 0x01ff) as u16) + } + #[doc = "Bits 8:16"] + #[inline(always)] + pub fn rxdiv_trim(&self) -> RXDIV_TRIM_R { + RXDIV_TRIM_R::new(((self.bits >> 8) & 0x01ff) as u16) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rxdiv_fb_en_tx(&self) -> RXDIV_FB_EN_TX_R { + RXDIV_FB_EN_TX_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rxdiv_fb_en_rx(&self) -> RXDIV_FB_EN_RX_R { + RXDIV_FB_EN_RX_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn fbdiv_en(&self) -> FBDIV_EN_R { + FBDIV_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 17:25"] + #[inline(always)] + pub fn txdiv_trim(&mut self) -> TXDIV_TRIM_W { + TXDIV_TRIM_W { w: self } + } + #[doc = "Bits 8:16"] + #[inline(always)] + pub fn rxdiv_trim(&mut self) -> RXDIV_TRIM_W { + RXDIV_TRIM_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rxdiv_fb_en_tx(&mut self) -> RXDIV_FB_EN_TX_W { + RXDIV_FB_EN_TX_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rxdiv_fb_en_rx(&mut self) -> RXDIV_FB_EN_RX_W { + RXDIV_FB_EN_RX_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn fbdiv_en(&mut self) -> FBDIV_EN_W { + FBDIV_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_div_ctrl_reg](index.html) module"] +pub struct ADPLL_DIV_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_DIV_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_div_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_DIV_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_div_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_DIV_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_DIV_CTRL_REG to value 0x0198_ff03"] +impl crate::Resettable for ADPLL_DIV_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0198_ff03 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl1_reg.rs new file mode 100644 index 0000000..17e483e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl1_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `ADPLL_FIF_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_FIF_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FIFRX_1M` reader - "] +pub struct FIFRX_1M_R(crate::FieldReader); +impl FIFRX_1M_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + FIFRX_1M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FIFRX_1M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FIFRX_1M` writer - "] +pub struct FIFRX_1M_W<'a> { + w: &'a mut W, +} +impl<'a> FIFRX_1M_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u32 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13"] + #[inline(always)] + pub fn fifrx_1m(&self) -> FIFRX_1M_R { + FIFRX_1M_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13"] + #[inline(always)] + pub fn fifrx_1m(&mut self) -> FIFRX_1M_W { + FIFRX_1M_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_fif_ctrl1_reg](index.html) module"] +pub struct ADPLL_FIF_CTRL1_REG_SPEC; +impl crate::RegisterSpec for ADPLL_FIF_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_fif_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_FIF_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_fif_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_FIF_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_FIF_CTRL1_REG to value 0x0400"] +impl crate::Resettable for ADPLL_FIF_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0400 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl2_reg.rs new file mode 100644 index 0000000..3c1e639 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fif_ctrl2_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `ADPLL_FIF_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_FIF_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FIFTX` reader - "] +pub struct FIFTX_R(crate::FieldReader); +impl FIFTX_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + FIFTX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FIFTX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FIFTX` writer - "] +pub struct FIFTX_W<'a> { + w: &'a mut W, +} +impl<'a> FIFTX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3fff << 16)) | ((value as u32 & 0x3fff) << 16); + self.w + } +} +#[doc = "Field `FIFRX_OFFSET` reader - "] +pub struct FIFRX_OFFSET_R(crate::FieldReader); +impl FIFRX_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + FIFRX_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FIFRX_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FIFRX_OFFSET` writer - "] +pub struct FIFRX_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> FIFRX_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u32 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 16:29"] + #[inline(always)] + pub fn fiftx(&self) -> FIFTX_R { + FIFTX_R::new(((self.bits >> 16) & 0x3fff) as u16) + } + #[doc = "Bits 0:13"] + #[inline(always)] + pub fn fifrx_offset(&self) -> FIFRX_OFFSET_R { + FIFRX_OFFSET_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 16:29"] + #[inline(always)] + pub fn fiftx(&mut self) -> FIFTX_W { + FIFTX_W { w: self } + } + #[doc = "Bits 0:13"] + #[inline(always)] + pub fn fifrx_offset(&mut self) -> FIFRX_OFFSET_W { + FIFRX_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_fif_ctrl2_reg](index.html) module"] +pub struct ADPLL_FIF_CTRL2_REG_SPEC; +impl crate::RegisterSpec for ADPLL_FIF_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_fif_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_FIF_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_fif_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_FIF_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_FIF_CTRL2_REG to value 0"] +impl crate::Resettable for ADPLL_FIF_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_freqmeas_rd_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_freqmeas_rd_reg.rs new file mode 100644 index 0000000..a02040c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_freqmeas_rd_reg.rs @@ -0,0 +1,186 @@ +#[doc = "Register `ADPLL_FREQMEAS_RD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_FREQMEAS_RD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MEASDONE_OUT` reader - "] +pub struct MEASDONE_OUT_R(crate::FieldReader); +impl MEASDONE_OUT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MEASDONE_OUT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MEASDONE_OUT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QUALMONDET` reader - "] +pub struct QUALMONDET_R(crate::FieldReader); +impl QUALMONDET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QUALMONDET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QUALMONDET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TDCBUB` reader - "] +pub struct TDCBUB_R(crate::FieldReader); +impl TDCBUB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TDCBUB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TDCBUB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PHVSA0` reader - "] +pub struct PHVSA0_R(crate::FieldReader); +impl PHVSA0_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PHVSA0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PHVSA0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PHVSA1` reader - "] +pub struct PHVSA1_R(crate::FieldReader); +impl PHVSA1_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PHVSA1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PHVSA1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FREQDIFF` reader - "] +pub struct FREQDIFF_R(crate::FieldReader); +impl FREQDIFF_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + FREQDIFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FREQDIFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 29"] + #[inline(always)] + pub fn measdone_out(&self) -> MEASDONE_OUT_R { + MEASDONE_OUT_R::new(((self.bits >> 29) & 1) != 0) + } + #[doc = "Bit 26"] + #[inline(always)] + pub fn qualmondet(&self) -> QUALMONDET_R { + QUALMONDET_R::new(((self.bits >> 26) & 1) != 0) + } + #[doc = "Bit 25"] + #[inline(always)] + pub fn tdcbub(&self) -> TDCBUB_R { + TDCBUB_R::new(((self.bits >> 25) & 1) != 0) + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn phvsa0(&self) -> PHVSA0_R { + PHVSA0_R::new(((self.bits >> 24) & 1) != 0) + } + #[doc = "Bit 23"] + #[inline(always)] + pub fn phvsa1(&self) -> PHVSA1_R { + PHVSA1_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bits 0:22"] + #[inline(always)] + pub fn freqdiff(&self) -> FREQDIFF_R { + FREQDIFF_R::new((self.bits & 0x007f_ffff) as u32) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_freqmeas_rd_reg](index.html) module"] +pub struct ADPLL_FREQMEAS_RD_REG_SPEC; +impl crate::RegisterSpec for ADPLL_FREQMEAS_RD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_freqmeas_rd_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_FREQMEAS_RD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_freqmeas_rd_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_FREQMEAS_RD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_FREQMEAS_RD_REG to value 0x2100_0000"] +impl crate::Resettable for ADPLL_FREQMEAS_RD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x2100_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fsm_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fsm_ctrl_reg.rs new file mode 100644 index 0000000..5298693 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_fsm_ctrl_reg.rs @@ -0,0 +1,325 @@ +#[doc = "Register `ADPLL_FSM_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_FSM_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TVPASETTLE` reader - "] +pub struct TVPASETTLE_R(crate::FieldReader); +impl TVPASETTLE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TVPASETTLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TVPASETTLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TVPASETTLE` writer - "] +pub struct TVPASETTLE_W<'a> { + w: &'a mut W, +} +impl<'a> TVPASETTLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 24)) | ((value as u32 & 0x3f) << 24); + self.w + } +} +#[doc = "Field `TSETTLE` reader - "] +pub struct TSETTLE_R(crate::FieldReader); +impl TSETTLE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TSETTLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TSETTLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TSETTLE` writer - "] +pub struct TSETTLE_W<'a> { + w: &'a mut W, +} +impl<'a> TSETTLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 20)) | ((value as u32 & 0x0f) << 20); + self.w + } +} +#[doc = "Field `TPASETTLE` reader - "] +pub struct TPASETTLE_R(crate::FieldReader); +impl TPASETTLE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TPASETTLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TPASETTLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TPASETTLE` writer - "] +pub struct TPASETTLE_W<'a> { + w: &'a mut W, +} +impl<'a> TPASETTLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); + self.w + } +} +#[doc = "Field `TMOD` reader - "] +pub struct TMOD_R(crate::FieldReader); +impl TMOD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TMOD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TMOD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TMOD` writer - "] +pub struct TMOD_W<'a> { + w: &'a mut W, +} +impl<'a> TMOD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 12)) | ((value as u32 & 0x0f) << 12); + self.w + } +} +#[doc = "Field `TFINE` reader - "] +pub struct TFINE_R(crate::FieldReader); +impl TFINE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TFINE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TFINE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TFINE` writer - "] +pub struct TFINE_W<'a> { + w: &'a mut W, +} +impl<'a> TFINE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `TMEDIUM` reader - "] +pub struct TMEDIUM_R(crate::FieldReader); +impl TMEDIUM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TMEDIUM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TMEDIUM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TMEDIUM` writer - "] +pub struct TMEDIUM_W<'a> { + w: &'a mut W, +} +impl<'a> TMEDIUM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u32 & 0x0f) << 4); + self.w + } +} +#[doc = "Field `TCOARSE` reader - "] +pub struct TCOARSE_R(crate::FieldReader); +impl TCOARSE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TCOARSE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TCOARSE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TCOARSE` writer - "] +pub struct TCOARSE_W<'a> { + w: &'a mut W, +} +impl<'a> TCOARSE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 24:29"] + #[inline(always)] + pub fn tvpasettle(&self) -> TVPASETTLE_R { + TVPASETTLE_R::new(((self.bits >> 24) & 0x3f) as u8) + } + #[doc = "Bits 20:23"] + #[inline(always)] + pub fn tsettle(&self) -> TSETTLE_R { + TSETTLE_R::new(((self.bits >> 20) & 0x0f) as u8) + } + #[doc = "Bits 16:19"] + #[inline(always)] + pub fn tpasettle(&self) -> TPASETTLE_R { + TPASETTLE_R::new(((self.bits >> 16) & 0x0f) as u8) + } + #[doc = "Bits 12:15"] + #[inline(always)] + pub fn tmod(&self) -> TMOD_R { + TMOD_R::new(((self.bits >> 12) & 0x0f) as u8) + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn tfine(&self) -> TFINE_R { + TFINE_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bits 4:7"] + #[inline(always)] + pub fn tmedium(&self) -> TMEDIUM_R { + TMEDIUM_R::new(((self.bits >> 4) & 0x0f) as u8) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn tcoarse(&self) -> TCOARSE_R { + TCOARSE_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 24:29"] + #[inline(always)] + pub fn tvpasettle(&mut self) -> TVPASETTLE_W { + TVPASETTLE_W { w: self } + } + #[doc = "Bits 20:23"] + #[inline(always)] + pub fn tsettle(&mut self) -> TSETTLE_W { + TSETTLE_W { w: self } + } + #[doc = "Bits 16:19"] + #[inline(always)] + pub fn tpasettle(&mut self) -> TPASETTLE_W { + TPASETTLE_W { w: self } + } + #[doc = "Bits 12:15"] + #[inline(always)] + pub fn tmod(&mut self) -> TMOD_W { + TMOD_W { w: self } + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn tfine(&mut self) -> TFINE_W { + TFINE_W { w: self } + } + #[doc = "Bits 4:7"] + #[inline(always)] + pub fn tmedium(&mut self) -> TMEDIUM_W { + TMEDIUM_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn tcoarse(&mut self) -> TCOARSE_W { + TCOARSE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_fsm_ctrl_reg](index.html) module"] +pub struct ADPLL_FSM_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_FSM_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_fsm_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_FSM_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_fsm_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_FSM_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_FSM_CTRL_REG to value 0x08f8_ae84"] +impl crate::Resettable for ADPLL_FSM_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x08f8_ae84 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_init_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_init_ctrl_reg.rs new file mode 100644 index 0000000..2105a98 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_init_ctrl_reg.rs @@ -0,0 +1,214 @@ +#[doc = "Register `ADPLL_INIT_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_INIT_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DCOMODIC` reader - "] +pub struct DCOMODIC_R(crate::FieldReader); +impl DCOMODIC_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + DCOMODIC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOMODIC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOMODIC` writer - "] +pub struct DCOMODIC_W<'a> { + w: &'a mut W, +} +impl<'a> DCOMODIC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1fff << 16)) | ((value as u32 & 0x1fff) << 16); + self.w + } +} +#[doc = "Field `DCOFINEIC` reader - "] +pub struct DCOFINEIC_R(crate::FieldReader); +impl DCOFINEIC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOFINEIC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOFINEIC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOFINEIC` writer - "] +pub struct DCOFINEIC_W<'a> { + w: &'a mut W, +} +impl<'a> DCOFINEIC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 8)) | ((value as u32 & 0x3f) << 8); + self.w + } +} +#[doc = "Field `DCOMEDIUMIC` reader - "] +pub struct DCOMEDIUMIC_R(crate::FieldReader); +impl DCOMEDIUMIC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOMEDIUMIC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOMEDIUMIC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOMEDIUMIC` writer - "] +pub struct DCOMEDIUMIC_W<'a> { + w: &'a mut W, +} +impl<'a> DCOMEDIUMIC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u32 & 7) << 4); + self.w + } +} +#[doc = "Field `DCOCOARSEIC` reader - "] +pub struct DCOCOARSEIC_R(crate::FieldReader); +impl DCOCOARSEIC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCOCOARSEIC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCOCOARSEIC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCOCOARSEIC` writer - "] +pub struct DCOCOARSEIC_W<'a> { + w: &'a mut W, +} +impl<'a> DCOCOARSEIC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 16:28"] + #[inline(always)] + pub fn dcomodic(&self) -> DCOMODIC_R { + DCOMODIC_R::new(((self.bits >> 16) & 0x1fff) as u16) + } + #[doc = "Bits 8:13"] + #[inline(always)] + pub fn dcofineic(&self) -> DCOFINEIC_R { + DCOFINEIC_R::new(((self.bits >> 8) & 0x3f) as u8) + } + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn dcomediumic(&self) -> DCOMEDIUMIC_R { + DCOMEDIUMIC_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn dcocoarseic(&self) -> DCOCOARSEIC_R { + DCOCOARSEIC_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 16:28"] + #[inline(always)] + pub fn dcomodic(&mut self) -> DCOMODIC_W { + DCOMODIC_W { w: self } + } + #[doc = "Bits 8:13"] + #[inline(always)] + pub fn dcofineic(&mut self) -> DCOFINEIC_W { + DCOFINEIC_W { w: self } + } + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn dcomediumic(&mut self) -> DCOMEDIUMIC_W { + DCOMEDIUMIC_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn dcocoarseic(&mut self) -> DCOCOARSEIC_W { + DCOCOARSEIC_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_init_ctrl_reg](index.html) module"] +pub struct ADPLL_INIT_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_INIT_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_init_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_INIT_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_init_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_INIT_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_INIT_CTRL_REG to value 0x05"] +impl crate::Resettable for ADPLL_INIT_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x05 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl1_reg.rs new file mode 100644 index 0000000..bfed578 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl1_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `ADPLL_KDCO_CAL_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_KDCO_CAL_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KDCOLF_IN_1M` reader - "] +pub struct KDCOLF_IN_1M_R(crate::FieldReader); +impl KDCOLF_IN_1M_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDCOLF_IN_1M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOLF_IN_1M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOLF_IN_1M` writer - "] +pub struct KDCOLF_IN_1M_W<'a> { + w: &'a mut W, +} +impl<'a> KDCOLF_IN_1M_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `KDCOHFIC_1M` reader - "] +pub struct KDCOHFIC_1M_R(crate::FieldReader); +impl KDCOHFIC_1M_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDCOHFIC_1M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOHFIC_1M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOHFIC_1M` writer - "] +pub struct KDCOHFIC_1M_W<'a> { + w: &'a mut W, +} +impl<'a> KDCOHFIC_1M_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn kdcolf_in_1m(&self) -> KDCOLF_IN_1M_R { + KDCOLF_IN_1M_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn kdcohfic_1m(&self) -> KDCOHFIC_1M_R { + KDCOHFIC_1M_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn kdcolf_in_1m(&mut self) -> KDCOLF_IN_1M_W { + KDCOLF_IN_1M_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn kdcohfic_1m(&mut self) -> KDCOHFIC_1M_W { + KDCOHFIC_1M_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_kdco_cal_ctrl1_reg](index.html) module"] +pub struct ADPLL_KDCO_CAL_CTRL1_REG_SPEC; +impl crate::RegisterSpec for ADPLL_KDCO_CAL_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_kdco_cal_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_KDCO_CAL_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_kdco_cal_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_KDCO_CAL_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_KDCO_CAL_CTRL1_REG to value 0x9b9b"] +impl crate::Resettable for ADPLL_KDCO_CAL_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x9b9b + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl2_reg.rs new file mode 100644 index 0000000..1a0c58c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_cal_ctrl2_reg.rs @@ -0,0 +1,355 @@ +#[doc = "Register `ADPLL_KDCO_CAL_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_KDCO_CAL_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KDCOESTDEV` reader - "] +pub struct KDCOESTDEV_R(crate::FieldReader); +impl KDCOESTDEV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDCOESTDEV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOESTDEV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOESTDEV` writer - "] +pub struct KDCOESTDEV_W<'a> { + w: &'a mut W, +} +impl<'a> KDCOESTDEV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 30)) | ((value as u32 & 3) << 30); + self.w + } +} +#[doc = "Field `KDCOCALTX` reader - "] +pub struct KDCOCALTX_R(crate::FieldReader); +impl KDCOCALTX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDCOCALTX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOCALTX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOCALTX` writer - "] +pub struct KDCOCALTX_W<'a> { + w: &'a mut W, +} +impl<'a> KDCOCALTX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 29)) | ((value as u32 & 1) << 29); + self.w + } +} +#[doc = "Field `KDCOCALRX` reader - "] +pub struct KDCOCALRX_R(crate::FieldReader); +impl KDCOCALRX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDCOCALRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOCALRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOCALRX` writer - "] +pub struct KDCOCALRX_W<'a> { + w: &'a mut W, +} +impl<'a> KDCOCALRX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 28)) | ((value as u32 & 1) << 28); + self.w + } +} +#[doc = "Field `KDCOLFCALEN` reader - "] +pub struct KDCOLFCALEN_R(crate::FieldReader); +impl KDCOLFCALEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDCOLFCALEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOLFCALEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOLFCALEN` writer - "] +pub struct KDCOLFCALEN_W<'a> { + w: &'a mut W, +} +impl<'a> KDCOLFCALEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 27)) | ((value as u32 & 1) << 27); + self.w + } +} +#[doc = "Field `TKDCOCAL` reader - "] +pub struct TKDCOCAL_R(crate::FieldReader); +impl TKDCOCAL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TKDCOCAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TKDCOCAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TKDCOCAL` writer - "] +pub struct TKDCOCAL_W<'a> { + w: &'a mut W, +} +impl<'a> TKDCOCAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 24)) | ((value as u32 & 7) << 24); + self.w + } +} +#[doc = "Field `KDCOCN_IC` reader - "] +pub struct KDCOCN_IC_R(crate::FieldReader); +impl KDCOCN_IC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDCOCN_IC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOCN_IC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOCN_IC` writer - "] +pub struct KDCOCN_IC_W<'a> { + w: &'a mut W, +} +impl<'a> KDCOCN_IC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 16)) | ((value as u32 & 0x7f) << 16); + self.w + } +} +#[doc = "Field `KMOD_ALPHA_1M` reader - "] +pub struct KMOD_ALPHA_1M_R(crate::FieldReader); +impl KMOD_ALPHA_1M_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KMOD_ALPHA_1M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KMOD_ALPHA_1M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KMOD_ALPHA_1M` writer - "] +pub struct KMOD_ALPHA_1M_W<'a> { + w: &'a mut W, +} +impl<'a> KMOD_ALPHA_1M_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 30:31"] + #[inline(always)] + pub fn kdcoestdev(&self) -> KDCOESTDEV_R { + KDCOESTDEV_R::new(((self.bits >> 30) & 3) as u8) + } + #[doc = "Bit 29"] + #[inline(always)] + pub fn kdcocaltx(&self) -> KDCOCALTX_R { + KDCOCALTX_R::new(((self.bits >> 29) & 1) != 0) + } + #[doc = "Bit 28"] + #[inline(always)] + pub fn kdcocalrx(&self) -> KDCOCALRX_R { + KDCOCALRX_R::new(((self.bits >> 28) & 1) != 0) + } + #[doc = "Bit 27"] + #[inline(always)] + pub fn kdcolfcalen(&self) -> KDCOLFCALEN_R { + KDCOLFCALEN_R::new(((self.bits >> 27) & 1) != 0) + } + #[doc = "Bits 24:26"] + #[inline(always)] + pub fn tkdcocal(&self) -> TKDCOCAL_R { + TKDCOCAL_R::new(((self.bits >> 24) & 7) as u8) + } + #[doc = "Bits 16:22"] + #[inline(always)] + pub fn kdcocn_ic(&self) -> KDCOCN_IC_R { + KDCOCN_IC_R::new(((self.bits >> 16) & 0x7f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn kmod_alpha_1m(&self) -> KMOD_ALPHA_1M_R { + KMOD_ALPHA_1M_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 30:31"] + #[inline(always)] + pub fn kdcoestdev(&mut self) -> KDCOESTDEV_W { + KDCOESTDEV_W { w: self } + } + #[doc = "Bit 29"] + #[inline(always)] + pub fn kdcocaltx(&mut self) -> KDCOCALTX_W { + KDCOCALTX_W { w: self } + } + #[doc = "Bit 28"] + #[inline(always)] + pub fn kdcocalrx(&mut self) -> KDCOCALRX_W { + KDCOCALRX_W { w: self } + } + #[doc = "Bit 27"] + #[inline(always)] + pub fn kdcolfcalen(&mut self) -> KDCOLFCALEN_W { + KDCOLFCALEN_W { w: self } + } + #[doc = "Bits 24:26"] + #[inline(always)] + pub fn tkdcocal(&mut self) -> TKDCOCAL_W { + TKDCOCAL_W { w: self } + } + #[doc = "Bits 16:22"] + #[inline(always)] + pub fn kdcocn_ic(&mut self) -> KDCOCN_IC_W { + KDCOCN_IC_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn kmod_alpha_1m(&mut self) -> KMOD_ALPHA_1M_W { + KMOD_ALPHA_1M_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_kdco_cal_ctrl2_reg](index.html) module"] +pub struct ADPLL_KDCO_CAL_CTRL2_REG_SPEC; +impl crate::RegisterSpec for ADPLL_KDCO_CAL_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_kdco_cal_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_KDCO_CAL_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_kdco_cal_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_KDCO_CAL_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_KDCO_CAL_CTRL2_REG to value 0x4c14_000a"] +impl crate::Resettable for ADPLL_KDCO_CAL_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x4c14_000a + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_rd_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_rd_reg.rs new file mode 100644 index 0000000..6578176 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdco_rd_reg.rs @@ -0,0 +1,146 @@ +#[doc = "Register `ADPLL_KDCO_RD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_KDCO_RD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CAL_KDCOCAL` reader - "] +pub struct CAL_KDCOCAL_R(crate::FieldReader); +impl CAL_KDCOCAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CAL_KDCOCAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CAL_KDCOCAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCOCN` reader - "] +pub struct KDCOCN_R(crate::FieldReader); +impl KDCOCN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDCOCN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCOCN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCO_HF_OUT` reader - "] +pub struct KDCO_HF_OUT_R(crate::FieldReader); +impl KDCO_HF_OUT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDCO_HF_OUT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCO_HF_OUT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDCO_HF_INT` reader - "] +pub struct KDCO_HF_INT_R(crate::FieldReader); +impl KDCO_HF_INT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDCO_HF_INT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDCO_HF_INT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 23"] + #[inline(always)] + pub fn cal_kdcocal(&self) -> CAL_KDCOCAL_R { + CAL_KDCOCAL_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bits 16:22"] + #[inline(always)] + pub fn kdcocn(&self) -> KDCOCN_R { + KDCOCN_R::new(((self.bits >> 16) & 0x7f) as u8) + } + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn kdco_hf_out(&self) -> KDCO_HF_OUT_R { + KDCO_HF_OUT_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn kdco_hf_int(&self) -> KDCO_HF_INT_R { + KDCO_HF_INT_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_kdco_rd_reg](index.html) module"] +pub struct ADPLL_KDCO_RD_REG_SPEC; +impl crate::RegisterSpec for ADPLL_KDCO_RD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_kdco_rd_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_KDCO_RD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_kdco_rd_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_KDCO_RD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_KDCO_RD_REG to value 0"] +impl crate::Resettable for ADPLL_KDCO_RD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtc_rd_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtc_rd_reg.rs new file mode 100644 index 0000000..b4e8246 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtc_rd_reg.rs @@ -0,0 +1,146 @@ +#[doc = "Register `ADPLL_KDTC_RD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_KDTC_RD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CAL_KDTCCAL` reader - "] +pub struct CAL_KDTCCAL_R(crate::FieldReader); +impl CAL_KDTCCAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CAL_KDTCCAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CAL_KDTCCAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTC_ALPHA_COMP` reader - "] +pub struct KDTC_ALPHA_COMP_R(crate::FieldReader); +impl KDTC_ALPHA_COMP_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + KDTC_ALPHA_COMP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTC_ALPHA_COMP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCCN` reader - "] +pub struct KDTCCN_R(crate::FieldReader); +impl KDTCCN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDTCCN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCCN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTC_OUT` reader - "] +pub struct KDTC_OUT_R(crate::FieldReader); +impl KDTC_OUT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + KDTC_OUT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTC_OUT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 25"] + #[inline(always)] + pub fn cal_kdtccal(&self) -> CAL_KDTCCAL_R { + CAL_KDTCCAL_R::new(((self.bits >> 25) & 1) != 0) + } + #[doc = "Bits 16:24"] + #[inline(always)] + pub fn kdtc_alpha_comp(&self) -> KDTC_ALPHA_COMP_R { + KDTC_ALPHA_COMP_R::new(((self.bits >> 16) & 0x01ff) as u16) + } + #[doc = "Bits 9:15"] + #[inline(always)] + pub fn kdtccn(&self) -> KDTCCN_R { + KDTCCN_R::new(((self.bits >> 9) & 0x7f) as u8) + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn kdtc_out(&self) -> KDTC_OUT_R { + KDTC_OUT_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_kdtc_rd_reg](index.html) module"] +pub struct ADPLL_KDTC_RD_REG_SPEC; +impl crate::RegisterSpec for ADPLL_KDTC_RD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_kdtc_rd_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_KDTC_RD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_kdtc_rd_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_KDTC_RD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_KDTC_RD_REG to value 0"] +impl crate::Resettable for ADPLL_KDTC_RD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl1_reg.rs new file mode 100644 index 0000000..c35b373 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl1_reg.rs @@ -0,0 +1,261 @@ +#[doc = "Register `ADPLL_KDTCTDC_CAL_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_KDTCTDC_CAL_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KDTCIC` reader - "] +pub struct KDTCIC_R(crate::FieldReader); +impl KDTCIC_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + KDTCIC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCIC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCIC` writer - "] +pub struct KDTCIC_W<'a> { + w: &'a mut W, +} +impl<'a> KDTCIC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 23)) | ((value as u32 & 0x01ff) << 23); + self.w + } +} +#[doc = "Field `KDTCCN_IC` reader - "] +pub struct KDTCCN_IC_R(crate::FieldReader); +impl KDTCCN_IC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDTCCN_IC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCCN_IC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCCN_IC` writer - "] +pub struct KDTCCN_IC_W<'a> { + w: &'a mut W, +} +impl<'a> KDTCCN_IC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 16)) | ((value as u32 & 0x7f) << 16); + self.w + } +} +#[doc = "Field `KDTC_PIPELINE_BYPASS` reader - "] +pub struct KDTC_PIPELINE_BYPASS_R(crate::FieldReader); +impl KDTC_PIPELINE_BYPASS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDTC_PIPELINE_BYPASS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTC_PIPELINE_BYPASS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTC_PIPELINE_BYPASS` writer - "] +pub struct KDTC_PIPELINE_BYPASS_W<'a> { + w: &'a mut W, +} +impl<'a> KDTC_PIPELINE_BYPASS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `KTDC_IN` reader - "] +pub struct KTDC_IN_R(crate::FieldReader); +impl KTDC_IN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + KTDC_IN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KTDC_IN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KTDC_IN` writer - "] +pub struct KTDC_IN_W<'a> { + w: &'a mut W, +} +impl<'a> KTDC_IN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 6)) | ((value as u32 & 0x01ff) << 6); + self.w + } +} +#[doc = "Field `KDTC_ALPHA` reader - "] +pub struct KDTC_ALPHA_R(crate::FieldReader); +impl KDTC_ALPHA_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDTC_ALPHA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTC_ALPHA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTC_ALPHA` writer - "] +pub struct KDTC_ALPHA_W<'a> { + w: &'a mut W, +} +impl<'a> KDTC_ALPHA_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u32 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bits 23:31"] + #[inline(always)] + pub fn kdtcic(&self) -> KDTCIC_R { + KDTCIC_R::new(((self.bits >> 23) & 0x01ff) as u16) + } + #[doc = "Bits 16:22"] + #[inline(always)] + pub fn kdtccn_ic(&self) -> KDTCCN_IC_R { + KDTCCN_IC_R::new(((self.bits >> 16) & 0x7f) as u8) + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn kdtc_pipeline_bypass(&self) -> KDTC_PIPELINE_BYPASS_R { + KDTC_PIPELINE_BYPASS_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bits 6:14"] + #[inline(always)] + pub fn ktdc_in(&self) -> KTDC_IN_R { + KTDC_IN_R::new(((self.bits >> 6) & 0x01ff) as u16) + } + #[doc = "Bits 0:5"] + #[inline(always)] + pub fn kdtc_alpha(&self) -> KDTC_ALPHA_R { + KDTC_ALPHA_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bits 23:31"] + #[inline(always)] + pub fn kdtcic(&mut self) -> KDTCIC_W { + KDTCIC_W { w: self } + } + #[doc = "Bits 16:22"] + #[inline(always)] + pub fn kdtccn_ic(&mut self) -> KDTCCN_IC_W { + KDTCCN_IC_W { w: self } + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn kdtc_pipeline_bypass(&mut self) -> KDTC_PIPELINE_BYPASS_W { + KDTC_PIPELINE_BYPASS_W { w: self } + } + #[doc = "Bits 6:14"] + #[inline(always)] + pub fn ktdc_in(&mut self) -> KTDC_IN_W { + KTDC_IN_W { w: self } + } + #[doc = "Bits 0:5"] + #[inline(always)] + pub fn kdtc_alpha(&mut self) -> KDTC_ALPHA_W { + KDTC_ALPHA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_kdtctdc_cal_ctrl1_reg](index.html) module"] +pub struct ADPLL_KDTCTDC_CAL_CTRL1_REG_SPEC; +impl crate::RegisterSpec for ADPLL_KDTCTDC_CAL_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_kdtctdc_cal_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_KDTCTDC_CAL_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_kdtctdc_cal_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_KDTCTDC_CAL_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_KDTCTDC_CAL_CTRL1_REG to value 0x7fff_ffff"] +impl crate::Resettable for ADPLL_KDTCTDC_CAL_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7fff_ffff + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl2_reg.rs new file mode 100644 index 0000000..6ad771e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_kdtctdc_cal_ctrl2_reg.rs @@ -0,0 +1,459 @@ +#[doc = "Register `ADPLL_KDTCTDC_CAL_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_KDTCTDC_CAL_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PHRDLY_EXTRA` reader - "] +pub struct PHRDLY_EXTRA_R(crate::FieldReader); +impl PHRDLY_EXTRA_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PHRDLY_EXTRA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PHRDLY_EXTRA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PHRDLY_EXTRA` writer - "] +pub struct PHRDLY_EXTRA_W<'a> { + w: &'a mut W, +} +impl<'a> PHRDLY_EXTRA_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `TKDTCCAL` reader - "] +pub struct TKDTCCAL_R(crate::FieldReader); +impl TKDTCCAL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TKDTCCAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TKDTCCAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TKDTCCAL` writer - "] +pub struct TKDTCCAL_W<'a> { + w: &'a mut W, +} +impl<'a> TKDTCCAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 11)) | ((value as u32 & 0x0f) << 11); + self.w + } +} +#[doc = "Field `PHRDLY` reader - "] +pub struct PHRDLY_R(crate::FieldReader); +impl PHRDLY_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PHRDLY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PHRDLY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PHRDLY` writer - "] +pub struct PHRDLY_W<'a> { + w: &'a mut W, +} +impl<'a> PHRDLY_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 9)) | ((value as u32 & 3) << 9); + self.w + } +} +#[doc = "Field `KTDCCALEN` reader - "] +pub struct KTDCCALEN_R(crate::FieldReader); +impl KTDCCALEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KTDCCALEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KTDCCALEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KTDCCALEN` writer - "] +pub struct KTDCCALEN_W<'a> { + w: &'a mut W, +} +impl<'a> KTDCCALEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `KDTCCALLG` reader - "] +pub struct KDTCCALLG_R(crate::FieldReader); +impl KDTCCALLG_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KDTCCALLG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCCALLG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCCALLG` writer - "] +pub struct KDTCCALLG_W<'a> { + w: &'a mut W, +} +impl<'a> KDTCCALLG_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u32 & 7) << 4); + self.w + } +} +#[doc = "Field `KDTCCAL_INV` reader - "] +pub struct KDTCCAL_INV_R(crate::FieldReader); +impl KDTCCAL_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDTCCAL_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCCAL_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCCAL_INV` writer - "] +pub struct KDTCCAL_INV_W<'a> { + w: &'a mut W, +} +impl<'a> KDTCCAL_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `KDTCCALMOD1P` reader - "] +pub struct KDTCCALMOD1P_R(crate::FieldReader); +impl KDTCCALMOD1P_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDTCCALMOD1P_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCCALMOD1P_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCCALMOD1P` writer - "] +pub struct KDTCCALMOD1P_W<'a> { + w: &'a mut W, +} +impl<'a> KDTCCALMOD1P_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `KDTCCALMOD` reader - "] +pub struct KDTCCALMOD_R(crate::FieldReader); +impl KDTCCALMOD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDTCCALMOD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCCALMOD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCCALMOD` writer - "] +pub struct KDTCCALMOD_W<'a> { + w: &'a mut W, +} +impl<'a> KDTCCALMOD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `KDTCCALEN` reader - "] +pub struct KDTCCALEN_R(crate::FieldReader); +impl KDTCCALEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KDTCCALEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KDTCCALEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KDTCCALEN` writer - "] +pub struct KDTCCALEN_W<'a> { + w: &'a mut W, +} +impl<'a> KDTCCALEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 15"] + #[inline(always)] + pub fn phrdly_extra(&self) -> PHRDLY_EXTRA_R { + PHRDLY_EXTRA_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bits 11:14"] + #[inline(always)] + pub fn tkdtccal(&self) -> TKDTCCAL_R { + TKDTCCAL_R::new(((self.bits >> 11) & 0x0f) as u8) + } + #[doc = "Bits 9:10"] + #[inline(always)] + pub fn phrdly(&self) -> PHRDLY_R { + PHRDLY_R::new(((self.bits >> 9) & 3) as u8) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn ktdccalen(&self) -> KTDCCALEN_R { + KTDCCALEN_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn kdtccallg(&self) -> KDTCCALLG_R { + KDTCCALLG_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn kdtccal_inv(&self) -> KDTCCAL_INV_R { + KDTCCAL_INV_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn kdtccalmod1p(&self) -> KDTCCALMOD1P_R { + KDTCCALMOD1P_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn kdtccalmod(&self) -> KDTCCALMOD_R { + KDTCCALMOD_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn kdtccalen(&self) -> KDTCCALEN_R { + KDTCCALEN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 15"] + #[inline(always)] + pub fn phrdly_extra(&mut self) -> PHRDLY_EXTRA_W { + PHRDLY_EXTRA_W { w: self } + } + #[doc = "Bits 11:14"] + #[inline(always)] + pub fn tkdtccal(&mut self) -> TKDTCCAL_W { + TKDTCCAL_W { w: self } + } + #[doc = "Bits 9:10"] + #[inline(always)] + pub fn phrdly(&mut self) -> PHRDLY_W { + PHRDLY_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn ktdccalen(&mut self) -> KTDCCALEN_W { + KTDCCALEN_W { w: self } + } + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn kdtccallg(&mut self) -> KDTCCALLG_W { + KDTCCALLG_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn kdtccal_inv(&mut self) -> KDTCCAL_INV_W { + KDTCCAL_INV_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn kdtccalmod1p(&mut self) -> KDTCCALMOD1P_W { + KDTCCALMOD1P_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn kdtccalmod(&mut self) -> KDTCCALMOD_W { + KDTCCALMOD_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn kdtccalen(&mut self) -> KDTCCALEN_W { + KDTCCALEN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_kdtctdc_cal_ctrl2_reg](index.html) module"] +pub struct ADPLL_KDTCTDC_CAL_CTRL2_REG_SPEC; +impl crate::RegisterSpec for ADPLL_KDTCTDC_CAL_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_kdtctdc_cal_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_KDTCTDC_CAL_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_kdtctdc_cal_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_KDTCTDC_CAL_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_KDTCTDC_CAL_CTRL2_REG to value 0x7f50"] +impl crate::Resettable for ADPLL_KDTCTDC_CAL_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7f50 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl1_reg.rs new file mode 100644 index 0000000..f342591 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl1_reg.rs @@ -0,0 +1,177 @@ +#[doc = "Register `ADPLL_LF_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_LF_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FINEKZ` reader - "] +pub struct FINEKZ_R(crate::FieldReader); +impl FINEKZ_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + FINEKZ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINEKZ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINEKZ` writer - "] +pub struct FINEKZ_W<'a> { + w: &'a mut W, +} +impl<'a> FINEKZ_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 10)) | ((value as u32 & 0x3f) << 10); + self.w + } +} +#[doc = "Field `FINEK` reader - "] +pub struct FINEK_R(crate::FieldReader); +impl FINEK_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + FINEK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINEK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINEK` writer - "] +pub struct FINEK_W<'a> { + w: &'a mut W, +} +impl<'a> FINEK_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `FINETAU` reader - "] +pub struct FINETAU_R(crate::FieldReader); +impl FINETAU_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + FINETAU_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINETAU_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINETAU` writer - "] +pub struct FINETAU_W<'a> { + w: &'a mut W, +} +impl<'a> FINETAU_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 10:15"] + #[inline(always)] + pub fn finekz(&self) -> FINEKZ_R { + FINEKZ_R::new(((self.bits >> 10) & 0x3f) as u8) + } + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn finek(&self) -> FINEK_R { + FINEK_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn finetau(&self) -> FINETAU_R { + FINETAU_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 10:15"] + #[inline(always)] + pub fn finekz(&mut self) -> FINEKZ_W { + FINEKZ_W { w: self } + } + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn finek(&mut self) -> FINEK_W { + FINEK_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn finetau(&mut self) -> FINETAU_W { + FINETAU_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_lf_ctrl1_reg](index.html) module"] +pub struct ADPLL_LF_CTRL1_REG_SPEC; +impl crate::RegisterSpec for ADPLL_LF_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_lf_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_LF_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_lf_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_LF_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_LF_CTRL1_REG to value 0x818c"] +impl crate::Resettable for ADPLL_LF_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x818c + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl2_reg.rs new file mode 100644 index 0000000..36b1f93 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_lf_ctrl2_reg.rs @@ -0,0 +1,298 @@ +#[doc = "Register `ADPLL_LF_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_LF_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RST_TAU_EN` reader - "] +pub struct RST_TAU_EN_R(crate::FieldReader); +impl RST_TAU_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RST_TAU_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RST_TAU_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RST_TAU_EN` writer - "] +pub struct RST_TAU_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RST_TAU_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 30)) | ((value as u32 & 1) << 30); + self.w + } +} +#[doc = "Field `MODKZ` reader - "] +pub struct MODKZ_R(crate::FieldReader); +impl MODKZ_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MODKZ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MODKZ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MODKZ` writer - "] +pub struct MODKZ_W<'a> { + w: &'a mut W, +} +impl<'a> MODKZ_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 24)) | ((value as u32 & 0x3f) << 24); + self.w + } +} +#[doc = "Field `MODK` reader - "] +pub struct MODK_R(crate::FieldReader); +impl MODK_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MODK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MODK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MODK` writer - "] +pub struct MODK_W<'a> { + w: &'a mut W, +} +impl<'a> MODK_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 18)) | ((value as u32 & 0x3f) << 18); + self.w + } +} +#[doc = "Field `MODTAU` reader - "] +pub struct MODTAU_R(crate::FieldReader); +impl MODTAU_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MODTAU_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MODTAU_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MODTAU` writer - "] +pub struct MODTAU_W<'a> { + w: &'a mut W, +} +impl<'a> MODTAU_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 12)) | ((value as u32 & 0x3f) << 12); + self.w + } +} +#[doc = "Field `MODK_TUNE` reader - "] +pub struct MODK_TUNE_R(crate::FieldReader); +impl MODK_TUNE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MODK_TUNE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MODK_TUNE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MODK_TUNE` writer - "] +pub struct MODK_TUNE_W<'a> { + w: &'a mut W, +} +impl<'a> MODK_TUNE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 6)) | ((value as u32 & 0x3f) << 6); + self.w + } +} +#[doc = "Field `MODTAU_TUNE` reader - "] +pub struct MODTAU_TUNE_R(crate::FieldReader); +impl MODTAU_TUNE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MODTAU_TUNE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MODTAU_TUNE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MODTAU_TUNE` writer - "] +pub struct MODTAU_TUNE_W<'a> { + w: &'a mut W, +} +impl<'a> MODTAU_TUNE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u32 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bit 30"] + #[inline(always)] + pub fn rst_tau_en(&self) -> RST_TAU_EN_R { + RST_TAU_EN_R::new(((self.bits >> 30) & 1) != 0) + } + #[doc = "Bits 24:29"] + #[inline(always)] + pub fn modkz(&self) -> MODKZ_R { + MODKZ_R::new(((self.bits >> 24) & 0x3f) as u8) + } + #[doc = "Bits 18:23"] + #[inline(always)] + pub fn modk(&self) -> MODK_R { + MODK_R::new(((self.bits >> 18) & 0x3f) as u8) + } + #[doc = "Bits 12:17"] + #[inline(always)] + pub fn modtau(&self) -> MODTAU_R { + MODTAU_R::new(((self.bits >> 12) & 0x3f) as u8) + } + #[doc = "Bits 6:11"] + #[inline(always)] + pub fn modk_tune(&self) -> MODK_TUNE_R { + MODK_TUNE_R::new(((self.bits >> 6) & 0x3f) as u8) + } + #[doc = "Bits 0:5"] + #[inline(always)] + pub fn modtau_tune(&self) -> MODTAU_TUNE_R { + MODTAU_TUNE_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bit 30"] + #[inline(always)] + pub fn rst_tau_en(&mut self) -> RST_TAU_EN_W { + RST_TAU_EN_W { w: self } + } + #[doc = "Bits 24:29"] + #[inline(always)] + pub fn modkz(&mut self) -> MODKZ_W { + MODKZ_W { w: self } + } + #[doc = "Bits 18:23"] + #[inline(always)] + pub fn modk(&mut self) -> MODK_W { + MODK_W { w: self } + } + #[doc = "Bits 12:17"] + #[inline(always)] + pub fn modtau(&mut self) -> MODTAU_W { + MODTAU_W { w: self } + } + #[doc = "Bits 6:11"] + #[inline(always)] + pub fn modk_tune(&mut self) -> MODK_TUNE_W { + MODK_TUNE_W { w: self } + } + #[doc = "Bits 0:5"] + #[inline(always)] + pub fn modtau_tune(&mut self) -> MODTAU_TUNE_W { + MODTAU_TUNE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_lf_ctrl2_reg](index.html) module"] +pub struct ADPLL_LF_CTRL2_REG_SPEC; +impl crate::RegisterSpec for ADPLL_LF_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_lf_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_LF_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_lf_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_LF_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_LF_CTRL2_REG to value 0x1ca2_879e"] +impl crate::Resettable for ADPLL_LF_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x1ca2_879e + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_misc_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_misc_ctrl_reg.rs new file mode 100644 index 0000000..45f966e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_misc_ctrl_reg.rs @@ -0,0 +1,308 @@ +#[doc = "Register `ADPLL_MISC_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_MISC_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PHR_FRAC_PRESET_VAL` reader - "] +pub struct PHR_FRAC_PRESET_VAL_R(crate::FieldReader); +impl PHR_FRAC_PRESET_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + PHR_FRAC_PRESET_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PHR_FRAC_PRESET_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PHR_FRAC_PRESET_VAL` writer - "] +pub struct PHR_FRAC_PRESET_VAL_W<'a> { + w: &'a mut W, +} +impl<'a> PHR_FRAC_PRESET_VAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xffff << 8)) | ((value as u32 & 0xffff) << 8); + self.w + } +} +#[doc = "Field `ENFCWMOD` reader - "] +pub struct ENFCWMOD_R(crate::FieldReader); +impl ENFCWMOD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ENFCWMOD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ENFCWMOD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ENFCWMOD` writer - "] +pub struct ENFCWMOD_W<'a> { + w: &'a mut W, +} +impl<'a> ENFCWMOD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `ENRESIDUE` reader - "] +pub struct ENRESIDUE_R(crate::FieldReader); +impl ENRESIDUE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ENRESIDUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ENRESIDUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ENRESIDUE` writer - "] +pub struct ENRESIDUE_W<'a> { + w: &'a mut W, +} +impl<'a> ENRESIDUE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `MODDLY` reader - "] +pub struct MODDLY_R(crate::FieldReader); +impl MODDLY_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MODDLY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MODDLY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MODDLY` writer - "] +pub struct MODDLY_W<'a> { + w: &'a mut W, +} +impl<'a> MODDLY_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u32 & 3) << 4); + self.w + } +} +#[doc = "Field `RESDLY` reader - "] +pub struct RESDLY_R(crate::FieldReader); +impl RESDLY_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESDLY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESDLY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESDLY` writer - "] +pub struct RESDLY_W<'a> { + w: &'a mut W, +} +impl<'a> RESDLY_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 2)) | ((value as u32 & 3) << 2); + self.w + } +} +#[doc = "Field `DLYFCWDT` reader - "] +pub struct DLYFCWDT_R(crate::FieldReader); +impl DLYFCWDT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DLYFCWDT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DLYFCWDT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DLYFCWDT` writer - "] +pub struct DLYFCWDT_W<'a> { + w: &'a mut W, +} +impl<'a> DLYFCWDT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u32 & 3); + self.w + } +} +impl R { + #[doc = "Bits 8:23"] + #[inline(always)] + pub fn phr_frac_preset_val(&self) -> PHR_FRAC_PRESET_VAL_R { + PHR_FRAC_PRESET_VAL_R::new(((self.bits >> 8) & 0xffff) as u16) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn enfcwmod(&self) -> ENFCWMOD_R { + ENFCWMOD_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn enresidue(&self) -> ENRESIDUE_R { + ENRESIDUE_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 4:5"] + #[inline(always)] + pub fn moddly(&self) -> MODDLY_R { + MODDLY_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bits 2:3"] + #[inline(always)] + pub fn resdly(&self) -> RESDLY_R { + RESDLY_R::new(((self.bits >> 2) & 3) as u8) + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn dlyfcwdt(&self) -> DLYFCWDT_R { + DLYFCWDT_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 8:23"] + #[inline(always)] + pub fn phr_frac_preset_val(&mut self) -> PHR_FRAC_PRESET_VAL_W { + PHR_FRAC_PRESET_VAL_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn enfcwmod(&mut self) -> ENFCWMOD_W { + ENFCWMOD_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn enresidue(&mut self) -> ENRESIDUE_W { + ENRESIDUE_W { w: self } + } + #[doc = "Bits 4:5"] + #[inline(always)] + pub fn moddly(&mut self) -> MODDLY_W { + MODDLY_W { w: self } + } + #[doc = "Bits 2:3"] + #[inline(always)] + pub fn resdly(&mut self) -> RESDLY_W { + RESDLY_W { w: self } + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn dlyfcwdt(&mut self) -> DLYFCWDT_W { + DLYFCWDT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_misc_ctrl_reg](index.html) module"] +pub struct ADPLL_MISC_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_MISC_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_misc_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_MISC_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_misc_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_MISC_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_MISC_CTRL_REG to value 0xda"] +impl crate::Resettable for ADPLL_MISC_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0xda + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_mon_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_mon_ctrl_reg.rs new file mode 100644 index 0000000..682acb4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_mon_ctrl_reg.rs @@ -0,0 +1,439 @@ +#[doc = "Register `ADPLL_MON_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_MON_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QUALMONFRCEN` reader - "] +pub struct QUALMONFRCEN_R(crate::FieldReader); +impl QUALMONFRCEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QUALMONFRCEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QUALMONFRCEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QUALMONFRCEN` writer - "] +pub struct QUALMONFRCEN_W<'a> { + w: &'a mut W, +} +impl<'a> QUALMONFRCEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 30)) | ((value as u32 & 1) << 30); + self.w + } +} +#[doc = "Field `QUALMONTRHLD` reader - "] +pub struct QUALMONTRHLD_R(crate::FieldReader); +impl QUALMONTRHLD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QUALMONTRHLD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QUALMONTRHLD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QUALMONTRHLD` writer - "] +pub struct QUALMONTRHLD_W<'a> { + w: &'a mut W, +} +impl<'a> QUALMONTRHLD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 24)) | ((value as u32 & 0x3f) << 24); + self.w + } +} +#[doc = "Field `QUALMONWND` reader - "] +pub struct QUALMONWND_R(crate::FieldReader); +impl QUALMONWND_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QUALMONWND_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QUALMONWND_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QUALMONWND` writer - "] +pub struct QUALMONWND_W<'a> { + w: &'a mut W, +} +impl<'a> QUALMONWND_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 18)) | ((value as u32 & 0x3f) << 18); + self.w + } +} +#[doc = "Field `QUALMONMOD` reader - "] +pub struct QUALMONMOD_R(crate::FieldReader); +impl QUALMONMOD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QUALMONMOD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QUALMONMOD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QUALMONMOD` writer - "] +pub struct QUALMONMOD_W<'a> { + w: &'a mut W, +} +impl<'a> QUALMONMOD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 16)) | ((value as u32 & 3) << 16); + self.w + } +} +#[doc = "Field `HOLD_STATE` reader - "] +pub struct HOLD_STATE_R(crate::FieldReader); +impl HOLD_STATE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + HOLD_STATE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HOLD_STATE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HOLD_STATE` writer - "] +pub struct HOLD_STATE_W<'a> { + w: &'a mut W, +} +impl<'a> HOLD_STATE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `RFMEAS_MODE` reader - "] +pub struct RFMEAS_MODE_R(crate::FieldReader); +impl RFMEAS_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFMEAS_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMEAS_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFMEAS_MODE` writer - "] +pub struct RFMEAS_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> RFMEAS_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `ENRFMEAS` reader - "] +pub struct ENRFMEAS_R(crate::FieldReader); +impl ENRFMEAS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ENRFMEAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ENRFMEAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ENRFMEAS` writer - "] +pub struct ENRFMEAS_W<'a> { + w: &'a mut W, +} +impl<'a> ENRFMEAS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `TMREN` reader - "] +pub struct TMREN_R(crate::FieldReader); +impl TMREN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TMREN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TMREN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TMREN` writer - "] +pub struct TMREN_W<'a> { + w: &'a mut W, +} +impl<'a> TMREN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `TFREQMEAS` reader - "] +pub struct TFREQMEAS_R(crate::FieldReader); +impl TFREQMEAS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TFREQMEAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TFREQMEAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TFREQMEAS` writer - "] +pub struct TFREQMEAS_W<'a> { + w: &'a mut W, +} +impl<'a> TFREQMEAS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bit 30"] + #[inline(always)] + pub fn qualmonfrcen(&self) -> QUALMONFRCEN_R { + QUALMONFRCEN_R::new(((self.bits >> 30) & 1) != 0) + } + #[doc = "Bits 24:29"] + #[inline(always)] + pub fn qualmontrhld(&self) -> QUALMONTRHLD_R { + QUALMONTRHLD_R::new(((self.bits >> 24) & 0x3f) as u8) + } + #[doc = "Bits 18:23"] + #[inline(always)] + pub fn qualmonwnd(&self) -> QUALMONWND_R { + QUALMONWND_R::new(((self.bits >> 18) & 0x3f) as u8) + } + #[doc = "Bits 16:17"] + #[inline(always)] + pub fn qualmonmod(&self) -> QUALMONMOD_R { + QUALMONMOD_R::new(((self.bits >> 16) & 3) as u8) + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn hold_state(&self) -> HOLD_STATE_R { + HOLD_STATE_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn rfmeas_mode(&self) -> RFMEAS_MODE_R { + RFMEAS_MODE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn enrfmeas(&self) -> ENRFMEAS_R { + ENRFMEAS_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn tmren(&self) -> TMREN_R { + TMREN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn tfreqmeas(&self) -> TFREQMEAS_R { + TFREQMEAS_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bit 30"] + #[inline(always)] + pub fn qualmonfrcen(&mut self) -> QUALMONFRCEN_W { + QUALMONFRCEN_W { w: self } + } + #[doc = "Bits 24:29"] + #[inline(always)] + pub fn qualmontrhld(&mut self) -> QUALMONTRHLD_W { + QUALMONTRHLD_W { w: self } + } + #[doc = "Bits 18:23"] + #[inline(always)] + pub fn qualmonwnd(&mut self) -> QUALMONWND_W { + QUALMONWND_W { w: self } + } + #[doc = "Bits 16:17"] + #[inline(always)] + pub fn qualmonmod(&mut self) -> QUALMONMOD_W { + QUALMONMOD_W { w: self } + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn hold_state(&mut self) -> HOLD_STATE_W { + HOLD_STATE_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn rfmeas_mode(&mut self) -> RFMEAS_MODE_W { + RFMEAS_MODE_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn enrfmeas(&mut self) -> ENRFMEAS_W { + ENRFMEAS_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn tmren(&mut self) -> TMREN_W { + TMREN_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn tfreqmeas(&mut self) -> TFREQMEAS_W { + TFREQMEAS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_mon_ctrl_reg](index.html) module"] +pub struct ADPLL_MON_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_MON_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_mon_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_MON_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_mon_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_MON_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_MON_CTRL_REG to value 0x00fc_0f83"] +impl crate::Resettable for ADPLL_MON_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x00fc_0f83 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl1_reg.rs new file mode 100644 index 0000000..115a7e2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl1_reg.rs @@ -0,0 +1,892 @@ +#[doc = "Register `ADPLL_OVERRULE_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_OVERRULE_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OVR_DTC_OH_WR` reader - "] +pub struct OVR_DTC_OH_WR_R(crate::FieldReader); +impl OVR_DTC_OH_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OVR_DTC_OH_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DTC_OH_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DTC_OH_WR` writer - "] +pub struct OVR_DTC_OH_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DTC_OH_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 25)) | ((value as u32 & 0x7f) << 25); + self.w + } +} +#[doc = "Field `OVR_DTC_OH_SEL` reader - "] +pub struct OVR_DTC_OH_SEL_R(crate::FieldReader); +impl OVR_DTC_OH_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DTC_OH_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DTC_OH_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DTC_OH_SEL` writer - "] +pub struct OVR_DTC_OH_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DTC_OH_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 24)) | ((value as u32 & 1) << 24); + self.w + } +} +#[doc = "Field `OVR_DCOAMP_WR` reader - "] +pub struct OVR_DCOAMP_WR_R(crate::FieldReader); +impl OVR_DCOAMP_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OVR_DCOAMP_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOAMP_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOAMP_WR` writer - "] +pub struct OVR_DCOAMP_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOAMP_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 17)) | ((value as u32 & 0x0f) << 17); + self.w + } +} +#[doc = "Field `OVR_DCOAMP_SEL` reader - "] +pub struct OVR_DCOAMP_SEL_R(crate::FieldReader); +impl OVR_DCOAMP_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DCOAMP_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOAMP_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOAMP_SEL` writer - "] +pub struct OVR_DCOAMP_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOAMP_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `OVR_DCOAMPHOLD_WR` reader - "] +pub struct OVR_DCOAMPHOLD_WR_R(crate::FieldReader); +impl OVR_DCOAMPHOLD_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DCOAMPHOLD_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOAMPHOLD_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOAMPHOLD_WR` writer - "] +pub struct OVR_DCOAMPHOLD_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOAMPHOLD_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u32 & 1) << 13); + self.w + } +} +#[doc = "Field `OVR_DCOAMPHOLD_SEL` reader - "] +pub struct OVR_DCOAMPHOLD_SEL_R(crate::FieldReader); +impl OVR_DCOAMPHOLD_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DCOAMPHOLD_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOAMPHOLD_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOAMPHOLD_SEL` writer - "] +pub struct OVR_DCOAMPHOLD_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOAMPHOLD_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u32 & 1) << 12); + self.w + } +} +#[doc = "Field `OVR_RDYFORDIV_WR` reader - "] +pub struct OVR_RDYFORDIV_WR_R(crate::FieldReader); +impl OVR_RDYFORDIV_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RDYFORDIV_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RDYFORDIV_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RDYFORDIV_WR` writer - "] +pub struct OVR_RDYFORDIV_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RDYFORDIV_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u32 & 1) << 11); + self.w + } +} +#[doc = "Field `OVR_RDYFORDIV_SEL` reader - "] +pub struct OVR_RDYFORDIV_SEL_R(crate::FieldReader); +impl OVR_RDYFORDIV_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RDYFORDIV_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RDYFORDIV_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RDYFORDIV_SEL` writer - "] +pub struct OVR_RDYFORDIV_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RDYFORDIV_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u32 & 1) << 10); + self.w + } +} +#[doc = "Field `OVR_VPAEN_WR` reader - "] +pub struct OVR_VPAEN_WR_R(crate::FieldReader); +impl OVR_VPAEN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_VPAEN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_VPAEN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_VPAEN_WR` writer - "] +pub struct OVR_VPAEN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_VPAEN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `OVR_VPAEN_SEL` reader - "] +pub struct OVR_VPAEN_SEL_R(crate::FieldReader); +impl OVR_VPAEN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_VPAEN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_VPAEN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_VPAEN_SEL` writer - "] +pub struct OVR_VPAEN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_VPAEN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `OVR_SRESETN_WR` reader - "] +pub struct OVR_SRESETN_WR_R(crate::FieldReader); +impl OVR_SRESETN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_SRESETN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_SRESETN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_SRESETN_WR` writer - "] +pub struct OVR_SRESETN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_SRESETN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `OVR_SRESETN_SEL` reader - "] +pub struct OVR_SRESETN_SEL_R(crate::FieldReader); +impl OVR_SRESETN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_SRESETN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_SRESETN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_SRESETN_SEL` writer - "] +pub struct OVR_SRESETN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_SRESETN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `OVR_ENPAIN_WR` reader - "] +pub struct OVR_ENPAIN_WR_R(crate::FieldReader); +impl OVR_ENPAIN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_ENPAIN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_ENPAIN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_ENPAIN_WR` writer - "] +pub struct OVR_ENPAIN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_ENPAIN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `OVR_ENPAIN_SEL` reader - "] +pub struct OVR_ENPAIN_SEL_R(crate::FieldReader); +impl OVR_ENPAIN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_ENPAIN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_ENPAIN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_ENPAIN_SEL` writer - "] +pub struct OVR_ENPAIN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_ENPAIN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `OVR_RXBIT_WR` reader - "] +pub struct OVR_RXBIT_WR_R(crate::FieldReader); +impl OVR_RXBIT_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RXBIT_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RXBIT_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RXBIT_WR` writer - "] +pub struct OVR_RXBIT_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RXBIT_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `OVR_RXBIT_SEL` reader - "] +pub struct OVR_RXBIT_SEL_R(crate::FieldReader); +impl OVR_RXBIT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RXBIT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RXBIT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RXBIT_SEL` writer - "] +pub struct OVR_RXBIT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RXBIT_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `OVR_ACTIVE_WR` reader - "] +pub struct OVR_ACTIVE_WR_R(crate::FieldReader); +impl OVR_ACTIVE_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_ACTIVE_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_ACTIVE_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_ACTIVE_WR` writer - "] +pub struct OVR_ACTIVE_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_ACTIVE_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `OVR_ACTIVE_SEL` reader - "] +pub struct OVR_ACTIVE_SEL_R(crate::FieldReader); +impl OVR_ACTIVE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_ACTIVE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_ACTIVE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_ACTIVE_SEL` writer - "] +pub struct OVR_ACTIVE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_ACTIVE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bits 25:31"] + #[inline(always)] + pub fn ovr_dtc_oh_wr(&self) -> OVR_DTC_OH_WR_R { + OVR_DTC_OH_WR_R::new(((self.bits >> 25) & 0x7f) as u8) + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn ovr_dtc_oh_sel(&self) -> OVR_DTC_OH_SEL_R { + OVR_DTC_OH_SEL_R::new(((self.bits >> 24) & 1) != 0) + } + #[doc = "Bits 17:20"] + #[inline(always)] + pub fn ovr_dcoamp_wr(&self) -> OVR_DCOAMP_WR_R { + OVR_DCOAMP_WR_R::new(((self.bits >> 17) & 0x0f) as u8) + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn ovr_dcoamp_sel(&self) -> OVR_DCOAMP_SEL_R { + OVR_DCOAMP_SEL_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn ovr_dcoamphold_wr(&self) -> OVR_DCOAMPHOLD_WR_R { + OVR_DCOAMPHOLD_WR_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn ovr_dcoamphold_sel(&self) -> OVR_DCOAMPHOLD_SEL_R { + OVR_DCOAMPHOLD_SEL_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn ovr_rdyfordiv_wr(&self) -> OVR_RDYFORDIV_WR_R { + OVR_RDYFORDIV_WR_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn ovr_rdyfordiv_sel(&self) -> OVR_RDYFORDIV_SEL_R { + OVR_RDYFORDIV_SEL_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn ovr_vpaen_wr(&self) -> OVR_VPAEN_WR_R { + OVR_VPAEN_WR_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn ovr_vpaen_sel(&self) -> OVR_VPAEN_SEL_R { + OVR_VPAEN_SEL_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn ovr_sresetn_wr(&self) -> OVR_SRESETN_WR_R { + OVR_SRESETN_WR_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ovr_sresetn_sel(&self) -> OVR_SRESETN_SEL_R { + OVR_SRESETN_SEL_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ovr_enpain_wr(&self) -> OVR_ENPAIN_WR_R { + OVR_ENPAIN_WR_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn ovr_enpain_sel(&self) -> OVR_ENPAIN_SEL_R { + OVR_ENPAIN_SEL_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn ovr_rxbit_wr(&self) -> OVR_RXBIT_WR_R { + OVR_RXBIT_WR_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn ovr_rxbit_sel(&self) -> OVR_RXBIT_SEL_R { + OVR_RXBIT_SEL_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn ovr_active_wr(&self) -> OVR_ACTIVE_WR_R { + OVR_ACTIVE_WR_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ovr_active_sel(&self) -> OVR_ACTIVE_SEL_R { + OVR_ACTIVE_SEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 25:31"] + #[inline(always)] + pub fn ovr_dtc_oh_wr(&mut self) -> OVR_DTC_OH_WR_W { + OVR_DTC_OH_WR_W { w: self } + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn ovr_dtc_oh_sel(&mut self) -> OVR_DTC_OH_SEL_W { + OVR_DTC_OH_SEL_W { w: self } + } + #[doc = "Bits 17:20"] + #[inline(always)] + pub fn ovr_dcoamp_wr(&mut self) -> OVR_DCOAMP_WR_W { + OVR_DCOAMP_WR_W { w: self } + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn ovr_dcoamp_sel(&mut self) -> OVR_DCOAMP_SEL_W { + OVR_DCOAMP_SEL_W { w: self } + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn ovr_dcoamphold_wr(&mut self) -> OVR_DCOAMPHOLD_WR_W { + OVR_DCOAMPHOLD_WR_W { w: self } + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn ovr_dcoamphold_sel(&mut self) -> OVR_DCOAMPHOLD_SEL_W { + OVR_DCOAMPHOLD_SEL_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn ovr_rdyfordiv_wr(&mut self) -> OVR_RDYFORDIV_WR_W { + OVR_RDYFORDIV_WR_W { w: self } + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn ovr_rdyfordiv_sel(&mut self) -> OVR_RDYFORDIV_SEL_W { + OVR_RDYFORDIV_SEL_W { w: self } + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn ovr_vpaen_wr(&mut self) -> OVR_VPAEN_WR_W { + OVR_VPAEN_WR_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn ovr_vpaen_sel(&mut self) -> OVR_VPAEN_SEL_W { + OVR_VPAEN_SEL_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn ovr_sresetn_wr(&mut self) -> OVR_SRESETN_WR_W { + OVR_SRESETN_WR_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ovr_sresetn_sel(&mut self) -> OVR_SRESETN_SEL_W { + OVR_SRESETN_SEL_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ovr_enpain_wr(&mut self) -> OVR_ENPAIN_WR_W { + OVR_ENPAIN_WR_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn ovr_enpain_sel(&mut self) -> OVR_ENPAIN_SEL_W { + OVR_ENPAIN_SEL_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn ovr_rxbit_wr(&mut self) -> OVR_RXBIT_WR_W { + OVR_RXBIT_WR_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn ovr_rxbit_sel(&mut self) -> OVR_RXBIT_SEL_W { + OVR_RXBIT_SEL_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn ovr_active_wr(&mut self) -> OVR_ACTIVE_WR_W { + OVR_ACTIVE_WR_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ovr_active_sel(&mut self) -> OVR_ACTIVE_SEL_W { + OVR_ACTIVE_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_overrule_ctrl1_reg](index.html) module"] +pub struct ADPLL_OVERRULE_CTRL1_REG_SPEC; +impl crate::RegisterSpec for ADPLL_OVERRULE_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_overrule_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_OVERRULE_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_overrule_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_OVERRULE_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_OVERRULE_CTRL1_REG to value 0"] +impl crate::Resettable for ADPLL_OVERRULE_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl2_reg.rs new file mode 100644 index 0000000..9ba39bb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl2_reg.rs @@ -0,0 +1,402 @@ +#[doc = "Register `ADPLL_OVERRULE_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_OVERRULE_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OVR_DCOMOD_WR` reader - "] +pub struct OVR_DCOMOD_WR_R(crate::FieldReader); +impl OVR_DCOMOD_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OVR_DCOMOD_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOMOD_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOMOD_WR` writer - "] +pub struct OVR_DCOMOD_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOMOD_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 24)) | ((value as u32 & 0xff) << 24); + self.w + } +} +#[doc = "Field `OVR_DCOMOD_SEL` reader - "] +pub struct OVR_DCOMOD_SEL_R(crate::FieldReader); +impl OVR_DCOMOD_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DCOMOD_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOMOD_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOMOD_SEL` writer - "] +pub struct OVR_DCOMOD_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOMOD_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 23)) | ((value as u32 & 1) << 23); + self.w + } +} +#[doc = "Field `OVR_DCOFINE_WR` reader - "] +pub struct OVR_DCOFINE_WR_R(crate::FieldReader); +impl OVR_DCOFINE_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OVR_DCOFINE_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOFINE_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOFINE_WR` writer - "] +pub struct OVR_DCOFINE_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOFINE_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 17)) | ((value as u32 & 0x3f) << 17); + self.w + } +} +#[doc = "Field `OVR_DCOFINE_SEL` reader - "] +pub struct OVR_DCOFINE_SEL_R(crate::FieldReader); +impl OVR_DCOFINE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DCOFINE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOFINE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOFINE_SEL` writer - "] +pub struct OVR_DCOFINE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOFINE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `OVR_DCOMEDIUM_WR` reader - "] +pub struct OVR_DCOMEDIUM_WR_R(crate::FieldReader); +impl OVR_DCOMEDIUM_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OVR_DCOMEDIUM_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOMEDIUM_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOMEDIUM_WR` writer - "] +pub struct OVR_DCOMEDIUM_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOMEDIUM_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 9)) | ((value as u32 & 7) << 9); + self.w + } +} +#[doc = "Field `OVR_DCOMEDIUM_SEL` reader - "] +pub struct OVR_DCOMEDIUM_SEL_R(crate::FieldReader); +impl OVR_DCOMEDIUM_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DCOMEDIUM_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOMEDIUM_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOMEDIUM_SEL` writer - "] +pub struct OVR_DCOMEDIUM_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOMEDIUM_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `OVR_DCOCOARSE_WR` reader - "] +pub struct OVR_DCOCOARSE_WR_R(crate::FieldReader); +impl OVR_DCOCOARSE_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OVR_DCOCOARSE_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOCOARSE_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOCOARSE_WR` writer - "] +pub struct OVR_DCOCOARSE_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOCOARSE_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 1)) | ((value as u32 & 0x0f) << 1); + self.w + } +} +#[doc = "Field `OVR_DCOCOARSE_SEL` reader - "] +pub struct OVR_DCOCOARSE_SEL_R(crate::FieldReader); +impl OVR_DCOCOARSE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_DCOCOARSE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_DCOCOARSE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_DCOCOARSE_SEL` writer - "] +pub struct OVR_DCOCOARSE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_DCOCOARSE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bits 24:31"] + #[inline(always)] + pub fn ovr_dcomod_wr(&self) -> OVR_DCOMOD_WR_R { + OVR_DCOMOD_WR_R::new(((self.bits >> 24) & 0xff) as u8) + } + #[doc = "Bit 23"] + #[inline(always)] + pub fn ovr_dcomod_sel(&self) -> OVR_DCOMOD_SEL_R { + OVR_DCOMOD_SEL_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bits 17:22"] + #[inline(always)] + pub fn ovr_dcofine_wr(&self) -> OVR_DCOFINE_WR_R { + OVR_DCOFINE_WR_R::new(((self.bits >> 17) & 0x3f) as u8) + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn ovr_dcofine_sel(&self) -> OVR_DCOFINE_SEL_R { + OVR_DCOFINE_SEL_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bits 9:11"] + #[inline(always)] + pub fn ovr_dcomedium_wr(&self) -> OVR_DCOMEDIUM_WR_R { + OVR_DCOMEDIUM_WR_R::new(((self.bits >> 9) & 7) as u8) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn ovr_dcomedium_sel(&self) -> OVR_DCOMEDIUM_SEL_R { + OVR_DCOMEDIUM_SEL_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 1:4"] + #[inline(always)] + pub fn ovr_dcocoarse_wr(&self) -> OVR_DCOCOARSE_WR_R { + OVR_DCOCOARSE_WR_R::new(((self.bits >> 1) & 0x0f) as u8) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ovr_dcocoarse_sel(&self) -> OVR_DCOCOARSE_SEL_R { + OVR_DCOCOARSE_SEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 24:31"] + #[inline(always)] + pub fn ovr_dcomod_wr(&mut self) -> OVR_DCOMOD_WR_W { + OVR_DCOMOD_WR_W { w: self } + } + #[doc = "Bit 23"] + #[inline(always)] + pub fn ovr_dcomod_sel(&mut self) -> OVR_DCOMOD_SEL_W { + OVR_DCOMOD_SEL_W { w: self } + } + #[doc = "Bits 17:22"] + #[inline(always)] + pub fn ovr_dcofine_wr(&mut self) -> OVR_DCOFINE_WR_W { + OVR_DCOFINE_WR_W { w: self } + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn ovr_dcofine_sel(&mut self) -> OVR_DCOFINE_SEL_W { + OVR_DCOFINE_SEL_W { w: self } + } + #[doc = "Bits 9:11"] + #[inline(always)] + pub fn ovr_dcomedium_wr(&mut self) -> OVR_DCOMEDIUM_WR_W { + OVR_DCOMEDIUM_WR_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn ovr_dcomedium_sel(&mut self) -> OVR_DCOMEDIUM_SEL_W { + OVR_DCOMEDIUM_SEL_W { w: self } + } + #[doc = "Bits 1:4"] + #[inline(always)] + pub fn ovr_dcocoarse_wr(&mut self) -> OVR_DCOCOARSE_WR_W { + OVR_DCOCOARSE_WR_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ovr_dcocoarse_sel(&mut self) -> OVR_DCOCOARSE_SEL_W { + OVR_DCOCOARSE_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_overrule_ctrl2_reg](index.html) module"] +pub struct ADPLL_OVERRULE_CTRL2_REG_SPEC; +impl crate::RegisterSpec for ADPLL_OVERRULE_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_overrule_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_OVERRULE_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_overrule_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_OVERRULE_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_OVERRULE_CTRL2_REG to value 0"] +impl crate::Resettable for ADPLL_OVERRULE_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl3_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl3_reg.rs new file mode 100644 index 0000000..0d56890 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_overrule_ctrl3_reg.rs @@ -0,0 +1,442 @@ +#[doc = "Register `ADPLL_OVERRULE_CTRL3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_OVERRULE_CTRL3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OVR_RXDIV_FB_EN_WR` reader - "] +pub struct OVR_RXDIV_FB_EN_WR_R(crate::FieldReader); +impl OVR_RXDIV_FB_EN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RXDIV_FB_EN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RXDIV_FB_EN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RXDIV_FB_EN_WR` writer - "] +pub struct OVR_RXDIV_FB_EN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RXDIV_FB_EN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `OVR_RXDIV_FB_EN_SEL` reader - "] +pub struct OVR_RXDIV_FB_EN_SEL_R(crate::FieldReader); +impl OVR_RXDIV_FB_EN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RXDIV_FB_EN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RXDIV_FB_EN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RXDIV_FB_EN_SEL` writer - "] +pub struct OVR_RXDIV_FB_EN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RXDIV_FB_EN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `OVR_FBDIV_EN_WR` reader - "] +pub struct OVR_FBDIV_EN_WR_R(crate::FieldReader); +impl OVR_FBDIV_EN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_FBDIV_EN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_FBDIV_EN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_FBDIV_EN_WR` writer - "] +pub struct OVR_FBDIV_EN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_FBDIV_EN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `OVR_FBDIV_EN_SEL` reader - "] +pub struct OVR_FBDIV_EN_SEL_R(crate::FieldReader); +impl OVR_FBDIV_EN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_FBDIV_EN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_FBDIV_EN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_FBDIV_EN_SEL` writer - "] +pub struct OVR_FBDIV_EN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_FBDIV_EN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `OVR_TXDIV_EN_WR` reader - "] +pub struct OVR_TXDIV_EN_WR_R(crate::FieldReader); +impl OVR_TXDIV_EN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_TXDIV_EN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_TXDIV_EN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_TXDIV_EN_WR` writer - "] +pub struct OVR_TXDIV_EN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_TXDIV_EN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `OVR_TXDIV_EN_SEL` reader - "] +pub struct OVR_TXDIV_EN_SEL_R(crate::FieldReader); +impl OVR_TXDIV_EN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_TXDIV_EN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_TXDIV_EN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_TXDIV_EN_SEL` writer - "] +pub struct OVR_TXDIV_EN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_TXDIV_EN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `OVR_RXDIV_EN_WR` reader - "] +pub struct OVR_RXDIV_EN_WR_R(crate::FieldReader); +impl OVR_RXDIV_EN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RXDIV_EN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RXDIV_EN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RXDIV_EN_WR` writer - "] +pub struct OVR_RXDIV_EN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RXDIV_EN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `OVR_RXDIV_EN_SEL` reader - "] +pub struct OVR_RXDIV_EN_SEL_R(crate::FieldReader); +impl OVR_RXDIV_EN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OVR_RXDIV_EN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OVR_RXDIV_EN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OVR_RXDIV_EN_SEL` writer - "] +pub struct OVR_RXDIV_EN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OVR_RXDIV_EN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 7"] + #[inline(always)] + pub fn ovr_rxdiv_fb_en_wr(&self) -> OVR_RXDIV_FB_EN_WR_R { + OVR_RXDIV_FB_EN_WR_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ovr_rxdiv_fb_en_sel(&self) -> OVR_RXDIV_FB_EN_SEL_R { + OVR_RXDIV_FB_EN_SEL_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ovr_fbdiv_en_wr(&self) -> OVR_FBDIV_EN_WR_R { + OVR_FBDIV_EN_WR_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn ovr_fbdiv_en_sel(&self) -> OVR_FBDIV_EN_SEL_R { + OVR_FBDIV_EN_SEL_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn ovr_txdiv_en_wr(&self) -> OVR_TXDIV_EN_WR_R { + OVR_TXDIV_EN_WR_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn ovr_txdiv_en_sel(&self) -> OVR_TXDIV_EN_SEL_R { + OVR_TXDIV_EN_SEL_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn ovr_rxdiv_en_wr(&self) -> OVR_RXDIV_EN_WR_R { + OVR_RXDIV_EN_WR_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ovr_rxdiv_en_sel(&self) -> OVR_RXDIV_EN_SEL_R { + OVR_RXDIV_EN_SEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 7"] + #[inline(always)] + pub fn ovr_rxdiv_fb_en_wr(&mut self) -> OVR_RXDIV_FB_EN_WR_W { + OVR_RXDIV_FB_EN_WR_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ovr_rxdiv_fb_en_sel(&mut self) -> OVR_RXDIV_FB_EN_SEL_W { + OVR_RXDIV_FB_EN_SEL_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ovr_fbdiv_en_wr(&mut self) -> OVR_FBDIV_EN_WR_W { + OVR_FBDIV_EN_WR_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn ovr_fbdiv_en_sel(&mut self) -> OVR_FBDIV_EN_SEL_W { + OVR_FBDIV_EN_SEL_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn ovr_txdiv_en_wr(&mut self) -> OVR_TXDIV_EN_WR_W { + OVR_TXDIV_EN_WR_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn ovr_txdiv_en_sel(&mut self) -> OVR_TXDIV_EN_SEL_W { + OVR_TXDIV_EN_SEL_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn ovr_rxdiv_en_wr(&mut self) -> OVR_RXDIV_EN_WR_W { + OVR_RXDIV_EN_WR_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ovr_rxdiv_en_sel(&mut self) -> OVR_RXDIV_EN_SEL_W { + OVR_RXDIV_EN_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_overrule_ctrl3_reg](index.html) module"] +pub struct ADPLL_OVERRULE_CTRL3_REG_SPEC; +impl crate::RegisterSpec for ADPLL_OVERRULE_CTRL3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_overrule_ctrl3_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_OVERRULE_CTRL3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_overrule_ctrl3_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_OVERRULE_CTRL3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_OVERRULE_CTRL3_REG to value 0"] +impl crate::Resettable for ADPLL_OVERRULE_CTRL3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_pllfcwdt_rd_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_pllfcwdt_rd_reg.rs new file mode 100644 index 0000000..b2323e4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_pllfcwdt_rd_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `ADPLL_PLLFCWDT_RD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_PLLFCWDT_RD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PLLFCWDT` reader - "] +pub struct PLLFCWDT_R(crate::FieldReader); +impl PLLFCWDT_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PLLFCWDT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PLLFCWDT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:22"] + #[inline(always)] + pub fn pllfcwdt(&self) -> PLLFCWDT_R { + PLLFCWDT_R::new((self.bits & 0x007f_ffff) as u32) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_pllfcwdt_rd_reg](index.html) module"] +pub struct ADPLL_PLLFCWDT_RD_REG_SPEC; +impl crate::RegisterSpec for ADPLL_PLLFCWDT_RD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_pllfcwdt_rd_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_PLLFCWDT_RD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_pllfcwdt_rd_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_PLLFCWDT_RD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_PLLFCWDT_RD_REG to value 0x0025_8800"] +impl crate::Resettable for ADPLL_PLLFCWDT_RD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0025_8800 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_rfpt_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_rfpt_ctrl_reg.rs new file mode 100644 index 0000000..7b4a381 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_rfpt_ctrl_reg.rs @@ -0,0 +1,197 @@ +#[doc = "Register `ADPLL_RFPT_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_RFPT_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFPT_RATE` reader - "] +pub struct RFPT_RATE_R(crate::FieldReader); +impl RFPT_RATE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFPT_RATE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFPT_RATE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFPT_RATE` writer - "] +pub struct RFPT_RATE_W<'a> { + w: &'a mut W, +} +impl<'a> RFPT_RATE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `INV_CKRFPT` reader - "] +pub struct INV_CKRFPT_R(crate::FieldReader); +impl INV_CKRFPT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INV_CKRFPT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INV_CKRFPT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INV_CKRFPT` writer - "] +pub struct INV_CKRFPT_W<'a> { + w: &'a mut W, +} +impl<'a> INV_CKRFPT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `RFPT_MUX` reader - "] +pub struct RFPT_MUX_R(crate::FieldReader); +impl RFPT_MUX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFPT_MUX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFPT_MUX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFPT_MUX` writer - "] +pub struct RFPT_MUX_W<'a> { + w: &'a mut W, +} +impl<'a> RFPT_MUX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 5"] + #[inline(always)] + pub fn rfpt_rate(&self) -> RFPT_RATE_R { + RFPT_RATE_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn inv_ckrfpt(&self) -> INV_CKRFPT_R { + INV_CKRFPT_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rfpt_mux(&self) -> RFPT_MUX_R { + RFPT_MUX_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bit 5"] + #[inline(always)] + pub fn rfpt_rate(&mut self) -> RFPT_RATE_W { + RFPT_RATE_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn inv_ckrfpt(&mut self) -> INV_CKRFPT_W { + INV_CKRFPT_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rfpt_mux(&mut self) -> RFPT_MUX_W { + RFPT_MUX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_rfpt_ctrl_reg](index.html) module"] +pub struct ADPLL_RFPT_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_RFPT_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_rfpt_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_RFPT_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_rfpt_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_RFPT_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_RFPT_CTRL_REG to value 0"] +impl crate::Resettable for ADPLL_RFPT_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_sdmod_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_sdmod_ctrl_reg.rs new file mode 100644 index 0000000..cd50637 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_sdmod_ctrl_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `ADPLL_SDMOD_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_SDMOD_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SDMMODETX` reader - "] +pub struct SDMMODETX_R(crate::FieldReader); +impl SDMMODETX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SDMMODETX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SDMMODETX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SDMMODETX` writer - "] +pub struct SDMMODETX_W<'a> { + w: &'a mut W, +} +impl<'a> SDMMODETX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 3)) | ((value as u32 & 7) << 3); + self.w + } +} +#[doc = "Field `SDMMODERX` reader - "] +pub struct SDMMODERX_R(crate::FieldReader); +impl SDMMODERX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SDMMODERX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SDMMODERX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SDMMODERX` writer - "] +pub struct SDMMODERX_W<'a> { + w: &'a mut W, +} +impl<'a> SDMMODERX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn sdmmodetx(&self) -> SDMMODETX_R { + SDMMODETX_R::new(((self.bits >> 3) & 7) as u8) + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn sdmmoderx(&self) -> SDMMODERX_R { + SDMMODERX_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn sdmmodetx(&mut self) -> SDMMODETX_W { + SDMMODETX_W { w: self } + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn sdmmoderx(&mut self) -> SDMMODERX_W { + SDMMODERX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_sdmod_ctrl_reg](index.html) module"] +pub struct ADPLL_SDMOD_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_SDMOD_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_sdmod_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_SDMOD_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_sdmod_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_SDMOD_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_SDMOD_CTRL_REG to value 0x39"] +impl crate::Resettable for ADPLL_SDMOD_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x39 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_tunestate_rd_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_tunestate_rd_reg.rs new file mode 100644 index 0000000..c2f4f8f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_tunestate_rd_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `ADPLL_TUNESTATE_RD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_TUNESTATE_RD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TMRVAL` reader - "] +pub struct TMRVAL_R(crate::FieldReader); +impl TMRVAL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TMRVAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TMRVAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TUNE_STATE` reader - "] +pub struct TUNE_STATE_R(crate::FieldReader); +impl TUNE_STATE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TUNE_STATE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TUNE_STATE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 4:13"] + #[inline(always)] + pub fn tmrval(&self) -> TMRVAL_R { + TMRVAL_R::new(((self.bits >> 4) & 0x03ff) as u16) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn tune_state(&self) -> TUNE_STATE_R { + TUNE_STATE_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_tunestate_rd_reg](index.html) module"] +pub struct ADPLL_TUNESTATE_RD_REG_SPEC; +impl crate::RegisterSpec for ADPLL_TUNESTATE_RD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_tunestate_rd_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_TUNESTATE_RD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_tunestate_rd_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_TUNESTATE_RD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_TUNESTATE_RD_REG to value 0"] +impl crate::Resettable for ADPLL_TUNESTATE_RD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/adplldig/adpll_txmod_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_txmod_ctrl_reg.rs new file mode 100644 index 0000000..e058503 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/adplldig/adpll_txmod_ctrl_reg.rs @@ -0,0 +1,328 @@ +#[doc = "Register `ADPLL_TXMOD_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ADPLL_TXMOD_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `INV_CKMODEXT` reader - "] +pub struct INV_CKMODEXT_R(crate::FieldReader); +impl INV_CKMODEXT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INV_CKMODEXT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INV_CKMODEXT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INV_CKMODEXT` writer - "] +pub struct INV_CKMODEXT_W<'a> { + w: &'a mut W, +} +impl<'a> INV_CKMODEXT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `TX_MODE` reader - "] +pub struct TX_MODE_R(crate::FieldReader); +impl TX_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TX_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TX_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TX_MODE` writer - "] +pub struct TX_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> TX_MODE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 6)) | ((value as u32 & 3) << 6); + self.w + } +} +#[doc = "Field `EO_PACKET_DIS` reader - "] +pub struct EO_PACKET_DIS_R(crate::FieldReader); +impl EO_PACKET_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EO_PACKET_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EO_PACKET_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EO_PACKET_DIS` writer - "] +pub struct EO_PACKET_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> EO_PACKET_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `MOD_INDEX` reader - "] +pub struct MOD_INDEX_R(crate::FieldReader); +impl MOD_INDEX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MOD_INDEX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MOD_INDEX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MOD_INDEX` writer - "] +pub struct MOD_INDEX_W<'a> { + w: &'a mut W, +} +impl<'a> MOD_INDEX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 2)) | ((value as u32 & 3) << 2); + self.w + } +} +#[doc = "Field `TX_DATA_INV` reader - "] +pub struct TX_DATA_INV_R(crate::FieldReader); +impl TX_DATA_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TX_DATA_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TX_DATA_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TX_DATA_INV` writer - "] +pub struct TX_DATA_INV_W<'a> { + w: &'a mut W, +} +impl<'a> TX_DATA_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `BT_SEL` reader - "] +pub struct BT_SEL_R(crate::FieldReader); +impl BT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BT_SEL` writer - "] +pub struct BT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> BT_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 8"] + #[inline(always)] + pub fn inv_ckmodext(&self) -> INV_CKMODEXT_R { + INV_CKMODEXT_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 6:7"] + #[inline(always)] + pub fn tx_mode(&self) -> TX_MODE_R { + TX_MODE_R::new(((self.bits >> 6) & 3) as u8) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn eo_packet_dis(&self) -> EO_PACKET_DIS_R { + EO_PACKET_DIS_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 2:3"] + #[inline(always)] + pub fn mod_index(&self) -> MOD_INDEX_R { + MOD_INDEX_R::new(((self.bits >> 2) & 3) as u8) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn tx_data_inv(&self) -> TX_DATA_INV_R { + TX_DATA_INV_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn bt_sel(&self) -> BT_SEL_R { + BT_SEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 8"] + #[inline(always)] + pub fn inv_ckmodext(&mut self) -> INV_CKMODEXT_W { + INV_CKMODEXT_W { w: self } + } + #[doc = "Bits 6:7"] + #[inline(always)] + pub fn tx_mode(&mut self) -> TX_MODE_W { + TX_MODE_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn eo_packet_dis(&mut self) -> EO_PACKET_DIS_W { + EO_PACKET_DIS_W { w: self } + } + #[doc = "Bits 2:3"] + #[inline(always)] + pub fn mod_index(&mut self) -> MOD_INDEX_W { + MOD_INDEX_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn tx_data_inv(&mut self) -> TX_DATA_INV_W { + TX_DATA_INV_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn bt_sel(&mut self) -> BT_SEL_W { + BT_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [adpll_txmod_ctrl_reg](index.html) module"] +pub struct ADPLL_TXMOD_CTRL_REG_SPEC; +impl crate::RegisterSpec for ADPLL_TXMOD_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [adpll_txmod_ctrl_reg::R](R) reader structure"] +impl crate::Readable for ADPLL_TXMOD_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [adpll_txmod_ctrl_reg::W](W) writer structure"] +impl crate::Writable for ADPLL_TXMOD_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ADPLL_TXMOD_CTRL_REG to value 0"] +impl crate::Resettable for ADPLL_TXMOD_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/anamisc.rs b/bitbox02-bt/vendor/da14531/src/anamisc.rs new file mode 100644 index 0000000..5e7238b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/anamisc.rs @@ -0,0 +1,28 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Select clock for oscillator calibration"] + pub clk_ref_sel_reg: crate::Reg, + #[doc = "0x02 - Count value for oscillator calibration"] + pub clk_ref_cnt_reg: crate::Reg, + #[doc = "0x04 - XTAL32M reference cycles, lower 16 bits"] + pub clk_ref_val_l_reg: crate::Reg, + #[doc = "0x06 - XTAL32M reference cycles, higher 16 bits"] + pub clk_ref_val_h_reg: crate::Reg, +} +#[doc = "CLK_REF_CNT_REG register accessor: an alias for `Reg`"] +pub type CLK_REF_CNT_REG = crate::Reg; +#[doc = "Count value for oscillator calibration"] +pub mod clk_ref_cnt_reg; +#[doc = "CLK_REF_SEL_REG register accessor: an alias for `Reg`"] +pub type CLK_REF_SEL_REG = crate::Reg; +#[doc = "Select clock for oscillator calibration"] +pub mod clk_ref_sel_reg; +#[doc = "CLK_REF_VAL_H_REG register accessor: an alias for `Reg`"] +pub type CLK_REF_VAL_H_REG = crate::Reg; +#[doc = "XTAL32M reference cycles, higher 16 bits"] +pub mod clk_ref_val_h_reg; +#[doc = "CLK_REF_VAL_L_REG register accessor: an alias for `Reg`"] +pub type CLK_REF_VAL_L_REG = crate::Reg; +#[doc = "XTAL32M reference cycles, lower 16 bits"] +pub mod clk_ref_val_l_reg; diff --git a/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_cnt_reg.rs b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_cnt_reg.rs new file mode 100644 index 0000000..5028c73 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_cnt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `CLK_REF_CNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_REF_CNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `REF_CNT_VAL` reader - Indicates the calibration time, with a decrement counter to 1."] +pub struct REF_CNT_VAL_R(crate::FieldReader); +impl REF_CNT_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + REF_CNT_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REF_CNT_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REF_CNT_VAL` writer - Indicates the calibration time, with a decrement counter to 1."] +pub struct REF_CNT_VAL_W<'a> { + w: &'a mut W, +} +impl<'a> REF_CNT_VAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - Indicates the calibration time, with a decrement counter to 1."] + #[inline(always)] + pub fn ref_cnt_val(&self) -> REF_CNT_VAL_R { + REF_CNT_VAL_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - Indicates the calibration time, with a decrement counter to 1."] + #[inline(always)] + pub fn ref_cnt_val(&mut self) -> REF_CNT_VAL_W { + REF_CNT_VAL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Count value for oscillator calibration\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ref_cnt_reg](index.html) module"] +pub struct CLK_REF_CNT_REG_SPEC; +impl crate::RegisterSpec for CLK_REF_CNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_ref_cnt_reg::R](R) reader structure"] +impl crate::Readable for CLK_REF_CNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_ref_cnt_reg::W](W) writer structure"] +impl crate::Writable for CLK_REF_CNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_REF_CNT_REG to value 0"] +impl crate::Resettable for CLK_REF_CNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_sel_reg.rs new file mode 100644 index 0000000..60775d8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_sel_reg.rs @@ -0,0 +1,197 @@ +#[doc = "Register `CLK_REF_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_REF_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `EXT_CNT_EN_SEL` reader - 0 : Enable XTAL_CNT counter by the REF_CLK selected by REF_CLK_SEL. 1 : Enable XTAL_CNT counter from an external input."] +pub struct EXT_CNT_EN_SEL_R(crate::FieldReader); +impl EXT_CNT_EN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EXT_CNT_EN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EXT_CNT_EN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EXT_CNT_EN_SEL` writer - 0 : Enable XTAL_CNT counter by the REF_CLK selected by REF_CLK_SEL. 1 : Enable XTAL_CNT counter from an external input."] +pub struct EXT_CNT_EN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> EXT_CNT_EN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `REF_CAL_START` reader - Writing a '1' starts a calibration of the clock selected by CLK_REF_SEL_REG\\[REF_CLK_SEL\\]. This bit is cleared when calibration is finished, and CLK_REF_VAL is ready."] +pub struct REF_CAL_START_R(crate::FieldReader); +impl REF_CAL_START_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + REF_CAL_START_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REF_CAL_START_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REF_CAL_START` writer - Writing a '1' starts a calibration of the clock selected by CLK_REF_SEL_REG\\[REF_CLK_SEL\\]. This bit is cleared when calibration is finished, and CLK_REF_VAL is ready."] +pub struct REF_CAL_START_W<'a> { + w: &'a mut W, +} +impl<'a> REF_CAL_START_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `REF_CLK_SEL` reader - Select clock input for calibration: 0x0 : RC32K 0x1 : RC32M 0x2 : XTAL32K 0x3 : RCX"] +pub struct REF_CLK_SEL_R(crate::FieldReader); +impl REF_CLK_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + REF_CLK_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REF_CLK_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REF_CLK_SEL` writer - Select clock input for calibration: 0x0 : RC32K 0x1 : RC32M 0x2 : XTAL32K 0x3 : RCX"] +pub struct REF_CLK_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> REF_CLK_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 3 - 0 : Enable XTAL_CNT counter by the REF_CLK selected by REF_CLK_SEL. 1 : Enable XTAL_CNT counter from an external input."] + #[inline(always)] + pub fn ext_cnt_en_sel(&self) -> EXT_CNT_EN_SEL_R { + EXT_CNT_EN_SEL_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Writing a '1' starts a calibration of the clock selected by CLK_REF_SEL_REG\\[REF_CLK_SEL\\]. This bit is cleared when calibration is finished, and CLK_REF_VAL is ready."] + #[inline(always)] + pub fn ref_cal_start(&self) -> REF_CAL_START_R { + REF_CAL_START_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1 - Select clock input for calibration: 0x0 : RC32K 0x1 : RC32M 0x2 : XTAL32K 0x3 : RCX"] + #[inline(always)] + pub fn ref_clk_sel(&self) -> REF_CLK_SEL_R { + REF_CLK_SEL_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 3 - 0 : Enable XTAL_CNT counter by the REF_CLK selected by REF_CLK_SEL. 1 : Enable XTAL_CNT counter from an external input."] + #[inline(always)] + pub fn ext_cnt_en_sel(&mut self) -> EXT_CNT_EN_SEL_W { + EXT_CNT_EN_SEL_W { w: self } + } + #[doc = "Bit 2 - Writing a '1' starts a calibration of the clock selected by CLK_REF_SEL_REG\\[REF_CLK_SEL\\]. This bit is cleared when calibration is finished, and CLK_REF_VAL is ready."] + #[inline(always)] + pub fn ref_cal_start(&mut self) -> REF_CAL_START_W { + REF_CAL_START_W { w: self } + } + #[doc = "Bits 0:1 - Select clock input for calibration: 0x0 : RC32K 0x1 : RC32M 0x2 : XTAL32K 0x3 : RCX"] + #[inline(always)] + pub fn ref_clk_sel(&mut self) -> REF_CLK_SEL_W { + REF_CLK_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Select clock for oscillator calibration\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ref_sel_reg](index.html) module"] +pub struct CLK_REF_SEL_REG_SPEC; +impl crate::RegisterSpec for CLK_REF_SEL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_ref_sel_reg::R](R) reader structure"] +impl crate::Readable for CLK_REF_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_ref_sel_reg::W](W) writer structure"] +impl crate::Writable for CLK_REF_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_REF_SEL_REG to value 0"] +impl crate::Resettable for CLK_REF_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_h_reg.rs b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_h_reg.rs new file mode 100644 index 0000000..e715439 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_h_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CLK_REF_VAL_H_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_REF_VAL_H_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL_CNT_VAL` reader - Returns the number of DIVN clock cycles counted during the calibration time, defined with REF_CNT_VAL"] +pub struct XTAL_CNT_VAL_R(crate::FieldReader); +impl XTAL_CNT_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + XTAL_CNT_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL_CNT_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Returns the number of DIVN clock cycles counted during the calibration time, defined with REF_CNT_VAL"] + #[inline(always)] + pub fn xtal_cnt_val(&self) -> XTAL_CNT_VAL_R { + XTAL_CNT_VAL_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "XTAL32M reference cycles, higher 16 bits\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ref_val_h_reg](index.html) module"] +pub struct CLK_REF_VAL_H_REG_SPEC; +impl crate::RegisterSpec for CLK_REF_VAL_H_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_ref_val_h_reg::R](R) reader structure"] +impl crate::Readable for CLK_REF_VAL_H_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_ref_val_h_reg::W](W) writer structure"] +impl crate::Writable for CLK_REF_VAL_H_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_REF_VAL_H_REG to value 0"] +impl crate::Resettable for CLK_REF_VAL_H_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_l_reg.rs b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_l_reg.rs new file mode 100644 index 0000000..aa7a9d7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/anamisc/clk_ref_val_l_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CLK_REF_VAL_L_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_REF_VAL_L_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL_CNT_VAL` reader - Returns the number of DIVN clock cycles counted during the calibration time, defined with REF_CNT_VAL"] +pub struct XTAL_CNT_VAL_R(crate::FieldReader); +impl XTAL_CNT_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + XTAL_CNT_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL_CNT_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Returns the number of DIVN clock cycles counted during the calibration time, defined with REF_CNT_VAL"] + #[inline(always)] + pub fn xtal_cnt_val(&self) -> XTAL_CNT_VAL_R { + XTAL_CNT_VAL_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "XTAL32M reference cycles, lower 16 bits\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ref_val_l_reg](index.html) module"] +pub struct CLK_REF_VAL_L_REG_SPEC; +impl crate::RegisterSpec for CLK_REF_VAL_L_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_ref_val_l_reg::R](R) reader structure"] +impl crate::Readable for CLK_REF_VAL_L_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_ref_val_l_reg::W](W) writer structure"] +impl crate::Writable for CLK_REF_VAL_L_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_REF_VAL_L_REG to value 0"] +impl crate::Resettable for CLK_REF_VAL_L_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble.rs b/bitbox02-bt/vendor/da14531/src/ble.rs new file mode 100644 index 0000000..e7d9199 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble.rs @@ -0,0 +1,364 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - BLE Control register"] + pub ble_rwblecntl_reg: crate::Reg, + #[doc = "0x04 - Version register"] + pub ble_version_reg: crate::Reg, + #[doc = "0x08 - Configuration register"] + pub ble_rwbleconf_reg: crate::Reg, + #[doc = "0x0c - Interrupt controller register"] + pub ble_intcntl_reg: crate::Reg, + #[doc = "0x10 - Interrupt status register"] + pub ble_intstat_reg: crate::Reg, + #[doc = "0x14 - Interrupt raw status register"] + pub ble_intrawstat_reg: crate::Reg, + #[doc = "0x18 - Interrupt acknowledge register"] + pub ble_intack_reg: crate::Reg, + #[doc = "0x1c - Base time reference counter"] + pub ble_basetimecnt_reg: crate::Reg, + #[doc = "0x20 - Fine time reference counter"] + pub ble_finetimecnt_reg: crate::Reg, + #[doc = "0x24 - BLE device address LSB register"] + pub ble_bdaddrl_reg: crate::Reg, + #[doc = "0x28 - BLE device address MSB register"] + pub ble_bdaddru_reg: crate::Reg, + #[doc = "0x2c - Rx Descriptor Pointer for the Receive Buffer Chained List"] + pub ble_currentrxdescptr_reg: + crate::Reg, + #[doc = "0x30 - Deep-Sleep control register"] + pub ble_deepslcntl_reg: crate::Reg, + #[doc = "0x34 - Time (measured in Low Power clock cycles) in Deep Sleep Mode before waking-up the device"] + pub ble_deepslwkup_reg: crate::Reg, + #[doc = "0x38 - Duration of the last deep sleep phase register"] + pub ble_deepslstat_reg: crate::Reg, + #[doc = "0x3c - Time in low power oscillator cycles register"] + pub ble_enbpreset_reg: crate::Reg, + #[doc = "0x40 - Phase correction value register"] + pub ble_finecntcorr_reg: crate::Reg, + #[doc = "0x44 - Base Time Counter"] + pub ble_basetimecntcorr_reg: crate::Reg, + _reserved18: [u8; 0x08], + #[doc = "0x50 - Diagnostics Register"] + pub ble_diagcntl_reg: crate::Reg, + #[doc = "0x54 - Debug use only"] + pub ble_diagstat_reg: crate::Reg, + #[doc = "0x58 - Upper limit for the memory zone"] + pub ble_debugaddmax_reg: crate::Reg, + #[doc = "0x5c - Lower limit for the memory zone"] + pub ble_debugaddmin_reg: crate::Reg, + #[doc = "0x60 - Error Type Status registers"] + pub ble_errortypestat_reg: crate::Reg, + #[doc = "0x64 - Software Profiling register"] + pub ble_swprofiling_reg: crate::Reg, + _reserved24: [u8; 0x08], + #[doc = "0x70 - Radio interface control register"] + pub ble_radiocntl0_reg: crate::Reg, + #[doc = "0x74 - Radio interface control register"] + pub ble_radiocntl1_reg: crate::Reg, + #[doc = "0x78 - Radio interface control register"] + pub ble_radiocntl2_reg: crate::Reg, + #[doc = "0x7c - Radio interface control register"] + pub ble_radiocntl3_reg: crate::Reg, + #[doc = "0x80 - RX/TX power up/down phase register"] + pub ble_radiopwrupdn_reg: crate::Reg, + _reserved29: [u8; 0x0c], + #[doc = "0x90 - Advertising Channel Map"] + pub ble_advchmap_reg: crate::Reg, + _reserved30: [u8; 0x0c], + #[doc = "0xa0 - Advertising Packet Interval"] + pub ble_advtim_reg: crate::Reg, + #[doc = "0xa4 - Active scan register"] + pub ble_actscanstat_reg: crate::Reg, + _reserved32: [u8; 0x08], + #[doc = "0xb0 - Start address of public devices list"] + pub ble_wlpubaddptr_reg: crate::Reg, + #[doc = "0xb4 - Start address of private devices list"] + pub ble_wlprivaddptr_reg: crate::Reg, + #[doc = "0xb8 - Devices in white list"] + pub ble_wlnbdev_reg: crate::Reg, + _reserved35: [u8; 0x04], + #[doc = "0xc0 - Start AES register"] + pub ble_aescntl_reg: crate::Reg, + #[doc = "0xc4 - AES encryption key"] + pub ble_aeskey31_0_reg: crate::Reg, + #[doc = "0xc8 - AES encryption key"] + pub ble_aeskey63_32_reg: crate::Reg, + #[doc = "0xcc - AES encryption key"] + pub ble_aeskey95_64_reg: crate::Reg, + #[doc = "0xd0 - AES encryption key"] + pub ble_aeskey127_96_reg: crate::Reg, + #[doc = "0xd4 - Pointer to the block to encrypt/decrypt"] + pub ble_aesptr_reg: crate::Reg, + #[doc = "0xd8 - AES / CCM plain MIC value"] + pub ble_txmicval_reg: crate::Reg, + #[doc = "0xdc - AES / CCM plain MIC value"] + pub ble_rxmicval_reg: crate::Reg, + #[doc = "0xe0 - RF Testing Register"] + pub ble_rftestcntl_reg: crate::Reg, + #[doc = "0xe4 - RF Testing Register"] + pub ble_rftesttxstat_reg: crate::Reg, + #[doc = "0xe8 - RF Testing Register"] + pub ble_rftestrxstat_reg: crate::Reg, + _reserved46: [u8; 0x04], + #[doc = "0xf0 - Timing Generator Register"] + pub ble_timgencntl_reg: crate::Reg, + #[doc = "0xf4 - Gross Timer Target value"] + pub ble_grosstimtgt_reg: crate::Reg, + #[doc = "0xf8 - Fine Timer Target value"] + pub ble_finetimtgt_reg: crate::Reg, + #[doc = "0xfc - Samples the Base Time Counter"] + pub ble_sampleclk_reg: crate::Reg, + #[doc = "0x100 - Coexistence interface Control 0 Register"] + pub ble_coexifcntl0_reg: crate::Reg, + #[doc = "0x104 - Coexistence interface Control 1 Register"] + pub ble_coexifcntl1_reg: crate::Reg, + #[doc = "0x108 - Coexistence interface Priority 0 Register"] + pub ble_blemprio0_reg: crate::Reg, + #[doc = "0x10c - Coexistence interface Priority 1 Register"] + pub ble_blemprio1_reg: crate::Reg, + _reserved54: [u8; 0xf0], + #[doc = "0x200 - BLE Control Register 2"] + pub ble_cntl2_reg: crate::Reg, + _reserved55: [u8; 0x04], + #[doc = "0x208 - Exchange Memory Base Register"] + pub ble_em_base_reg: crate::Reg, + #[doc = "0x20c - Debug use only"] + pub ble_diagcntl2_reg: crate::Reg, + #[doc = "0x210 - Debug use only"] + pub ble_diagcntl3_reg: crate::Reg, +} +#[doc = "BLE_ACTSCANSTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_ACTSCANSTAT_REG = crate::Reg; +#[doc = "Active scan register"] +pub mod ble_actscanstat_reg; +#[doc = "BLE_ADVCHMAP_REG register accessor: an alias for `Reg`"] +pub type BLE_ADVCHMAP_REG = crate::Reg; +#[doc = "Advertising Channel Map"] +pub mod ble_advchmap_reg; +#[doc = "BLE_ADVTIM_REG register accessor: an alias for `Reg`"] +pub type BLE_ADVTIM_REG = crate::Reg; +#[doc = "Advertising Packet Interval"] +pub mod ble_advtim_reg; +#[doc = "BLE_AESCNTL_REG register accessor: an alias for `Reg`"] +pub type BLE_AESCNTL_REG = crate::Reg; +#[doc = "Start AES register"] +pub mod ble_aescntl_reg; +#[doc = "BLE_AESKEY127_96_REG register accessor: an alias for `Reg`"] +pub type BLE_AESKEY127_96_REG = crate::Reg; +#[doc = "AES encryption key"] +pub mod ble_aeskey127_96_reg; +#[doc = "BLE_AESKEY31_0_REG register accessor: an alias for `Reg`"] +pub type BLE_AESKEY31_0_REG = crate::Reg; +#[doc = "AES encryption key"] +pub mod ble_aeskey31_0_reg; +#[doc = "BLE_AESKEY63_32_REG register accessor: an alias for `Reg`"] +pub type BLE_AESKEY63_32_REG = crate::Reg; +#[doc = "AES encryption key"] +pub mod ble_aeskey63_32_reg; +#[doc = "BLE_AESKEY95_64_REG register accessor: an alias for `Reg`"] +pub type BLE_AESKEY95_64_REG = crate::Reg; +#[doc = "AES encryption key"] +pub mod ble_aeskey95_64_reg; +#[doc = "BLE_AESPTR_REG register accessor: an alias for `Reg`"] +pub type BLE_AESPTR_REG = crate::Reg; +#[doc = "Pointer to the block to encrypt/decrypt"] +pub mod ble_aesptr_reg; +#[doc = "BLE_BASETIMECNTCORR_REG register accessor: an alias for `Reg`"] +pub type BLE_BASETIMECNTCORR_REG = + crate::Reg; +#[doc = "Base Time Counter"] +pub mod ble_basetimecntcorr_reg; +#[doc = "BLE_BASETIMECNT_REG register accessor: an alias for `Reg`"] +pub type BLE_BASETIMECNT_REG = crate::Reg; +#[doc = "Base time reference counter"] +pub mod ble_basetimecnt_reg; +#[doc = "BLE_BDADDRL_REG register accessor: an alias for `Reg`"] +pub type BLE_BDADDRL_REG = crate::Reg; +#[doc = "BLE device address LSB register"] +pub mod ble_bdaddrl_reg; +#[doc = "BLE_BDADDRU_REG register accessor: an alias for `Reg`"] +pub type BLE_BDADDRU_REG = crate::Reg; +#[doc = "BLE device address MSB register"] +pub mod ble_bdaddru_reg; +#[doc = "BLE_BLEMPRIO0_REG register accessor: an alias for `Reg`"] +pub type BLE_BLEMPRIO0_REG = crate::Reg; +#[doc = "Coexistence interface Priority 0 Register"] +pub mod ble_blemprio0_reg; +#[doc = "BLE_BLEMPRIO1_REG register accessor: an alias for `Reg`"] +pub type BLE_BLEMPRIO1_REG = crate::Reg; +#[doc = "Coexistence interface Priority 1 Register"] +pub mod ble_blemprio1_reg; +#[doc = "BLE_CNTL2_REG register accessor: an alias for `Reg`"] +pub type BLE_CNTL2_REG = crate::Reg; +#[doc = "BLE Control Register 2"] +pub mod ble_cntl2_reg; +#[doc = "BLE_COEXIFCNTL0_REG register accessor: an alias for `Reg`"] +pub type BLE_COEXIFCNTL0_REG = crate::Reg; +#[doc = "Coexistence interface Control 0 Register"] +pub mod ble_coexifcntl0_reg; +#[doc = "BLE_COEXIFCNTL1_REG register accessor: an alias for `Reg`"] +pub type BLE_COEXIFCNTL1_REG = crate::Reg; +#[doc = "Coexistence interface Control 1 Register"] +pub mod ble_coexifcntl1_reg; +#[doc = "BLE_CURRENTRXDESCPTR_REG register accessor: an alias for `Reg`"] +pub type BLE_CURRENTRXDESCPTR_REG = + crate::Reg; +#[doc = "Rx Descriptor Pointer for the Receive Buffer Chained List"] +pub mod ble_currentrxdescptr_reg; +#[doc = "BLE_DEBUGADDMAX_REG register accessor: an alias for `Reg`"] +pub type BLE_DEBUGADDMAX_REG = crate::Reg; +#[doc = "Upper limit for the memory zone"] +pub mod ble_debugaddmax_reg; +#[doc = "BLE_DEBUGADDMIN_REG register accessor: an alias for `Reg`"] +pub type BLE_DEBUGADDMIN_REG = crate::Reg; +#[doc = "Lower limit for the memory zone"] +pub mod ble_debugaddmin_reg; +#[doc = "BLE_DEEPSLCNTL_REG register accessor: an alias for `Reg`"] +pub type BLE_DEEPSLCNTL_REG = crate::Reg; +#[doc = "Deep-Sleep control register"] +pub mod ble_deepslcntl_reg; +#[doc = "BLE_DEEPSLSTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_DEEPSLSTAT_REG = crate::Reg; +#[doc = "Duration of the last deep sleep phase register"] +pub mod ble_deepslstat_reg; +#[doc = "BLE_DEEPSLWKUP_REG register accessor: an alias for `Reg`"] +pub type BLE_DEEPSLWKUP_REG = crate::Reg; +#[doc = "Time (measured in Low Power clock cycles) in Deep Sleep Mode before waking-up the device"] +pub mod ble_deepslwkup_reg; +#[doc = "BLE_DIAGCNTL2_REG register accessor: an alias for `Reg`"] +pub type BLE_DIAGCNTL2_REG = crate::Reg; +#[doc = "Debug use only"] +pub mod ble_diagcntl2_reg; +#[doc = "BLE_DIAGCNTL3_REG register accessor: an alias for `Reg`"] +pub type BLE_DIAGCNTL3_REG = crate::Reg; +#[doc = "Debug use only"] +pub mod ble_diagcntl3_reg; +#[doc = "BLE_DIAGCNTL_REG register accessor: an alias for `Reg`"] +pub type BLE_DIAGCNTL_REG = crate::Reg; +#[doc = "Diagnostics Register"] +pub mod ble_diagcntl_reg; +#[doc = "BLE_DIAGSTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_DIAGSTAT_REG = crate::Reg; +#[doc = "Debug use only"] +pub mod ble_diagstat_reg; +#[doc = "BLE_EM_BASE_REG register accessor: an alias for `Reg`"] +pub type BLE_EM_BASE_REG = crate::Reg; +#[doc = "Exchange Memory Base Register"] +pub mod ble_em_base_reg; +#[doc = "BLE_ENBPRESET_REG register accessor: an alias for `Reg`"] +pub type BLE_ENBPRESET_REG = crate::Reg; +#[doc = "Time in low power oscillator cycles register"] +pub mod ble_enbpreset_reg; +#[doc = "BLE_ERRORTYPESTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_ERRORTYPESTAT_REG = crate::Reg; +#[doc = "Error Type Status registers"] +pub mod ble_errortypestat_reg; +#[doc = "BLE_FINECNTCORR_REG register accessor: an alias for `Reg`"] +pub type BLE_FINECNTCORR_REG = crate::Reg; +#[doc = "Phase correction value register"] +pub mod ble_finecntcorr_reg; +#[doc = "BLE_FINETIMECNT_REG register accessor: an alias for `Reg`"] +pub type BLE_FINETIMECNT_REG = crate::Reg; +#[doc = "Fine time reference counter"] +pub mod ble_finetimecnt_reg; +#[doc = "BLE_FINETIMTGT_REG register accessor: an alias for `Reg`"] +pub type BLE_FINETIMTGT_REG = crate::Reg; +#[doc = "Fine Timer Target value"] +pub mod ble_finetimtgt_reg; +#[doc = "BLE_GROSSTIMTGT_REG register accessor: an alias for `Reg`"] +pub type BLE_GROSSTIMTGT_REG = crate::Reg; +#[doc = "Gross Timer Target value"] +pub mod ble_grosstimtgt_reg; +#[doc = "BLE_INTACK_REG register accessor: an alias for `Reg`"] +pub type BLE_INTACK_REG = crate::Reg; +#[doc = "Interrupt acknowledge register"] +pub mod ble_intack_reg; +#[doc = "BLE_INTCNTL_REG register accessor: an alias for `Reg`"] +pub type BLE_INTCNTL_REG = crate::Reg; +#[doc = "Interrupt controller register"] +pub mod ble_intcntl_reg; +#[doc = "BLE_INTRAWSTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_INTRAWSTAT_REG = crate::Reg; +#[doc = "Interrupt raw status register"] +pub mod ble_intrawstat_reg; +#[doc = "BLE_INTSTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_INTSTAT_REG = crate::Reg; +#[doc = "Interrupt status register"] +pub mod ble_intstat_reg; +#[doc = "BLE_RADIOCNTL0_REG register accessor: an alias for `Reg`"] +pub type BLE_RADIOCNTL0_REG = crate::Reg; +#[doc = "Radio interface control register"] +pub mod ble_radiocntl0_reg; +#[doc = "BLE_RADIOCNTL1_REG register accessor: an alias for `Reg`"] +pub type BLE_RADIOCNTL1_REG = crate::Reg; +#[doc = "Radio interface control register"] +pub mod ble_radiocntl1_reg; +#[doc = "BLE_RADIOCNTL2_REG register accessor: an alias for `Reg`"] +pub type BLE_RADIOCNTL2_REG = crate::Reg; +#[doc = "Radio interface control register"] +pub mod ble_radiocntl2_reg; +#[doc = "BLE_RADIOCNTL3_REG register accessor: an alias for `Reg`"] +pub type BLE_RADIOCNTL3_REG = crate::Reg; +#[doc = "Radio interface control register"] +pub mod ble_radiocntl3_reg; +#[doc = "BLE_RADIOPWRUPDN_REG register accessor: an alias for `Reg`"] +pub type BLE_RADIOPWRUPDN_REG = crate::Reg; +#[doc = "RX/TX power up/down phase register"] +pub mod ble_radiopwrupdn_reg; +#[doc = "BLE_RFTESTCNTL_REG register accessor: an alias for `Reg`"] +pub type BLE_RFTESTCNTL_REG = crate::Reg; +#[doc = "RF Testing Register"] +pub mod ble_rftestcntl_reg; +#[doc = "BLE_RFTESTRXSTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_RFTESTRXSTAT_REG = crate::Reg; +#[doc = "RF Testing Register"] +pub mod ble_rftestrxstat_reg; +#[doc = "BLE_RFTESTTXSTAT_REG register accessor: an alias for `Reg`"] +pub type BLE_RFTESTTXSTAT_REG = crate::Reg; +#[doc = "RF Testing Register"] +pub mod ble_rftesttxstat_reg; +#[doc = "BLE_RWBLECNTL_REG register accessor: an alias for `Reg`"] +pub type BLE_RWBLECNTL_REG = crate::Reg; +#[doc = "BLE Control register"] +pub mod ble_rwblecntl_reg; +#[doc = "BLE_RWBLECONF_REG register accessor: an alias for `Reg`"] +pub type BLE_RWBLECONF_REG = crate::Reg; +#[doc = "Configuration register"] +pub mod ble_rwbleconf_reg; +#[doc = "BLE_RXMICVAL_REG register accessor: an alias for `Reg`"] +pub type BLE_RXMICVAL_REG = crate::Reg; +#[doc = "AES / CCM plain MIC value"] +pub mod ble_rxmicval_reg; +#[doc = "BLE_SAMPLECLK_REG register accessor: an alias for `Reg`"] +pub type BLE_SAMPLECLK_REG = crate::Reg; +#[doc = "Samples the Base Time Counter"] +pub mod ble_sampleclk_reg; +#[doc = "BLE_SWPROFILING_REG register accessor: an alias for `Reg`"] +pub type BLE_SWPROFILING_REG = crate::Reg; +#[doc = "Software Profiling register"] +pub mod ble_swprofiling_reg; +#[doc = "BLE_TIMGENCNTL_REG register accessor: an alias for `Reg`"] +pub type BLE_TIMGENCNTL_REG = crate::Reg; +#[doc = "Timing Generator Register"] +pub mod ble_timgencntl_reg; +#[doc = "BLE_TXMICVAL_REG register accessor: an alias for `Reg`"] +pub type BLE_TXMICVAL_REG = crate::Reg; +#[doc = "AES / CCM plain MIC value"] +pub mod ble_txmicval_reg; +#[doc = "BLE_VERSION_REG register accessor: an alias for `Reg`"] +pub type BLE_VERSION_REG = crate::Reg; +#[doc = "Version register"] +pub mod ble_version_reg; +#[doc = "BLE_WLNBDEV_REG register accessor: an alias for `Reg`"] +pub type BLE_WLNBDEV_REG = crate::Reg; +#[doc = "Devices in white list"] +pub mod ble_wlnbdev_reg; +#[doc = "BLE_WLPRIVADDPTR_REG register accessor: an alias for `Reg`"] +pub type BLE_WLPRIVADDPTR_REG = crate::Reg; +#[doc = "Start address of private devices list"] +pub mod ble_wlprivaddptr_reg; +#[doc = "BLE_WLPUBADDPTR_REG register accessor: an alias for `Reg`"] +pub type BLE_WLPUBADDPTR_REG = crate::Reg; +#[doc = "Start address of public devices list"] +pub mod ble_wlpubaddptr_reg; diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_actscanstat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_actscanstat_reg.rs new file mode 100644 index 0000000..0a485e6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_actscanstat_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `BLE_ACTSCANSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_ACTSCANSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BACKOFF` reader - Active scan mode back-off counter initialization value."] +pub struct BACKOFF_R(crate::FieldReader); +impl BACKOFF_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + BACKOFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BACKOFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UPPERLIMIT` reader - Active scan mode upper limit counter value."] +pub struct UPPERLIMIT_R(crate::FieldReader); +impl UPPERLIMIT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + UPPERLIMIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UPPERLIMIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 16:24 - Active scan mode back-off counter initialization value."] + #[inline(always)] + pub fn backoff(&self) -> BACKOFF_R { + BACKOFF_R::new(((self.bits >> 16) & 0x01ff) as u16) + } + #[doc = "Bits 0:8 - Active scan mode upper limit counter value."] + #[inline(always)] + pub fn upperlimit(&self) -> UPPERLIMIT_R { + UPPERLIMIT_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Active scan register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_actscanstat_reg](index.html) module"] +pub struct BLE_ACTSCANSTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_ACTSCANSTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_actscanstat_reg::R](R) reader structure"] +impl crate::Readable for BLE_ACTSCANSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_actscanstat_reg::W](W) writer structure"] +impl crate::Writable for BLE_ACTSCANSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_ACTSCANSTAT_REG to value 0x0001_0001"] +impl crate::Resettable for BLE_ACTSCANSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0001_0001 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_advchmap_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_advchmap_reg.rs new file mode 100644 index 0000000..1c7c9c4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_advchmap_reg.rs @@ -0,0 +1,107 @@ +#[doc = "Register `BLE_ADVCHMAP_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_ADVCHMAP_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADVCHMAP` reader - Advertising Channel Map, defined as per the advertising connection settings. Contains advertising channels index 37 to 39. If ADVCHMAP\\[i\\] +equals: 0: Do not use data channel i+37. 1: Use data channel i+37."] +pub struct ADVCHMAP_R(crate::FieldReader); +impl ADVCHMAP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADVCHMAP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADVCHMAP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADVCHMAP` writer - Advertising Channel Map, defined as per the advertising connection settings. Contains advertising channels index 37 to 39. If ADVCHMAP\\[i\\] +equals: 0: Do not use data channel i+37. 1: Use data channel i+37."] +pub struct ADVCHMAP_W<'a> { + w: &'a mut W, +} +impl<'a> ADVCHMAP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bits 0:2 - Advertising Channel Map, defined as per the advertising connection settings. Contains advertising channels index 37 to 39. If ADVCHMAP\\[i\\] +equals: 0: Do not use data channel i+37. 1: Use data channel i+37."] + #[inline(always)] + pub fn advchmap(&self) -> ADVCHMAP_R { + ADVCHMAP_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 0:2 - Advertising Channel Map, defined as per the advertising connection settings. Contains advertising channels index 37 to 39. If ADVCHMAP\\[i\\] +equals: 0: Do not use data channel i+37. 1: Use data channel i+37."] + #[inline(always)] + pub fn advchmap(&mut self) -> ADVCHMAP_W { + ADVCHMAP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Advertising Channel Map\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_advchmap_reg](index.html) module"] +pub struct BLE_ADVCHMAP_REG_SPEC; +impl crate::RegisterSpec for BLE_ADVCHMAP_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_advchmap_reg::R](R) reader structure"] +impl crate::Readable for BLE_ADVCHMAP_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_advchmap_reg::W](W) writer structure"] +impl crate::Writable for BLE_ADVCHMAP_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_ADVCHMAP_REG to value 0x07"] +impl crate::Resettable for BLE_ADVCHMAP_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_advtim_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_advtim_reg.rs new file mode 100644 index 0000000..370322c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_advtim_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_ADVTIM_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_ADVTIM_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADVINT` reader - Advertising Packet Interval defines the time interval in between two ADV_xxx packet sent. Value is in us. Value to program depends on the used Advertising Packet type and the device filtering policy."] +pub struct ADVINT_R(crate::FieldReader); +impl ADVINT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADVINT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADVINT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADVINT` writer - Advertising Packet Interval defines the time interval in between two ADV_xxx packet sent. Value is in us. Value to program depends on the used Advertising Packet type and the device filtering policy."] +pub struct ADVINT_W<'a> { + w: &'a mut W, +} +impl<'a> ADVINT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u32 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Advertising Packet Interval defines the time interval in between two ADV_xxx packet sent. Value is in us. Value to program depends on the used Advertising Packet type and the device filtering policy."] + #[inline(always)] + pub fn advint(&self) -> ADVINT_R { + ADVINT_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Advertising Packet Interval defines the time interval in between two ADV_xxx packet sent. Value is in us. Value to program depends on the used Advertising Packet type and the device filtering policy."] + #[inline(always)] + pub fn advint(&mut self) -> ADVINT_W { + ADVINT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Advertising Packet Interval\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_advtim_reg](index.html) module"] +pub struct BLE_ADVTIM_REG_SPEC; +impl crate::RegisterSpec for BLE_ADVTIM_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_advtim_reg::R](R) reader structure"] +impl crate::Readable for BLE_ADVTIM_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_advtim_reg::W](W) writer structure"] +impl crate::Writable for BLE_ADVTIM_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_ADVTIM_REG to value 0"] +impl crate::Resettable for BLE_ADVTIM_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_aescntl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_aescntl_reg.rs new file mode 100644 index 0000000..7575958 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_aescntl_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `BLE_AESCNTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_AESCNTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `AES_MODE` reader - 0: Cipher mode 1: Decipher mode"] +pub struct AES_MODE_R(crate::FieldReader); +impl AES_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + AES_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AES_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AES_MODE` writer - 0: Cipher mode 1: Decipher mode"] +pub struct AES_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> AES_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `AES_START` writer - Writing a 1 starts AES-128 ciphering/deciphering process. This bit is reset once the process is finished (i.e. ble_crypt_irq interrupt occurs, even masked)"] +pub struct AES_START_W<'a> { + w: &'a mut W, +} +impl<'a> AES_START_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1 - 0: Cipher mode 1: Decipher mode"] + #[inline(always)] + pub fn aes_mode(&self) -> AES_MODE_R { + AES_MODE_R::new(((self.bits >> 1) & 1) != 0) + } +} +impl W { + #[doc = "Bit 1 - 0: Cipher mode 1: Decipher mode"] + #[inline(always)] + pub fn aes_mode(&mut self) -> AES_MODE_W { + AES_MODE_W { w: self } + } + #[doc = "Bit 0 - Writing a 1 starts AES-128 ciphering/deciphering process. This bit is reset once the process is finished (i.e. ble_crypt_irq interrupt occurs, even masked)"] + #[inline(always)] + pub fn aes_start(&mut self) -> AES_START_W { + AES_START_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Start AES register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_aescntl_reg](index.html) module"] +pub struct BLE_AESCNTL_REG_SPEC; +impl crate::RegisterSpec for BLE_AESCNTL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_aescntl_reg::R](R) reader structure"] +impl crate::Readable for BLE_AESCNTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_aescntl_reg::W](W) writer structure"] +impl crate::Writable for BLE_AESCNTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_AESCNTL_REG to value 0"] +impl crate::Resettable for BLE_AESCNTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey127_96_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey127_96_reg.rs new file mode 100644 index 0000000..b4157dd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey127_96_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_AESKEY127_96_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_AESKEY127_96_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `AESKEY127_96` reader - AES encryption 128-bit key. Bit 127 down to 96"] +pub struct AESKEY127_96_R(crate::FieldReader); +impl AESKEY127_96_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + AESKEY127_96_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AESKEY127_96_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AESKEY127_96` writer - AES encryption 128-bit key. Bit 127 down to 96"] +pub struct AESKEY127_96_W<'a> { + w: &'a mut W, +} +impl<'a> AESKEY127_96_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 127 down to 96"] + #[inline(always)] + pub fn aeskey127_96(&self) -> AESKEY127_96_R { + AESKEY127_96_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 127 down to 96"] + #[inline(always)] + pub fn aeskey127_96(&mut self) -> AESKEY127_96_W { + AESKEY127_96_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "AES encryption key\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_aeskey127_96_reg](index.html) module"] +pub struct BLE_AESKEY127_96_REG_SPEC; +impl crate::RegisterSpec for BLE_AESKEY127_96_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_aeskey127_96_reg::R](R) reader structure"] +impl crate::Readable for BLE_AESKEY127_96_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_aeskey127_96_reg::W](W) writer structure"] +impl crate::Writable for BLE_AESKEY127_96_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_AESKEY127_96_REG to value 0"] +impl crate::Resettable for BLE_AESKEY127_96_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey31_0_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey31_0_reg.rs new file mode 100644 index 0000000..d842803 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey31_0_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_AESKEY31_0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_AESKEY31_0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `AESKEY31_0` reader - AES encryption 128-bit key. Bit 31 down to 0"] +pub struct AESKEY31_0_R(crate::FieldReader); +impl AESKEY31_0_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + AESKEY31_0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AESKEY31_0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AESKEY31_0` writer - AES encryption 128-bit key. Bit 31 down to 0"] +pub struct AESKEY31_0_W<'a> { + w: &'a mut W, +} +impl<'a> AESKEY31_0_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 31 down to 0"] + #[inline(always)] + pub fn aeskey31_0(&self) -> AESKEY31_0_R { + AESKEY31_0_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 31 down to 0"] + #[inline(always)] + pub fn aeskey31_0(&mut self) -> AESKEY31_0_W { + AESKEY31_0_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "AES encryption key\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_aeskey31_0_reg](index.html) module"] +pub struct BLE_AESKEY31_0_REG_SPEC; +impl crate::RegisterSpec for BLE_AESKEY31_0_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_aeskey31_0_reg::R](R) reader structure"] +impl crate::Readable for BLE_AESKEY31_0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_aeskey31_0_reg::W](W) writer structure"] +impl crate::Writable for BLE_AESKEY31_0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_AESKEY31_0_REG to value 0"] +impl crate::Resettable for BLE_AESKEY31_0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey63_32_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey63_32_reg.rs new file mode 100644 index 0000000..8dc2635 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey63_32_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_AESKEY63_32_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_AESKEY63_32_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `AESKEY63_32` reader - AES encryption 128-bit key. Bit 63 down to 32"] +pub struct AESKEY63_32_R(crate::FieldReader); +impl AESKEY63_32_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + AESKEY63_32_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AESKEY63_32_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AESKEY63_32` writer - AES encryption 128-bit key. Bit 63 down to 32"] +pub struct AESKEY63_32_W<'a> { + w: &'a mut W, +} +impl<'a> AESKEY63_32_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 63 down to 32"] + #[inline(always)] + pub fn aeskey63_32(&self) -> AESKEY63_32_R { + AESKEY63_32_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 63 down to 32"] + #[inline(always)] + pub fn aeskey63_32(&mut self) -> AESKEY63_32_W { + AESKEY63_32_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "AES encryption key\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_aeskey63_32_reg](index.html) module"] +pub struct BLE_AESKEY63_32_REG_SPEC; +impl crate::RegisterSpec for BLE_AESKEY63_32_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_aeskey63_32_reg::R](R) reader structure"] +impl crate::Readable for BLE_AESKEY63_32_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_aeskey63_32_reg::W](W) writer structure"] +impl crate::Writable for BLE_AESKEY63_32_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_AESKEY63_32_REG to value 0"] +impl crate::Resettable for BLE_AESKEY63_32_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey95_64_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey95_64_reg.rs new file mode 100644 index 0000000..0c9279f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_aeskey95_64_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_AESKEY95_64_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_AESKEY95_64_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `AESKEY95_64` reader - AES encryption 128-bit key. Bit 95 down to 64"] +pub struct AESKEY95_64_R(crate::FieldReader); +impl AESKEY95_64_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + AESKEY95_64_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AESKEY95_64_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AESKEY95_64` writer - AES encryption 128-bit key. Bit 95 down to 64"] +pub struct AESKEY95_64_W<'a> { + w: &'a mut W, +} +impl<'a> AESKEY95_64_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 95 down to 64"] + #[inline(always)] + pub fn aeskey95_64(&self) -> AESKEY95_64_R { + AESKEY95_64_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - AES encryption 128-bit key. Bit 95 down to 64"] + #[inline(always)] + pub fn aeskey95_64(&mut self) -> AESKEY95_64_W { + AESKEY95_64_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "AES encryption key\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_aeskey95_64_reg](index.html) module"] +pub struct BLE_AESKEY95_64_REG_SPEC; +impl crate::RegisterSpec for BLE_AESKEY95_64_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_aeskey95_64_reg::R](R) reader structure"] +impl crate::Readable for BLE_AESKEY95_64_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_aeskey95_64_reg::W](W) writer structure"] +impl crate::Writable for BLE_AESKEY95_64_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_AESKEY95_64_REG to value 0"] +impl crate::Resettable for BLE_AESKEY95_64_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_aesptr_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_aesptr_reg.rs new file mode 100644 index 0000000..6ffbf78 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_aesptr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_AESPTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_AESPTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `AESPTR` reader - Pointer to the memory zone where the block to cipher/decipher using AES-128 is stored."] +pub struct AESPTR_R(crate::FieldReader); +impl AESPTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + AESPTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AESPTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AESPTR` writer - Pointer to the memory zone where the block to cipher/decipher using AES-128 is stored."] +pub struct AESPTR_W<'a> { + w: &'a mut W, +} +impl<'a> AESPTR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bits 0:15 - Pointer to the memory zone where the block to cipher/decipher using AES-128 is stored."] + #[inline(always)] + pub fn aesptr(&self) -> AESPTR_R { + AESPTR_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bits 0:15 - Pointer to the memory zone where the block to cipher/decipher using AES-128 is stored."] + #[inline(always)] + pub fn aesptr(&mut self) -> AESPTR_W { + AESPTR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Pointer to the block to encrypt/decrypt\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_aesptr_reg](index.html) module"] +pub struct BLE_AESPTR_REG_SPEC; +impl crate::RegisterSpec for BLE_AESPTR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_aesptr_reg::R](R) reader structure"] +impl crate::Readable for BLE_AESPTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_aesptr_reg::W](W) writer structure"] +impl crate::Writable for BLE_AESPTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_AESPTR_REG to value 0"] +impl crate::Resettable for BLE_AESPTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_basetimecnt_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_basetimecnt_reg.rs new file mode 100644 index 0000000..cd165b1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_basetimecnt_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `BLE_BASETIMECNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_BASETIMECNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BASETIMECNT` reader - Value of the 625us base time reference counter. Updated each time SAMPCLK is written. Used by the SW in order to synchronize with the HW"] +pub struct BASETIMECNT_R(crate::FieldReader); +impl BASETIMECNT_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + BASETIMECNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BASETIMECNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:26 - Value of the 625us base time reference counter. Updated each time SAMPCLK is written. Used by the SW in order to synchronize with the HW"] + #[inline(always)] + pub fn basetimecnt(&self) -> BASETIMECNT_R { + BASETIMECNT_R::new((self.bits & 0x07ff_ffff) as u32) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Base time reference counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_basetimecnt_reg](index.html) module"] +pub struct BLE_BASETIMECNT_REG_SPEC; +impl crate::RegisterSpec for BLE_BASETIMECNT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_basetimecnt_reg::R](R) reader structure"] +impl crate::Readable for BLE_BASETIMECNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_basetimecnt_reg::W](W) writer structure"] +impl crate::Writable for BLE_BASETIMECNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_BASETIMECNT_REG to value 0"] +impl crate::Resettable for BLE_BASETIMECNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_basetimecntcorr_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_basetimecntcorr_reg.rs new file mode 100644 index 0000000..deb7d39 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_basetimecntcorr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_BASETIMECNTCORR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_BASETIMECNTCORR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BASETIMECNTCORR` reader - Base Time Counter correction value."] +pub struct BASETIMECNTCORR_R(crate::FieldReader); +impl BASETIMECNTCORR_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + BASETIMECNTCORR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BASETIMECNTCORR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BASETIMECNTCORR` writer - Base Time Counter correction value."] +pub struct BASETIMECNTCORR_W<'a> { + w: &'a mut W, +} +impl<'a> BASETIMECNTCORR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !0x07ff_ffff) | (value as u32 & 0x07ff_ffff); + self.w + } +} +impl R { + #[doc = "Bits 0:26 - Base Time Counter correction value."] + #[inline(always)] + pub fn basetimecntcorr(&self) -> BASETIMECNTCORR_R { + BASETIMECNTCORR_R::new((self.bits & 0x07ff_ffff) as u32) + } +} +impl W { + #[doc = "Bits 0:26 - Base Time Counter correction value."] + #[inline(always)] + pub fn basetimecntcorr(&mut self) -> BASETIMECNTCORR_W { + BASETIMECNTCORR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Base Time Counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_basetimecntcorr_reg](index.html) module"] +pub struct BLE_BASETIMECNTCORR_REG_SPEC; +impl crate::RegisterSpec for BLE_BASETIMECNTCORR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_basetimecntcorr_reg::R](R) reader structure"] +impl crate::Readable for BLE_BASETIMECNTCORR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_basetimecntcorr_reg::W](W) writer structure"] +impl crate::Writable for BLE_BASETIMECNTCORR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_BASETIMECNTCORR_REG to value 0"] +impl crate::Resettable for BLE_BASETIMECNTCORR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_bdaddrl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_bdaddrl_reg.rs new file mode 100644 index 0000000..fa4d5f9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_bdaddrl_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_BDADDRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_BDADDRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BDADDRL` reader - Bluetooth Low Energy Device Address. LSB part."] +pub struct BDADDRL_R(crate::FieldReader); +impl BDADDRL_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + BDADDRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BDADDRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BDADDRL` writer - Bluetooth Low Energy Device Address. LSB part."] +pub struct BDADDRL_W<'a> { + w: &'a mut W, +} +impl<'a> BDADDRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - Bluetooth Low Energy Device Address. LSB part."] + #[inline(always)] + pub fn bdaddrl(&self) -> BDADDRL_R { + BDADDRL_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - Bluetooth Low Energy Device Address. LSB part."] + #[inline(always)] + pub fn bdaddrl(&mut self) -> BDADDRL_W { + BDADDRL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "BLE device address LSB register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_bdaddrl_reg](index.html) module"] +pub struct BLE_BDADDRL_REG_SPEC; +impl crate::RegisterSpec for BLE_BDADDRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_bdaddrl_reg::R](R) reader structure"] +impl crate::Readable for BLE_BDADDRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_bdaddrl_reg::W](W) writer structure"] +impl crate::Writable for BLE_BDADDRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_BDADDRL_REG to value 0"] +impl crate::Resettable for BLE_BDADDRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_bdaddru_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_bdaddru_reg.rs new file mode 100644 index 0000000..7f54071 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_bdaddru_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `BLE_BDADDRU_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_BDADDRU_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PRIV_NPUB` reader - Bluetooth Low Energy Device Address privacy indicator 0: Public Bluetooth Device Address 1: Private Bluetooth Device Address"] +pub struct PRIV_NPUB_R(crate::FieldReader); +impl PRIV_NPUB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PRIV_NPUB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PRIV_NPUB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PRIV_NPUB` writer - Bluetooth Low Energy Device Address privacy indicator 0: Public Bluetooth Device Address 1: Private Bluetooth Device Address"] +pub struct PRIV_NPUB_W<'a> { + w: &'a mut W, +} +impl<'a> PRIV_NPUB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `BDADDRU` reader - Bluetooth Low Energy Device Address. MSB part."] +pub struct BDADDRU_R(crate::FieldReader); +impl BDADDRU_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + BDADDRU_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BDADDRU_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BDADDRU` writer - Bluetooth Low Energy Device Address. MSB part."] +pub struct BDADDRU_W<'a> { + w: &'a mut W, +} +impl<'a> BDADDRU_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bit 16 - Bluetooth Low Energy Device Address privacy indicator 0: Public Bluetooth Device Address 1: Private Bluetooth Device Address"] + #[inline(always)] + pub fn priv_npub(&self) -> PRIV_NPUB_R { + PRIV_NPUB_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bits 0:15 - Bluetooth Low Energy Device Address. MSB part."] + #[inline(always)] + pub fn bdaddru(&self) -> BDADDRU_R { + BDADDRU_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bit 16 - Bluetooth Low Energy Device Address privacy indicator 0: Public Bluetooth Device Address 1: Private Bluetooth Device Address"] + #[inline(always)] + pub fn priv_npub(&mut self) -> PRIV_NPUB_W { + PRIV_NPUB_W { w: self } + } + #[doc = "Bits 0:15 - Bluetooth Low Energy Device Address. MSB part."] + #[inline(always)] + pub fn bdaddru(&mut self) -> BDADDRU_W { + BDADDRU_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "BLE device address MSB register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_bdaddru_reg](index.html) module"] +pub struct BLE_BDADDRU_REG_SPEC; +impl crate::RegisterSpec for BLE_BDADDRU_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_bdaddru_reg::R](R) reader structure"] +impl crate::Readable for BLE_BDADDRU_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_bdaddru_reg::W](W) writer structure"] +impl crate::Writable for BLE_BDADDRU_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_BDADDRU_REG to value 0"] +impl crate::Resettable for BLE_BDADDRU_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_blemprio0_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_blemprio0_reg.rs new file mode 100644 index 0000000..69e302b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_blemprio0_reg.rs @@ -0,0 +1,362 @@ +#[doc = "Register `BLE_BLEMPRIO0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_BLEMPRIO0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BLEM7` reader - Set Priority value for Passive Scanning"] +pub struct BLEM7_R(crate::FieldReader); +impl BLEM7_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM7_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM7_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM7` writer - Set Priority value for Passive Scanning"] +pub struct BLEM7_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM7_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 28)) | ((value as u32 & 0x0f) << 28); + self.w + } +} +#[doc = "Field `BLEM6` reader - Set Priority value for Non-Connectable Advertising"] +pub struct BLEM6_R(crate::FieldReader); +impl BLEM6_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM6_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM6_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM6` writer - Set Priority value for Non-Connectable Advertising"] +pub struct BLEM6_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM6_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 24)) | ((value as u32 & 0x0f) << 24); + self.w + } +} +#[doc = "Field `BLEM5` reader - Set Priority value for Connectable Advertising BLE message"] +pub struct BLEM5_R(crate::FieldReader); +impl BLEM5_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM5_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM5_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM5` writer - Set Priority value for Connectable Advertising BLE message"] +pub struct BLEM5_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM5_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 20)) | ((value as u32 & 0x0f) << 20); + self.w + } +} +#[doc = "Field `BLEM4` reader - Set Priority value for Active Scanning BLE message"] +pub struct BLEM4_R(crate::FieldReader); +impl BLEM4_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM4` writer - Set Priority value for Active Scanning BLE message"] +pub struct BLEM4_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM4_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); + self.w + } +} +#[doc = "Field `BLEM3` reader - Set Priority value for Initiating (Scanning) BLE message"] +pub struct BLEM3_R(crate::FieldReader); +impl BLEM3_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM3` writer - Set Priority value for Initiating (Scanning) BLE message"] +pub struct BLEM3_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM3_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 12)) | ((value as u32 & 0x0f) << 12); + self.w + } +} +#[doc = "Field `BLEM2` reader - Set Priority value for Data Channel transmission BLE message"] +pub struct BLEM2_R(crate::FieldReader); +impl BLEM2_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM2` writer - Set Priority value for Data Channel transmission BLE message"] +pub struct BLEM2_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM2_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `BLEM1` reader - Set Priority value for LLCP BLE message"] +pub struct BLEM1_R(crate::FieldReader); +impl BLEM1_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM1` writer - Set Priority value for LLCP BLE message"] +pub struct BLEM1_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM1_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u32 & 0x0f) << 4); + self.w + } +} +#[doc = "Field `BLEM0` reader - Set Priority value for Initiating (Connection Request Response) BLE message"] +pub struct BLEM0_R(crate::FieldReader); +impl BLEM0_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEM0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEM0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEM0` writer - Set Priority value for Initiating (Connection Request Response) BLE message"] +pub struct BLEM0_W<'a> { + w: &'a mut W, +} +impl<'a> BLEM0_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 28:31 - Set Priority value for Passive Scanning"] + #[inline(always)] + pub fn blem7(&self) -> BLEM7_R { + BLEM7_R::new(((self.bits >> 28) & 0x0f) as u8) + } + #[doc = "Bits 24:27 - Set Priority value for Non-Connectable Advertising"] + #[inline(always)] + pub fn blem6(&self) -> BLEM6_R { + BLEM6_R::new(((self.bits >> 24) & 0x0f) as u8) + } + #[doc = "Bits 20:23 - Set Priority value for Connectable Advertising BLE message"] + #[inline(always)] + pub fn blem5(&self) -> BLEM5_R { + BLEM5_R::new(((self.bits >> 20) & 0x0f) as u8) + } + #[doc = "Bits 16:19 - Set Priority value for Active Scanning BLE message"] + #[inline(always)] + pub fn blem4(&self) -> BLEM4_R { + BLEM4_R::new(((self.bits >> 16) & 0x0f) as u8) + } + #[doc = "Bits 12:15 - Set Priority value for Initiating (Scanning) BLE message"] + #[inline(always)] + pub fn blem3(&self) -> BLEM3_R { + BLEM3_R::new(((self.bits >> 12) & 0x0f) as u8) + } + #[doc = "Bits 8:11 - Set Priority value for Data Channel transmission BLE message"] + #[inline(always)] + pub fn blem2(&self) -> BLEM2_R { + BLEM2_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bits 4:7 - Set Priority value for LLCP BLE message"] + #[inline(always)] + pub fn blem1(&self) -> BLEM1_R { + BLEM1_R::new(((self.bits >> 4) & 0x0f) as u8) + } + #[doc = "Bits 0:3 - Set Priority value for Initiating (Connection Request Response) BLE message"] + #[inline(always)] + pub fn blem0(&self) -> BLEM0_R { + BLEM0_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 28:31 - Set Priority value for Passive Scanning"] + #[inline(always)] + pub fn blem7(&mut self) -> BLEM7_W { + BLEM7_W { w: self } + } + #[doc = "Bits 24:27 - Set Priority value for Non-Connectable Advertising"] + #[inline(always)] + pub fn blem6(&mut self) -> BLEM6_W { + BLEM6_W { w: self } + } + #[doc = "Bits 20:23 - Set Priority value for Connectable Advertising BLE message"] + #[inline(always)] + pub fn blem5(&mut self) -> BLEM5_W { + BLEM5_W { w: self } + } + #[doc = "Bits 16:19 - Set Priority value for Active Scanning BLE message"] + #[inline(always)] + pub fn blem4(&mut self) -> BLEM4_W { + BLEM4_W { w: self } + } + #[doc = "Bits 12:15 - Set Priority value for Initiating (Scanning) BLE message"] + #[inline(always)] + pub fn blem3(&mut self) -> BLEM3_W { + BLEM3_W { w: self } + } + #[doc = "Bits 8:11 - Set Priority value for Data Channel transmission BLE message"] + #[inline(always)] + pub fn blem2(&mut self) -> BLEM2_W { + BLEM2_W { w: self } + } + #[doc = "Bits 4:7 - Set Priority value for LLCP BLE message"] + #[inline(always)] + pub fn blem1(&mut self) -> BLEM1_W { + BLEM1_W { w: self } + } + #[doc = "Bits 0:3 - Set Priority value for Initiating (Connection Request Response) BLE message"] + #[inline(always)] + pub fn blem0(&mut self) -> BLEM0_W { + BLEM0_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Coexistence interface Priority 0 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_blemprio0_reg](index.html) module"] +pub struct BLE_BLEMPRIO0_REG_SPEC; +impl crate::RegisterSpec for BLE_BLEMPRIO0_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_blemprio0_reg::R](R) reader structure"] +impl crate::Readable for BLE_BLEMPRIO0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_blemprio0_reg::W](W) writer structure"] +impl crate::Writable for BLE_BLEMPRIO0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_BLEMPRIO0_REG to value 0x3489_adef"] +impl crate::Resettable for BLE_BLEMPRIO0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x3489_adef + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_blemprio1_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_blemprio1_reg.rs new file mode 100644 index 0000000..3fbe824 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_blemprio1_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_BLEMPRIO1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_BLEMPRIO1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BLEMDEFAULT` reader - Set default priority value for other BLE message than those defined above"] +pub struct BLEMDEFAULT_R(crate::FieldReader); +impl BLEMDEFAULT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLEMDEFAULT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLEMDEFAULT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLEMDEFAULT` writer - Set default priority value for other BLE message than those defined above"] +pub struct BLEMDEFAULT_W<'a> { + w: &'a mut W, +} +impl<'a> BLEMDEFAULT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 28)) | ((value as u32 & 0x0f) << 28); + self.w + } +} +impl R { + #[doc = "Bits 28:31 - Set default priority value for other BLE message than those defined above"] + #[inline(always)] + pub fn blemdefault(&self) -> BLEMDEFAULT_R { + BLEMDEFAULT_R::new(((self.bits >> 28) & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 28:31 - Set default priority value for other BLE message than those defined above"] + #[inline(always)] + pub fn blemdefault(&mut self) -> BLEMDEFAULT_W { + BLEMDEFAULT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Coexistence interface Priority 1 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_blemprio1_reg](index.html) module"] +pub struct BLE_BLEMPRIO1_REG_SPEC; +impl crate::RegisterSpec for BLE_BLEMPRIO1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_blemprio1_reg::R](R) reader structure"] +impl crate::Readable for BLE_BLEMPRIO1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_blemprio1_reg::W](W) writer structure"] +impl crate::Writable for BLE_BLEMPRIO1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_BLEMPRIO1_REG to value 0x3000_0000"] +impl crate::Resettable for BLE_BLEMPRIO1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x3000_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_cntl2_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_cntl2_reg.rs new file mode 100644 index 0000000..ddd13e5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_cntl2_reg.rs @@ -0,0 +1,675 @@ +#[doc = "Register `BLE_CNTL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_CNTL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BLE_PHY_ERR_MSK_N` reader - "] +pub struct BLE_PHY_ERR_MSK_N_R(crate::FieldReader); +impl BLE_PHY_ERR_MSK_N_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_PHY_ERR_MSK_N_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_PHY_ERR_MSK_N_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_PHY_ERR_MSK_N` writer - "] +pub struct BLE_PHY_ERR_MSK_N_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_PHY_ERR_MSK_N_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 24)) | ((value as u32 & 1) << 24); + self.w + } +} +#[doc = "Field `BLE_ARP_ERR_MSK_N` reader - When cleared to \"0\" then it masks the BLE_ARP_ERR_STAT in order to not trigger a BLE_ERROR_IRQ."] +pub struct BLE_ARP_ERR_MSK_N_R(crate::FieldReader); +impl BLE_ARP_ERR_MSK_N_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_ARP_ERR_MSK_N_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_ARP_ERR_MSK_N_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_ARP_ERR_MSK_N` writer - When cleared to \"0\" then it masks the BLE_ARP_ERR_STAT in order to not trigger a BLE_ERROR_IRQ."] +pub struct BLE_ARP_ERR_MSK_N_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_ARP_ERR_MSK_N_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 23)) | ((value as u32 & 1) << 23); + self.w + } +} +#[doc = "Field `BLE_ARP_PHY_ERR_STAT` reader - When set to \"1\" then an error occured in BLE ARP sub-block and the BLE_GEN_IRQ will be aserted. It will be set if the ARP_ERROR or PHY_ERROR will be asserted and if the BLE_ARP_ERR_MSK is set to \"1\". Writing the value \"1\" will acknowledge and clear this field."] +pub struct BLE_ARP_PHY_ERR_STAT_R(crate::FieldReader); +impl BLE_ARP_PHY_ERR_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_ARP_PHY_ERR_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_ARP_PHY_ERR_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_ARP_PHY_ERR_STAT` writer - When set to \"1\" then an error occured in BLE ARP sub-block and the BLE_GEN_IRQ will be aserted. It will be set if the ARP_ERROR or PHY_ERROR will be asserted and if the BLE_ARP_ERR_MSK is set to \"1\". Writing the value \"1\" will acknowledge and clear this field."] +pub struct BLE_ARP_PHY_ERR_STAT_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_ARP_PHY_ERR_STAT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 22)) | ((value as u32 & 1) << 22); + self.w + } +} +#[doc = "Field `BLE_RSSI_SEL` reader - 0: (default) Select Peak-hold RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_LATCHED_RD\\[9:2\\]. 1: Select the Average RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_AVG_RD\\[9:2\\]."] +pub struct BLE_RSSI_SEL_R(crate::FieldReader); +impl BLE_RSSI_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_RSSI_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_RSSI_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_RSSI_SEL` writer - 0: (default) Select Peak-hold RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_LATCHED_RD\\[9:2\\]. 1: Select the Average RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_AVG_RD\\[9:2\\]."] +pub struct BLE_RSSI_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_RSSI_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 21)) | ((value as u32 & 1) << 21); + self.w + } +} +#[doc = "Field `WAKEUPLPSTAT` reader - The status of the BLE_WAKEUP_LP_IRQ. The Interrupt Service Routine of BLE_WAKEUP_LP_IRQ should return only when the WAKEUPLPSTAT is cleared. Note that BLE_WAKEUP_LP_IRQ is automatically acknowledged after the power up of the Radio Subsystem, plus one Low Power Clock period."] +pub struct WAKEUPLPSTAT_R(crate::FieldReader); +impl WAKEUPLPSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WAKEUPLPSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WAKEUPLPSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SW_RPL_SPI` reader - Keep to 0."] +pub struct SW_RPL_SPI_R(crate::FieldReader); +impl SW_RPL_SPI_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SW_RPL_SPI_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SW_RPL_SPI_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SW_RPL_SPI` writer - Keep to 0."] +pub struct SW_RPL_SPI_W<'a> { + w: &'a mut W, +} +impl<'a> SW_RPL_SPI_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `BB_ONLY` reader - Keep to 0."] +pub struct BB_ONLY_R(crate::FieldReader); +impl BB_ONLY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BB_ONLY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BB_ONLY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BB_ONLY` writer - Keep to 0."] +pub struct BB_ONLY_W<'a> { + w: &'a mut W, +} +impl<'a> BB_ONLY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 18)) | ((value as u32 & 1) << 18); + self.w + } +} +#[doc = "Field `BLE_PTI_SOURCE_SEL` reader - 0: Provide to COEX block the PTI value indicated by the Control Structure. Recommended value is \"0\". 1: Provide to COEX block the PTI value generated dynamically by the BLE core, which is based on the PTI of the Control Structure."] +pub struct BLE_PTI_SOURCE_SEL_R(crate::FieldReader); +impl BLE_PTI_SOURCE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_PTI_SOURCE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_PTI_SOURCE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_PTI_SOURCE_SEL` writer - 0: Provide to COEX block the PTI value indicated by the Control Structure. Recommended value is \"0\". 1: Provide to COEX block the PTI value generated dynamically by the BLE core, which is based on the PTI of the Control Structure."] +pub struct BLE_PTI_SOURCE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_PTI_SOURCE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 17)) | ((value as u32 & 1) << 17); + self.w + } +} +#[doc = "Field `BLE_CLK_SEL` reader - BLE Clock Select. Specifies the BLE master clock absolute frequency in MHz. Typical values are 16 and 8. Value depends on the selected XTAL frequency and the value of CLK_RADIO_REG\\[BLE_DIV\\] +bitfield. For example, if XTAL oscillates at 16MHz and CLK_RADIO_REG\\[BLE_DIV\\] += 1 (divide by 2), then BLE master clock frequency is 8MHz and BLE_CLK_SEL should be set to value 8. The selected BLE master clock frequency (affected by BLE_DIV and BLE_CLK_SEL) must be modified and set only during the initialization time, i.e. before setting BLE_RWBLECNTL_REG\\[RWBLE_EN\\] +to 1. Refer also to BLE_RWBLECONF_REG\\[CLK_SEL\\]."] +pub struct BLE_CLK_SEL_R(crate::FieldReader); +impl BLE_CLK_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLE_CLK_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_CLK_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_CLK_SEL` writer - BLE Clock Select. Specifies the BLE master clock absolute frequency in MHz. Typical values are 16 and 8. Value depends on the selected XTAL frequency and the value of CLK_RADIO_REG\\[BLE_DIV\\] +bitfield. For example, if XTAL oscillates at 16MHz and CLK_RADIO_REG\\[BLE_DIV\\] += 1 (divide by 2), then BLE master clock frequency is 8MHz and BLE_CLK_SEL should be set to value 8. The selected BLE master clock frequency (affected by BLE_DIV and BLE_CLK_SEL) must be modified and set only during the initialization time, i.e. before setting BLE_RWBLECNTL_REG\\[RWBLE_EN\\] +to 1. Refer also to BLE_RWBLECONF_REG\\[CLK_SEL\\]."] +pub struct BLE_CLK_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_CLK_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 9)) | ((value as u32 & 0x3f) << 9); + self.w + } +} +#[doc = "Field `RADIO_PWRDN_ALLOW` reader - This active high signal indicates when it is allowed for the BLE core (embedded in the Radio sub-System power domain) to be powered down. After the assertion of the BLE_DEEPSLCNTL_REG\\[DEEP_SLEEP_ON\\] +a hardware sequence based on the Low Power clock will cause the assertion of RADIO_PWRDN_ALLOW. The RADIO_PWRDN_ALLOW will be cleared to \"0\" when the BLE core exits from the sleep state, i.e. when the BLE_SLP_IRQ will be asserted."] +pub struct RADIO_PWRDN_ALLOW_R(crate::FieldReader); +impl RADIO_PWRDN_ALLOW_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_PWRDN_ALLOW_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_PWRDN_ALLOW_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MON_LP_CLK` reader - The SW can only write a \"0\" to this bit. Whenever a positive edge of the low power clock used by the BLE Timers is detected, then the HW will automatically set this bit to \"1\". This functionality will not work if BLE Timer is in reset state (refer to CLK_RADIO_REG\\[BLE_LP_RESET\\]). This bit can be used for SW synchronization, to debug the low power clock, etc."] +pub struct MON_LP_CLK_R(crate::FieldReader); +impl MON_LP_CLK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MON_LP_CLK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MON_LP_CLK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_CLK_STAT` reader - 0: BLE uses low power clock 1: BLE uses master clock"] +pub struct BLE_CLK_STAT_R(crate::FieldReader); +impl BLE_CLK_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_CLK_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_CLK_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_DIAG_OVR` reader - 1: Overrule BLE_DIAG. 0: BLE_DIAG is not overruled."] +pub struct BLE_DIAG_OVR_R(crate::FieldReader); +impl BLE_DIAG_OVR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_DIAG_OVR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_DIAG_OVR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_DIAG_OVR` writer - 1: Overrule BLE_DIAG. 0: BLE_DIAG is not overruled."] +pub struct BLE_DIAG_OVR_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_DIAG_OVR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `EMACCERRMSK` reader - Exchange Memory Access Error Mask: When cleared to \"0\" the EM_ACC_ERR will not cause an BLE_ERROR_IRQ interrupt. When set to \"1\" an BLE_ERROR_IRQ will be generated as long as EM_ACC_ERR is \"1\"."] +pub struct EMACCERRMSK_R(crate::FieldReader); +impl EMACCERRMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EMACCERRMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EMACCERRMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EMACCERRMSK` writer - Exchange Memory Access Error Mask: When cleared to \"0\" the EM_ACC_ERR will not cause an BLE_ERROR_IRQ interrupt. When set to \"1\" an BLE_ERROR_IRQ will be generated as long as EM_ACC_ERR is \"1\"."] +pub struct EMACCERRMSK_W<'a> { + w: &'a mut W, +} +impl<'a> EMACCERRMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `EMACCERRACK` writer - Exchange Memory Access Error Acknowledge. When the SW writes a \"1\" to this bit then the EMACCERRSTAT bit will be cleared. When the SW writes \"0\" it will have no affect. The read value is always \"0\"."] +pub struct EMACCERRACK_W<'a> { + w: &'a mut W, +} +impl<'a> EMACCERRACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `EMACCERRSTAT` reader - Exchange Memory Access Error Status: The bit is read-only and can be cleared only by writing a \"1\" at EMACCERRACK bitfield. This bit will be set to \"1\" by the hardware when the controller will access an EM page that is not mapped according to the EM_MAPPING value. When this bit is \"1\" then the BLE_ERROR_IRQ will be asserted as long as EMACCERRMSK is \"1\"."] +pub struct EMACCERRSTAT_R(crate::FieldReader); +impl EMACCERRSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EMACCERRSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EMACCERRSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 24"] + #[inline(always)] + pub fn ble_phy_err_msk_n(&self) -> BLE_PHY_ERR_MSK_N_R { + BLE_PHY_ERR_MSK_N_R::new(((self.bits >> 24) & 1) != 0) + } + #[doc = "Bit 23 - When cleared to \"0\" then it masks the BLE_ARP_ERR_STAT in order to not trigger a BLE_ERROR_IRQ."] + #[inline(always)] + pub fn ble_arp_err_msk_n(&self) -> BLE_ARP_ERR_MSK_N_R { + BLE_ARP_ERR_MSK_N_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bit 22 - When set to \"1\" then an error occured in BLE ARP sub-block and the BLE_GEN_IRQ will be aserted. It will be set if the ARP_ERROR or PHY_ERROR will be asserted and if the BLE_ARP_ERR_MSK is set to \"1\". Writing the value \"1\" will acknowledge and clear this field."] + #[inline(always)] + pub fn ble_arp_phy_err_stat(&self) -> BLE_ARP_PHY_ERR_STAT_R { + BLE_ARP_PHY_ERR_STAT_R::new(((self.bits >> 22) & 1) != 0) + } + #[doc = "Bit 21 - 0: (default) Select Peak-hold RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_LATCHED_RD\\[9:2\\]. 1: Select the Average RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_AVG_RD\\[9:2\\]."] + #[inline(always)] + pub fn ble_rssi_sel(&self) -> BLE_RSSI_SEL_R { + BLE_RSSI_SEL_R::new(((self.bits >> 21) & 1) != 0) + } + #[doc = "Bit 20 - The status of the BLE_WAKEUP_LP_IRQ. The Interrupt Service Routine of BLE_WAKEUP_LP_IRQ should return only when the WAKEUPLPSTAT is cleared. Note that BLE_WAKEUP_LP_IRQ is automatically acknowledged after the power up of the Radio Subsystem, plus one Low Power Clock period."] + #[inline(always)] + pub fn wakeuplpstat(&self) -> WAKEUPLPSTAT_R { + WAKEUPLPSTAT_R::new(((self.bits >> 20) & 1) != 0) + } + #[doc = "Bit 19 - Keep to 0."] + #[inline(always)] + pub fn sw_rpl_spi(&self) -> SW_RPL_SPI_R { + SW_RPL_SPI_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bit 18 - Keep to 0."] + #[inline(always)] + pub fn bb_only(&self) -> BB_ONLY_R { + BB_ONLY_R::new(((self.bits >> 18) & 1) != 0) + } + #[doc = "Bit 17 - 0: Provide to COEX block the PTI value indicated by the Control Structure. Recommended value is \"0\". 1: Provide to COEX block the PTI value generated dynamically by the BLE core, which is based on the PTI of the Control Structure."] + #[inline(always)] + pub fn ble_pti_source_sel(&self) -> BLE_PTI_SOURCE_SEL_R { + BLE_PTI_SOURCE_SEL_R::new(((self.bits >> 17) & 1) != 0) + } + #[doc = "Bits 9:14 - BLE Clock Select. Specifies the BLE master clock absolute frequency in MHz. Typical values are 16 and 8. Value depends on the selected XTAL frequency and the value of CLK_RADIO_REG\\[BLE_DIV\\] +bitfield. For example, if XTAL oscillates at 16MHz and CLK_RADIO_REG\\[BLE_DIV\\] += 1 (divide by 2), then BLE master clock frequency is 8MHz and BLE_CLK_SEL should be set to value 8. The selected BLE master clock frequency (affected by BLE_DIV and BLE_CLK_SEL) must be modified and set only during the initialization time, i.e. before setting BLE_RWBLECNTL_REG\\[RWBLE_EN\\] +to 1. Refer also to BLE_RWBLECONF_REG\\[CLK_SEL\\]."] + #[inline(always)] + pub fn ble_clk_sel(&self) -> BLE_CLK_SEL_R { + BLE_CLK_SEL_R::new(((self.bits >> 9) & 0x3f) as u8) + } + #[doc = "Bit 8 - This active high signal indicates when it is allowed for the BLE core (embedded in the Radio sub-System power domain) to be powered down. After the assertion of the BLE_DEEPSLCNTL_REG\\[DEEP_SLEEP_ON\\] +a hardware sequence based on the Low Power clock will cause the assertion of RADIO_PWRDN_ALLOW. The RADIO_PWRDN_ALLOW will be cleared to \"0\" when the BLE core exits from the sleep state, i.e. when the BLE_SLP_IRQ will be asserted."] + #[inline(always)] + pub fn radio_pwrdn_allow(&self) -> RADIO_PWRDN_ALLOW_R { + RADIO_PWRDN_ALLOW_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - The SW can only write a \"0\" to this bit. Whenever a positive edge of the low power clock used by the BLE Timers is detected, then the HW will automatically set this bit to \"1\". This functionality will not work if BLE Timer is in reset state (refer to CLK_RADIO_REG\\[BLE_LP_RESET\\]). This bit can be used for SW synchronization, to debug the low power clock, etc."] + #[inline(always)] + pub fn mon_lp_clk(&self) -> MON_LP_CLK_R { + MON_LP_CLK_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - 0: BLE uses low power clock 1: BLE uses master clock"] + #[inline(always)] + pub fn ble_clk_stat(&self) -> BLE_CLK_STAT_R { + BLE_CLK_STAT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 3 - 1: Overrule BLE_DIAG. 0: BLE_DIAG is not overruled."] + #[inline(always)] + pub fn ble_diag_ovr(&self) -> BLE_DIAG_OVR_R { + BLE_DIAG_OVR_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Exchange Memory Access Error Mask: When cleared to \"0\" the EM_ACC_ERR will not cause an BLE_ERROR_IRQ interrupt. When set to \"1\" an BLE_ERROR_IRQ will be generated as long as EM_ACC_ERR is \"1\"."] + #[inline(always)] + pub fn emaccerrmsk(&self) -> EMACCERRMSK_R { + EMACCERRMSK_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 0 - Exchange Memory Access Error Status: The bit is read-only and can be cleared only by writing a \"1\" at EMACCERRACK bitfield. This bit will be set to \"1\" by the hardware when the controller will access an EM page that is not mapped according to the EM_MAPPING value. When this bit is \"1\" then the BLE_ERROR_IRQ will be asserted as long as EMACCERRMSK is \"1\"."] + #[inline(always)] + pub fn emaccerrstat(&self) -> EMACCERRSTAT_R { + EMACCERRSTAT_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 24"] + #[inline(always)] + pub fn ble_phy_err_msk_n(&mut self) -> BLE_PHY_ERR_MSK_N_W { + BLE_PHY_ERR_MSK_N_W { w: self } + } + #[doc = "Bit 23 - When cleared to \"0\" then it masks the BLE_ARP_ERR_STAT in order to not trigger a BLE_ERROR_IRQ."] + #[inline(always)] + pub fn ble_arp_err_msk_n(&mut self) -> BLE_ARP_ERR_MSK_N_W { + BLE_ARP_ERR_MSK_N_W { w: self } + } + #[doc = "Bit 22 - When set to \"1\" then an error occured in BLE ARP sub-block and the BLE_GEN_IRQ will be aserted. It will be set if the ARP_ERROR or PHY_ERROR will be asserted and if the BLE_ARP_ERR_MSK is set to \"1\". Writing the value \"1\" will acknowledge and clear this field."] + #[inline(always)] + pub fn ble_arp_phy_err_stat(&mut self) -> BLE_ARP_PHY_ERR_STAT_W { + BLE_ARP_PHY_ERR_STAT_W { w: self } + } + #[doc = "Bit 21 - 0: (default) Select Peak-hold RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_LATCHED_RD\\[9:2\\]. 1: Select the Average RSSI value during the SYNC_FOUND event: CS->RXRSSI\\[7:0\\] += RF_RSSI_RESULT_REG->RSSI_AVG_RD\\[9:2\\]."] + #[inline(always)] + pub fn ble_rssi_sel(&mut self) -> BLE_RSSI_SEL_W { + BLE_RSSI_SEL_W { w: self } + } + #[doc = "Bit 19 - Keep to 0."] + #[inline(always)] + pub fn sw_rpl_spi(&mut self) -> SW_RPL_SPI_W { + SW_RPL_SPI_W { w: self } + } + #[doc = "Bit 18 - Keep to 0."] + #[inline(always)] + pub fn bb_only(&mut self) -> BB_ONLY_W { + BB_ONLY_W { w: self } + } + #[doc = "Bit 17 - 0: Provide to COEX block the PTI value indicated by the Control Structure. Recommended value is \"0\". 1: Provide to COEX block the PTI value generated dynamically by the BLE core, which is based on the PTI of the Control Structure."] + #[inline(always)] + pub fn ble_pti_source_sel(&mut self) -> BLE_PTI_SOURCE_SEL_W { + BLE_PTI_SOURCE_SEL_W { w: self } + } + #[doc = "Bits 9:14 - BLE Clock Select. Specifies the BLE master clock absolute frequency in MHz. Typical values are 16 and 8. Value depends on the selected XTAL frequency and the value of CLK_RADIO_REG\\[BLE_DIV\\] +bitfield. For example, if XTAL oscillates at 16MHz and CLK_RADIO_REG\\[BLE_DIV\\] += 1 (divide by 2), then BLE master clock frequency is 8MHz and BLE_CLK_SEL should be set to value 8. The selected BLE master clock frequency (affected by BLE_DIV and BLE_CLK_SEL) must be modified and set only during the initialization time, i.e. before setting BLE_RWBLECNTL_REG\\[RWBLE_EN\\] +to 1. Refer also to BLE_RWBLECONF_REG\\[CLK_SEL\\]."] + #[inline(always)] + pub fn ble_clk_sel(&mut self) -> BLE_CLK_SEL_W { + BLE_CLK_SEL_W { w: self } + } + #[doc = "Bit 3 - 1: Overrule BLE_DIAG. 0: BLE_DIAG is not overruled."] + #[inline(always)] + pub fn ble_diag_ovr(&mut self) -> BLE_DIAG_OVR_W { + BLE_DIAG_OVR_W { w: self } + } + #[doc = "Bit 2 - Exchange Memory Access Error Mask: When cleared to \"0\" the EM_ACC_ERR will not cause an BLE_ERROR_IRQ interrupt. When set to \"1\" an BLE_ERROR_IRQ will be generated as long as EM_ACC_ERR is \"1\"."] + #[inline(always)] + pub fn emaccerrmsk(&mut self) -> EMACCERRMSK_W { + EMACCERRMSK_W { w: self } + } + #[doc = "Bit 1 - Exchange Memory Access Error Acknowledge. When the SW writes a \"1\" to this bit then the EMACCERRSTAT bit will be cleared. When the SW writes \"0\" it will have no affect. The read value is always \"0\"."] + #[inline(always)] + pub fn emaccerrack(&mut self) -> EMACCERRACK_W { + EMACCERRACK_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "BLE Control Register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_cntl2_reg](index.html) module"] +pub struct BLE_CNTL2_REG_SPEC; +impl crate::RegisterSpec for BLE_CNTL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_cntl2_reg::R](R) reader structure"] +impl crate::Readable for BLE_CNTL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_cntl2_reg::W](W) writer structure"] +impl crate::Writable for BLE_CNTL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_CNTL2_REG to value 0x04"] +impl crate::Resettable for BLE_CNTL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x04 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl0_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl0_reg.rs new file mode 100644 index 0000000..6c0bf26 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl0_reg.rs @@ -0,0 +1,308 @@ +#[doc = "Register `BLE_COEXIFCNTL0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_COEXIFCNTL0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WLCRXPRIOMODE` reader - Defines Bluetooth Low Energy packet ble_rx mode behavior. 00: Rx indication excluding Rx Power up delay (starts when correlator is enabled) 01: Rx indication including Rx Power up delay 10: Rx High priority indicator 11: n/a"] +pub struct WLCRXPRIOMODE_R(crate::FieldReader); +impl WLCRXPRIOMODE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLCRXPRIOMODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLCRXPRIOMODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLCRXPRIOMODE` writer - Defines Bluetooth Low Energy packet ble_rx mode behavior. 00: Rx indication excluding Rx Power up delay (starts when correlator is enabled) 01: Rx indication including Rx Power up delay 10: Rx High priority indicator 11: n/a"] +pub struct WLCRXPRIOMODE_W<'a> { + w: &'a mut W, +} +impl<'a> WLCRXPRIOMODE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 20)) | ((value as u32 & 3) << 20); + self.w + } +} +#[doc = "Field `WLCTXPRIOMODE` reader - Defines Bluetooth Low Energy packet ble_tx mode behavior 00: Tx indication excluding Tx Power up delay 01: Tx indication including Tx Power up delay 10: Tx High priority indicator 11: n/a"] +pub struct WLCTXPRIOMODE_R(crate::FieldReader); +impl WLCTXPRIOMODE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLCTXPRIOMODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLCTXPRIOMODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLCTXPRIOMODE` writer - Defines Bluetooth Low Energy packet ble_tx mode behavior 00: Tx indication excluding Tx Power up delay 01: Tx indication including Tx Power up delay 10: Tx High priority indicator 11: n/a"] +pub struct WLCTXPRIOMODE_W<'a> { + w: &'a mut W, +} +impl<'a> WLCTXPRIOMODE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 16)) | ((value as u32 & 3) << 16); + self.w + } +} +#[doc = "Field `WLANTXMSK` reader - Determines how wlan_tx impact BLE Tx and Rx 00: wlan_tx has no impact (default mode) 01: wlan_tx can stop BLE Tx, no impact on BLE Rx 10: wlan_tx can stop BLE Rx, no impact on BLE Tx 11: wlan_tx can stop both BLE Tx and BLE Rx"] +pub struct WLANTXMSK_R(crate::FieldReader); +impl WLANTXMSK_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLANTXMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLANTXMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLANTXMSK` writer - Determines how wlan_tx impact BLE Tx and Rx 00: wlan_tx has no impact (default mode) 01: wlan_tx can stop BLE Tx, no impact on BLE Rx 10: wlan_tx can stop BLE Rx, no impact on BLE Tx 11: wlan_tx can stop both BLE Tx and BLE Rx"] +pub struct WLANTXMSK_W<'a> { + w: &'a mut W, +} +impl<'a> WLANTXMSK_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 6)) | ((value as u32 & 3) << 6); + self.w + } +} +#[doc = "Field `WLANRXMSK` reader - Determines how wlan_rx impact BLE Tx and Rx 00: wlan_rx has no impact 01: wlan_rx can stop BLE Tx, no impact on BLE Rx (default mode) 10: wlan_rx can stop BLE Rx, no impact on BLE Tx 11: wlan_rx can stop both BLE Tx and BLE Rx"] +pub struct WLANRXMSK_R(crate::FieldReader); +impl WLANRXMSK_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLANRXMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLANRXMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLANRXMSK` writer - Determines how wlan_rx impact BLE Tx and Rx 00: wlan_rx has no impact 01: wlan_rx can stop BLE Tx, no impact on BLE Rx (default mode) 10: wlan_rx can stop BLE Rx, no impact on BLE Tx 11: wlan_rx can stop both BLE Tx and BLE Rx"] +pub struct WLANRXMSK_W<'a> { + w: &'a mut W, +} +impl<'a> WLANRXMSK_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u32 & 3) << 4); + self.w + } +} +#[doc = "Field `SYNCGEN_EN` reader - Determines whether ble_sync is generated or not. 0: ble_sync pulse not generated 1: ble_sync pulse generated"] +pub struct SYNCGEN_EN_R(crate::FieldReader); +impl SYNCGEN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SYNCGEN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYNCGEN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYNCGEN_EN` writer - Determines whether ble_sync is generated or not. 0: ble_sync pulse not generated 1: ble_sync pulse generated"] +pub struct SYNCGEN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SYNCGEN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `COEX_EN` reader - Enable / Disable control of the MWS/WLAN Coexistence control 0: Coexistence interface disabled 1: Coexistence interface enabled"] +pub struct COEX_EN_R(crate::FieldReader); +impl COEX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + COEX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for COEX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `COEX_EN` writer - Enable / Disable control of the MWS/WLAN Coexistence control 0: Coexistence interface disabled 1: Coexistence interface enabled"] +pub struct COEX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> COEX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bits 20:21 - Defines Bluetooth Low Energy packet ble_rx mode behavior. 00: Rx indication excluding Rx Power up delay (starts when correlator is enabled) 01: Rx indication including Rx Power up delay 10: Rx High priority indicator 11: n/a"] + #[inline(always)] + pub fn wlcrxpriomode(&self) -> WLCRXPRIOMODE_R { + WLCRXPRIOMODE_R::new(((self.bits >> 20) & 3) as u8) + } + #[doc = "Bits 16:17 - Defines Bluetooth Low Energy packet ble_tx mode behavior 00: Tx indication excluding Tx Power up delay 01: Tx indication including Tx Power up delay 10: Tx High priority indicator 11: n/a"] + #[inline(always)] + pub fn wlctxpriomode(&self) -> WLCTXPRIOMODE_R { + WLCTXPRIOMODE_R::new(((self.bits >> 16) & 3) as u8) + } + #[doc = "Bits 6:7 - Determines how wlan_tx impact BLE Tx and Rx 00: wlan_tx has no impact (default mode) 01: wlan_tx can stop BLE Tx, no impact on BLE Rx 10: wlan_tx can stop BLE Rx, no impact on BLE Tx 11: wlan_tx can stop both BLE Tx and BLE Rx"] + #[inline(always)] + pub fn wlantxmsk(&self) -> WLANTXMSK_R { + WLANTXMSK_R::new(((self.bits >> 6) & 3) as u8) + } + #[doc = "Bits 4:5 - Determines how wlan_rx impact BLE Tx and Rx 00: wlan_rx has no impact 01: wlan_rx can stop BLE Tx, no impact on BLE Rx (default mode) 10: wlan_rx can stop BLE Rx, no impact on BLE Tx 11: wlan_rx can stop both BLE Tx and BLE Rx"] + #[inline(always)] + pub fn wlanrxmsk(&self) -> WLANRXMSK_R { + WLANRXMSK_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bit 1 - Determines whether ble_sync is generated or not. 0: ble_sync pulse not generated 1: ble_sync pulse generated"] + #[inline(always)] + pub fn syncgen_en(&self) -> SYNCGEN_EN_R { + SYNCGEN_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Enable / Disable control of the MWS/WLAN Coexistence control 0: Coexistence interface disabled 1: Coexistence interface enabled"] + #[inline(always)] + pub fn coex_en(&self) -> COEX_EN_R { + COEX_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 20:21 - Defines Bluetooth Low Energy packet ble_rx mode behavior. 00: Rx indication excluding Rx Power up delay (starts when correlator is enabled) 01: Rx indication including Rx Power up delay 10: Rx High priority indicator 11: n/a"] + #[inline(always)] + pub fn wlcrxpriomode(&mut self) -> WLCRXPRIOMODE_W { + WLCRXPRIOMODE_W { w: self } + } + #[doc = "Bits 16:17 - Defines Bluetooth Low Energy packet ble_tx mode behavior 00: Tx indication excluding Tx Power up delay 01: Tx indication including Tx Power up delay 10: Tx High priority indicator 11: n/a"] + #[inline(always)] + pub fn wlctxpriomode(&mut self) -> WLCTXPRIOMODE_W { + WLCTXPRIOMODE_W { w: self } + } + #[doc = "Bits 6:7 - Determines how wlan_tx impact BLE Tx and Rx 00: wlan_tx has no impact (default mode) 01: wlan_tx can stop BLE Tx, no impact on BLE Rx 10: wlan_tx can stop BLE Rx, no impact on BLE Tx 11: wlan_tx can stop both BLE Tx and BLE Rx"] + #[inline(always)] + pub fn wlantxmsk(&mut self) -> WLANTXMSK_W { + WLANTXMSK_W { w: self } + } + #[doc = "Bits 4:5 - Determines how wlan_rx impact BLE Tx and Rx 00: wlan_rx has no impact 01: wlan_rx can stop BLE Tx, no impact on BLE Rx (default mode) 10: wlan_rx can stop BLE Rx, no impact on BLE Tx 11: wlan_rx can stop both BLE Tx and BLE Rx"] + #[inline(always)] + pub fn wlanrxmsk(&mut self) -> WLANRXMSK_W { + WLANRXMSK_W { w: self } + } + #[doc = "Bit 1 - Determines whether ble_sync is generated or not. 0: ble_sync pulse not generated 1: ble_sync pulse generated"] + #[inline(always)] + pub fn syncgen_en(&mut self) -> SYNCGEN_EN_W { + SYNCGEN_EN_W { w: self } + } + #[doc = "Bit 0 - Enable / Disable control of the MWS/WLAN Coexistence control 0: Coexistence interface disabled 1: Coexistence interface enabled"] + #[inline(always)] + pub fn coex_en(&mut self) -> COEX_EN_W { + COEX_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Coexistence interface Control 0 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_coexifcntl0_reg](index.html) module"] +pub struct BLE_COEXIFCNTL0_REG_SPEC; +impl crate::RegisterSpec for BLE_COEXIFCNTL0_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_coexifcntl0_reg::R](R) reader structure"] +impl crate::Readable for BLE_COEXIFCNTL0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_coexifcntl0_reg::W](W) writer structure"] +impl crate::Writable for BLE_COEXIFCNTL0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_COEXIFCNTL0_REG to value 0x10"] +impl crate::Resettable for BLE_COEXIFCNTL0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x10 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl1_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl1_reg.rs new file mode 100644 index 0000000..b2bd4cb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_coexifcntl1_reg.rs @@ -0,0 +1,222 @@ +#[doc = "Register `BLE_COEXIFCNTL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_COEXIFCNTL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WLCPRXTHR` reader - Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines the threshold for Rx priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPRXTHR, then Rx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] +pub struct WLCPRXTHR_R(crate::FieldReader); +impl WLCPRXTHR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLCPRXTHR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLCPRXTHR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLCPRXTHR` writer - Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines the threshold for Rx priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPRXTHR, then Rx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] +pub struct WLCPRXTHR_W<'a> { + w: &'a mut W, +} +impl<'a> WLCPRXTHR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 24)) | ((value as u32 & 0x1f) << 24); + self.w + } +} +#[doc = "Field `WLCPTXTHR` reader - Applies on ble_tx if WLCTXPRIOMODE equals 10 Determines the threshold for priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPTXTHR, then Tx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] +pub struct WLCPTXTHR_R(crate::FieldReader); +impl WLCPTXTHR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLCPTXTHR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLCPTXTHR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLCPTXTHR` writer - Applies on ble_tx if WLCTXPRIOMODE equals 10 Determines the threshold for priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPTXTHR, then Tx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] +pub struct WLCPTXTHR_W<'a> { + w: &'a mut W, +} +impl<'a> WLCPTXTHR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 16)) | ((value as u32 & 0x1f) << 16); + self.w + } +} +#[doc = "Field `WLCPDURATION` reader - Applies on ble_tx if WLCTXPRIOMODE equals 10 Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines how many s the priority information must be maintained Note that if WLCPDURATION = 0x00, then Tx/Rx priority levels are maintained till Tx/Rx EN are de-asserted."] +pub struct WLCPDURATION_R(crate::FieldReader); +impl WLCPDURATION_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLCPDURATION_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLCPDURATION_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLCPDURATION` writer - Applies on ble_tx if WLCTXPRIOMODE equals 10 Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines how many s the priority information must be maintained Note that if WLCPDURATION = 0x00, then Tx/Rx priority levels are maintained till Tx/Rx EN are de-asserted."] +pub struct WLCPDURATION_W<'a> { + w: &'a mut W, +} +impl<'a> WLCPDURATION_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 8)) | ((value as u32 & 0x7f) << 8); + self.w + } +} +#[doc = "Field `WLCPDELAY` reader - Applies on ble_tx if WLCTXPRIOMODE equals 10. Applies on ble_rx if WLCRXPRIOMODE equals 10. Determines the delay (in us) in Tx/Rx enables rises the time Bluetooth Low energy Tx/Rx priority has to be provided ."] +pub struct WLCPDELAY_R(crate::FieldReader); +impl WLCPDELAY_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WLCPDELAY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLCPDELAY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLCPDELAY` writer - Applies on ble_tx if WLCTXPRIOMODE equals 10. Applies on ble_rx if WLCRXPRIOMODE equals 10. Determines the delay (in us) in Tx/Rx enables rises the time Bluetooth Low energy Tx/Rx priority has to be provided ."] +pub struct WLCPDELAY_W<'a> { + w: &'a mut W, +} +impl<'a> WLCPDELAY_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x7f) | (value as u32 & 0x7f); + self.w + } +} +impl R { + #[doc = "Bits 24:28 - Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines the threshold for Rx priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPRXTHR, then Rx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] + #[inline(always)] + pub fn wlcprxthr(&self) -> WLCPRXTHR_R { + WLCPRXTHR_R::new(((self.bits >> 24) & 0x1f) as u8) + } + #[doc = "Bits 16:20 - Applies on ble_tx if WLCTXPRIOMODE equals 10 Determines the threshold for priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPTXTHR, then Tx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] + #[inline(always)] + pub fn wlcptxthr(&self) -> WLCPTXTHR_R { + WLCPTXTHR_R::new(((self.bits >> 16) & 0x1f) as u8) + } + #[doc = "Bits 8:14 - Applies on ble_tx if WLCTXPRIOMODE equals 10 Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines how many s the priority information must be maintained Note that if WLCPDURATION = 0x00, then Tx/Rx priority levels are maintained till Tx/Rx EN are de-asserted."] + #[inline(always)] + pub fn wlcpduration(&self) -> WLCPDURATION_R { + WLCPDURATION_R::new(((self.bits >> 8) & 0x7f) as u8) + } + #[doc = "Bits 0:6 - Applies on ble_tx if WLCTXPRIOMODE equals 10. Applies on ble_rx if WLCRXPRIOMODE equals 10. Determines the delay (in us) in Tx/Rx enables rises the time Bluetooth Low energy Tx/Rx priority has to be provided ."] + #[inline(always)] + pub fn wlcpdelay(&self) -> WLCPDELAY_R { + WLCPDELAY_R::new((self.bits & 0x7f) as u8) + } +} +impl W { + #[doc = "Bits 24:28 - Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines the threshold for Rx priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPRXTHR, then Rx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] + #[inline(always)] + pub fn wlcprxthr(&mut self) -> WLCPRXTHR_W { + WLCPRXTHR_W { w: self } + } + #[doc = "Bits 16:20 - Applies on ble_tx if WLCTXPRIOMODE equals 10 Determines the threshold for priority setting. If ble_pti\\[3:0\\] +output value is greater than WLCPTXTHR, then Tx Bluetooth Low Energy priority is considered as high, and must be provided to the WLAN coexistence interface"] + #[inline(always)] + pub fn wlcptxthr(&mut self) -> WLCPTXTHR_W { + WLCPTXTHR_W { w: self } + } + #[doc = "Bits 8:14 - Applies on ble_tx if WLCTXPRIOMODE equals 10 Applies on ble_rx if WLCRXPRIOMODE equals 10 Determines how many s the priority information must be maintained Note that if WLCPDURATION = 0x00, then Tx/Rx priority levels are maintained till Tx/Rx EN are de-asserted."] + #[inline(always)] + pub fn wlcpduration(&mut self) -> WLCPDURATION_W { + WLCPDURATION_W { w: self } + } + #[doc = "Bits 0:6 - Applies on ble_tx if WLCTXPRIOMODE equals 10. Applies on ble_rx if WLCRXPRIOMODE equals 10. Determines the delay (in us) in Tx/Rx enables rises the time Bluetooth Low energy Tx/Rx priority has to be provided ."] + #[inline(always)] + pub fn wlcpdelay(&mut self) -> WLCPDELAY_W { + WLCPDELAY_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Coexistence interface Control 1 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_coexifcntl1_reg](index.html) module"] +pub struct BLE_COEXIFCNTL1_REG_SPEC; +impl crate::RegisterSpec for BLE_COEXIFCNTL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_coexifcntl1_reg::R](R) reader structure"] +impl crate::Readable for BLE_COEXIFCNTL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_coexifcntl1_reg::W](W) writer structure"] +impl crate::Writable for BLE_COEXIFCNTL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_COEXIFCNTL1_REG to value 0"] +impl crate::Resettable for BLE_COEXIFCNTL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_currentrxdescptr_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_currentrxdescptr_reg.rs new file mode 100644 index 0000000..c495965 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_currentrxdescptr_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `BLE_CURRENTRXDESCPTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_CURRENTRXDESCPTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ETPTR` reader - Exchange Table Pointer that determines the starting point of the Exchange Table"] +pub struct ETPTR_R(crate::FieldReader); +impl ETPTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ETPTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ETPTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ETPTR` writer - Exchange Table Pointer that determines the starting point of the Exchange Table"] +pub struct ETPTR_W<'a> { + w: &'a mut W, +} +impl<'a> ETPTR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xffff << 16)) | ((value as u32 & 0xffff) << 16); + self.w + } +} +#[doc = "Field `CURRENTRXDESCPTR` reader - Rx Descriptor Pointer that determines the starting point of the Receive Buffer Chained List"] +pub struct CURRENTRXDESCPTR_R(crate::FieldReader); +impl CURRENTRXDESCPTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CURRENTRXDESCPTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CURRENTRXDESCPTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CURRENTRXDESCPTR` writer - Rx Descriptor Pointer that determines the starting point of the Receive Buffer Chained List"] +pub struct CURRENTRXDESCPTR_W<'a> { + w: &'a mut W, +} +impl<'a> CURRENTRXDESCPTR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x7fff) | (value as u32 & 0x7fff); + self.w + } +} +impl R { + #[doc = "Bits 16:31 - Exchange Table Pointer that determines the starting point of the Exchange Table"] + #[inline(always)] + pub fn etptr(&self) -> ETPTR_R { + ETPTR_R::new(((self.bits >> 16) & 0xffff) as u16) + } + #[doc = "Bits 0:14 - Rx Descriptor Pointer that determines the starting point of the Receive Buffer Chained List"] + #[inline(always)] + pub fn currentrxdescptr(&self) -> CURRENTRXDESCPTR_R { + CURRENTRXDESCPTR_R::new((self.bits & 0x7fff) as u16) + } +} +impl W { + #[doc = "Bits 16:31 - Exchange Table Pointer that determines the starting point of the Exchange Table"] + #[inline(always)] + pub fn etptr(&mut self) -> ETPTR_W { + ETPTR_W { w: self } + } + #[doc = "Bits 0:14 - Rx Descriptor Pointer that determines the starting point of the Receive Buffer Chained List"] + #[inline(always)] + pub fn currentrxdescptr(&mut self) -> CURRENTRXDESCPTR_W { + CURRENTRXDESCPTR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Rx Descriptor Pointer for the Receive Buffer Chained List\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_currentrxdescptr_reg](index.html) module"] +pub struct BLE_CURRENTRXDESCPTR_REG_SPEC; +impl crate::RegisterSpec for BLE_CURRENTRXDESCPTR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_currentrxdescptr_reg::R](R) reader structure"] +impl crate::Readable for BLE_CURRENTRXDESCPTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_currentrxdescptr_reg::W](W) writer structure"] +impl crate::Writable for BLE_CURRENTRXDESCPTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_CURRENTRXDESCPTR_REG to value 0"] +impl crate::Resettable for BLE_CURRENTRXDESCPTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmax_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmax_reg.rs new file mode 100644 index 0000000..40d7683 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmax_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `BLE_DEBUGADDMAX_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DEBUGADDMAX_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `REG_ADDMAX` reader - Upper limit for the Register zone indicated by the reg_inzone flag"] +pub struct REG_ADDMAX_R(crate::FieldReader); +impl REG_ADDMAX_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + REG_ADDMAX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REG_ADDMAX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REG_ADDMAX` writer - Upper limit for the Register zone indicated by the reg_inzone flag"] +pub struct REG_ADDMAX_W<'a> { + w: &'a mut W, +} +impl<'a> REG_ADDMAX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xffff << 16)) | ((value as u32 & 0xffff) << 16); + self.w + } +} +#[doc = "Field `EM_ADDMAX` reader - Upper limit for the Exchange Memory zone indicated by the em_inzone flag"] +pub struct EM_ADDMAX_R(crate::FieldReader); +impl EM_ADDMAX_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + EM_ADDMAX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EM_ADDMAX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EM_ADDMAX` writer - Upper limit for the Exchange Memory zone indicated by the em_inzone flag"] +pub struct EM_ADDMAX_W<'a> { + w: &'a mut W, +} +impl<'a> EM_ADDMAX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bits 16:31 - Upper limit for the Register zone indicated by the reg_inzone flag"] + #[inline(always)] + pub fn reg_addmax(&self) -> REG_ADDMAX_R { + REG_ADDMAX_R::new(((self.bits >> 16) & 0xffff) as u16) + } + #[doc = "Bits 0:15 - Upper limit for the Exchange Memory zone indicated by the em_inzone flag"] + #[inline(always)] + pub fn em_addmax(&self) -> EM_ADDMAX_R { + EM_ADDMAX_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bits 16:31 - Upper limit for the Register zone indicated by the reg_inzone flag"] + #[inline(always)] + pub fn reg_addmax(&mut self) -> REG_ADDMAX_W { + REG_ADDMAX_W { w: self } + } + #[doc = "Bits 0:15 - Upper limit for the Exchange Memory zone indicated by the em_inzone flag"] + #[inline(always)] + pub fn em_addmax(&mut self) -> EM_ADDMAX_W { + EM_ADDMAX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Upper limit for the memory zone\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_debugaddmax_reg](index.html) module"] +pub struct BLE_DEBUGADDMAX_REG_SPEC; +impl crate::RegisterSpec for BLE_DEBUGADDMAX_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_debugaddmax_reg::R](R) reader structure"] +impl crate::Readable for BLE_DEBUGADDMAX_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_debugaddmax_reg::W](W) writer structure"] +impl crate::Writable for BLE_DEBUGADDMAX_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DEBUGADDMAX_REG to value 0"] +impl crate::Resettable for BLE_DEBUGADDMAX_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmin_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmin_reg.rs new file mode 100644 index 0000000..35878df --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_debugaddmin_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `BLE_DEBUGADDMIN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DEBUGADDMIN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `REG_ADDMIN` reader - Lower limit for the Register zone indicated by the reg_inzone flag"] +pub struct REG_ADDMIN_R(crate::FieldReader); +impl REG_ADDMIN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + REG_ADDMIN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REG_ADDMIN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REG_ADDMIN` writer - Lower limit for the Register zone indicated by the reg_inzone flag"] +pub struct REG_ADDMIN_W<'a> { + w: &'a mut W, +} +impl<'a> REG_ADDMIN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xffff << 16)) | ((value as u32 & 0xffff) << 16); + self.w + } +} +#[doc = "Field `EM_ADDMIN` reader - Lower limit for the Exchange Memory zone indicated by the em_inzone flag"] +pub struct EM_ADDMIN_R(crate::FieldReader); +impl EM_ADDMIN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + EM_ADDMIN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EM_ADDMIN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EM_ADDMIN` writer - Lower limit for the Exchange Memory zone indicated by the em_inzone flag"] +pub struct EM_ADDMIN_W<'a> { + w: &'a mut W, +} +impl<'a> EM_ADDMIN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bits 16:31 - Lower limit for the Register zone indicated by the reg_inzone flag"] + #[inline(always)] + pub fn reg_addmin(&self) -> REG_ADDMIN_R { + REG_ADDMIN_R::new(((self.bits >> 16) & 0xffff) as u16) + } + #[doc = "Bits 0:15 - Lower limit for the Exchange Memory zone indicated by the em_inzone flag"] + #[inline(always)] + pub fn em_addmin(&self) -> EM_ADDMIN_R { + EM_ADDMIN_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bits 16:31 - Lower limit for the Register zone indicated by the reg_inzone flag"] + #[inline(always)] + pub fn reg_addmin(&mut self) -> REG_ADDMIN_W { + REG_ADDMIN_W { w: self } + } + #[doc = "Bits 0:15 - Lower limit for the Exchange Memory zone indicated by the em_inzone flag"] + #[inline(always)] + pub fn em_addmin(&mut self) -> EM_ADDMIN_W { + EM_ADDMIN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Lower limit for the memory zone\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_debugaddmin_reg](index.html) module"] +pub struct BLE_DEBUGADDMIN_REG_SPEC; +impl crate::RegisterSpec for BLE_DEBUGADDMIN_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_debugaddmin_reg::R](R) reader structure"] +impl crate::Readable for BLE_DEBUGADDMIN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_debugaddmin_reg::W](W) writer structure"] +impl crate::Writable for BLE_DEBUGADDMIN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DEBUGADDMIN_REG to value 0"] +impl crate::Resettable for BLE_DEBUGADDMIN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_deepslcntl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_deepslcntl_reg.rs new file mode 100644 index 0000000..6bde19a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_deepslcntl_reg.rs @@ -0,0 +1,271 @@ +#[doc = "Register `BLE_DEEPSLCNTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DEEPSLCNTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `EXTWKUPDSB` reader - External Wake-Up disable 0: RW-BLE Core can be woken by external wake-up 1: RW-BLE Core cannot be woken up by external wake-up"] +pub struct EXTWKUPDSB_R(crate::FieldReader); +impl EXTWKUPDSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EXTWKUPDSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EXTWKUPDSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EXTWKUPDSB` writer - External Wake-Up disable 0: RW-BLE Core can be woken by external wake-up 1: RW-BLE Core cannot be woken up by external wake-up"] +pub struct EXTWKUPDSB_W<'a> { + w: &'a mut W, +} +impl<'a> EXTWKUPDSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `DEEP_SLEEP_STAT` reader - Indicator of current Deep Sleep clock mux status: 0: RW-BLE Core is not yet in Deep Sleep Mode 1: RW-BLE Core is in Deep Sleep Mode (only low_power_clk is running)"] +pub struct DEEP_SLEEP_STAT_R(crate::FieldReader); +impl DEEP_SLEEP_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEEP_SLEEP_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEEP_SLEEP_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SOFT_WAKEUP_REQ` reader - Wake Up Request from BLE Software. Applies when system is in Deep Sleep Mode. It wakes up the BLE Core when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct SOFT_WAKEUP_REQ_R(crate::FieldReader); +impl SOFT_WAKEUP_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SOFT_WAKEUP_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SOFT_WAKEUP_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SOFT_WAKEUP_REQ` writer - Wake Up Request from BLE Software. Applies when system is in Deep Sleep Mode. It wakes up the BLE Core when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct SOFT_WAKEUP_REQ_W<'a> { + w: &'a mut W, +} +impl<'a> SOFT_WAKEUP_REQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `DEEP_SLEEP_CORR_EN` writer - 625us base time reference integer and fractional part correction. Applies when system has been woken-up from Deep Sleep Mode. It enables Fine Counter and Base Time counter when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct DEEP_SLEEP_CORR_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DEEP_SLEEP_CORR_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `DEEP_SLEEP_ON` writer - 0: BLE Core in normal active mode 1: Request RW-BLE Core to switch in deep sleep mode. This bit is reset on DEEP_SLEEP_STAT falling edge."] +pub struct DEEP_SLEEP_ON_W<'a> { + w: &'a mut W, +} +impl<'a> DEEP_SLEEP_ON_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `DEEP_SLEEP_IRQ_EN` reader - Always set to \"3\" when DEEP_SLEEP_ON is set to \"1\". It controls the generation of BLE_WAKEUP_LP_IRQ."] +pub struct DEEP_SLEEP_IRQ_EN_R(crate::FieldReader); +impl DEEP_SLEEP_IRQ_EN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEEP_SLEEP_IRQ_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEEP_SLEEP_IRQ_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEEP_SLEEP_IRQ_EN` writer - Always set to \"3\" when DEEP_SLEEP_ON is set to \"1\". It controls the generation of BLE_WAKEUP_LP_IRQ."] +pub struct DEEP_SLEEP_IRQ_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DEEP_SLEEP_IRQ_EN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u32 & 3); + self.w + } +} +impl R { + #[doc = "Bit 31 - External Wake-Up disable 0: RW-BLE Core can be woken by external wake-up 1: RW-BLE Core cannot be woken up by external wake-up"] + #[inline(always)] + pub fn extwkupdsb(&self) -> EXTWKUPDSB_R { + EXTWKUPDSB_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bit 15 - Indicator of current Deep Sleep clock mux status: 0: RW-BLE Core is not yet in Deep Sleep Mode 1: RW-BLE Core is in Deep Sleep Mode (only low_power_clk is running)"] + #[inline(always)] + pub fn deep_sleep_stat(&self) -> DEEP_SLEEP_STAT_R { + DEEP_SLEEP_STAT_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 4 - Wake Up Request from BLE Software. Applies when system is in Deep Sleep Mode. It wakes up the BLE Core when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn soft_wakeup_req(&self) -> SOFT_WAKEUP_REQ_R { + SOFT_WAKEUP_REQ_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 0:1 - Always set to \"3\" when DEEP_SLEEP_ON is set to \"1\". It controls the generation of BLE_WAKEUP_LP_IRQ."] + #[inline(always)] + pub fn deep_sleep_irq_en(&self) -> DEEP_SLEEP_IRQ_EN_R { + DEEP_SLEEP_IRQ_EN_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 31 - External Wake-Up disable 0: RW-BLE Core can be woken by external wake-up 1: RW-BLE Core cannot be woken up by external wake-up"] + #[inline(always)] + pub fn extwkupdsb(&mut self) -> EXTWKUPDSB_W { + EXTWKUPDSB_W { w: self } + } + #[doc = "Bit 4 - Wake Up Request from BLE Software. Applies when system is in Deep Sleep Mode. It wakes up the BLE Core when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn soft_wakeup_req(&mut self) -> SOFT_WAKEUP_REQ_W { + SOFT_WAKEUP_REQ_W { w: self } + } + #[doc = "Bit 3 - 625us base time reference integer and fractional part correction. Applies when system has been woken-up from Deep Sleep Mode. It enables Fine Counter and Base Time counter when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn deep_sleep_corr_en(&mut self) -> DEEP_SLEEP_CORR_EN_W { + DEEP_SLEEP_CORR_EN_W { w: self } + } + #[doc = "Bit 2 - 0: BLE Core in normal active mode 1: Request RW-BLE Core to switch in deep sleep mode. This bit is reset on DEEP_SLEEP_STAT falling edge."] + #[inline(always)] + pub fn deep_sleep_on(&mut self) -> DEEP_SLEEP_ON_W { + DEEP_SLEEP_ON_W { w: self } + } + #[doc = "Bits 0:1 - Always set to \"3\" when DEEP_SLEEP_ON is set to \"1\". It controls the generation of BLE_WAKEUP_LP_IRQ."] + #[inline(always)] + pub fn deep_sleep_irq_en(&mut self) -> DEEP_SLEEP_IRQ_EN_W { + DEEP_SLEEP_IRQ_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Deep-Sleep control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_deepslcntl_reg](index.html) module"] +pub struct BLE_DEEPSLCNTL_REG_SPEC; +impl crate::RegisterSpec for BLE_DEEPSLCNTL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_deepslcntl_reg::R](R) reader structure"] +impl crate::Readable for BLE_DEEPSLCNTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_deepslcntl_reg::W](W) writer structure"] +impl crate::Writable for BLE_DEEPSLCNTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DEEPSLCNTL_REG to value 0"] +impl crate::Resettable for BLE_DEEPSLCNTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_deepslstat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_deepslstat_reg.rs new file mode 100644 index 0000000..78b8267 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_deepslstat_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `BLE_DEEPSLSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DEEPSLSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DEEPSLDUR` reader - Actual duration of the last deep sleep phase measured in low_power_clk clock cycle. DEEPSLDUR is set to zero at the beginning of the deep sleep phase, and is incremented at each low_power_clk clock cycle until the end of the deep sleep phase."] +pub struct DEEPSLDUR_R(crate::FieldReader); +impl DEEPSLDUR_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + DEEPSLDUR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEEPSLDUR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:31 - Actual duration of the last deep sleep phase measured in low_power_clk clock cycle. DEEPSLDUR is set to zero at the beginning of the deep sleep phase, and is incremented at each low_power_clk clock cycle until the end of the deep sleep phase."] + #[inline(always)] + pub fn deepsldur(&self) -> DEEPSLDUR_R { + DEEPSLDUR_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Duration of the last deep sleep phase register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_deepslstat_reg](index.html) module"] +pub struct BLE_DEEPSLSTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_DEEPSLSTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_deepslstat_reg::R](R) reader structure"] +impl crate::Readable for BLE_DEEPSLSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_deepslstat_reg::W](W) writer structure"] +impl crate::Writable for BLE_DEEPSLSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DEEPSLSTAT_REG to value 0"] +impl crate::Resettable for BLE_DEEPSLSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_deepslwkup_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_deepslwkup_reg.rs new file mode 100644 index 0000000..1698c84 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_deepslwkup_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_DEEPSLWKUP_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DEEPSLWKUP_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DEEPSLTIME` reader - Determines the time in low_power_clk clock cycles to spend in Deep Sleep Mode before waking-up the device. This ensures a maximum of 37 hours and 16mn sleep mode capabilities at 32kHz. This ensures a maximum of 36 hours and 16mn sleep mode capabilities at 32.768kHz"] +pub struct DEEPSLTIME_R(crate::FieldReader); +impl DEEPSLTIME_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + DEEPSLTIME_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEEPSLTIME_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEEPSLTIME` writer - Determines the time in low_power_clk clock cycles to spend in Deep Sleep Mode before waking-up the device. This ensures a maximum of 37 hours and 16mn sleep mode capabilities at 32kHz. This ensures a maximum of 36 hours and 16mn sleep mode capabilities at 32.768kHz"] +pub struct DEEPSLTIME_W<'a> { + w: &'a mut W, +} +impl<'a> DEEPSLTIME_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - Determines the time in low_power_clk clock cycles to spend in Deep Sleep Mode before waking-up the device. This ensures a maximum of 37 hours and 16mn sleep mode capabilities at 32kHz. This ensures a maximum of 36 hours and 16mn sleep mode capabilities at 32.768kHz"] + #[inline(always)] + pub fn deepsltime(&self) -> DEEPSLTIME_R { + DEEPSLTIME_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - Determines the time in low_power_clk clock cycles to spend in Deep Sleep Mode before waking-up the device. This ensures a maximum of 37 hours and 16mn sleep mode capabilities at 32kHz. This ensures a maximum of 36 hours and 16mn sleep mode capabilities at 32.768kHz"] + #[inline(always)] + pub fn deepsltime(&mut self) -> DEEPSLTIME_W { + DEEPSLTIME_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Time (measured in Low Power clock cycles) in Deep Sleep Mode before waking-up the device\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_deepslwkup_reg](index.html) module"] +pub struct BLE_DEEPSLWKUP_REG_SPEC; +impl crate::RegisterSpec for BLE_DEEPSLWKUP_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_deepslwkup_reg::R](R) reader structure"] +impl crate::Readable for BLE_DEEPSLWKUP_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_deepslwkup_reg::W](W) writer structure"] +impl crate::Writable for BLE_DEEPSLWKUP_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DEEPSLWKUP_REG to value 0"] +impl crate::Resettable for BLE_DEEPSLWKUP_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl2_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl2_reg.rs new file mode 100644 index 0000000..e9c1542 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl2_reg.rs @@ -0,0 +1,402 @@ +#[doc = "Register `BLE_DIAGCNTL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DIAGCNTL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DIAG7_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG7_EN_R(crate::FieldReader); +impl DIAG7_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG7_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG7_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG7_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG7_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG7_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `DIAG7` reader - Only relevant when DIAG7_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG7."] +pub struct DIAG7_R(crate::FieldReader); +impl DIAG7_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG7_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG7_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG7` writer - Only relevant when DIAG7_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG7."] +pub struct DIAG7_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG7_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 24)) | ((value as u32 & 0x3f) << 24); + self.w + } +} +#[doc = "Field `DIAG6_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG6_EN_R(crate::FieldReader); +impl DIAG6_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG6_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG6_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG6_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG6_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG6_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 23)) | ((value as u32 & 1) << 23); + self.w + } +} +#[doc = "Field `DIAG6` reader - Only relevant when DIAG6_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG6."] +pub struct DIAG6_R(crate::FieldReader); +impl DIAG6_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG6_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG6_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG6` writer - Only relevant when DIAG6_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG6."] +pub struct DIAG6_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG6_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 16)) | ((value as u32 & 0x3f) << 16); + self.w + } +} +#[doc = "Field `DIAG5_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG5_EN_R(crate::FieldReader); +impl DIAG5_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG5_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG5_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG5_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG5_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG5_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `DIAG5` reader - Only relevant when DIAG5_EN= 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG5."] +pub struct DIAG5_R(crate::FieldReader); +impl DIAG5_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG5_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG5_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG5` writer - Only relevant when DIAG5_EN= 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG5."] +pub struct DIAG5_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG5_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 8)) | ((value as u32 & 0x3f) << 8); + self.w + } +} +#[doc = "Field `DIAG4_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG4_EN_R(crate::FieldReader); +impl DIAG4_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG4_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG4_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG4_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG4_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG4_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `DIAG4` reader - Only relevant when DIAG4_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG4."] +pub struct DIAG4_R(crate::FieldReader); +impl DIAG4_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG4` writer - Only relevant when DIAG4_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG4."] +pub struct DIAG4_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG4_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u32 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bit 31 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag7_en(&self) -> DIAG7_EN_R { + DIAG7_EN_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bits 24:29 - Only relevant when DIAG7_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG7."] + #[inline(always)] + pub fn diag7(&self) -> DIAG7_R { + DIAG7_R::new(((self.bits >> 24) & 0x3f) as u8) + } + #[doc = "Bit 23 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag6_en(&self) -> DIAG6_EN_R { + DIAG6_EN_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bits 16:21 - Only relevant when DIAG6_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG6."] + #[inline(always)] + pub fn diag6(&self) -> DIAG6_R { + DIAG6_R::new(((self.bits >> 16) & 0x3f) as u8) + } + #[doc = "Bit 15 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag5_en(&self) -> DIAG5_EN_R { + DIAG5_EN_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bits 8:13 - Only relevant when DIAG5_EN= 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG5."] + #[inline(always)] + pub fn diag5(&self) -> DIAG5_R { + DIAG5_R::new(((self.bits >> 8) & 0x3f) as u8) + } + #[doc = "Bit 7 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag4_en(&self) -> DIAG4_EN_R { + DIAG4_EN_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 0:5 - Only relevant when DIAG4_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG4."] + #[inline(always)] + pub fn diag4(&self) -> DIAG4_R { + DIAG4_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bit 31 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag7_en(&mut self) -> DIAG7_EN_W { + DIAG7_EN_W { w: self } + } + #[doc = "Bits 24:29 - Only relevant when DIAG7_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG7."] + #[inline(always)] + pub fn diag7(&mut self) -> DIAG7_W { + DIAG7_W { w: self } + } + #[doc = "Bit 23 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag6_en(&mut self) -> DIAG6_EN_W { + DIAG6_EN_W { w: self } + } + #[doc = "Bits 16:21 - Only relevant when DIAG6_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG6."] + #[inline(always)] + pub fn diag6(&mut self) -> DIAG6_W { + DIAG6_W { w: self } + } + #[doc = "Bit 15 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag5_en(&mut self) -> DIAG5_EN_W { + DIAG5_EN_W { w: self } + } + #[doc = "Bits 8:13 - Only relevant when DIAG5_EN= 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG5."] + #[inline(always)] + pub fn diag5(&mut self) -> DIAG5_W { + DIAG5_W { w: self } + } + #[doc = "Bit 7 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag4_en(&mut self) -> DIAG4_EN_W { + DIAG4_EN_W { w: self } + } + #[doc = "Bits 0:5 - Only relevant when DIAG4_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG4."] + #[inline(always)] + pub fn diag4(&mut self) -> DIAG4_W { + DIAG4_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Debug use only\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_diagcntl2_reg](index.html) module"] +pub struct BLE_DIAGCNTL2_REG_SPEC; +impl crate::RegisterSpec for BLE_DIAGCNTL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_diagcntl2_reg::R](R) reader structure"] +impl crate::Readable for BLE_DIAGCNTL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_diagcntl2_reg::W](W) writer structure"] +impl crate::Writable for BLE_DIAGCNTL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DIAGCNTL2_REG to value 0"] +impl crate::Resettable for BLE_DIAGCNTL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl3_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl3_reg.rs new file mode 100644 index 0000000..9fa25bd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl3_reg.rs @@ -0,0 +1,738 @@ +#[doc = "Register `BLE_DIAGCNTL3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DIAGCNTL3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DIAG7_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG7_INV_R(crate::FieldReader); +impl DIAG7_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG7_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG7_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG7_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG7_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG7_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `DIAG7_BIT` reader - Selects which bit from the DIAG7 word will be forwarded to bit 7 of the BLE DIagnostic Port."] +pub struct DIAG7_BIT_R(crate::FieldReader); +impl DIAG7_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG7_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG7_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG7_BIT` writer - Selects which bit from the DIAG7 word will be forwarded to bit 7 of the BLE DIagnostic Port."] +pub struct DIAG7_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG7_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 28)) | ((value as u32 & 7) << 28); + self.w + } +} +#[doc = "Field `DIAG6_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG6_INV_R(crate::FieldReader); +impl DIAG6_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG6_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG6_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG6_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG6_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG6_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 27)) | ((value as u32 & 1) << 27); + self.w + } +} +#[doc = "Field `DIAG6_BIT` reader - Selects which bit from the DIAG6 word will be forwarded to bit 6 of the BLE DIagnostic Port."] +pub struct DIAG6_BIT_R(crate::FieldReader); +impl DIAG6_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG6_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG6_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG6_BIT` writer - Selects which bit from the DIAG6 word will be forwarded to bit 6 of the BLE DIagnostic Port."] +pub struct DIAG6_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG6_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 24)) | ((value as u32 & 7) << 24); + self.w + } +} +#[doc = "Field `DIAG5_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG5_INV_R(crate::FieldReader); +impl DIAG5_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG5_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG5_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG5_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG5_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG5_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 23)) | ((value as u32 & 1) << 23); + self.w + } +} +#[doc = "Field `DIAG5_BIT` reader - Selects which bit from the DIAG5 word will be forwarded to bit 5 of the BLE DIagnostic Port."] +pub struct DIAG5_BIT_R(crate::FieldReader); +impl DIAG5_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG5_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG5_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG5_BIT` writer - Selects which bit from the DIAG5 word will be forwarded to bit 5 of the BLE DIagnostic Port."] +pub struct DIAG5_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG5_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 20)) | ((value as u32 & 7) << 20); + self.w + } +} +#[doc = "Field `DIAG4_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG4_INV_R(crate::FieldReader); +impl DIAG4_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG4_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG4_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG4_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG4_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG4_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `DIAG4_BIT` reader - Selects which bit from the DIAG4 word will be forwarded to bit 4 of the BLE DIagnostic Port."] +pub struct DIAG4_BIT_R(crate::FieldReader); +impl DIAG4_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG4_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG4_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG4_BIT` writer - Selects which bit from the DIAG4 word will be forwarded to bit 4 of the BLE DIagnostic Port."] +pub struct DIAG4_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG4_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 16)) | ((value as u32 & 7) << 16); + self.w + } +} +#[doc = "Field `DIAG3_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG3_INV_R(crate::FieldReader); +impl DIAG3_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG3_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG3_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG3_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG3_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG3_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `DIAG3_BIT` reader - Selects which bit from the DIAG3 word will be forwarded to bit 3 of the BLE DIagnostic Port."] +pub struct DIAG3_BIT_R(crate::FieldReader); +impl DIAG3_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG3_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG3_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG3_BIT` writer - Selects which bit from the DIAG3 word will be forwarded to bit 3 of the BLE DIagnostic Port."] +pub struct DIAG3_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG3_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 12)) | ((value as u32 & 7) << 12); + self.w + } +} +#[doc = "Field `DIAG2_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG2_INV_R(crate::FieldReader); +impl DIAG2_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG2_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG2_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG2_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG2_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG2_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u32 & 1) << 11); + self.w + } +} +#[doc = "Field `DIAG2_BIT` reader - Selects which bit from the DIAG2 word will be forwarded to bit 2 of the BLE DIagnostic Port."] +pub struct DIAG2_BIT_R(crate::FieldReader); +impl DIAG2_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG2_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG2_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG2_BIT` writer - Selects which bit from the DIAG2 word will be forwarded to bit 2 of the BLE DIagnostic Port."] +pub struct DIAG2_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG2_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 8)) | ((value as u32 & 7) << 8); + self.w + } +} +#[doc = "Field `DIAG1_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG1_INV_R(crate::FieldReader); +impl DIAG1_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG1_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG1_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG1_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG1_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG1_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `DIAG1_BIT` reader - Selects which bit from the DIAG1 word will be forwarded to bit 1 of the BLE DIagnostic Port."] +pub struct DIAG1_BIT_R(crate::FieldReader); +impl DIAG1_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG1_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG1_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG1_BIT` writer - Selects which bit from the DIAG1 word will be forwarded to bit 1 of the BLE DIagnostic Port."] +pub struct DIAG1_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG1_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u32 & 7) << 4); + self.w + } +} +#[doc = "Field `DIAG0_INV` reader - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG0_INV_R(crate::FieldReader); +impl DIAG0_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG0_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG0_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG0_INV` writer - If set, then the specific diagnostic bit will be inverted."] +pub struct DIAG0_INV_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG0_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `DIAG0_BIT` reader - Selects which bit from the DIAG0 word will be forwarded to bit 0 of the BLE DIagnostic Port."] +pub struct DIAG0_BIT_R(crate::FieldReader); +impl DIAG0_BIT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG0_BIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG0_BIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG0_BIT` writer - Selects which bit from the DIAG0 word will be forwarded to bit 0 of the BLE DIagnostic Port."] +pub struct DIAG0_BIT_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG0_BIT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bit 31 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag7_inv(&self) -> DIAG7_INV_R { + DIAG7_INV_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bits 28:30 - Selects which bit from the DIAG7 word will be forwarded to bit 7 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag7_bit(&self) -> DIAG7_BIT_R { + DIAG7_BIT_R::new(((self.bits >> 28) & 7) as u8) + } + #[doc = "Bit 27 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag6_inv(&self) -> DIAG6_INV_R { + DIAG6_INV_R::new(((self.bits >> 27) & 1) != 0) + } + #[doc = "Bits 24:26 - Selects which bit from the DIAG6 word will be forwarded to bit 6 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag6_bit(&self) -> DIAG6_BIT_R { + DIAG6_BIT_R::new(((self.bits >> 24) & 7) as u8) + } + #[doc = "Bit 23 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag5_inv(&self) -> DIAG5_INV_R { + DIAG5_INV_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bits 20:22 - Selects which bit from the DIAG5 word will be forwarded to bit 5 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag5_bit(&self) -> DIAG5_BIT_R { + DIAG5_BIT_R::new(((self.bits >> 20) & 7) as u8) + } + #[doc = "Bit 19 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag4_inv(&self) -> DIAG4_INV_R { + DIAG4_INV_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 16:18 - Selects which bit from the DIAG4 word will be forwarded to bit 4 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag4_bit(&self) -> DIAG4_BIT_R { + DIAG4_BIT_R::new(((self.bits >> 16) & 7) as u8) + } + #[doc = "Bit 15 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag3_inv(&self) -> DIAG3_INV_R { + DIAG3_INV_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bits 12:14 - Selects which bit from the DIAG3 word will be forwarded to bit 3 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag3_bit(&self) -> DIAG3_BIT_R { + DIAG3_BIT_R::new(((self.bits >> 12) & 7) as u8) + } + #[doc = "Bit 11 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag2_inv(&self) -> DIAG2_INV_R { + DIAG2_INV_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bits 8:10 - Selects which bit from the DIAG2 word will be forwarded to bit 2 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag2_bit(&self) -> DIAG2_BIT_R { + DIAG2_BIT_R::new(((self.bits >> 8) & 7) as u8) + } + #[doc = "Bit 7 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag1_inv(&self) -> DIAG1_INV_R { + DIAG1_INV_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 4:6 - Selects which bit from the DIAG1 word will be forwarded to bit 1 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag1_bit(&self) -> DIAG1_BIT_R { + DIAG1_BIT_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bit 3 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag0_inv(&self) -> DIAG0_INV_R { + DIAG0_INV_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bits 0:2 - Selects which bit from the DIAG0 word will be forwarded to bit 0 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag0_bit(&self) -> DIAG0_BIT_R { + DIAG0_BIT_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bit 31 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag7_inv(&mut self) -> DIAG7_INV_W { + DIAG7_INV_W { w: self } + } + #[doc = "Bits 28:30 - Selects which bit from the DIAG7 word will be forwarded to bit 7 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag7_bit(&mut self) -> DIAG7_BIT_W { + DIAG7_BIT_W { w: self } + } + #[doc = "Bit 27 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag6_inv(&mut self) -> DIAG6_INV_W { + DIAG6_INV_W { w: self } + } + #[doc = "Bits 24:26 - Selects which bit from the DIAG6 word will be forwarded to bit 6 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag6_bit(&mut self) -> DIAG6_BIT_W { + DIAG6_BIT_W { w: self } + } + #[doc = "Bit 23 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag5_inv(&mut self) -> DIAG5_INV_W { + DIAG5_INV_W { w: self } + } + #[doc = "Bits 20:22 - Selects which bit from the DIAG5 word will be forwarded to bit 5 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag5_bit(&mut self) -> DIAG5_BIT_W { + DIAG5_BIT_W { w: self } + } + #[doc = "Bit 19 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag4_inv(&mut self) -> DIAG4_INV_W { + DIAG4_INV_W { w: self } + } + #[doc = "Bits 16:18 - Selects which bit from the DIAG4 word will be forwarded to bit 4 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag4_bit(&mut self) -> DIAG4_BIT_W { + DIAG4_BIT_W { w: self } + } + #[doc = "Bit 15 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag3_inv(&mut self) -> DIAG3_INV_W { + DIAG3_INV_W { w: self } + } + #[doc = "Bits 12:14 - Selects which bit from the DIAG3 word will be forwarded to bit 3 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag3_bit(&mut self) -> DIAG3_BIT_W { + DIAG3_BIT_W { w: self } + } + #[doc = "Bit 11 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag2_inv(&mut self) -> DIAG2_INV_W { + DIAG2_INV_W { w: self } + } + #[doc = "Bits 8:10 - Selects which bit from the DIAG2 word will be forwarded to bit 2 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag2_bit(&mut self) -> DIAG2_BIT_W { + DIAG2_BIT_W { w: self } + } + #[doc = "Bit 7 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag1_inv(&mut self) -> DIAG1_INV_W { + DIAG1_INV_W { w: self } + } + #[doc = "Bits 4:6 - Selects which bit from the DIAG1 word will be forwarded to bit 1 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag1_bit(&mut self) -> DIAG1_BIT_W { + DIAG1_BIT_W { w: self } + } + #[doc = "Bit 3 - If set, then the specific diagnostic bit will be inverted."] + #[inline(always)] + pub fn diag0_inv(&mut self) -> DIAG0_INV_W { + DIAG0_INV_W { w: self } + } + #[doc = "Bits 0:2 - Selects which bit from the DIAG0 word will be forwarded to bit 0 of the BLE DIagnostic Port."] + #[inline(always)] + pub fn diag0_bit(&mut self) -> DIAG0_BIT_W { + DIAG0_BIT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Debug use only\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_diagcntl3_reg](index.html) module"] +pub struct BLE_DIAGCNTL3_REG_SPEC; +impl crate::RegisterSpec for BLE_DIAGCNTL3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_diagcntl3_reg::R](R) reader structure"] +impl crate::Readable for BLE_DIAGCNTL3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_diagcntl3_reg::W](W) writer structure"] +impl crate::Writable for BLE_DIAGCNTL3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DIAGCNTL3_REG to value 0"] +impl crate::Resettable for BLE_DIAGCNTL3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl_reg.rs new file mode 100644 index 0000000..8b28690 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_diagcntl_reg.rs @@ -0,0 +1,402 @@ +#[doc = "Register `BLE_DIAGCNTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DIAGCNTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DIAG3_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG3_EN_R(crate::FieldReader); +impl DIAG3_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG3_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG3_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG3_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG3_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG3_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `DIAG3` reader - Only relevant when DIAG3_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG3."] +pub struct DIAG3_R(crate::FieldReader); +impl DIAG3_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG3` writer - Only relevant when DIAG3_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG3."] +pub struct DIAG3_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG3_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 24)) | ((value as u32 & 0x3f) << 24); + self.w + } +} +#[doc = "Field `DIAG2_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG2_EN_R(crate::FieldReader); +impl DIAG2_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG2_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG2_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG2_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG2_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG2_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 23)) | ((value as u32 & 1) << 23); + self.w + } +} +#[doc = "Field `DIAG2` reader - Only relevant when DIAG2_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG2."] +pub struct DIAG2_R(crate::FieldReader); +impl DIAG2_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG2` writer - Only relevant when DIAG2_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG2."] +pub struct DIAG2_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG2_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 16)) | ((value as u32 & 0x3f) << 16); + self.w + } +} +#[doc = "Field `DIAG1_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG1_EN_R(crate::FieldReader); +impl DIAG1_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG1_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG1_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG1_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG1_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG1_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `DIAG1` reader - Only relevant when DIAG1_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG1."] +pub struct DIAG1_R(crate::FieldReader); +impl DIAG1_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG1` writer - Only relevant when DIAG1_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG1."] +pub struct DIAG1_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG1_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 8)) | ((value as u32 & 0x3f) << 8); + self.w + } +} +#[doc = "Field `DIAG0_EN` reader - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG0_EN_R(crate::FieldReader); +impl DIAG0_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG0_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG0_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG0_EN` writer - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] +pub struct DIAG0_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG0_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `DIAG0` reader - Only relevant when DIAG0_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG0."] +pub struct DIAG0_R(crate::FieldReader); +impl DIAG0_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG0` writer - Only relevant when DIAG0_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG0."] +pub struct DIAG0_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG0_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u32 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bit 31 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag3_en(&self) -> DIAG3_EN_R { + DIAG3_EN_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bits 24:29 - Only relevant when DIAG3_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG3."] + #[inline(always)] + pub fn diag3(&self) -> DIAG3_R { + DIAG3_R::new(((self.bits >> 24) & 0x3f) as u8) + } + #[doc = "Bit 23 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag2_en(&self) -> DIAG2_EN_R { + DIAG2_EN_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bits 16:21 - Only relevant when DIAG2_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG2."] + #[inline(always)] + pub fn diag2(&self) -> DIAG2_R { + DIAG2_R::new(((self.bits >> 16) & 0x3f) as u8) + } + #[doc = "Bit 15 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag1_en(&self) -> DIAG1_EN_R { + DIAG1_EN_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bits 8:13 - Only relevant when DIAG1_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG1."] + #[inline(always)] + pub fn diag1(&self) -> DIAG1_R { + DIAG1_R::new(((self.bits >> 8) & 0x3f) as u8) + } + #[doc = "Bit 7 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag0_en(&self) -> DIAG0_EN_R { + DIAG0_EN_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 0:5 - Only relevant when DIAG0_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG0."] + #[inline(always)] + pub fn diag0(&self) -> DIAG0_R { + DIAG0_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bit 31 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag3_en(&mut self) -> DIAG3_EN_W { + DIAG3_EN_W { w: self } + } + #[doc = "Bits 24:29 - Only relevant when DIAG3_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG3."] + #[inline(always)] + pub fn diag3(&mut self) -> DIAG3_W { + DIAG3_W { w: self } + } + #[doc = "Bit 23 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag2_en(&mut self) -> DIAG2_EN_W { + DIAG2_EN_W { w: self } + } + #[doc = "Bits 16:21 - Only relevant when DIAG2_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG2."] + #[inline(always)] + pub fn diag2(&mut self) -> DIAG2_W { + DIAG2_W { w: self } + } + #[doc = "Bit 15 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag1_en(&mut self) -> DIAG1_EN_W { + DIAG1_EN_W { w: self } + } + #[doc = "Bits 8:13 - Only relevant when DIAG1_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG1."] + #[inline(always)] + pub fn diag1(&mut self) -> DIAG1_W { + DIAG1_W { w: self } + } + #[doc = "Bit 7 - 0: Disable diagnostic port 0 output. All outputs are set to 0x0. 1: Enable diagnostic port 0 output."] + #[inline(always)] + pub fn diag0_en(&mut self) -> DIAG0_EN_W { + DIAG0_EN_W { w: self } + } + #[doc = "Bits 0:5 - Only relevant when DIAG0_EN = 1. Selection of the outputs that must be driven to the diagnostic port BLE_DIAG0."] + #[inline(always)] + pub fn diag0(&mut self) -> DIAG0_W { + DIAG0_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Diagnostics Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_diagcntl_reg](index.html) module"] +pub struct BLE_DIAGCNTL_REG_SPEC; +impl crate::RegisterSpec for BLE_DIAGCNTL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_diagcntl_reg::R](R) reader structure"] +impl crate::Readable for BLE_DIAGCNTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_diagcntl_reg::W](W) writer structure"] +impl crate::Writable for BLE_DIAGCNTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DIAGCNTL_REG to value 0"] +impl crate::Resettable for BLE_DIAGCNTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_diagstat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_diagstat_reg.rs new file mode 100644 index 0000000..c3ccbaa --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_diagstat_reg.rs @@ -0,0 +1,154 @@ +#[doc = "Register `BLE_DIAGSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_DIAGSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DIAG3STAT` reader - Directly connected to ble_dbg3\\[7:0\\] +output. Debug use only."] +pub struct DIAG3STAT_R(crate::FieldReader); +impl DIAG3STAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG3STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG3STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG2STAT` reader - Directly connected to ble_dbg2\\[7:0\\] +output. Debug use only."] +pub struct DIAG2STAT_R(crate::FieldReader); +impl DIAG2STAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG2STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG2STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG1STAT` reader - Directly connected to ble_dbg1\\[7:0\\] +output. Debug use only."] +pub struct DIAG1STAT_R(crate::FieldReader); +impl DIAG1STAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG1STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG1STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG0STAT` reader - Directly connected to ble_dbg0\\[7:0\\] +output. Debug use only."] +pub struct DIAG0STAT_R(crate::FieldReader); +impl DIAG0STAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG0STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG0STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 24:31 - Directly connected to ble_dbg3\\[7:0\\] +output. Debug use only."] + #[inline(always)] + pub fn diag3stat(&self) -> DIAG3STAT_R { + DIAG3STAT_R::new(((self.bits >> 24) & 0xff) as u8) + } + #[doc = "Bits 16:23 - Directly connected to ble_dbg2\\[7:0\\] +output. Debug use only."] + #[inline(always)] + pub fn diag2stat(&self) -> DIAG2STAT_R { + DIAG2STAT_R::new(((self.bits >> 16) & 0xff) as u8) + } + #[doc = "Bits 8:15 - Directly connected to ble_dbg1\\[7:0\\] +output. Debug use only."] + #[inline(always)] + pub fn diag1stat(&self) -> DIAG1STAT_R { + DIAG1STAT_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7 - Directly connected to ble_dbg0\\[7:0\\] +output. Debug use only."] + #[inline(always)] + pub fn diag0stat(&self) -> DIAG0STAT_R { + DIAG0STAT_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Debug use only\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_diagstat_reg](index.html) module"] +pub struct BLE_DIAGSTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_DIAGSTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_diagstat_reg::R](R) reader structure"] +impl crate::Readable for BLE_DIAGSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_diagstat_reg::W](W) writer structure"] +impl crate::Writable for BLE_DIAGSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_DIAGSTAT_REG to value 0"] +impl crate::Resettable for BLE_DIAGSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_em_base_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_em_base_reg.rs new file mode 100644 index 0000000..e5a3f87 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_em_base_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_EM_BASE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_EM_BASE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BLE_EM_BASE_16_10` reader - The physical address on the system memory map of the base of the Exchange Memory."] +pub struct BLE_EM_BASE_16_10_R(crate::FieldReader); +impl BLE_EM_BASE_16_10_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLE_EM_BASE_16_10_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_EM_BASE_16_10_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_EM_BASE_16_10` writer - The physical address on the system memory map of the base of the Exchange Memory."] +pub struct BLE_EM_BASE_16_10_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_EM_BASE_16_10_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 10)) | ((value as u32 & 0x7f) << 10); + self.w + } +} +impl R { + #[doc = "Bits 10:16 - The physical address on the system memory map of the base of the Exchange Memory."] + #[inline(always)] + pub fn ble_em_base_16_10(&self) -> BLE_EM_BASE_16_10_R { + BLE_EM_BASE_16_10_R::new(((self.bits >> 10) & 0x7f) as u8) + } +} +impl W { + #[doc = "Bits 10:16 - The physical address on the system memory map of the base of the Exchange Memory."] + #[inline(always)] + pub fn ble_em_base_16_10(&mut self) -> BLE_EM_BASE_16_10_W { + BLE_EM_BASE_16_10_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Exchange Memory Base Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_em_base_reg](index.html) module"] +pub struct BLE_EM_BASE_REG_SPEC; +impl crate::RegisterSpec for BLE_EM_BASE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_em_base_reg::R](R) reader structure"] +impl crate::Readable for BLE_EM_BASE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_em_base_reg::W](W) writer structure"] +impl crate::Writable for BLE_EM_BASE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_EM_BASE_REG to value 0"] +impl crate::Resettable for BLE_EM_BASE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_enbpreset_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_enbpreset_reg.rs new file mode 100644 index 0000000..a9ad64c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_enbpreset_reg.rs @@ -0,0 +1,201 @@ +#[doc = "Register `BLE_ENBPRESET_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_ENBPRESET_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TWEXT` reader - Minimum and recommended value is \"TWIRQ_RESET + 1\". In the case of wake-up due to an external wake-up request, TWEXT specifies the time delay in low power oscillator cycles to deassert BLE_WAKEUP_LP_IRQ. Refer also to GP_CONTROL_REG\\[BLE_WAKEUP_REQ\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] +pub struct TWEXT_R(crate::FieldReader); +impl TWEXT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TWEXT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TWEXT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TWEXT` writer - Minimum and recommended value is \"TWIRQ_RESET + 1\". In the case of wake-up due to an external wake-up request, TWEXT specifies the time delay in low power oscillator cycles to deassert BLE_WAKEUP_LP_IRQ. Refer also to GP_CONTROL_REG\\[BLE_WAKEUP_REQ\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] +pub struct TWEXT_W<'a> { + w: &'a mut W, +} +impl<'a> TWEXT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x07ff << 21)) | ((value as u32 & 0x07ff) << 21); + self.w + } +} +#[doc = "Field `TWIRQ_SET` reader - Minimum value is \"TWIRQ_RESET + 1\". Time in low power oscillator cycles to set BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] +pub struct TWIRQ_SET_R(crate::FieldReader); +impl TWIRQ_SET_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TWIRQ_SET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TWIRQ_SET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TWIRQ_SET` writer - Minimum value is \"TWIRQ_RESET + 1\". Time in low power oscillator cycles to set BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] +pub struct TWIRQ_SET_W<'a> { + w: &'a mut W, +} +impl<'a> TWIRQ_SET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x07ff << 10)) | ((value as u32 & 0x07ff) << 10); + self.w + } +} +#[doc = "Field `TWIRQ_RESET` reader - Recommended value is 1. Time in low power oscillator cycles to reset BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...32 ms\\] +for 32kHz; \\[0...31.25 ms\\] +for 32.768kHz."] +pub struct TWIRQ_RESET_R(crate::FieldReader); +impl TWIRQ_RESET_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TWIRQ_RESET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TWIRQ_RESET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TWIRQ_RESET` writer - Recommended value is 1. Time in low power oscillator cycles to reset BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...32 ms\\] +for 32kHz; \\[0...31.25 ms\\] +for 32.768kHz."] +pub struct TWIRQ_RESET_W<'a> { + w: &'a mut W, +} +impl<'a> TWIRQ_RESET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 21:31 - Minimum and recommended value is \"TWIRQ_RESET + 1\". In the case of wake-up due to an external wake-up request, TWEXT specifies the time delay in low power oscillator cycles to deassert BLE_WAKEUP_LP_IRQ. Refer also to GP_CONTROL_REG\\[BLE_WAKEUP_REQ\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] + #[inline(always)] + pub fn twext(&self) -> TWEXT_R { + TWEXT_R::new(((self.bits >> 21) & 0x07ff) as u16) + } + #[doc = "Bits 10:20 - Minimum value is \"TWIRQ_RESET + 1\". Time in low power oscillator cycles to set BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] + #[inline(always)] + pub fn twirq_set(&self) -> TWIRQ_SET_R { + TWIRQ_SET_R::new(((self.bits >> 10) & 0x07ff) as u16) + } + #[doc = "Bits 0:9 - Recommended value is 1. Time in low power oscillator cycles to reset BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...32 ms\\] +for 32kHz; \\[0...31.25 ms\\] +for 32.768kHz."] + #[inline(always)] + pub fn twirq_reset(&self) -> TWIRQ_RESET_R { + TWIRQ_RESET_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 21:31 - Minimum and recommended value is \"TWIRQ_RESET + 1\". In the case of wake-up due to an external wake-up request, TWEXT specifies the time delay in low power oscillator cycles to deassert BLE_WAKEUP_LP_IRQ. Refer also to GP_CONTROL_REG\\[BLE_WAKEUP_REQ\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] + #[inline(always)] + pub fn twext(&mut self) -> TWEXT_W { + TWEXT_W { w: self } + } + #[doc = "Bits 10:20 - Minimum value is \"TWIRQ_RESET + 1\". Time in low power oscillator cycles to set BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...64 ms\\] +for 32kHz; \\[0...62.5 ms\\] +for 32.768kHz"] + #[inline(always)] + pub fn twirq_set(&mut self) -> TWIRQ_SET_W { + TWIRQ_SET_W { w: self } + } + #[doc = "Bits 0:9 - Recommended value is 1. Time in low power oscillator cycles to reset BLE_WAKEUP_LP_IRQ before the BLE sleep timer expiration. Refer also to BLE_DEEPSLWKUP_REG\\[DEEPSLTIME\\]. Range is \\[0...32 ms\\] +for 32kHz; \\[0...31.25 ms\\] +for 32.768kHz."] + #[inline(always)] + pub fn twirq_reset(&mut self) -> TWIRQ_RESET_W { + TWIRQ_RESET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Time in low power oscillator cycles register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_enbpreset_reg](index.html) module"] +pub struct BLE_ENBPRESET_REG_SPEC; +impl crate::RegisterSpec for BLE_ENBPRESET_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_enbpreset_reg::R](R) reader structure"] +impl crate::Readable for BLE_ENBPRESET_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_enbpreset_reg::W](W) writer structure"] +impl crate::Writable for BLE_ENBPRESET_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_ENBPRESET_REG to value 0"] +impl crate::Resettable for BLE_ENBPRESET_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_errortypestat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_errortypestat_reg.rs new file mode 100644 index 0000000..9c54f40 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_errortypestat_reg.rs @@ -0,0 +1,426 @@ +#[doc = "Register `BLE_ERRORTYPESTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_ERRORTYPESTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CONCEVTIRQ_ERROR` reader - Indicates whether two consecutive and concurrent ble_event_irq have been generated, and not acknowledged in time by the BLE Software. 0: No error 1: Error occurred"] +pub struct CONCEVTIRQ_ERROR_R(crate::FieldReader); +impl CONCEVTIRQ_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CONCEVTIRQ_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CONCEVTIRQ_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXDATA_PTR_ERROR` reader - Indicates whether Rx data buffer pointer value programmed is null: this is a major programming failure. 0: No error 1: Error occurred"] +pub struct RXDATA_PTR_ERROR_R(crate::FieldReader); +impl RXDATA_PTR_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXDATA_PTR_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXDATA_PTR_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXDATA_PTR_ERROR` reader - Indicates whether Tx data buffer pointer value programmed is null during Advertising / Scanning / Initiating events, or during Master / Slave connections with non-null packet length: this is a major programming failure. 0: No error 1: Error occurred"] +pub struct TXDATA_PTR_ERROR_R(crate::FieldReader); +impl TXDATA_PTR_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TXDATA_PTR_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXDATA_PTR_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXDESC_EMPTY_ERROR` reader - Indicates whether Rx Descriptor pointer value programmed in register is null: this is a major programming failure. 0: No error 1: Error occurred"] +pub struct RXDESC_EMPTY_ERROR_R(crate::FieldReader); +impl RXDESC_EMPTY_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXDESC_EMPTY_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXDESC_EMPTY_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXDESC_EMPTY_ERROR` reader - Indicates whether Tx Descriptor pointer value programmed in Control Structure is null during Advertising / Scanning / Initiating events: this is a major programming failure. 0: No error 1: Error occurred"] +pub struct TXDESC_EMPTY_ERROR_R(crate::FieldReader); +impl TXDESC_EMPTY_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TXDESC_EMPTY_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXDESC_EMPTY_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CSFORMAT_ERROR` reader - Indicates whether CS-FORMAT has been programmed with an invalid value: this is a major software programming failure. 0: No error 1: Error occurred"] +pub struct CSFORMAT_ERROR_R(crate::FieldReader); +impl CSFORMAT_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CSFORMAT_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CSFORMAT_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LLCHMAP_ERROR` reader - Indicates Link Layer Channel Map error, happens when actual number of CS-LLCHMAP bit set to one is different from CS-NBCHGOOD at the beginning of Frequency Hopping process 0: No error 1: Error occurred"] +pub struct LLCHMAP_ERROR_R(crate::FieldReader); +impl LLCHMAP_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LLCHMAP_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LLCHMAP_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADV_UNDERRUN` reader - Indicates Advertising Interval Under run, occurs if time between two consecutive Advertising packet (in Advertising mode) is lower than the expected value. 0: No error 1: Error occurred"] +pub struct ADV_UNDERRUN_R(crate::FieldReader); +impl ADV_UNDERRUN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADV_UNDERRUN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADV_UNDERRUN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFS_UNDERRUN` reader - Indicates Inter Frame Space Under run, occurs if IFS time is not enough to update and read Control Structure/Descriptors, and/or White List parsing is not finished and/or Decryption time is too long to be finished on time 0: No error 1: Error occurred"] +pub struct IFS_UNDERRUN_R(crate::FieldReader); +impl IFS_UNDERRUN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + IFS_UNDERRUN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFS_UNDERRUN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WHITELIST_ERROR` reader - Indicates White List Timeout error, occurs if White List parsing is not finished on time 0: No error 1: Error occurred"] +pub struct WHITELIST_ERROR_R(crate::FieldReader); +impl WHITELIST_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WHITELIST_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WHITELIST_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVT_CNTL_APFM_ERROR` reader - Indicates Anticipated Pre-Fetch Mechanism error: happens when 2 consecutive events are programmed, and when the first event is not completely finished while second pre-fetch instant is reached. 0: No error 1: Error occured"] +pub struct EVT_CNTL_APFM_ERROR_R(crate::FieldReader); +impl EVT_CNTL_APFM_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVT_CNTL_APFM_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVT_CNTL_APFM_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVT_SCHDL_APFM_ERROR` reader - Indicates Anticipated Pre-Fetch Mechanism error: happens when 2 consecutive events are programmed, and when the first event is not completely finished while second pre-fetch instant is reached. 0: No error 1: Error occured"] +pub struct EVT_SCHDL_APFM_ERROR_R(crate::FieldReader); +impl EVT_SCHDL_APFM_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVT_SCHDL_APFM_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVT_SCHDL_APFM_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVT_SCHDL_ENTRY_ERROR` reader - Indicates Event Scheduler faced Invalid timing programing on two consecutive ET entries (e.g first one with 624s offset and second one with no offset) 0: No error 1: Error occurred"] +pub struct EVT_SCHDL_ENTRY_ERROR_R(crate::FieldReader); +impl EVT_SCHDL_ENTRY_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVT_SCHDL_ENTRY_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVT_SCHDL_ENTRY_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVT_SCHDL_EMACC_ERROR` reader - Indicates Event Scheduler Exchange Memory access error, happens when Exchange Memory accesses are not served in time, and blocks the Exchange Table entry read 0: No error 1: Error occurred"] +pub struct EVT_SCHDL_EMACC_ERROR_R(crate::FieldReader); +impl EVT_SCHDL_EMACC_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVT_SCHDL_EMACC_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVT_SCHDL_EMACC_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_EMACC_ERROR` reader - Indicates Radio Controller Exchange Memory access error, happens when Exchange Memory accesses are not served in time and data are corrupted. 0: No error 1: Error occurred"] +pub struct RADIO_EMACC_ERROR_R(crate::FieldReader); +impl RADIO_EMACC_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_EMACC_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_EMACC_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PKTCNTL_EMACC_ERROR` reader - Indicates Packet Controller Exchange Memory access error, happens when Exchange Memory accesses are not served in time and Tx/Rx data are corrupted 0: No error 1: Error occurred"] +pub struct PKTCNTL_EMACC_ERROR_R(crate::FieldReader); +impl PKTCNTL_EMACC_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PKTCNTL_EMACC_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PKTCNTL_EMACC_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXCRYPT_ERROR` reader - Indicates real time decryption error, happens when AES-CCM decryption is too slow compared to Packet Controller requests. A 16-bytes block has to be decrypted prior the next block is received by the Packet Controller 0: No error 1: Error occurred"] +pub struct RXCRYPT_ERROR_R(crate::FieldReader); +impl RXCRYPT_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXCRYPT_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXCRYPT_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXCRYPT_ERROR` reader - Indicates Real Time encryption error, happens when AES-CCM encryption is too slow compared to Packet Controller requests. A 16-bytes block has to be encrypted and prepared on Packet Controller request, and needs to be ready before the Packet Controller has to send ti 0: No error 1: Error occurred"] +pub struct TXCRYPT_ERROR_R(crate::FieldReader); +impl TXCRYPT_ERROR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TXCRYPT_ERROR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXCRYPT_ERROR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 17 - Indicates whether two consecutive and concurrent ble_event_irq have been generated, and not acknowledged in time by the BLE Software. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn concevtirq_error(&self) -> CONCEVTIRQ_ERROR_R { + CONCEVTIRQ_ERROR_R::new(((self.bits >> 17) & 1) != 0) + } + #[doc = "Bit 16 - Indicates whether Rx data buffer pointer value programmed is null: this is a major programming failure. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn rxdata_ptr_error(&self) -> RXDATA_PTR_ERROR_R { + RXDATA_PTR_ERROR_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bit 15 - Indicates whether Tx data buffer pointer value programmed is null during Advertising / Scanning / Initiating events, or during Master / Slave connections with non-null packet length: this is a major programming failure. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn txdata_ptr_error(&self) -> TXDATA_PTR_ERROR_R { + TXDATA_PTR_ERROR_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14 - Indicates whether Rx Descriptor pointer value programmed in register is null: this is a major programming failure. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn rxdesc_empty_error(&self) -> RXDESC_EMPTY_ERROR_R { + RXDESC_EMPTY_ERROR_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13 - Indicates whether Tx Descriptor pointer value programmed in Control Structure is null during Advertising / Scanning / Initiating events: this is a major programming failure. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn txdesc_empty_error(&self) -> TXDESC_EMPTY_ERROR_R { + TXDESC_EMPTY_ERROR_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12 - Indicates whether CS-FORMAT has been programmed with an invalid value: this is a major software programming failure. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn csformat_error(&self) -> CSFORMAT_ERROR_R { + CSFORMAT_ERROR_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11 - Indicates Link Layer Channel Map error, happens when actual number of CS-LLCHMAP bit set to one is different from CS-NBCHGOOD at the beginning of Frequency Hopping process 0: No error 1: Error occurred"] + #[inline(always)] + pub fn llchmap_error(&self) -> LLCHMAP_ERROR_R { + LLCHMAP_ERROR_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - Indicates Advertising Interval Under run, occurs if time between two consecutive Advertising packet (in Advertising mode) is lower than the expected value. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn adv_underrun(&self) -> ADV_UNDERRUN_R { + ADV_UNDERRUN_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - Indicates Inter Frame Space Under run, occurs if IFS time is not enough to update and read Control Structure/Descriptors, and/or White List parsing is not finished and/or Decryption time is too long to be finished on time 0: No error 1: Error occurred"] + #[inline(always)] + pub fn ifs_underrun(&self) -> IFS_UNDERRUN_R { + IFS_UNDERRUN_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - Indicates White List Timeout error, occurs if White List parsing is not finished on time 0: No error 1: Error occurred"] + #[inline(always)] + pub fn whitelist_error(&self) -> WHITELIST_ERROR_R { + WHITELIST_ERROR_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - Indicates Anticipated Pre-Fetch Mechanism error: happens when 2 consecutive events are programmed, and when the first event is not completely finished while second pre-fetch instant is reached. 0: No error 1: Error occured"] + #[inline(always)] + pub fn evt_cntl_apfm_error(&self) -> EVT_CNTL_APFM_ERROR_R { + EVT_CNTL_APFM_ERROR_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Indicates Anticipated Pre-Fetch Mechanism error: happens when 2 consecutive events are programmed, and when the first event is not completely finished while second pre-fetch instant is reached. 0: No error 1: Error occured"] + #[inline(always)] + pub fn evt_schdl_apfm_error(&self) -> EVT_SCHDL_APFM_ERROR_R { + EVT_SCHDL_APFM_ERROR_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Indicates Event Scheduler faced Invalid timing programing on two consecutive ET entries (e.g first one with 624s offset and second one with no offset) 0: No error 1: Error occurred"] + #[inline(always)] + pub fn evt_schdl_entry_error(&self) -> EVT_SCHDL_ENTRY_ERROR_R { + EVT_SCHDL_ENTRY_ERROR_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Indicates Event Scheduler Exchange Memory access error, happens when Exchange Memory accesses are not served in time, and blocks the Exchange Table entry read 0: No error 1: Error occurred"] + #[inline(always)] + pub fn evt_schdl_emacc_error(&self) -> EVT_SCHDL_EMACC_ERROR_R { + EVT_SCHDL_EMACC_ERROR_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Indicates Radio Controller Exchange Memory access error, happens when Exchange Memory accesses are not served in time and data are corrupted. 0: No error 1: Error occurred"] + #[inline(always)] + pub fn radio_emacc_error(&self) -> RADIO_EMACC_ERROR_R { + RADIO_EMACC_ERROR_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Indicates Packet Controller Exchange Memory access error, happens when Exchange Memory accesses are not served in time and Tx/Rx data are corrupted 0: No error 1: Error occurred"] + #[inline(always)] + pub fn pktcntl_emacc_error(&self) -> PKTCNTL_EMACC_ERROR_R { + PKTCNTL_EMACC_ERROR_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Indicates real time decryption error, happens when AES-CCM decryption is too slow compared to Packet Controller requests. A 16-bytes block has to be decrypted prior the next block is received by the Packet Controller 0: No error 1: Error occurred"] + #[inline(always)] + pub fn rxcrypt_error(&self) -> RXCRYPT_ERROR_R { + RXCRYPT_ERROR_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Indicates Real Time encryption error, happens when AES-CCM encryption is too slow compared to Packet Controller requests. A 16-bytes block has to be encrypted and prepared on Packet Controller request, and needs to be ready before the Packet Controller has to send ti 0: No error 1: Error occurred"] + #[inline(always)] + pub fn txcrypt_error(&self) -> TXCRYPT_ERROR_R { + TXCRYPT_ERROR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Error Type Status registers\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_errortypestat_reg](index.html) module"] +pub struct BLE_ERRORTYPESTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_ERRORTYPESTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_errortypestat_reg::R](R) reader structure"] +impl crate::Readable for BLE_ERRORTYPESTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_errortypestat_reg::W](W) writer structure"] +impl crate::Writable for BLE_ERRORTYPESTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_ERRORTYPESTAT_REG to value 0"] +impl crate::Resettable for BLE_ERRORTYPESTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_finecntcorr_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_finecntcorr_reg.rs new file mode 100644 index 0000000..8da5405 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_finecntcorr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_FINECNTCORR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_FINECNTCORR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FINECNTCORR` reader - Phase correction value for the 625us reference counter (i.e. Fine Counter) in us."] +pub struct FINECNTCORR_R(crate::FieldReader); +impl FINECNTCORR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + FINECNTCORR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINECNTCORR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINECNTCORR` writer - Phase correction value for the 625us reference counter (i.e. Fine Counter) in us."] +pub struct FINECNTCORR_W<'a> { + w: &'a mut W, +} +impl<'a> FINECNTCORR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 0:9 - Phase correction value for the 625us reference counter (i.e. Fine Counter) in us."] + #[inline(always)] + pub fn finecntcorr(&self) -> FINECNTCORR_R { + FINECNTCORR_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 0:9 - Phase correction value for the 625us reference counter (i.e. Fine Counter) in us."] + #[inline(always)] + pub fn finecntcorr(&mut self) -> FINECNTCORR_W { + FINECNTCORR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Phase correction value register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_finecntcorr_reg](index.html) module"] +pub struct BLE_FINECNTCORR_REG_SPEC; +impl crate::RegisterSpec for BLE_FINECNTCORR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_finecntcorr_reg::R](R) reader structure"] +impl crate::Readable for BLE_FINECNTCORR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_finecntcorr_reg::W](W) writer structure"] +impl crate::Writable for BLE_FINECNTCORR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_FINECNTCORR_REG to value 0"] +impl crate::Resettable for BLE_FINECNTCORR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_finetimecnt_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_finetimecnt_reg.rs new file mode 100644 index 0000000..3d20911 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_finetimecnt_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `BLE_FINETIMECNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_FINETIMECNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FINECNT` reader - Value of the current s fine time reference counter. Updated each time SAMPCLK is written. Used by the SW in order to synchronize with the HW, and obtain a more precise sleep duration"] +pub struct FINECNT_R(crate::FieldReader); +impl FINECNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + FINECNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINECNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:9 - Value of the current s fine time reference counter. Updated each time SAMPCLK is written. Used by the SW in order to synchronize with the HW, and obtain a more precise sleep duration"] + #[inline(always)] + pub fn finecnt(&self) -> FINECNT_R { + FINECNT_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Fine time reference counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_finetimecnt_reg](index.html) module"] +pub struct BLE_FINETIMECNT_REG_SPEC; +impl crate::RegisterSpec for BLE_FINETIMECNT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_finetimecnt_reg::R](R) reader structure"] +impl crate::Readable for BLE_FINETIMECNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_finetimecnt_reg::W](W) writer structure"] +impl crate::Writable for BLE_FINETIMECNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_FINETIMECNT_REG to value 0"] +impl crate::Resettable for BLE_FINETIMECNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_finetimtgt_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_finetimtgt_reg.rs new file mode 100644 index 0000000..117e7c2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_finetimtgt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_FINETIMTGT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_FINETIMTGT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FINETARGET` reader - Fine Timer Target value on which a ble_finetgtim_irq must be generated. This timer has a precision of 625 usec: interrupt is generated only when FINETARGET = BASETIMECNT"] +pub struct FINETARGET_R(crate::FieldReader); +impl FINETARGET_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + FINETARGET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINETARGET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINETARGET` writer - Fine Timer Target value on which a ble_finetgtim_irq must be generated. This timer has a precision of 625 usec: interrupt is generated only when FINETARGET = BASETIMECNT"] +pub struct FINETARGET_W<'a> { + w: &'a mut W, +} +impl<'a> FINETARGET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !0x07ff_ffff) | (value as u32 & 0x07ff_ffff); + self.w + } +} +impl R { + #[doc = "Bits 0:26 - Fine Timer Target value on which a ble_finetgtim_irq must be generated. This timer has a precision of 625 usec: interrupt is generated only when FINETARGET = BASETIMECNT"] + #[inline(always)] + pub fn finetarget(&self) -> FINETARGET_R { + FINETARGET_R::new((self.bits & 0x07ff_ffff) as u32) + } +} +impl W { + #[doc = "Bits 0:26 - Fine Timer Target value on which a ble_finetgtim_irq must be generated. This timer has a precision of 625 usec: interrupt is generated only when FINETARGET = BASETIMECNT"] + #[inline(always)] + pub fn finetarget(&mut self) -> FINETARGET_W { + FINETARGET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Fine Timer Target value\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_finetimtgt_reg](index.html) module"] +pub struct BLE_FINETIMTGT_REG_SPEC; +impl crate::RegisterSpec for BLE_FINETIMTGT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_finetimtgt_reg::R](R) reader structure"] +impl crate::Readable for BLE_FINETIMTGT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_finetimtgt_reg::W](W) writer structure"] +impl crate::Writable for BLE_FINETIMTGT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_FINETIMTGT_REG to value 0"] +impl crate::Resettable for BLE_FINETIMTGT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_grosstimtgt_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_grosstimtgt_reg.rs new file mode 100644 index 0000000..295bb62 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_grosstimtgt_reg.rs @@ -0,0 +1,115 @@ +#[doc = "Register `BLE_GROSSTIMTGT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_GROSSTIMTGT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GROSSTARGET` reader - Gross Timer Target value on which a ble_grosstgtim_irq must be generated. This timer has a precision of 10ms: interrupt is generated only when GROSSTARGET\\[22:0\\] += BASETIMECNT\\[26:4\\] +and BASETIMECNT\\[3:0\\] += 0."] +pub struct GROSSTARGET_R(crate::FieldReader); +impl GROSSTARGET_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + GROSSTARGET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GROSSTARGET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GROSSTARGET` writer - Gross Timer Target value on which a ble_grosstgtim_irq must be generated. This timer has a precision of 10ms: interrupt is generated only when GROSSTARGET\\[22:0\\] += BASETIMECNT\\[26:4\\] +and BASETIMECNT\\[3:0\\] += 0."] +pub struct GROSSTARGET_W<'a> { + w: &'a mut W, +} +impl<'a> GROSSTARGET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !0x007f_ffff) | (value as u32 & 0x007f_ffff); + self.w + } +} +impl R { + #[doc = "Bits 0:22 - Gross Timer Target value on which a ble_grosstgtim_irq must be generated. This timer has a precision of 10ms: interrupt is generated only when GROSSTARGET\\[22:0\\] += BASETIMECNT\\[26:4\\] +and BASETIMECNT\\[3:0\\] += 0."] + #[inline(always)] + pub fn grosstarget(&self) -> GROSSTARGET_R { + GROSSTARGET_R::new((self.bits & 0x007f_ffff) as u32) + } +} +impl W { + #[doc = "Bits 0:22 - Gross Timer Target value on which a ble_grosstgtim_irq must be generated. This timer has a precision of 10ms: interrupt is generated only when GROSSTARGET\\[22:0\\] += BASETIMECNT\\[26:4\\] +and BASETIMECNT\\[3:0\\] += 0."] + #[inline(always)] + pub fn grosstarget(&mut self) -> GROSSTARGET_W { + GROSSTARGET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Gross Timer Target value\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_grosstimtgt_reg](index.html) module"] +pub struct BLE_GROSSTIMTGT_REG_SPEC; +impl crate::RegisterSpec for BLE_GROSSTIMTGT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_grosstimtgt_reg::R](R) reader structure"] +impl crate::Readable for BLE_GROSSTIMTGT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_grosstimtgt_reg::W](W) writer structure"] +impl crate::Writable for BLE_GROSSTIMTGT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_GROSSTIMTGT_REG to value 0"] +impl crate::Resettable for BLE_GROSSTIMTGT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_intack_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_intack_reg.rs new file mode 100644 index 0000000..96fca9e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_intack_reg.rs @@ -0,0 +1,334 @@ +#[doc = "Register `BLE_INTACK_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_INTACK_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SWINTACK` writer - SW triggered interrupt acknowledgement bit Software writing 1 acknowledges the SW triggered interrupt. This bit resets SWINTSTAT and SWINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct SWINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> SWINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `EVENTAPFAINTACK` writer - End of event / Anticipated Pre-Fetch Abort interrupt acknowledgement bit Software writing 1 acknowledges the End of event / Anticipated Pre-Fetch Abort interrupt. This bit resets EVENTAPFAINTSTAT and EVENTAPFAINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct EVENTAPFAINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> EVENTAPFAINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `FINETGTIMINTACK` writer - Fine Target Timer interrupt acknowledgement bit Software writing 1 acknowledges the Fine Timer interrupt. This bit resets FINETGTIMINTSTAT and FINETGTIMINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct FINETGTIMINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> FINETGTIMINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `GROSSTGTIMINTACK` writer - Gross Target Timer interrupt acknowledgement bit Software writing 1 acknowledges the Gross Timer interrupt. This bit resets GROSSTGTIMINTSTAT and GROSSTGTIMINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct GROSSTGTIMINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> GROSSTGTIMINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `ERRORINTACK` writer - Error interrupt acknowledgement bit Software writing 1 acknowledges the Error interrupt. This bit resets ERRORINTSTAT and ERRORINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct ERRORINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> ERRORINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `CRYPTINTACK` writer - Encryption engine interrupt acknowledgement bit Software writing 1 acknowledges the Encryption engine interrupt. This bit resets CRYPTINTSTAT and CRYPTINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct CRYPTINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> CRYPTINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `EVENTINTACK` writer - End of Event interrupt acknowledgment bit Software writing 1 acknowledges the End of Advertising / Scanning / Connection interrupt. This bit resets SLPINTSTAT and SLPINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct EVENTINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> EVENTINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `SLPINTACK` writer - End of Deep Sleep interrupt acknowledgment bit Software writing 1 acknowledges the End of Sleep Mode interrupt. This bit resets SLPINTSTAT and SLPINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct SLPINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> SLPINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RXINTACK` writer - Packet Reception interrupt acknowledgment bit Software writing 1 acknowledges the Rx interrupt. This bit resets RXINTSTAT and RXINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct RXINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> RXINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `CSCNTINTACK` writer - 625us base time reference interrupt acknowledgment bit Software writing 1 acknowledges the CLKN interrupt. This bit resets CLKINTSTAT and CLKINTRAWSTAT flags. Resets at 0 when action is performed"] +pub struct CSCNTINTACK_W<'a> { + w: &'a mut W, +} +impl<'a> CSCNTINTACK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl W { + #[doc = "Bit 9 - SW triggered interrupt acknowledgement bit Software writing 1 acknowledges the SW triggered interrupt. This bit resets SWINTSTAT and SWINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn swintack(&mut self) -> SWINTACK_W { + SWINTACK_W { w: self } + } + #[doc = "Bit 8 - End of event / Anticipated Pre-Fetch Abort interrupt acknowledgement bit Software writing 1 acknowledges the End of event / Anticipated Pre-Fetch Abort interrupt. This bit resets EVENTAPFAINTSTAT and EVENTAPFAINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn eventapfaintack(&mut self) -> EVENTAPFAINTACK_W { + EVENTAPFAINTACK_W { w: self } + } + #[doc = "Bit 7 - Fine Target Timer interrupt acknowledgement bit Software writing 1 acknowledges the Fine Timer interrupt. This bit resets FINETGTIMINTSTAT and FINETGTIMINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn finetgtimintack(&mut self) -> FINETGTIMINTACK_W { + FINETGTIMINTACK_W { w: self } + } + #[doc = "Bit 6 - Gross Target Timer interrupt acknowledgement bit Software writing 1 acknowledges the Gross Timer interrupt. This bit resets GROSSTGTIMINTSTAT and GROSSTGTIMINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn grosstgtimintack(&mut self) -> GROSSTGTIMINTACK_W { + GROSSTGTIMINTACK_W { w: self } + } + #[doc = "Bit 5 - Error interrupt acknowledgement bit Software writing 1 acknowledges the Error interrupt. This bit resets ERRORINTSTAT and ERRORINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn errorintack(&mut self) -> ERRORINTACK_W { + ERRORINTACK_W { w: self } + } + #[doc = "Bit 4 - Encryption engine interrupt acknowledgement bit Software writing 1 acknowledges the Encryption engine interrupt. This bit resets CRYPTINTSTAT and CRYPTINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn cryptintack(&mut self) -> CRYPTINTACK_W { + CRYPTINTACK_W { w: self } + } + #[doc = "Bit 3 - End of Event interrupt acknowledgment bit Software writing 1 acknowledges the End of Advertising / Scanning / Connection interrupt. This bit resets SLPINTSTAT and SLPINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn eventintack(&mut self) -> EVENTINTACK_W { + EVENTINTACK_W { w: self } + } + #[doc = "Bit 2 - End of Deep Sleep interrupt acknowledgment bit Software writing 1 acknowledges the End of Sleep Mode interrupt. This bit resets SLPINTSTAT and SLPINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn slpintack(&mut self) -> SLPINTACK_W { + SLPINTACK_W { w: self } + } + #[doc = "Bit 1 - Packet Reception interrupt acknowledgment bit Software writing 1 acknowledges the Rx interrupt. This bit resets RXINTSTAT and RXINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn rxintack(&mut self) -> RXINTACK_W { + RXINTACK_W { w: self } + } + #[doc = "Bit 0 - 625us base time reference interrupt acknowledgment bit Software writing 1 acknowledges the CLKN interrupt. This bit resets CLKINTSTAT and CLKINTRAWSTAT flags. Resets at 0 when action is performed"] + #[inline(always)] + pub fn cscntintack(&mut self) -> CSCNTINTACK_W { + CSCNTINTACK_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt acknowledge register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_intack_reg](index.html) module"] +pub struct BLE_INTACK_REG_SPEC; +impl crate::RegisterSpec for BLE_INTACK_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_intack_reg::R](R) reader structure"] +impl crate::Readable for BLE_INTACK_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_intack_reg::W](W) writer structure"] +impl crate::Writable for BLE_INTACK_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_INTACK_REG to value 0"] +impl crate::Resettable for BLE_INTACK_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_intcntl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_intcntl_reg.rs new file mode 100644 index 0000000..94e2ae1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_intcntl_reg.rs @@ -0,0 +1,583 @@ +#[doc = "Register `BLE_INTCNTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_INTCNTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CSCNTDEVMSK` reader - CSCNT interrupt mask during event. This bit allows to enable CSCNT interrupt generation during events (i.e. advertising, scanning, initiating, and connection) 0: CSCNT Interrupt not generated during events. 1: CSCNT Interrupt generated during events."] +pub struct CSCNTDEVMSK_R(crate::FieldReader); +impl CSCNTDEVMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CSCNTDEVMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CSCNTDEVMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CSCNTDEVMSK` writer - CSCNT interrupt mask during event. This bit allows to enable CSCNT interrupt generation during events (i.e. advertising, scanning, initiating, and connection) 0: CSCNT Interrupt not generated during events. 1: CSCNT Interrupt generated during events."] +pub struct CSCNTDEVMSK_W<'a> { + w: &'a mut W, +} +impl<'a> CSCNTDEVMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `SWINTMSK` reader - SW triggered interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct SWINTMSK_R(crate::FieldReader); +impl SWINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SWINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SWINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SWINTMSK` writer - SW triggered interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct SWINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> SWINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `EVENTAPFAINTMSK` reader - End of event / anticipated pre-fetch abort interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct EVENTAPFAINTMSK_R(crate::FieldReader); +impl EVENTAPFAINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVENTAPFAINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENTAPFAINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVENTAPFAINTMSK` writer - End of event / anticipated pre-fetch abort interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct EVENTAPFAINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> EVENTAPFAINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `FINETGTIMINTMSK` reader - Fine Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct FINETGTIMINTMSK_R(crate::FieldReader); +impl FINETGTIMINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FINETGTIMINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINETGTIMINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINETGTIMINTMSK` writer - Fine Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct FINETGTIMINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> FINETGTIMINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `GROSSTGTIMINTMSK` reader - Gross Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct GROSSTGTIMINTMSK_R(crate::FieldReader); +impl GROSSTGTIMINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GROSSTGTIMINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GROSSTGTIMINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GROSSTGTIMINTMSK` writer - Gross Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct GROSSTGTIMINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> GROSSTGTIMINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `ERRORINTMSK` reader - Error Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct ERRORINTMSK_R(crate::FieldReader); +impl ERRORINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ERRORINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ERRORINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ERRORINTMSK` writer - Error Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct ERRORINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> ERRORINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `CRYPTINTMSK` reader - Encryption engine Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct CRYPTINTMSK_R(crate::FieldReader); +impl CRYPTINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CRYPTINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CRYPTINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CRYPTINTMSK` writer - Encryption engine Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct CRYPTINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> CRYPTINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `EVENTINTMSK` reader - End of event Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct EVENTINTMSK_R(crate::FieldReader); +impl EVENTINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVENTINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENTINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVENTINTMSK` writer - End of event Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct EVENTINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> EVENTINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `SLPINTMSK` reader - Sleep Mode Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct SLPINTMSK_R(crate::FieldReader); +impl SLPINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SLPINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SLPINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SLPINTMSK` writer - Sleep Mode Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct SLPINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> SLPINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RXINTMSK` reader - Rx Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct RXINTMSK_R(crate::FieldReader); +impl RXINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXINTMSK` writer - Rx Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct RXINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> RXINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `CSCNTINTMSK` reader - 625us Base Time Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct CSCNTINTMSK_R(crate::FieldReader); +impl CSCNTINTMSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CSCNTINTMSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CSCNTINTMSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CSCNTINTMSK` writer - 625us Base Time Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] +pub struct CSCNTINTMSK_W<'a> { + w: &'a mut W, +} +impl<'a> CSCNTINTMSK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 15 - CSCNT interrupt mask during event. This bit allows to enable CSCNT interrupt generation during events (i.e. advertising, scanning, initiating, and connection) 0: CSCNT Interrupt not generated during events. 1: CSCNT Interrupt generated during events."] + #[inline(always)] + pub fn cscntdevmsk(&self) -> CSCNTDEVMSK_R { + CSCNTDEVMSK_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 9 - SW triggered interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn swintmsk(&self) -> SWINTMSK_R { + SWINTMSK_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - End of event / anticipated pre-fetch abort interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn eventapfaintmsk(&self) -> EVENTAPFAINTMSK_R { + EVENTAPFAINTMSK_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - Fine Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn finetgtimintmsk(&self) -> FINETGTIMINTMSK_R { + FINETGTIMINTMSK_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Gross Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn grosstgtimintmsk(&self) -> GROSSTGTIMINTMSK_R { + GROSSTGTIMINTMSK_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Error Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn errorintmsk(&self) -> ERRORINTMSK_R { + ERRORINTMSK_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Encryption engine Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn cryptintmsk(&self) -> CRYPTINTMSK_R { + CRYPTINTMSK_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - End of event Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn eventintmsk(&self) -> EVENTINTMSK_R { + EVENTINTMSK_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Sleep Mode Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn slpintmsk(&self) -> SLPINTMSK_R { + SLPINTMSK_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Rx Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn rxintmsk(&self) -> RXINTMSK_R { + RXINTMSK_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 625us Base Time Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn cscntintmsk(&self) -> CSCNTINTMSK_R { + CSCNTINTMSK_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 15 - CSCNT interrupt mask during event. This bit allows to enable CSCNT interrupt generation during events (i.e. advertising, scanning, initiating, and connection) 0: CSCNT Interrupt not generated during events. 1: CSCNT Interrupt generated during events."] + #[inline(always)] + pub fn cscntdevmsk(&mut self) -> CSCNTDEVMSK_W { + CSCNTDEVMSK_W { w: self } + } + #[doc = "Bit 9 - SW triggered interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn swintmsk(&mut self) -> SWINTMSK_W { + SWINTMSK_W { w: self } + } + #[doc = "Bit 8 - End of event / anticipated pre-fetch abort interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn eventapfaintmsk(&mut self) -> EVENTAPFAINTMSK_W { + EVENTAPFAINTMSK_W { w: self } + } + #[doc = "Bit 7 - Fine Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn finetgtimintmsk(&mut self) -> FINETGTIMINTMSK_W { + FINETGTIMINTMSK_W { w: self } + } + #[doc = "Bit 6 - Gross Target Timer Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn grosstgtimintmsk(&mut self) -> GROSSTGTIMINTMSK_W { + GROSSTGTIMINTMSK_W { w: self } + } + #[doc = "Bit 5 - Error Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn errorintmsk(&mut self) -> ERRORINTMSK_W { + ERRORINTMSK_W { w: self } + } + #[doc = "Bit 4 - Encryption engine Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn cryptintmsk(&mut self) -> CRYPTINTMSK_W { + CRYPTINTMSK_W { w: self } + } + #[doc = "Bit 3 - End of event Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn eventintmsk(&mut self) -> EVENTINTMSK_W { + EVENTINTMSK_W { w: self } + } + #[doc = "Bit 2 - Sleep Mode Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn slpintmsk(&mut self) -> SLPINTMSK_W { + SLPINTMSK_W { w: self } + } + #[doc = "Bit 1 - Rx Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn rxintmsk(&mut self) -> RXINTMSK_W { + RXINTMSK_W { w: self } + } + #[doc = "Bit 0 - 625us Base Time Interrupt Mask 0: Interrupt not generated 1: Interrupt generated"] + #[inline(always)] + pub fn cscntintmsk(&mut self) -> CSCNTINTMSK_W { + CSCNTINTMSK_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt controller register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_intcntl_reg](index.html) module"] +pub struct BLE_INTCNTL_REG_SPEC; +impl crate::RegisterSpec for BLE_INTCNTL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_intcntl_reg::R](R) reader structure"] +impl crate::Readable for BLE_INTCNTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_intcntl_reg::W](W) writer structure"] +impl crate::Writable for BLE_INTCNTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_INTCNTL_REG to value 0x811f"] +impl crate::Resettable for BLE_INTCNTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x811f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_intrawstat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_intrawstat_reg.rs new file mode 100644 index 0000000..77c7527 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_intrawstat_reg.rs @@ -0,0 +1,266 @@ +#[doc = "Register `BLE_INTRAWSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_INTRAWSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SWINTRAWSTAT` reader - SW triggered interrupt raw status 0: No SW triggered interrupt. 1: A SW triggered interrupt is pending."] +pub struct SWINTRAWSTAT_R(crate::FieldReader); +impl SWINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SWINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SWINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVENTAPFAINTRAWSTAT` reader - End of event / Anticipated Pre-Fetch Abort interrupt raw status 0: No End of Event interrupt. 1: An End of Event interrupt is pending."] +pub struct EVENTAPFAINTRAWSTAT_R(crate::FieldReader); +impl EVENTAPFAINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVENTAPFAINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENTAPFAINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINETGTIMINTRAWSTAT` reader - Fine Target Timer Error interrupt raw status 0: No Fine Target Timer interrupt. 1: A Fine Target Timer interrupt is pending."] +pub struct FINETGTIMINTRAWSTAT_R(crate::FieldReader); +impl FINETGTIMINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FINETGTIMINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINETGTIMINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GROSSTGTIMINTRAWSTAT` reader - Gross Target Timer interrupt raw status 0: No Gross Target Timer interrupt. 1: A Gross Target Timer interrupt is pending."] +pub struct GROSSTGTIMINTRAWSTAT_R(crate::FieldReader); +impl GROSSTGTIMINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GROSSTGTIMINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GROSSTGTIMINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ERRORINTRAWSTAT` reader - Error interrupt raw status 0: No Error interrupt. 1: An Error interrupt is pending."] +pub struct ERRORINTRAWSTAT_R(crate::FieldReader); +impl ERRORINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ERRORINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ERRORINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CRYPTINTRAWSTAT` reader - Encryption engine interrupt raw status 0: No Encryption / Decryption interrupt. 1: An Encryption / Decryption interrupt is pending."] +pub struct CRYPTINTRAWSTAT_R(crate::FieldReader); +impl CRYPTINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CRYPTINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CRYPTINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVENTINTRAWSTAT` reader - End of Event interrupt raw status 0: No End of Advertising / Scanning / Connection interrupt. 1: An End of Advertising / Scanning / Connection interrupt is pending."] +pub struct EVENTINTRAWSTAT_R(crate::FieldReader); +impl EVENTINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVENTINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENTINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SLPINTRAWSTAT` reader - Sleep interrupt raw status 0: No End of Sleep Mode interrupt. 1: An End of Sleep Mode interrupt is pending."] +pub struct SLPINTRAWSTAT_R(crate::FieldReader); +impl SLPINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SLPINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SLPINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXINTRAWSTAT` reader - Packet Reception interrupt raw status 0: No Rx interrupt. 1: An Rx interrupt is pending."] +pub struct RXINTRAWSTAT_R(crate::FieldReader); +impl RXINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CSCNTINTRAWSTAT` reader - 625us base time reference interrupt raw status 0: No 625us Base Time interrupt. 1: A 625us Base Time interrupt is pending."] +pub struct CSCNTINTRAWSTAT_R(crate::FieldReader); +impl CSCNTINTRAWSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CSCNTINTRAWSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CSCNTINTRAWSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 9 - SW triggered interrupt raw status 0: No SW triggered interrupt. 1: A SW triggered interrupt is pending."] + #[inline(always)] + pub fn swintrawstat(&self) -> SWINTRAWSTAT_R { + SWINTRAWSTAT_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - End of event / Anticipated Pre-Fetch Abort interrupt raw status 0: No End of Event interrupt. 1: An End of Event interrupt is pending."] + #[inline(always)] + pub fn eventapfaintrawstat(&self) -> EVENTAPFAINTRAWSTAT_R { + EVENTAPFAINTRAWSTAT_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - Fine Target Timer Error interrupt raw status 0: No Fine Target Timer interrupt. 1: A Fine Target Timer interrupt is pending."] + #[inline(always)] + pub fn finetgtimintrawstat(&self) -> FINETGTIMINTRAWSTAT_R { + FINETGTIMINTRAWSTAT_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Gross Target Timer interrupt raw status 0: No Gross Target Timer interrupt. 1: A Gross Target Timer interrupt is pending."] + #[inline(always)] + pub fn grosstgtimintrawstat(&self) -> GROSSTGTIMINTRAWSTAT_R { + GROSSTGTIMINTRAWSTAT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Error interrupt raw status 0: No Error interrupt. 1: An Error interrupt is pending."] + #[inline(always)] + pub fn errorintrawstat(&self) -> ERRORINTRAWSTAT_R { + ERRORINTRAWSTAT_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Encryption engine interrupt raw status 0: No Encryption / Decryption interrupt. 1: An Encryption / Decryption interrupt is pending."] + #[inline(always)] + pub fn cryptintrawstat(&self) -> CRYPTINTRAWSTAT_R { + CRYPTINTRAWSTAT_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - End of Event interrupt raw status 0: No End of Advertising / Scanning / Connection interrupt. 1: An End of Advertising / Scanning / Connection interrupt is pending."] + #[inline(always)] + pub fn eventintrawstat(&self) -> EVENTINTRAWSTAT_R { + EVENTINTRAWSTAT_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Sleep interrupt raw status 0: No End of Sleep Mode interrupt. 1: An End of Sleep Mode interrupt is pending."] + #[inline(always)] + pub fn slpintrawstat(&self) -> SLPINTRAWSTAT_R { + SLPINTRAWSTAT_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Packet Reception interrupt raw status 0: No Rx interrupt. 1: An Rx interrupt is pending."] + #[inline(always)] + pub fn rxintrawstat(&self) -> RXINTRAWSTAT_R { + RXINTRAWSTAT_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 625us base time reference interrupt raw status 0: No 625us Base Time interrupt. 1: A 625us Base Time interrupt is pending."] + #[inline(always)] + pub fn cscntintrawstat(&self) -> CSCNTINTRAWSTAT_R { + CSCNTINTRAWSTAT_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt raw status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_intrawstat_reg](index.html) module"] +pub struct BLE_INTRAWSTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_INTRAWSTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_intrawstat_reg::R](R) reader structure"] +impl crate::Readable for BLE_INTRAWSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_intrawstat_reg::W](W) writer structure"] +impl crate::Writable for BLE_INTRAWSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_INTRAWSTAT_REG to value 0"] +impl crate::Resettable for BLE_INTRAWSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_intstat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_intstat_reg.rs new file mode 100644 index 0000000..8a830d2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_intstat_reg.rs @@ -0,0 +1,266 @@ +#[doc = "Register `BLE_INTSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_INTSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SWINTSTAT` reader - SW triggered interrupt status 0: No SW triggered interrupt. 1: A SW triggered interrupt is pending"] +pub struct SWINTSTAT_R(crate::FieldReader); +impl SWINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SWINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SWINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVENTAPFAINTSTAT` reader - End of event / Anticipated Pre-Fetch Abort interrupt status 0: No End of Event interrupt. 1: An End of Event interrupt is pending."] +pub struct EVENTAPFAINTSTAT_R(crate::FieldReader); +impl EVENTAPFAINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVENTAPFAINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENTAPFAINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FINETGTIMINTSTAT` reader - Masked Fine Target Timer Error interrupt status 0: No Fine Target Timer interrupt. 1: A Fine Target Timer interrupt is pending."] +pub struct FINETGTIMINTSTAT_R(crate::FieldReader); +impl FINETGTIMINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FINETGTIMINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FINETGTIMINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GROSSTGTIMINTSTAT` reader - Masked Gross Target Timer interrupt status 0: No Gross Target Timer interrupt. 1: A Gross Target Timer interrupt is pending."] +pub struct GROSSTGTIMINTSTAT_R(crate::FieldReader); +impl GROSSTGTIMINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GROSSTGTIMINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GROSSTGTIMINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ERRORINTSTAT` reader - Masked Error interrupt status 0: No Error interrupt. 1: An Error interrupt is pending."] +pub struct ERRORINTSTAT_R(crate::FieldReader); +impl ERRORINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ERRORINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ERRORINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CRYPTINTSTAT` reader - Masked Encryption engine interrupt status 0: No Encryption / Decryption interrupt. 1: An Encryption / Decryption interrupt is pending."] +pub struct CRYPTINTSTAT_R(crate::FieldReader); +impl CRYPTINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CRYPTINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CRYPTINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVENTINTSTAT` reader - Masked End of Event interrupt status 0: No End of Advertising / Scanning / Connection interrupt. 1: An End of Advertising / Scanning / Connection interrupt is pending."] +pub struct EVENTINTSTAT_R(crate::FieldReader); +impl EVENTINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EVENTINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENTINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SLPINTSTAT` reader - Masked Sleep interrupt status 0: No End of Sleep Mode interrupt. 1: An End of Sleep Mode interrupt is pending."] +pub struct SLPINTSTAT_R(crate::FieldReader); +impl SLPINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SLPINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SLPINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXINTSTAT` reader - Masked Packet Reception interrupt status 0: No Rx interrupt. 1: An Rx interrupt is pending."] +pub struct RXINTSTAT_R(crate::FieldReader); +impl RXINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CSCNTINTSTAT` reader - Masked 625us base time reference interrupt status 0: No 625us Base Time interrupt. 1: A 625us Base Time interrupt is pending."] +pub struct CSCNTINTSTAT_R(crate::FieldReader); +impl CSCNTINTSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CSCNTINTSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CSCNTINTSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 9 - SW triggered interrupt status 0: No SW triggered interrupt. 1: A SW triggered interrupt is pending"] + #[inline(always)] + pub fn swintstat(&self) -> SWINTSTAT_R { + SWINTSTAT_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - End of event / Anticipated Pre-Fetch Abort interrupt status 0: No End of Event interrupt. 1: An End of Event interrupt is pending."] + #[inline(always)] + pub fn eventapfaintstat(&self) -> EVENTAPFAINTSTAT_R { + EVENTAPFAINTSTAT_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - Masked Fine Target Timer Error interrupt status 0: No Fine Target Timer interrupt. 1: A Fine Target Timer interrupt is pending."] + #[inline(always)] + pub fn finetgtimintstat(&self) -> FINETGTIMINTSTAT_R { + FINETGTIMINTSTAT_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Masked Gross Target Timer interrupt status 0: No Gross Target Timer interrupt. 1: A Gross Target Timer interrupt is pending."] + #[inline(always)] + pub fn grosstgtimintstat(&self) -> GROSSTGTIMINTSTAT_R { + GROSSTGTIMINTSTAT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Masked Error interrupt status 0: No Error interrupt. 1: An Error interrupt is pending."] + #[inline(always)] + pub fn errorintstat(&self) -> ERRORINTSTAT_R { + ERRORINTSTAT_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Masked Encryption engine interrupt status 0: No Encryption / Decryption interrupt. 1: An Encryption / Decryption interrupt is pending."] + #[inline(always)] + pub fn cryptintstat(&self) -> CRYPTINTSTAT_R { + CRYPTINTSTAT_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Masked End of Event interrupt status 0: No End of Advertising / Scanning / Connection interrupt. 1: An End of Advertising / Scanning / Connection interrupt is pending."] + #[inline(always)] + pub fn eventintstat(&self) -> EVENTINTSTAT_R { + EVENTINTSTAT_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Masked Sleep interrupt status 0: No End of Sleep Mode interrupt. 1: An End of Sleep Mode interrupt is pending."] + #[inline(always)] + pub fn slpintstat(&self) -> SLPINTSTAT_R { + SLPINTSTAT_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Masked Packet Reception interrupt status 0: No Rx interrupt. 1: An Rx interrupt is pending."] + #[inline(always)] + pub fn rxintstat(&self) -> RXINTSTAT_R { + RXINTSTAT_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Masked 625us base time reference interrupt status 0: No 625us Base Time interrupt. 1: A 625us Base Time interrupt is pending."] + #[inline(always)] + pub fn cscntintstat(&self) -> CSCNTINTSTAT_R { + CSCNTINTSTAT_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_intstat_reg](index.html) module"] +pub struct BLE_INTSTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_INTSTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_intstat_reg::R](R) reader structure"] +impl crate::Readable for BLE_INTSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_intstat_reg::W](W) writer structure"] +impl crate::Writable for BLE_INTSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_INTSTAT_REG to value 0"] +impl crate::Resettable for BLE_INTSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl0_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl0_reg.rs new file mode 100644 index 0000000..6b4f16f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl0_reg.rs @@ -0,0 +1,64 @@ +#[doc = "Register `BLE_RADIOCNTL0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RADIOCNTL0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Radio interface control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_radiocntl0_reg](index.html) module"] +pub struct BLE_RADIOCNTL0_REG_SPEC; +impl crate::RegisterSpec for BLE_RADIOCNTL0_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_radiocntl0_reg::R](R) reader structure"] +impl crate::Readable for BLE_RADIOCNTL0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_radiocntl0_reg::W](W) writer structure"] +impl crate::Writable for BLE_RADIOCNTL0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RADIOCNTL0_REG to value 0x02"] +impl crate::Resettable for BLE_RADIOCNTL0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x02 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl1_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl1_reg.rs new file mode 100644 index 0000000..c2aec54 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl1_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_RADIOCNTL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RADIOCNTL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XRFSEL` reader - Extended radio selection field, Must be set to \"2\"."] +pub struct XRFSEL_R(crate::FieldReader); +impl XRFSEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XRFSEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XRFSEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XRFSEL` writer - Extended radio selection field, Must be set to \"2\"."] +pub struct XRFSEL_W<'a> { + w: &'a mut W, +} +impl<'a> XRFSEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 16)) | ((value as u32 & 0x1f) << 16); + self.w + } +} +impl R { + #[doc = "Bits 16:20 - Extended radio selection field, Must be set to \"2\"."] + #[inline(always)] + pub fn xrfsel(&self) -> XRFSEL_R { + XRFSEL_R::new(((self.bits >> 16) & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 16:20 - Extended radio selection field, Must be set to \"2\"."] + #[inline(always)] + pub fn xrfsel(&mut self) -> XRFSEL_W { + XRFSEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Radio interface control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_radiocntl1_reg](index.html) module"] +pub struct BLE_RADIOCNTL1_REG_SPEC; +impl crate::RegisterSpec for BLE_RADIOCNTL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_radiocntl1_reg::R](R) reader structure"] +impl crate::Readable for BLE_RADIOCNTL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_radiocntl1_reg::W](W) writer structure"] +impl crate::Writable for BLE_RADIOCNTL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RADIOCNTL1_REG to value 0"] +impl crate::Resettable for BLE_RADIOCNTL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl2_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl2_reg.rs new file mode 100644 index 0000000..5547776 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl2_reg.rs @@ -0,0 +1,64 @@ +#[doc = "Register `BLE_RADIOCNTL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RADIOCNTL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Radio interface control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_radiocntl2_reg](index.html) module"] +pub struct BLE_RADIOCNTL2_REG_SPEC; +impl crate::RegisterSpec for BLE_RADIOCNTL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_radiocntl2_reg::R](R) reader structure"] +impl crate::Readable for BLE_RADIOCNTL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_radiocntl2_reg::W](W) writer structure"] +impl crate::Writable for BLE_RADIOCNTL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RADIOCNTL2_REG to value 0"] +impl crate::Resettable for BLE_RADIOCNTL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl3_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl3_reg.rs new file mode 100644 index 0000000..2b4fd7f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_radiocntl3_reg.rs @@ -0,0 +1,64 @@ +#[doc = "Register `BLE_RADIOCNTL3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RADIOCNTL3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Radio interface control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_radiocntl3_reg](index.html) module"] +pub struct BLE_RADIOCNTL3_REG_SPEC; +impl crate::RegisterSpec for BLE_RADIOCNTL3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_radiocntl3_reg::R](R) reader structure"] +impl crate::Readable for BLE_RADIOCNTL3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_radiocntl3_reg::W](W) writer structure"] +impl crate::Writable for BLE_RADIOCNTL3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RADIOCNTL3_REG to value 0x40"] +impl crate::Resettable for BLE_RADIOCNTL3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x40 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_radiopwrupdn_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_radiopwrupdn_reg.rs new file mode 100644 index 0000000..80bb990 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_radiopwrupdn_reg.rs @@ -0,0 +1,214 @@ +#[doc = "Register `BLE_RADIOPWRUPDN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RADIOPWRUPDN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTRIP_DELAY` reader - Defines round trip delay value. This value correspond to the addition of data latency in Tx and data latency in Rx. Value is in usec."] +pub struct RTRIP_DELAY_R(crate::FieldReader); +impl RTRIP_DELAY_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTRIP_DELAY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTRIP_DELAY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTRIP_DELAY` writer - Defines round trip delay value. This value correspond to the addition of data latency in Tx and data latency in Rx. Value is in usec."] +pub struct RTRIP_DELAY_W<'a> { + w: &'a mut W, +} +impl<'a> RTRIP_DELAY_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 24)) | ((value as u32 & 0x7f) << 24); + self.w + } +} +#[doc = "Field `RXPWRUP` reader - This register holds the length in s of the RX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] +pub struct RXPWRUP_R(crate::FieldReader); +impl RXPWRUP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RXPWRUP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXPWRUP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXPWRUP` writer - This register holds the length in s of the RX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] +pub struct RXPWRUP_W<'a> { + w: &'a mut W, +} +impl<'a> RXPWRUP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 16)) | ((value as u32 & 0xff) << 16); + self.w + } +} +#[doc = "Field `TXPWRDN` reader - This register extends the length in s of the TX power down phase for the current radio device. Default value is 3 usec (reset value). Operating range depends on the selected radio."] +pub struct TXPWRDN_R(crate::FieldReader); +impl TXPWRDN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TXPWRDN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXPWRDN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXPWRDN` writer - This register extends the length in s of the TX power down phase for the current radio device. Default value is 3 usec (reset value). Operating range depends on the selected radio."] +pub struct TXPWRDN_W<'a> { + w: &'a mut W, +} +impl<'a> TXPWRDN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `TXPWRUP` reader - This register holds the length in s of the TX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] +pub struct TXPWRUP_R(crate::FieldReader); +impl TXPWRUP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TXPWRUP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXPWRUP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXPWRUP` writer - This register holds the length in s of the TX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] +pub struct TXPWRUP_W<'a> { + w: &'a mut W, +} +impl<'a> TXPWRUP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 24:30 - Defines round trip delay value. This value correspond to the addition of data latency in Tx and data latency in Rx. Value is in usec."] + #[inline(always)] + pub fn rtrip_delay(&self) -> RTRIP_DELAY_R { + RTRIP_DELAY_R::new(((self.bits >> 24) & 0x7f) as u8) + } + #[doc = "Bits 16:23 - This register holds the length in s of the RX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] + #[inline(always)] + pub fn rxpwrup(&self) -> RXPWRUP_R { + RXPWRUP_R::new(((self.bits >> 16) & 0xff) as u8) + } + #[doc = "Bits 8:11 - This register extends the length in s of the TX power down phase for the current radio device. Default value is 3 usec (reset value). Operating range depends on the selected radio."] + #[inline(always)] + pub fn txpwrdn(&self) -> TXPWRDN_R { + TXPWRDN_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bits 0:7 - This register holds the length in s of the TX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] + #[inline(always)] + pub fn txpwrup(&self) -> TXPWRUP_R { + TXPWRUP_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 24:30 - Defines round trip delay value. This value correspond to the addition of data latency in Tx and data latency in Rx. Value is in usec."] + #[inline(always)] + pub fn rtrip_delay(&mut self) -> RTRIP_DELAY_W { + RTRIP_DELAY_W { w: self } + } + #[doc = "Bits 16:23 - This register holds the length in s of the RX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] + #[inline(always)] + pub fn rxpwrup(&mut self) -> RXPWRUP_W { + RXPWRUP_W { w: self } + } + #[doc = "Bits 8:11 - This register extends the length in s of the TX power down phase for the current radio device. Default value is 3 usec (reset value). Operating range depends on the selected radio."] + #[inline(always)] + pub fn txpwrdn(&mut self) -> TXPWRDN_W { + TXPWRDN_W { w: self } + } + #[doc = "Bits 0:7 - This register holds the length in s of the TX power up phase for the current radio device. Default value is 210 usec (reset value). Operating range depends on the selected radio."] + #[inline(always)] + pub fn txpwrup(&mut self) -> TXPWRUP_W { + TXPWRUP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RX/TX power up/down phase register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_radiopwrupdn_reg](index.html) module"] +pub struct BLE_RADIOPWRUPDN_REG_SPEC; +impl crate::RegisterSpec for BLE_RADIOPWRUPDN_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_radiopwrupdn_reg::R](R) reader structure"] +impl crate::Readable for BLE_RADIOPWRUPDN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_radiopwrupdn_reg::W](W) writer structure"] +impl crate::Writable for BLE_RADIOPWRUPDN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RADIOPWRUPDN_REG to value 0x00d2_03d2"] +impl crate::Resettable for BLE_RADIOPWRUPDN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x00d2_03d2 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_rftestcntl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_rftestcntl_reg.rs new file mode 100644 index 0000000..ffcc3e2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_rftestcntl_reg.rs @@ -0,0 +1,448 @@ +#[doc = "Register `BLE_RFTESTCNTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RFTESTCNTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `INFINITERX` reader - Applicable in RF Test Mode only 0: Normal mode of operation 1: Infinite Rx window"] +pub struct INFINITERX_R(crate::FieldReader); +impl INFINITERX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INFINITERX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INFINITERX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INFINITERX` writer - Applicable in RF Test Mode only 0: Normal mode of operation 1: Infinite Rx window"] +pub struct INFINITERX_W<'a> { + w: &'a mut W, +} +impl<'a> INFINITERX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `RXPKTCNTEN` reader - Applicable in RF Test Mode only 0: Rx packet count disabled 1: Rx packet count enabled, and reported in CS-RXCCMPKTCNT and BLE_RFTESTRXSTAT_REG\\[RXPKTCNT\\] +on RF abort command"] +pub struct RXPKTCNTEN_R(crate::FieldReader); +impl RXPKTCNTEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RXPKTCNTEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXPKTCNTEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXPKTCNTEN` writer - Applicable in RF Test Mode only 0: Rx packet count disabled 1: Rx packet count enabled, and reported in CS-RXCCMPKTCNT and BLE_RFTESTRXSTAT_REG\\[RXPKTCNT\\] +on RF abort command"] +pub struct RXPKTCNTEN_W<'a> { + w: &'a mut W, +} +impl<'a> RXPKTCNTEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 27)) | ((value as u32 & 1) << 27); + self.w + } +} +#[doc = "Field `INFINITETX` reader - Applicable in RF Test Mode only 0: Normal mode of operation. 1: Infinite Tx packet / Normal start of a packet but endless payload"] +pub struct INFINITETX_R(crate::FieldReader); +impl INFINITETX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INFINITETX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INFINITETX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INFINITETX` writer - Applicable in RF Test Mode only 0: Normal mode of operation. 1: Infinite Tx packet / Normal start of a packet but endless payload"] +pub struct INFINITETX_W<'a> { + w: &'a mut W, +} +impl<'a> INFINITETX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `TXLENGTHSRC` reader - Applicable only in Tx/Rx RF Test mode 0: Normal mode of operation: TxDESC-TXADVLEN controls the Tx packet payload size 1: Uses BLE_RFTESTCNTL_REG\\[TXLENGTH\\] +packet length (can support up to 512 bytes transmit)"] +pub struct TXLENGTHSRC_R(crate::FieldReader); +impl TXLENGTHSRC_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TXLENGTHSRC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXLENGTHSRC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXLENGTHSRC` writer - Applicable only in Tx/Rx RF Test mode 0: Normal mode of operation: TxDESC-TXADVLEN controls the Tx packet payload size 1: Uses BLE_RFTESTCNTL_REG\\[TXLENGTH\\] +packet length (can support up to 512 bytes transmit)"] +pub struct TXLENGTHSRC_W<'a> { + w: &'a mut W, +} +impl<'a> TXLENGTHSRC_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u32 & 1) << 14); + self.w + } +} +#[doc = "Field `PRBSTYPE` reader - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload are PRBS9 type 1: Tx Packet Payload are PRBS15 type"] +pub struct PRBSTYPE_R(crate::FieldReader); +impl PRBSTYPE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PRBSTYPE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PRBSTYPE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PRBSTYPE` writer - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload are PRBS9 type 1: Tx Packet Payload are PRBS15 type"] +pub struct PRBSTYPE_W<'a> { + w: &'a mut W, +} +impl<'a> PRBSTYPE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u32 & 1) << 13); + self.w + } +} +#[doc = "Field `TXPLDSRC` reader - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload source is the Control Structure 1: Tx Packet Payload are PRBS generator"] +pub struct TXPLDSRC_R(crate::FieldReader); +impl TXPLDSRC_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TXPLDSRC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXPLDSRC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXPLDSRC` writer - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload source is the Control Structure 1: Tx Packet Payload are PRBS generator"] +pub struct TXPLDSRC_W<'a> { + w: &'a mut W, +} +impl<'a> TXPLDSRC_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u32 & 1) << 12); + self.w + } +} +#[doc = "Field `TXPKTCNTEN` reader - Applicable in RF Test Mode only 0: Tx packet count disabled 1: Tx packet count enabled, and reported in CS-TXCCMPKTCNT and BLE_RFTESTTXSTAT_REG\\[TXPKTCNT\\] +on RF abort command"] +pub struct TXPKTCNTEN_R(crate::FieldReader); +impl TXPKTCNTEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TXPKTCNTEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXPKTCNTEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXPKTCNTEN` writer - Applicable in RF Test Mode only 0: Tx packet count disabled 1: Tx packet count enabled, and reported in CS-TXCCMPKTCNT and BLE_RFTESTTXSTAT_REG\\[TXPKTCNT\\] +on RF abort command"] +pub struct TXPKTCNTEN_W<'a> { + w: &'a mut W, +} +impl<'a> TXPKTCNTEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u32 & 1) << 11); + self.w + } +} +#[doc = "Field `TXLENGTH` reader - Applicable only for Tx/Rx RF Test mode, and valid when BLE_RFTESTCNTL_REG\\[TXLENGTHSRC\\] += 1 Tx packet length in number of byte"] +pub struct TXLENGTH_R(crate::FieldReader); +impl TXLENGTH_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TXLENGTH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXLENGTH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TXLENGTH` writer - Applicable only for Tx/Rx RF Test mode, and valid when BLE_RFTESTCNTL_REG\\[TXLENGTHSRC\\] += 1 Tx packet length in number of byte"] +pub struct TXLENGTH_W<'a> { + w: &'a mut W, +} +impl<'a> TXLENGTH_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x01ff) | (value as u32 & 0x01ff); + self.w + } +} +impl R { + #[doc = "Bit 31 - Applicable in RF Test Mode only 0: Normal mode of operation 1: Infinite Rx window"] + #[inline(always)] + pub fn infiniterx(&self) -> INFINITERX_R { + INFINITERX_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bit 27 - Applicable in RF Test Mode only 0: Rx packet count disabled 1: Rx packet count enabled, and reported in CS-RXCCMPKTCNT and BLE_RFTESTRXSTAT_REG\\[RXPKTCNT\\] +on RF abort command"] + #[inline(always)] + pub fn rxpktcnten(&self) -> RXPKTCNTEN_R { + RXPKTCNTEN_R::new(((self.bits >> 27) & 1) != 0) + } + #[doc = "Bit 15 - Applicable in RF Test Mode only 0: Normal mode of operation. 1: Infinite Tx packet / Normal start of a packet but endless payload"] + #[inline(always)] + pub fn infinitetx(&self) -> INFINITETX_R { + INFINITETX_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14 - Applicable only in Tx/Rx RF Test mode 0: Normal mode of operation: TxDESC-TXADVLEN controls the Tx packet payload size 1: Uses BLE_RFTESTCNTL_REG\\[TXLENGTH\\] +packet length (can support up to 512 bytes transmit)"] + #[inline(always)] + pub fn txlengthsrc(&self) -> TXLENGTHSRC_R { + TXLENGTHSRC_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13 - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload are PRBS9 type 1: Tx Packet Payload are PRBS15 type"] + #[inline(always)] + pub fn prbstype(&self) -> PRBSTYPE_R { + PRBSTYPE_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12 - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload source is the Control Structure 1: Tx Packet Payload are PRBS generator"] + #[inline(always)] + pub fn txpldsrc(&self) -> TXPLDSRC_R { + TXPLDSRC_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11 - Applicable in RF Test Mode only 0: Tx packet count disabled 1: Tx packet count enabled, and reported in CS-TXCCMPKTCNT and BLE_RFTESTTXSTAT_REG\\[TXPKTCNT\\] +on RF abort command"] + #[inline(always)] + pub fn txpktcnten(&self) -> TXPKTCNTEN_R { + TXPKTCNTEN_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bits 0:8 - Applicable only for Tx/Rx RF Test mode, and valid when BLE_RFTESTCNTL_REG\\[TXLENGTHSRC\\] += 1 Tx packet length in number of byte"] + #[inline(always)] + pub fn txlength(&self) -> TXLENGTH_R { + TXLENGTH_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Bit 31 - Applicable in RF Test Mode only 0: Normal mode of operation 1: Infinite Rx window"] + #[inline(always)] + pub fn infiniterx(&mut self) -> INFINITERX_W { + INFINITERX_W { w: self } + } + #[doc = "Bit 27 - Applicable in RF Test Mode only 0: Rx packet count disabled 1: Rx packet count enabled, and reported in CS-RXCCMPKTCNT and BLE_RFTESTRXSTAT_REG\\[RXPKTCNT\\] +on RF abort command"] + #[inline(always)] + pub fn rxpktcnten(&mut self) -> RXPKTCNTEN_W { + RXPKTCNTEN_W { w: self } + } + #[doc = "Bit 15 - Applicable in RF Test Mode only 0: Normal mode of operation. 1: Infinite Tx packet / Normal start of a packet but endless payload"] + #[inline(always)] + pub fn infinitetx(&mut self) -> INFINITETX_W { + INFINITETX_W { w: self } + } + #[doc = "Bit 14 - Applicable only in Tx/Rx RF Test mode 0: Normal mode of operation: TxDESC-TXADVLEN controls the Tx packet payload size 1: Uses BLE_RFTESTCNTL_REG\\[TXLENGTH\\] +packet length (can support up to 512 bytes transmit)"] + #[inline(always)] + pub fn txlengthsrc(&mut self) -> TXLENGTHSRC_W { + TXLENGTHSRC_W { w: self } + } + #[doc = "Bit 13 - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload are PRBS9 type 1: Tx Packet Payload are PRBS15 type"] + #[inline(always)] + pub fn prbstype(&mut self) -> PRBSTYPE_W { + PRBSTYPE_W { w: self } + } + #[doc = "Bit 12 - Applicable only in Tx/Rx RF Test mode 0: Tx Packet Payload source is the Control Structure 1: Tx Packet Payload are PRBS generator"] + #[inline(always)] + pub fn txpldsrc(&mut self) -> TXPLDSRC_W { + TXPLDSRC_W { w: self } + } + #[doc = "Bit 11 - Applicable in RF Test Mode only 0: Tx packet count disabled 1: Tx packet count enabled, and reported in CS-TXCCMPKTCNT and BLE_RFTESTTXSTAT_REG\\[TXPKTCNT\\] +on RF abort command"] + #[inline(always)] + pub fn txpktcnten(&mut self) -> TXPKTCNTEN_W { + TXPKTCNTEN_W { w: self } + } + #[doc = "Bits 0:8 - Applicable only for Tx/Rx RF Test mode, and valid when BLE_RFTESTCNTL_REG\\[TXLENGTHSRC\\] += 1 Tx packet length in number of byte"] + #[inline(always)] + pub fn txlength(&mut self) -> TXLENGTH_W { + TXLENGTH_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RF Testing Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_rftestcntl_reg](index.html) module"] +pub struct BLE_RFTESTCNTL_REG_SPEC; +impl crate::RegisterSpec for BLE_RFTESTCNTL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_rftestcntl_reg::R](R) reader structure"] +impl crate::Readable for BLE_RFTESTCNTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_rftestcntl_reg::W](W) writer structure"] +impl crate::Writable for BLE_RFTESTCNTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RFTESTCNTL_REG to value 0"] +impl crate::Resettable for BLE_RFTESTCNTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_rftestrxstat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_rftestrxstat_reg.rs new file mode 100644 index 0000000..1eca3b9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_rftestrxstat_reg.rs @@ -0,0 +1,88 @@ +#[doc = "Register `BLE_RFTESTRXSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RFTESTRXSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RXPKTCNT` reader - Reports number of correctly received packet during Test Modes (no sync error, no CRC error). Value is valid if BLE_RFTESTCNTL_REG\\[RXPKTCNTEN\\] +is set"] +pub struct RXPKTCNT_R(crate::FieldReader); +impl RXPKTCNT_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + RXPKTCNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXPKTCNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:31 - Reports number of correctly received packet during Test Modes (no sync error, no CRC error). Value is valid if BLE_RFTESTCNTL_REG\\[RXPKTCNTEN\\] +is set"] + #[inline(always)] + pub fn rxpktcnt(&self) -> RXPKTCNT_R { + RXPKTCNT_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RF Testing Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_rftestrxstat_reg](index.html) module"] +pub struct BLE_RFTESTRXSTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_RFTESTRXSTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_rftestrxstat_reg::R](R) reader structure"] +impl crate::Readable for BLE_RFTESTRXSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_rftestrxstat_reg::W](W) writer structure"] +impl crate::Writable for BLE_RFTESTRXSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RFTESTRXSTAT_REG to value 0"] +impl crate::Resettable for BLE_RFTESTRXSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_rftesttxstat_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_rftesttxstat_reg.rs new file mode 100644 index 0000000..411b2e3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_rftesttxstat_reg.rs @@ -0,0 +1,88 @@ +#[doc = "Register `BLE_RFTESTTXSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RFTESTTXSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TXPKTCNT` reader - Reports number of transmitted packet during Test Modes. Value is valid if BLE_RFTESTCNTL_REG\\[TXPKTCNTEN\\] +is set"] +pub struct TXPKTCNT_R(crate::FieldReader); +impl TXPKTCNT_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + TXPKTCNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXPKTCNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:31 - Reports number of transmitted packet during Test Modes. Value is valid if BLE_RFTESTCNTL_REG\\[TXPKTCNTEN\\] +is set"] + #[inline(always)] + pub fn txpktcnt(&self) -> TXPKTCNT_R { + TXPKTCNT_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RF Testing Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_rftesttxstat_reg](index.html) module"] +pub struct BLE_RFTESTTXSTAT_REG_SPEC; +impl crate::RegisterSpec for BLE_RFTESTTXSTAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_rftesttxstat_reg::R](R) reader structure"] +impl crate::Readable for BLE_RFTESTTXSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_rftesttxstat_reg::W](W) writer structure"] +impl crate::Writable for BLE_RFTESTTXSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RFTESTTXSTAT_REG to value 0"] +impl crate::Resettable for BLE_RFTESTTXSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_rwblecntl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_rwblecntl_reg.rs new file mode 100644 index 0000000..8cbc9fc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_rwblecntl_reg.rs @@ -0,0 +1,772 @@ +#[doc = "Register `BLE_RWBLECNTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RWBLECNTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MASTER_SOFT_RST` writer - Reset the complete BLE Core except registers and timing generator, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct MASTER_SOFT_RST_W<'a> { + w: &'a mut W, +} +impl<'a> MASTER_SOFT_RST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `MASTER_TGSOFT_RST` writer - Reset the timing generator, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct MASTER_TGSOFT_RST_W<'a> { + w: &'a mut W, +} +impl<'a> MASTER_TGSOFT_RST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 30)) | ((value as u32 & 1) << 30); + self.w + } +} +#[doc = "Field `REG_SOFT_RST` reader - Reset the complete register block, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0. Note that INT STAT will not be cleared, so the user should also write to BLE_INTACK_REG after the SW Reset"] +pub struct REG_SOFT_RST_R(crate::FieldReader); +impl REG_SOFT_RST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + REG_SOFT_RST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REG_SOFT_RST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REG_SOFT_RST` writer - Reset the complete register block, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0. Note that INT STAT will not be cleared, so the user should also write to BLE_INTACK_REG after the SW Reset"] +pub struct REG_SOFT_RST_W<'a> { + w: &'a mut W, +} +impl<'a> REG_SOFT_RST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 29)) | ((value as u32 & 1) << 29); + self.w + } +} +#[doc = "Field `SWINT_REQ` writer - Forces the generation of ble_sw_irq when written with a 1, and proper masking is set. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct SWINT_REQ_W<'a> { + w: &'a mut W, +} +impl<'a> SWINT_REQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 28)) | ((value as u32 & 1) << 28); + self.w + } +} +#[doc = "Field `RFTEST_ABORT` writer - Abort the current RF Testing defined as per CS-FORMAT when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0. Note that when RFTEST_ABORT is requested: 1) In case of infinite Tx, the Packet Controller FSM stops at the end of the current byte in process, and processes accordingly the packet CRC. 2) In case of Infinite Rx, the Packet Controller FSM either stops as the end of the current Packet reception (if Access address has been detected), or simply stop the processing switching off the RF."] +pub struct RFTEST_ABORT_W<'a> { + w: &'a mut W, +} +impl<'a> RFTEST_ABORT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 26)) | ((value as u32 & 1) << 26); + self.w + } +} +#[doc = "Field `ADVERT_ABORT` writer - Abort the current Advertising event when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct ADVERT_ABORT_W<'a> { + w: &'a mut W, +} +impl<'a> ADVERT_ABORT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 25)) | ((value as u32 & 1) << 25); + self.w + } +} +#[doc = "Field `SCAN_ABORT` writer - Abort the current scan window when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] +pub struct SCAN_ABORT_W<'a> { + w: &'a mut W, +} +impl<'a> SCAN_ABORT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 24)) | ((value as u32 & 1) << 24); + self.w + } +} +#[doc = "Field `MD_DSB` reader - 0: Normal operation of MD bits management 1: Allow a single Tx/Rx exchange whatever the MD bits are. value forced by SW from Tx Descriptorvalue just saved in Rx Descriptor during reception"] +pub struct MD_DSB_R(crate::FieldReader); +impl MD_DSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MD_DSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MD_DSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MD_DSB` writer - 0: Normal operation of MD bits management 1: Allow a single Tx/Rx exchange whatever the MD bits are. value forced by SW from Tx Descriptorvalue just saved in Rx Descriptor during reception"] +pub struct MD_DSB_W<'a> { + w: &'a mut W, +} +impl<'a> MD_DSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 22)) | ((value as u32 & 1) << 22); + self.w + } +} +#[doc = "Field `SN_DSB` reader - 0: Normal operation of Sequence number 1: Sequence Number Management disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no SN error reported."] +pub struct SN_DSB_R(crate::FieldReader); +impl SN_DSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SN_DSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SN_DSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SN_DSB` writer - 0: Normal operation of Sequence number 1: Sequence Number Management disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no SN error reported."] +pub struct SN_DSB_W<'a> { + w: &'a mut W, +} +impl<'a> SN_DSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 21)) | ((value as u32 & 1) << 21); + self.w + } +} +#[doc = "Field `NESN_DSB` reader - 0: Normal operation of Acknowledge 1: Acknowledge scheme disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no NESN error reported."] +pub struct NESN_DSB_R(crate::FieldReader); +impl NESN_DSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + NESN_DSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for NESN_DSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `NESN_DSB` writer - 0: Normal operation of Acknowledge 1: Acknowledge scheme disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no NESN error reported."] +pub struct NESN_DSB_W<'a> { + w: &'a mut W, +} +impl<'a> NESN_DSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 20)) | ((value as u32 & 1) << 20); + self.w + } +} +#[doc = "Field `CRYPT_DSB` reader - 0: Normal operation. Encryption / Decryption enabled. 1: Encryption / Decryption disabled. Note that if CS-CRYPT_EN is set, then MIC is generated, and only data encryption is disabled, meaning data sent are plain data."] +pub struct CRYPT_DSB_R(crate::FieldReader); +impl CRYPT_DSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CRYPT_DSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CRYPT_DSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CRYPT_DSB` writer - 0: Normal operation. Encryption / Decryption enabled. 1: Encryption / Decryption disabled. Note that if CS-CRYPT_EN is set, then MIC is generated, and only data encryption is disabled, meaning data sent are plain data."] +pub struct CRYPT_DSB_W<'a> { + w: &'a mut W, +} +impl<'a> CRYPT_DSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `WHIT_DSB` reader - 0: Normal operation. Whitening enabled. 1: Whitening disabled."] +pub struct WHIT_DSB_R(crate::FieldReader); +impl WHIT_DSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WHIT_DSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WHIT_DSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WHIT_DSB` writer - 0: Normal operation. Whitening enabled. 1: Whitening disabled."] +pub struct WHIT_DSB_W<'a> { + w: &'a mut W, +} +impl<'a> WHIT_DSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 18)) | ((value as u32 & 1) << 18); + self.w + } +} +#[doc = "Field `CRC_DSB` reader - 0: Normal operation. CRC removed from data stream. 1: CRC stripping disabled on Rx packets, CRC replaced by 0x000 in Tx."] +pub struct CRC_DSB_R(crate::FieldReader); +impl CRC_DSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CRC_DSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CRC_DSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CRC_DSB` writer - 0: Normal operation. CRC removed from data stream. 1: CRC stripping disabled on Rx packets, CRC replaced by 0x000 in Tx."] +pub struct CRC_DSB_W<'a> { + w: &'a mut W, +} +impl<'a> CRC_DSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 17)) | ((value as u32 & 1) << 17); + self.w + } +} +#[doc = "Field `HOP_REMAP_DSB` reader - 0: Normal operation. Frequency Hopping Remapping algorithm enabled. 1: Frequency Hopping Remapping algorithm disabled"] +pub struct HOP_REMAP_DSB_R(crate::FieldReader); +impl HOP_REMAP_DSB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + HOP_REMAP_DSB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HOP_REMAP_DSB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HOP_REMAP_DSB` writer - 0: Normal operation. Frequency Hopping Remapping algorithm enabled. 1: Frequency Hopping Remapping algorithm disabled"] +pub struct HOP_REMAP_DSB_W<'a> { + w: &'a mut W, +} +impl<'a> HOP_REMAP_DSB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `ADVERTFILT_EN` reader - Advertising Channels Error Filtering Enable control 0: BLE Core reports all errors to RW-BLE Software 1: BLE Core reports only correctly received packet, without error to RW-BLE Software"] +pub struct ADVERTFILT_EN_R(crate::FieldReader); +impl ADVERTFILT_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADVERTFILT_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADVERTFILT_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADVERTFILT_EN` writer - Advertising Channels Error Filtering Enable control 0: BLE Core reports all errors to RW-BLE Software 1: BLE Core reports only correctly received packet, without error to RW-BLE Software"] +pub struct ADVERTFILT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ADVERTFILT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `RWBLE_EN` reader - 0: Disable BLE Core Exchange Table pre-fetch mechanism. 1: Enable BLE Core Exchange table pre-fetch mechanism."] +pub struct RWBLE_EN_R(crate::FieldReader); +impl RWBLE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RWBLE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RWBLE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RWBLE_EN` writer - 0: Disable BLE Core Exchange Table pre-fetch mechanism. 1: Enable BLE Core Exchange table pre-fetch mechanism."] +pub struct RWBLE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RWBLE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `RXWINSZDEF` reader - Default Rx Window size in us. Used when device: is master connectedperforms its second receipt.0 is not a valid value. Recommended value is 10 (in decimal)."] +pub struct RXWINSZDEF_R(crate::FieldReader); +impl RXWINSZDEF_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RXWINSZDEF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXWINSZDEF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RXWINSZDEF` writer - Default Rx Window size in us. Used when device: is master connectedperforms its second receipt.0 is not a valid value. Recommended value is 10 (in decimal)."] +pub struct RXWINSZDEF_W<'a> { + w: &'a mut W, +} +impl<'a> RXWINSZDEF_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u32 & 0x0f) << 4); + self.w + } +} +#[doc = "Field `SYNCERR` reader - Indicates the maximum number of errors allowed to recognize the synchronization word."] +pub struct SYNCERR_R(crate::FieldReader); +impl SYNCERR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SYNCERR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYNCERR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYNCERR` writer - Indicates the maximum number of errors allowed to recognize the synchronization word."] +pub struct SYNCERR_W<'a> { + w: &'a mut W, +} +impl<'a> SYNCERR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bit 29 - Reset the complete register block, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0. Note that INT STAT will not be cleared, so the user should also write to BLE_INTACK_REG after the SW Reset"] + #[inline(always)] + pub fn reg_soft_rst(&self) -> REG_SOFT_RST_R { + REG_SOFT_RST_R::new(((self.bits >> 29) & 1) != 0) + } + #[doc = "Bit 22 - 0: Normal operation of MD bits management 1: Allow a single Tx/Rx exchange whatever the MD bits are. value forced by SW from Tx Descriptorvalue just saved in Rx Descriptor during reception"] + #[inline(always)] + pub fn md_dsb(&self) -> MD_DSB_R { + MD_DSB_R::new(((self.bits >> 22) & 1) != 0) + } + #[doc = "Bit 21 - 0: Normal operation of Sequence number 1: Sequence Number Management disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no SN error reported."] + #[inline(always)] + pub fn sn_dsb(&self) -> SN_DSB_R { + SN_DSB_R::new(((self.bits >> 21) & 1) != 0) + } + #[doc = "Bit 20 - 0: Normal operation of Acknowledge 1: Acknowledge scheme disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no NESN error reported."] + #[inline(always)] + pub fn nesn_dsb(&self) -> NESN_DSB_R { + NESN_DSB_R::new(((self.bits >> 20) & 1) != 0) + } + #[doc = "Bit 19 - 0: Normal operation. Encryption / Decryption enabled. 1: Encryption / Decryption disabled. Note that if CS-CRYPT_EN is set, then MIC is generated, and only data encryption is disabled, meaning data sent are plain data."] + #[inline(always)] + pub fn crypt_dsb(&self) -> CRYPT_DSB_R { + CRYPT_DSB_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bit 18 - 0: Normal operation. Whitening enabled. 1: Whitening disabled."] + #[inline(always)] + pub fn whit_dsb(&self) -> WHIT_DSB_R { + WHIT_DSB_R::new(((self.bits >> 18) & 1) != 0) + } + #[doc = "Bit 17 - 0: Normal operation. CRC removed from data stream. 1: CRC stripping disabled on Rx packets, CRC replaced by 0x000 in Tx."] + #[inline(always)] + pub fn crc_dsb(&self) -> CRC_DSB_R { + CRC_DSB_R::new(((self.bits >> 17) & 1) != 0) + } + #[doc = "Bit 16 - 0: Normal operation. Frequency Hopping Remapping algorithm enabled. 1: Frequency Hopping Remapping algorithm disabled"] + #[inline(always)] + pub fn hop_remap_dsb(&self) -> HOP_REMAP_DSB_R { + HOP_REMAP_DSB_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bit 9 - Advertising Channels Error Filtering Enable control 0: BLE Core reports all errors to RW-BLE Software 1: BLE Core reports only correctly received packet, without error to RW-BLE Software"] + #[inline(always)] + pub fn advertfilt_en(&self) -> ADVERTFILT_EN_R { + ADVERTFILT_EN_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - 0: Disable BLE Core Exchange Table pre-fetch mechanism. 1: Enable BLE Core Exchange table pre-fetch mechanism."] + #[inline(always)] + pub fn rwble_en(&self) -> RWBLE_EN_R { + RWBLE_EN_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 4:7 - Default Rx Window size in us. Used when device: is master connectedperforms its second receipt.0 is not a valid value. Recommended value is 10 (in decimal)."] + #[inline(always)] + pub fn rxwinszdef(&self) -> RXWINSZDEF_R { + RXWINSZDEF_R::new(((self.bits >> 4) & 0x0f) as u8) + } + #[doc = "Bits 0:2 - Indicates the maximum number of errors allowed to recognize the synchronization word."] + #[inline(always)] + pub fn syncerr(&self) -> SYNCERR_R { + SYNCERR_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bit 31 - Reset the complete BLE Core except registers and timing generator, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn master_soft_rst(&mut self) -> MASTER_SOFT_RST_W { + MASTER_SOFT_RST_W { w: self } + } + #[doc = "Bit 30 - Reset the timing generator, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn master_tgsoft_rst(&mut self) -> MASTER_TGSOFT_RST_W { + MASTER_TGSOFT_RST_W { w: self } + } + #[doc = "Bit 29 - Reset the complete register block, when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0. Note that INT STAT will not be cleared, so the user should also write to BLE_INTACK_REG after the SW Reset"] + #[inline(always)] + pub fn reg_soft_rst(&mut self) -> REG_SOFT_RST_W { + REG_SOFT_RST_W { w: self } + } + #[doc = "Bit 28 - Forces the generation of ble_sw_irq when written with a 1, and proper masking is set. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn swint_req(&mut self) -> SWINT_REQ_W { + SWINT_REQ_W { w: self } + } + #[doc = "Bit 26 - Abort the current RF Testing defined as per CS-FORMAT when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0. Note that when RFTEST_ABORT is requested: 1) In case of infinite Tx, the Packet Controller FSM stops at the end of the current byte in process, and processes accordingly the packet CRC. 2) In case of Infinite Rx, the Packet Controller FSM either stops as the end of the current Packet reception (if Access address has been detected), or simply stop the processing switching off the RF."] + #[inline(always)] + pub fn rftest_abort(&mut self) -> RFTEST_ABORT_W { + RFTEST_ABORT_W { w: self } + } + #[doc = "Bit 25 - Abort the current Advertising event when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn advert_abort(&mut self) -> ADVERT_ABORT_W { + ADVERT_ABORT_W { w: self } + } + #[doc = "Bit 24 - Abort the current scan window when written with a 1. Resets at 0 when action is performed. No action happens if it is written with 0."] + #[inline(always)] + pub fn scan_abort(&mut self) -> SCAN_ABORT_W { + SCAN_ABORT_W { w: self } + } + #[doc = "Bit 22 - 0: Normal operation of MD bits management 1: Allow a single Tx/Rx exchange whatever the MD bits are. value forced by SW from Tx Descriptorvalue just saved in Rx Descriptor during reception"] + #[inline(always)] + pub fn md_dsb(&mut self) -> MD_DSB_W { + MD_DSB_W { w: self } + } + #[doc = "Bit 21 - 0: Normal operation of Sequence number 1: Sequence Number Management disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no SN error reported."] + #[inline(always)] + pub fn sn_dsb(&mut self) -> SN_DSB_W { + SN_DSB_W { w: self } + } + #[doc = "Bit 20 - 0: Normal operation of Acknowledge 1: Acknowledge scheme disabled: value forced by SW from Tx Descriptorvalue ignored in Rx, where no NESN error reported."] + #[inline(always)] + pub fn nesn_dsb(&mut self) -> NESN_DSB_W { + NESN_DSB_W { w: self } + } + #[doc = "Bit 19 - 0: Normal operation. Encryption / Decryption enabled. 1: Encryption / Decryption disabled. Note that if CS-CRYPT_EN is set, then MIC is generated, and only data encryption is disabled, meaning data sent are plain data."] + #[inline(always)] + pub fn crypt_dsb(&mut self) -> CRYPT_DSB_W { + CRYPT_DSB_W { w: self } + } + #[doc = "Bit 18 - 0: Normal operation. Whitening enabled. 1: Whitening disabled."] + #[inline(always)] + pub fn whit_dsb(&mut self) -> WHIT_DSB_W { + WHIT_DSB_W { w: self } + } + #[doc = "Bit 17 - 0: Normal operation. CRC removed from data stream. 1: CRC stripping disabled on Rx packets, CRC replaced by 0x000 in Tx."] + #[inline(always)] + pub fn crc_dsb(&mut self) -> CRC_DSB_W { + CRC_DSB_W { w: self } + } + #[doc = "Bit 16 - 0: Normal operation. Frequency Hopping Remapping algorithm enabled. 1: Frequency Hopping Remapping algorithm disabled"] + #[inline(always)] + pub fn hop_remap_dsb(&mut self) -> HOP_REMAP_DSB_W { + HOP_REMAP_DSB_W { w: self } + } + #[doc = "Bit 9 - Advertising Channels Error Filtering Enable control 0: BLE Core reports all errors to RW-BLE Software 1: BLE Core reports only correctly received packet, without error to RW-BLE Software"] + #[inline(always)] + pub fn advertfilt_en(&mut self) -> ADVERTFILT_EN_W { + ADVERTFILT_EN_W { w: self } + } + #[doc = "Bit 8 - 0: Disable BLE Core Exchange Table pre-fetch mechanism. 1: Enable BLE Core Exchange table pre-fetch mechanism."] + #[inline(always)] + pub fn rwble_en(&mut self) -> RWBLE_EN_W { + RWBLE_EN_W { w: self } + } + #[doc = "Bits 4:7 - Default Rx Window size in us. Used when device: is master connectedperforms its second receipt.0 is not a valid value. Recommended value is 10 (in decimal)."] + #[inline(always)] + pub fn rxwinszdef(&mut self) -> RXWINSZDEF_W { + RXWINSZDEF_W { w: self } + } + #[doc = "Bits 0:2 - Indicates the maximum number of errors allowed to recognize the synchronization word."] + #[inline(always)] + pub fn syncerr(&mut self) -> SYNCERR_W { + SYNCERR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "BLE Control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_rwblecntl_reg](index.html) module"] +pub struct BLE_RWBLECNTL_REG_SPEC; +impl crate::RegisterSpec for BLE_RWBLECNTL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_rwblecntl_reg::R](R) reader structure"] +impl crate::Readable for BLE_RWBLECNTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_rwblecntl_reg::W](W) writer structure"] +impl crate::Writable for BLE_RWBLECNTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RWBLECNTL_REG to value 0"] +impl crate::Resettable for BLE_RWBLECNTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_rwbleconf_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_rwbleconf_reg.rs new file mode 100644 index 0000000..45d9586 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_rwbleconf_reg.rs @@ -0,0 +1,266 @@ +#[doc = "Register `BLE_RWBLECONF_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RWBLECONF_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADD_WIDTH` reader - Value of the RW_BLE_ADDRESS_WIDTH parameter concerted into binary."] +pub struct ADD_WIDTH_R(crate::FieldReader); +impl ADD_WIDTH_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADD_WIDTH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADD_WIDTH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIF` reader - Radio Interface ID"] +pub struct RFIF_R(crate::FieldReader); +impl RFIF_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CLK_SEL` reader - Operating Frequency (in MHz)"] +pub struct CLK_SEL_R(crate::FieldReader); +impl CLK_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CLK_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLK_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DECIPHER` reader - 0: AES deciphering not present"] +pub struct DECIPHER_R(crate::FieldReader); +impl DECIPHER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DECIPHER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DECIPHER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DMMODE` reader - 0: BLE Core is used as a standalone BLE device"] +pub struct DMMODE_R(crate::FieldReader); +impl DMMODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DMMODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DMMODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INTMODE` reader - 1: Interrupts are trigger level generated, i.e. stays active at 1 till acknowledgement"] +pub struct INTMODE_R(crate::FieldReader); +impl INTMODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INTMODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INTMODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `COEX` reader - 1: WLAN Coexistence mechanism present"] +pub struct COEX_R(crate::FieldReader); +impl COEX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + COEX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for COEX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `USEDBG` reader - 1: Diagnostic port instantiated"] +pub struct USEDBG_R(crate::FieldReader); +impl USEDBG_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + USEDBG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for USEDBG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `USECRYPT` reader - 1: AES-CCM Encryption block present"] +pub struct USECRYPT_R(crate::FieldReader); +impl USECRYPT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + USECRYPT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for USECRYPT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BUSWIDTH` reader - Processor bus width: 1: 32 bits"] +pub struct BUSWIDTH_R(crate::FieldReader); +impl BUSWIDTH_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BUSWIDTH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BUSWIDTH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 24:29 - Value of the RW_BLE_ADDRESS_WIDTH parameter concerted into binary."] + #[inline(always)] + pub fn add_width(&self) -> ADD_WIDTH_R { + ADD_WIDTH_R::new(((self.bits >> 24) & 0x3f) as u8) + } + #[doc = "Bits 16:22 - Radio Interface ID"] + #[inline(always)] + pub fn rfif(&self) -> RFIF_R { + RFIF_R::new(((self.bits >> 16) & 0x7f) as u8) + } + #[doc = "Bits 8:13 - Operating Frequency (in MHz)"] + #[inline(always)] + pub fn clk_sel(&self) -> CLK_SEL_R { + CLK_SEL_R::new(((self.bits >> 8) & 0x3f) as u8) + } + #[doc = "Bit 6 - 0: AES deciphering not present"] + #[inline(always)] + pub fn decipher(&self) -> DECIPHER_R { + DECIPHER_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - 0: BLE Core is used as a standalone BLE device"] + #[inline(always)] + pub fn dmmode(&self) -> DMMODE_R { + DMMODE_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - 1: Interrupts are trigger level generated, i.e. stays active at 1 till acknowledgement"] + #[inline(always)] + pub fn intmode(&self) -> INTMODE_R { + INTMODE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - 1: WLAN Coexistence mechanism present"] + #[inline(always)] + pub fn coex(&self) -> COEX_R { + COEX_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - 1: Diagnostic port instantiated"] + #[inline(always)] + pub fn usedbg(&self) -> USEDBG_R { + USEDBG_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - 1: AES-CCM Encryption block present"] + #[inline(always)] + pub fn usecrypt(&self) -> USECRYPT_R { + USECRYPT_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Processor bus width: 1: 32 bits"] + #[inline(always)] + pub fn buswidth(&self) -> BUSWIDTH_R { + BUSWIDTH_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_rwbleconf_reg](index.html) module"] +pub struct BLE_RWBLECONF_REG_SPEC; +impl crate::RegisterSpec for BLE_RWBLECONF_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_rwbleconf_reg::R](R) reader structure"] +impl crate::Readable for BLE_RWBLECONF_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_rwbleconf_reg::W](W) writer structure"] +impl crate::Writable for BLE_RWBLECONF_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RWBLECONF_REG to value 0x0f02_001f"] +impl crate::Resettable for BLE_RWBLECONF_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f02_001f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_rxmicval_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_rxmicval_reg.rs new file mode 100644 index 0000000..2beb350 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_rxmicval_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `BLE_RXMICVAL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_RXMICVAL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RXMICVAL` reader - AES-CCM plain MIC value. Valid on once MIC has been extracted from Rx packet."] +pub struct RXMICVAL_R(crate::FieldReader); +impl RXMICVAL_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + RXMICVAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXMICVAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:31 - AES-CCM plain MIC value. Valid on once MIC has been extracted from Rx packet."] + #[inline(always)] + pub fn rxmicval(&self) -> RXMICVAL_R { + RXMICVAL_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "AES / CCM plain MIC value\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_rxmicval_reg](index.html) module"] +pub struct BLE_RXMICVAL_REG_SPEC; +impl crate::RegisterSpec for BLE_RXMICVAL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_rxmicval_reg::R](R) reader structure"] +impl crate::Readable for BLE_RXMICVAL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_rxmicval_reg::W](W) writer structure"] +impl crate::Writable for BLE_RXMICVAL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_RXMICVAL_REG to value 0"] +impl crate::Resettable for BLE_RXMICVAL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_sampleclk_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_sampleclk_reg.rs new file mode 100644 index 0000000..484f27e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_sampleclk_reg.rs @@ -0,0 +1,91 @@ +#[doc = "Register `BLE_SAMPLECLK_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_SAMPLECLK_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SAMP` writer - Writing a 1 samples the Base Time Counter value in BASETIMECNT register. Resets at 0 when action is performed."] +pub struct SAMP_W<'a> { + w: &'a mut W, +} +impl<'a> SAMP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl W { + #[doc = "Bit 0 - Writing a 1 samples the Base Time Counter value in BASETIMECNT register. Resets at 0 when action is performed."] + #[inline(always)] + pub fn samp(&mut self) -> SAMP_W { + SAMP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Samples the Base Time Counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_sampleclk_reg](index.html) module"] +pub struct BLE_SAMPLECLK_REG_SPEC; +impl crate::RegisterSpec for BLE_SAMPLECLK_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_sampleclk_reg::R](R) reader structure"] +impl crate::Readable for BLE_SAMPLECLK_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_sampleclk_reg::W](W) writer structure"] +impl crate::Writable for BLE_SAMPLECLK_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_SAMPLECLK_REG to value 0"] +impl crate::Resettable for BLE_SAMPLECLK_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_swprofiling_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_swprofiling_reg.rs new file mode 100644 index 0000000..9eea034 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_swprofiling_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_SWPROFILING_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_SWPROFILING_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SWPROFVAL` reader - Software Profiling register: used by BLE Software for profiling purpose: this value is copied on Diagnostic port"] +pub struct SWPROFVAL_R(crate::FieldReader); +impl SWPROFVAL_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + SWPROFVAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SWPROFVAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SWPROFVAL` writer - Software Profiling register: used by BLE Software for profiling purpose: this value is copied on Diagnostic port"] +pub struct SWPROFVAL_W<'a> { + w: &'a mut W, +} +impl<'a> SWPROFVAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - Software Profiling register: used by BLE Software for profiling purpose: this value is copied on Diagnostic port"] + #[inline(always)] + pub fn swprofval(&self) -> SWPROFVAL_R { + SWPROFVAL_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - Software Profiling register: used by BLE Software for profiling purpose: this value is copied on Diagnostic port"] + #[inline(always)] + pub fn swprofval(&mut self) -> SWPROFVAL_W { + SWPROFVAL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Software Profiling register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_swprofiling_reg](index.html) module"] +pub struct BLE_SWPROFILING_REG_SPEC; +impl crate::RegisterSpec for BLE_SWPROFILING_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_swprofiling_reg::R](R) reader structure"] +impl crate::Readable for BLE_SWPROFILING_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_swprofiling_reg::W](W) writer structure"] +impl crate::Writable for BLE_SWPROFILING_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_SWPROFILING_REG to value 0"] +impl crate::Resettable for BLE_SWPROFILING_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_timgencntl_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_timgencntl_reg.rs new file mode 100644 index 0000000..daa3426 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_timgencntl_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `BLE_TIMGENCNTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_TIMGENCNTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `APFM_EN` reader - Controls the Anticipated pre-Fetch Abort mechanism 0: Disabled 1: Enabled"] +pub struct APFM_EN_R(crate::FieldReader); +impl APFM_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + APFM_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for APFM_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `APFM_EN` writer - Controls the Anticipated pre-Fetch Abort mechanism 0: Disabled 1: Enabled"] +pub struct APFM_EN_W<'a> { + w: &'a mut W, +} +impl<'a> APFM_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `PREFETCHABORT_TIME` reader - Defines the instant in usec at which immediate abort is required after anticipated pre-fetch abort."] +pub struct PREFETCHABORT_TIME_R(crate::FieldReader); +impl PREFETCHABORT_TIME_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + PREFETCHABORT_TIME_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PREFETCHABORT_TIME_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PREFETCHABORT_TIME` writer - Defines the instant in usec at which immediate abort is required after anticipated pre-fetch abort."] +pub struct PREFETCHABORT_TIME_W<'a> { + w: &'a mut W, +} +impl<'a> PREFETCHABORT_TIME_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x03ff << 16)) | ((value as u32 & 0x03ff) << 16); + self.w + } +} +#[doc = "Field `PREFETCH_TIME` reader - Defines Exchange Table pre-fetch instant in us"] +pub struct PREFETCH_TIME_R(crate::FieldReader); +impl PREFETCH_TIME_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + PREFETCH_TIME_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PREFETCH_TIME_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PREFETCH_TIME` writer - Defines Exchange Table pre-fetch instant in us"] +pub struct PREFETCH_TIME_W<'a> { + w: &'a mut W, +} +impl<'a> PREFETCH_TIME_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x01ff) | (value as u32 & 0x01ff); + self.w + } +} +impl R { + #[doc = "Bit 31 - Controls the Anticipated pre-Fetch Abort mechanism 0: Disabled 1: Enabled"] + #[inline(always)] + pub fn apfm_en(&self) -> APFM_EN_R { + APFM_EN_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bits 16:25 - Defines the instant in usec at which immediate abort is required after anticipated pre-fetch abort."] + #[inline(always)] + pub fn prefetchabort_time(&self) -> PREFETCHABORT_TIME_R { + PREFETCHABORT_TIME_R::new(((self.bits >> 16) & 0x03ff) as u16) + } + #[doc = "Bits 0:8 - Defines Exchange Table pre-fetch instant in us"] + #[inline(always)] + pub fn prefetch_time(&self) -> PREFETCH_TIME_R { + PREFETCH_TIME_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Bit 31 - Controls the Anticipated pre-Fetch Abort mechanism 0: Disabled 1: Enabled"] + #[inline(always)] + pub fn apfm_en(&mut self) -> APFM_EN_W { + APFM_EN_W { w: self } + } + #[doc = "Bits 16:25 - Defines the instant in usec at which immediate abort is required after anticipated pre-fetch abort."] + #[inline(always)] + pub fn prefetchabort_time(&mut self) -> PREFETCHABORT_TIME_W { + PREFETCHABORT_TIME_W { w: self } + } + #[doc = "Bits 0:8 - Defines Exchange Table pre-fetch instant in us"] + #[inline(always)] + pub fn prefetch_time(&mut self) -> PREFETCH_TIME_W { + PREFETCH_TIME_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timing Generator Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_timgencntl_reg](index.html) module"] +pub struct BLE_TIMGENCNTL_REG_SPEC; +impl crate::RegisterSpec for BLE_TIMGENCNTL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_timgencntl_reg::R](R) reader structure"] +impl crate::Readable for BLE_TIMGENCNTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_timgencntl_reg::W](W) writer structure"] +impl crate::Writable for BLE_TIMGENCNTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_TIMGENCNTL_REG to value 0x7fff_ffff"] +impl crate::Resettable for BLE_TIMGENCNTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7fff_ffff + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_txmicval_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_txmicval_reg.rs new file mode 100644 index 0000000..64a9a47 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_txmicval_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `BLE_TXMICVAL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_TXMICVAL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TXMICVAL` reader - AES-CCM plain MIC value. Valid on when MIC has been calculated (in Tx)"] +pub struct TXMICVAL_R(crate::FieldReader); +impl TXMICVAL_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + TXMICVAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXMICVAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:31 - AES-CCM plain MIC value. Valid on when MIC has been calculated (in Tx)"] + #[inline(always)] + pub fn txmicval(&self) -> TXMICVAL_R { + TXMICVAL_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "AES / CCM plain MIC value\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_txmicval_reg](index.html) module"] +pub struct BLE_TXMICVAL_REG_SPEC; +impl crate::RegisterSpec for BLE_TXMICVAL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_txmicval_reg::R](R) reader structure"] +impl crate::Readable for BLE_TXMICVAL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_txmicval_reg::W](W) writer structure"] +impl crate::Writable for BLE_TXMICVAL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_TXMICVAL_REG to value 0"] +impl crate::Resettable for BLE_TXMICVAL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_version_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_version_reg.rs new file mode 100644 index 0000000..17ea898 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_version_reg.rs @@ -0,0 +1,146 @@ +#[doc = "Register `BLE_VERSION_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_VERSION_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TYP` reader - BLE Core Type"] +pub struct TYP_R(crate::FieldReader); +impl TYP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TYP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TYP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REL` reader - BLE Core version Major release number."] +pub struct REL_R(crate::FieldReader); +impl REL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + REL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UPG` reader - BLE Core upgrade Upgrade number."] +pub struct UPG_R(crate::FieldReader); +impl UPG_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UPG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UPG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BUILD` reader - BLE Core Build Build number."] +pub struct BUILD_R(crate::FieldReader); +impl BUILD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BUILD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BUILD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 24:31 - BLE Core Type"] + #[inline(always)] + pub fn typ(&self) -> TYP_R { + TYP_R::new(((self.bits >> 24) & 0xff) as u8) + } + #[doc = "Bits 16:23 - BLE Core version Major release number."] + #[inline(always)] + pub fn rel(&self) -> REL_R { + REL_R::new(((self.bits >> 16) & 0xff) as u8) + } + #[doc = "Bits 8:15 - BLE Core upgrade Upgrade number."] + #[inline(always)] + pub fn upg(&self) -> UPG_R { + UPG_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7 - BLE Core Build Build number."] + #[inline(always)] + pub fn build(&self) -> BUILD_R { + BUILD_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Version register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_version_reg](index.html) module"] +pub struct BLE_VERSION_REG_SPEC; +impl crate::RegisterSpec for BLE_VERSION_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_version_reg::R](R) reader structure"] +impl crate::Readable for BLE_VERSION_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_version_reg::W](W) writer structure"] +impl crate::Writable for BLE_VERSION_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_VERSION_REG to value 0x0701_0000"] +impl crate::Resettable for BLE_VERSION_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0701_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_wlnbdev_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_wlnbdev_reg.rs new file mode 100644 index 0000000..97529d8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_wlnbdev_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `BLE_WLNBDEV_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_WLNBDEV_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `NBPRIVDEV` reader - Number of private devices in the white list."] +pub struct NBPRIVDEV_R(crate::FieldReader); +impl NBPRIVDEV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + NBPRIVDEV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for NBPRIVDEV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `NBPRIVDEV` writer - Number of private devices in the white list."] +pub struct NBPRIVDEV_W<'a> { + w: &'a mut W, +} +impl<'a> NBPRIVDEV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `NBPUBDEV` reader - Number of public devices in the white list."] +pub struct NBPUBDEV_R(crate::FieldReader); +impl NBPUBDEV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + NBPUBDEV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for NBPUBDEV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `NBPUBDEV` writer - Number of public devices in the white list."] +pub struct NBPUBDEV_W<'a> { + w: &'a mut W, +} +impl<'a> NBPUBDEV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15 - Number of private devices in the white list."] + #[inline(always)] + pub fn nbprivdev(&self) -> NBPRIVDEV_R { + NBPRIVDEV_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7 - Number of public devices in the white list."] + #[inline(always)] + pub fn nbpubdev(&self) -> NBPUBDEV_R { + NBPUBDEV_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15 - Number of private devices in the white list."] + #[inline(always)] + pub fn nbprivdev(&mut self) -> NBPRIVDEV_W { + NBPRIVDEV_W { w: self } + } + #[doc = "Bits 0:7 - Number of public devices in the white list."] + #[inline(always)] + pub fn nbpubdev(&mut self) -> NBPUBDEV_W { + NBPUBDEV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Devices in white list\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_wlnbdev_reg](index.html) module"] +pub struct BLE_WLNBDEV_REG_SPEC; +impl crate::RegisterSpec for BLE_WLNBDEV_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_wlnbdev_reg::R](R) reader structure"] +impl crate::Readable for BLE_WLNBDEV_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_wlnbdev_reg::W](W) writer structure"] +impl crate::Writable for BLE_WLNBDEV_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_WLNBDEV_REG to value 0"] +impl crate::Resettable for BLE_WLNBDEV_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_wlprivaddptr_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_wlprivaddptr_reg.rs new file mode 100644 index 0000000..03ca9a6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_wlprivaddptr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_WLPRIVADDPTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_WLPRIVADDPTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WLPRIVADDPTR` reader - Start address pointer of the private devices white list."] +pub struct WLPRIVADDPTR_R(crate::FieldReader); +impl WLPRIVADDPTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + WLPRIVADDPTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLPRIVADDPTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLPRIVADDPTR` writer - Start address pointer of the private devices white list."] +pub struct WLPRIVADDPTR_W<'a> { + w: &'a mut W, +} +impl<'a> WLPRIVADDPTR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bits 0:15 - Start address pointer of the private devices white list."] + #[inline(always)] + pub fn wlprivaddptr(&self) -> WLPRIVADDPTR_R { + WLPRIVADDPTR_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bits 0:15 - Start address pointer of the private devices white list."] + #[inline(always)] + pub fn wlprivaddptr(&mut self) -> WLPRIVADDPTR_W { + WLPRIVADDPTR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Start address of private devices list\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_wlprivaddptr_reg](index.html) module"] +pub struct BLE_WLPRIVADDPTR_REG_SPEC; +impl crate::RegisterSpec for BLE_WLPRIVADDPTR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_wlprivaddptr_reg::R](R) reader structure"] +impl crate::Readable for BLE_WLPRIVADDPTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_wlprivaddptr_reg::W](W) writer structure"] +impl crate::Writable for BLE_WLPRIVADDPTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_WLPRIVADDPTR_REG to value 0"] +impl crate::Resettable for BLE_WLPRIVADDPTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/ble/ble_wlpubaddptr_reg.rs b/bitbox02-bt/vendor/da14531/src/ble/ble_wlpubaddptr_reg.rs new file mode 100644 index 0000000..5d0fb45 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/ble/ble_wlpubaddptr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_WLPUBADDPTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_WLPUBADDPTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WLPUBADDPTR` reader - Start address pointer of the public devices white list."] +pub struct WLPUBADDPTR_R(crate::FieldReader); +impl WLPUBADDPTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + WLPUBADDPTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WLPUBADDPTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WLPUBADDPTR` writer - Start address pointer of the public devices white list."] +pub struct WLPUBADDPTR_W<'a> { + w: &'a mut W, +} +impl<'a> WLPUBADDPTR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bits 0:15 - Start address pointer of the public devices white list."] + #[inline(always)] + pub fn wlpubaddptr(&self) -> WLPUBADDPTR_R { + WLPUBADDPTR_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bits 0:15 - Start address pointer of the public devices white list."] + #[inline(always)] + pub fn wlpubaddptr(&mut self) -> WLPUBADDPTR_W { + WLPUBADDPTR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Start address of public devices list\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_wlpubaddptr_reg](index.html) module"] +pub struct BLE_WLPUBADDPTR_REG_SPEC; +impl crate::RegisterSpec for BLE_WLPUBADDPTR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ble_wlpubaddptr_reg::R](R) reader structure"] +impl crate::Readable for BLE_WLPUBADDPTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_wlpubaddptr_reg::W](W) writer structure"] +impl crate::Writable for BLE_WLPUBADDPTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_WLPUBADDPTR_REG to value 0"] +impl crate::Resettable for BLE_WLPUBADDPTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version.rs b/bitbox02-bt/vendor/da14531/src/chip_version.rs new file mode 100644 index 0000000..243454b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version.rs @@ -0,0 +1,59 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Chip identification register 1."] + pub chip_id1_reg: crate::Reg, + _reserved1: [u8; 0x02], + #[doc = "0x04 - Chip identification register 2."] + pub chip_id2_reg: crate::Reg, + _reserved2: [u8; 0x02], + #[doc = "0x08 - Chip identification register 3."] + pub chip_id3_reg: crate::Reg, + _reserved3: [u8; 0x02], + #[doc = "0x0c - Chip identification register 4."] + pub chip_id4_reg: crate::Reg, + _reserved4: [u8; 0x02], + #[doc = "0x10 - "] + pub chip_swc_reg: crate::Reg, + _reserved5: [u8; 0x02], + #[doc = "0x14 - "] + pub chip_revision_reg: crate::Reg, + _reserved6: [u8; 0xe2], + #[doc = "0xf8 - "] + pub chip_test1_reg: crate::Reg, + _reserved7: [u8; 0x02], + #[doc = "0xfc - "] + pub chip_test2_reg: crate::Reg, +} +#[doc = "CHIP_ID1_REG register accessor: an alias for `Reg`"] +pub type CHIP_ID1_REG = crate::Reg; +#[doc = "Chip identification register 1."] +pub mod chip_id1_reg; +#[doc = "CHIP_ID2_REG register accessor: an alias for `Reg`"] +pub type CHIP_ID2_REG = crate::Reg; +#[doc = "Chip identification register 2."] +pub mod chip_id2_reg; +#[doc = "CHIP_ID3_REG register accessor: an alias for `Reg`"] +pub type CHIP_ID3_REG = crate::Reg; +#[doc = "Chip identification register 3."] +pub mod chip_id3_reg; +#[doc = "CHIP_ID4_REG register accessor: an alias for `Reg`"] +pub type CHIP_ID4_REG = crate::Reg; +#[doc = "Chip identification register 4."] +pub mod chip_id4_reg; +#[doc = "CHIP_REVISION_REG register accessor: an alias for `Reg`"] +pub type CHIP_REVISION_REG = crate::Reg; +#[doc = ""] +pub mod chip_revision_reg; +#[doc = "CHIP_SWC_REG register accessor: an alias for `Reg`"] +pub type CHIP_SWC_REG = crate::Reg; +#[doc = ""] +pub mod chip_swc_reg; +#[doc = "CHIP_TEST1_REG register accessor: an alias for `Reg`"] +pub type CHIP_TEST1_REG = crate::Reg; +#[doc = ""] +pub mod chip_test1_reg; +#[doc = "CHIP_TEST2_REG register accessor: an alias for `Reg`"] +pub type CHIP_TEST2_REG = crate::Reg; +#[doc = ""] +pub mod chip_test2_reg; diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_id1_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id1_reg.rs new file mode 100644 index 0000000..d628f8d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id1_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_ID1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_ID1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_ID1` reader - First character of device type \"2632\" in ASCII."] +pub struct CHIP_ID1_R(crate::FieldReader); +impl CHIP_ID1_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_ID1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_ID1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7 - First character of device type \"2632\" in ASCII."] + #[inline(always)] + pub fn chip_id1(&self) -> CHIP_ID1_R { + CHIP_ID1_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Chip identification register 1.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_id1_reg](index.html) module"] +pub struct CHIP_ID1_REG_SPEC; +impl crate::RegisterSpec for CHIP_ID1_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_id1_reg::R](R) reader structure"] +impl crate::Readable for CHIP_ID1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_id1_reg::W](W) writer structure"] +impl crate::Writable for CHIP_ID1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_ID1_REG to value 0x32"] +impl crate::Resettable for CHIP_ID1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x32 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_id2_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id2_reg.rs new file mode 100644 index 0000000..8b46caa --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id2_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_ID2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_ID2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_ID2` reader - Second character of device type \"2632\" in ASCII."] +pub struct CHIP_ID2_R(crate::FieldReader); +impl CHIP_ID2_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_ID2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_ID2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7 - Second character of device type \"2632\" in ASCII."] + #[inline(always)] + pub fn chip_id2(&self) -> CHIP_ID2_R { + CHIP_ID2_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Chip identification register 2.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_id2_reg](index.html) module"] +pub struct CHIP_ID2_REG_SPEC; +impl crate::RegisterSpec for CHIP_ID2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_id2_reg::R](R) reader structure"] +impl crate::Readable for CHIP_ID2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_id2_reg::W](W) writer structure"] +impl crate::Writable for CHIP_ID2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_ID2_REG to value 0x36"] +impl crate::Resettable for CHIP_ID2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x36 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_id3_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id3_reg.rs new file mode 100644 index 0000000..3d06699 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id3_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_ID3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_ID3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_ID3` reader - Third character of device type \"2632\" in ASCII."] +pub struct CHIP_ID3_R(crate::FieldReader); +impl CHIP_ID3_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_ID3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_ID3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7 - Third character of device type \"2632\" in ASCII."] + #[inline(always)] + pub fn chip_id3(&self) -> CHIP_ID3_R { + CHIP_ID3_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Chip identification register 3.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_id3_reg](index.html) module"] +pub struct CHIP_ID3_REG_SPEC; +impl crate::RegisterSpec for CHIP_ID3_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_id3_reg::R](R) reader structure"] +impl crate::Readable for CHIP_ID3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_id3_reg::W](W) writer structure"] +impl crate::Writable for CHIP_ID3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_ID3_REG to value 0x33"] +impl crate::Resettable for CHIP_ID3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x33 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_id4_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id4_reg.rs new file mode 100644 index 0000000..bfce48a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_id4_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_ID4_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_ID4_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_ID4` reader - Fourth character of device type \"2632\" in ASCII."] +pub struct CHIP_ID4_R(crate::FieldReader); +impl CHIP_ID4_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_ID4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_ID4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7 - Fourth character of device type \"2632\" in ASCII."] + #[inline(always)] + pub fn chip_id4(&self) -> CHIP_ID4_R { + CHIP_ID4_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Chip identification register 4.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_id4_reg](index.html) module"] +pub struct CHIP_ID4_REG_SPEC; +impl crate::RegisterSpec for CHIP_ID4_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_id4_reg::R](R) reader structure"] +impl crate::Readable for CHIP_ID4_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_id4_reg::W](W) writer structure"] +impl crate::Writable for CHIP_ID4_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_ID4_REG to value 0x32"] +impl crate::Resettable for CHIP_ID4_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x32 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_revision_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_revision_reg.rs new file mode 100644 index 0000000..795cdd9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_revision_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_REVISION_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_REVISION_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_REVISION` reader - "] +pub struct CHIP_REVISION_R(crate::FieldReader); +impl CHIP_REVISION_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_REVISION_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_REVISION_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn chip_revision(&self) -> CHIP_REVISION_R { + CHIP_REVISION_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_revision_reg](index.html) module"] +pub struct CHIP_REVISION_REG_SPEC; +impl crate::RegisterSpec for CHIP_REVISION_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_revision_reg::R](R) reader structure"] +impl crate::Readable for CHIP_REVISION_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_revision_reg::W](W) writer structure"] +impl crate::Writable for CHIP_REVISION_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_REVISION_REG to value 0x41"] +impl crate::Resettable for CHIP_REVISION_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x41 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_swc_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_swc_reg.rs new file mode 100644 index 0000000..9e0b0a5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_swc_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_SWC_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_SWC_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_SWC` reader - "] +pub struct CHIP_SWC_R(crate::FieldReader); +impl CHIP_SWC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_SWC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_SWC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn chip_swc(&self) -> CHIP_SWC_R { + CHIP_SWC_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_swc_reg](index.html) module"] +pub struct CHIP_SWC_REG_SPEC; +impl crate::RegisterSpec for CHIP_SWC_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_swc_reg::R](R) reader structure"] +impl crate::Readable for CHIP_SWC_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_swc_reg::W](W) writer structure"] +impl crate::Writable for CHIP_SWC_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_SWC_REG to value 0"] +impl crate::Resettable for CHIP_SWC_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_test1_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_test1_reg.rs new file mode 100644 index 0000000..fc7a510 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_test1_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_TEST1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_TEST1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_LAYOUT_REVISION` reader - "] +pub struct CHIP_LAYOUT_REVISION_R(crate::FieldReader); +impl CHIP_LAYOUT_REVISION_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_LAYOUT_REVISION_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_LAYOUT_REVISION_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn chip_layout_revision(&self) -> CHIP_LAYOUT_REVISION_R { + CHIP_LAYOUT_REVISION_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_test1_reg](index.html) module"] +pub struct CHIP_TEST1_REG_SPEC; +impl crate::RegisterSpec for CHIP_TEST1_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_test1_reg::R](R) reader structure"] +impl crate::Readable for CHIP_TEST1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_test1_reg::W](W) writer structure"] +impl crate::Writable for CHIP_TEST1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_TEST1_REG to value 0x41"] +impl crate::Resettable for CHIP_TEST1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x41 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/chip_version/chip_test2_reg.rs b/bitbox02-bt/vendor/da14531/src/chip_version/chip_test2_reg.rs new file mode 100644 index 0000000..c69195f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/chip_version/chip_test2_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `CHIP_TEST2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CHIP_TEST2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CHIP_METAL_OPTION` reader - "] +pub struct CHIP_METAL_OPTION_R(crate::FieldReader); +impl CHIP_METAL_OPTION_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CHIP_METAL_OPTION_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHIP_METAL_OPTION_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn chip_metal_option(&self) -> CHIP_METAL_OPTION_R { + CHIP_METAL_OPTION_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [chip_test2_reg](index.html) module"] +pub struct CHIP_TEST2_REG_SPEC; +impl crate::RegisterSpec for CHIP_TEST2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [chip_test2_reg::R](R) reader structure"] +impl crate::Readable for CHIP_TEST2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [chip_test2_reg::W](W) writer structure"] +impl crate::Writable for CHIP_TEST2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CHIP_TEST2_REG to value 0"] +impl crate::Resettable for CHIP_TEST2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon.rs b/bitbox02-bt/vendor/da14531/src/crg_aon.rs new file mode 100644 index 0000000..4273171 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon.rs @@ -0,0 +1,59 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Hardware Reset control register"] + pub hwr_ctrl_reg: crate::Reg, + _reserved1: [u8; 0x02], + #[doc = "0x04 - Reset status register"] + pub reset_stat_reg: crate::Reg, + _reserved2: [u8; 0x02], + #[doc = "0x08 - "] + pub ram_lpmx_reg: crate::Reg, + _reserved3: [u8; 0x02], + #[doc = "0x0c - Control the state retention of the GPIO ports"] + pub pad_latch_reg: crate::Reg, + _reserved4: [u8; 0x02], + #[doc = "0x10 - Hibernation control register"] + pub hibern_ctrl_reg: crate::Reg, + _reserved5: [u8; 0x0e], + #[doc = "0x20 - "] + pub power_aon_ctrl_reg: crate::Reg, + _reserved6: [u8; 0x02], + #[doc = "0x24 - "] + pub gp_data_reg: crate::Reg, + _reserved7: [u8; 0xca], + #[doc = "0xf0 - "] + pub test_vdd_reg: crate::Reg, +} +#[doc = "GP_DATA_REG register accessor: an alias for `Reg`"] +pub type GP_DATA_REG = crate::Reg; +#[doc = ""] +pub mod gp_data_reg; +#[doc = "HIBERN_CTRL_REG register accessor: an alias for `Reg`"] +pub type HIBERN_CTRL_REG = crate::Reg; +#[doc = "Hibernation control register"] +pub mod hibern_ctrl_reg; +#[doc = "HWR_CTRL_REG register accessor: an alias for `Reg`"] +pub type HWR_CTRL_REG = crate::Reg; +#[doc = "Hardware Reset control register"] +pub mod hwr_ctrl_reg; +#[doc = "PAD_LATCH_REG register accessor: an alias for `Reg`"] +pub type PAD_LATCH_REG = crate::Reg; +#[doc = "Control the state retention of the GPIO ports"] +pub mod pad_latch_reg; +#[doc = "POWER_AON_CTRL_REG register accessor: an alias for `Reg`"] +pub type POWER_AON_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod power_aon_ctrl_reg; +#[doc = "RAM_LPMX_REG register accessor: an alias for `Reg`"] +pub type RAM_LPMX_REG = crate::Reg; +#[doc = ""] +pub mod ram_lpmx_reg; +#[doc = "RESET_STAT_REG register accessor: an alias for `Reg`"] +pub type RESET_STAT_REG = crate::Reg; +#[doc = "Reset status register"] +pub mod reset_stat_reg; +#[doc = "TEST_VDD_REG register accessor: an alias for `Reg`"] +pub type TEST_VDD_REG = crate::Reg; +#[doc = ""] +pub mod test_vdd_reg; diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/gp_data_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/gp_data_reg.rs new file mode 100644 index 0000000..58d0f2e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/gp_data_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `GP_DATA_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_DATA_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ANA_SPARE` reader - "] +pub struct ANA_SPARE_R(crate::FieldReader); +impl ANA_SPARE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ANA_SPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ANA_SPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ANA_SPARE` writer - "] +pub struct ANA_SPARE_W<'a> { + w: &'a mut W, +} +impl<'a> ANA_SPARE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 5)) | ((value as u16 & 7) << 5); + self.w + } +} +#[doc = "Field `DISABLE_CLAMP_OVERRULE` reader - "] +pub struct DISABLE_CLAMP_OVERRULE_R(crate::FieldReader); +impl DISABLE_CLAMP_OVERRULE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DISABLE_CLAMP_OVERRULE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DISABLE_CLAMP_OVERRULE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DISABLE_CLAMP_OVERRULE` writer - "] +pub struct DISABLE_CLAMP_OVERRULE_W<'a> { + w: &'a mut W, +} +impl<'a> DISABLE_CLAMP_OVERRULE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `SW_GP_DATA` reader - "] +pub struct SW_GP_DATA_R(crate::FieldReader); +impl SW_GP_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SW_GP_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SW_GP_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SW_GP_DATA` writer - "] +pub struct SW_GP_DATA_W<'a> { + w: &'a mut W, +} +impl<'a> SW_GP_DATA_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 5:7"] + #[inline(always)] + pub fn ana_spare(&self) -> ANA_SPARE_R { + ANA_SPARE_R::new(((self.bits >> 5) & 7) as u8) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn disable_clamp_overrule(&self) -> DISABLE_CLAMP_OVERRULE_R { + DISABLE_CLAMP_OVERRULE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn sw_gp_data(&self) -> SW_GP_DATA_R { + SW_GP_DATA_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 5:7"] + #[inline(always)] + pub fn ana_spare(&mut self) -> ANA_SPARE_W { + ANA_SPARE_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn disable_clamp_overrule(&mut self) -> DISABLE_CLAMP_OVERRULE_W { + DISABLE_CLAMP_OVERRULE_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn sw_gp_data(&mut self) -> SW_GP_DATA_W { + SW_GP_DATA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_data_reg](index.html) module"] +pub struct GP_DATA_REG_SPEC; +impl crate::RegisterSpec for GP_DATA_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_data_reg::R](R) reader structure"] +impl crate::Readable for GP_DATA_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_data_reg::W](W) writer structure"] +impl crate::Writable for GP_DATA_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_DATA_REG to value 0"] +impl crate::Resettable for GP_DATA_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/hibern_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/hibern_ctrl_reg.rs new file mode 100644 index 0000000..4da7f77 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/hibern_ctrl_reg.rs @@ -0,0 +1,201 @@ +#[doc = "Register `HIBERN_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `HIBERN_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `HIBERN_WKUP_MASK` reader - Selects which pin to wakeup from"] +pub struct HIBERN_WKUP_MASK_R(crate::FieldReader); +impl HIBERN_WKUP_MASK_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + HIBERN_WKUP_MASK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HIBERN_WKUP_MASK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HIBERN_WKUP_MASK` writer - Selects which pin to wakeup from"] +pub struct HIBERN_WKUP_MASK_W<'a> { + w: &'a mut W, +} +impl<'a> HIBERN_WKUP_MASK_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 2)) | ((value as u16 & 0x1f) << 2); + self.w + } +} +#[doc = "Field `HIBERN_WKUP_POLARITY` reader - Selects the polarity of the wakeup source. The polarity must be chosen such that the ANA_STATUS_REG\\[CLKLESS_WAKEUP_STAT\\] +is '1'. Any change on the selected GPIOs will make the CLKLESS_WAKEUP_STAT go to '0', and wakeup the system from hibernation."] +pub struct HIBERN_WKUP_POLARITY_R(crate::FieldReader); +impl HIBERN_WKUP_POLARITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + HIBERN_WKUP_POLARITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HIBERN_WKUP_POLARITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HIBERN_WKUP_POLARITY` writer - Selects the polarity of the wakeup source. The polarity must be chosen such that the ANA_STATUS_REG\\[CLKLESS_WAKEUP_STAT\\] +is '1'. Any change on the selected GPIOs will make the CLKLESS_WAKEUP_STAT go to '0', and wakeup the system from hibernation."] +pub struct HIBERN_WKUP_POLARITY_W<'a> { + w: &'a mut W, +} +impl<'a> HIBERN_WKUP_POLARITY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `HIBERNATION_ENABLE` reader - Enables the hibernation mode when sleeping 0: deep sleep mode, PD_SLP remains on 1: hibernation mode, PD_SLP goes off. REMAP_ADR0 needs to be set to the correct source to boot from before going to sleep."] +pub struct HIBERNATION_ENABLE_R(crate::FieldReader); +impl HIBERNATION_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + HIBERNATION_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HIBERNATION_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HIBERNATION_ENABLE` writer - Enables the hibernation mode when sleeping 0: deep sleep mode, PD_SLP remains on 1: hibernation mode, PD_SLP goes off. REMAP_ADR0 needs to be set to the correct source to boot from before going to sleep."] +pub struct HIBERNATION_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> HIBERNATION_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 2:6 - Selects which pin to wakeup from"] + #[inline(always)] + pub fn hibern_wkup_mask(&self) -> HIBERN_WKUP_MASK_R { + HIBERN_WKUP_MASK_R::new(((self.bits >> 2) & 0x1f) as u8) + } + #[doc = "Bit 1 - Selects the polarity of the wakeup source. The polarity must be chosen such that the ANA_STATUS_REG\\[CLKLESS_WAKEUP_STAT\\] +is '1'. Any change on the selected GPIOs will make the CLKLESS_WAKEUP_STAT go to '0', and wakeup the system from hibernation."] + #[inline(always)] + pub fn hibern_wkup_polarity(&self) -> HIBERN_WKUP_POLARITY_R { + HIBERN_WKUP_POLARITY_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Enables the hibernation mode when sleeping 0: deep sleep mode, PD_SLP remains on 1: hibernation mode, PD_SLP goes off. REMAP_ADR0 needs to be set to the correct source to boot from before going to sleep."] + #[inline(always)] + pub fn hibernation_enable(&self) -> HIBERNATION_ENABLE_R { + HIBERNATION_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 2:6 - Selects which pin to wakeup from"] + #[inline(always)] + pub fn hibern_wkup_mask(&mut self) -> HIBERN_WKUP_MASK_W { + HIBERN_WKUP_MASK_W { w: self } + } + #[doc = "Bit 1 - Selects the polarity of the wakeup source. The polarity must be chosen such that the ANA_STATUS_REG\\[CLKLESS_WAKEUP_STAT\\] +is '1'. Any change on the selected GPIOs will make the CLKLESS_WAKEUP_STAT go to '0', and wakeup the system from hibernation."] + #[inline(always)] + pub fn hibern_wkup_polarity(&mut self) -> HIBERN_WKUP_POLARITY_W { + HIBERN_WKUP_POLARITY_W { w: self } + } + #[doc = "Bit 0 - Enables the hibernation mode when sleeping 0: deep sleep mode, PD_SLP remains on 1: hibernation mode, PD_SLP goes off. REMAP_ADR0 needs to be set to the correct source to boot from before going to sleep."] + #[inline(always)] + pub fn hibernation_enable(&mut self) -> HIBERNATION_ENABLE_W { + HIBERNATION_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Hibernation control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [hibern_ctrl_reg](index.html) module"] +pub struct HIBERN_CTRL_REG_SPEC; +impl crate::RegisterSpec for HIBERN_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [hibern_ctrl_reg::R](R) reader structure"] +impl crate::Readable for HIBERN_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [hibern_ctrl_reg::W](W) writer structure"] +impl crate::Writable for HIBERN_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets HIBERN_CTRL_REG to value 0"] +impl crate::Resettable for HIBERN_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/hwr_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/hwr_ctrl_reg.rs new file mode 100644 index 0000000..02ff9cf --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/hwr_ctrl_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `HWR_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `HWR_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DISABLE_HWR` reader - Disables the RST functionality on P00"] +pub struct DISABLE_HWR_R(crate::FieldReader); +impl DISABLE_HWR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DISABLE_HWR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DISABLE_HWR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DISABLE_HWR` writer - Disables the RST functionality on P00"] +pub struct DISABLE_HWR_W<'a> { + w: &'a mut W, +} +impl<'a> DISABLE_HWR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Disables the RST functionality on P00"] + #[inline(always)] + pub fn disable_hwr(&self) -> DISABLE_HWR_R { + DISABLE_HWR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Disables the RST functionality on P00"] + #[inline(always)] + pub fn disable_hwr(&mut self) -> DISABLE_HWR_W { + DISABLE_HWR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Hardware Reset control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [hwr_ctrl_reg](index.html) module"] +pub struct HWR_CTRL_REG_SPEC; +impl crate::RegisterSpec for HWR_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [hwr_ctrl_reg::R](R) reader structure"] +impl crate::Readable for HWR_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [hwr_ctrl_reg::W](W) writer structure"] +impl crate::Writable for HWR_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets HWR_CTRL_REG to value 0"] +impl crate::Resettable for HWR_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/pad_latch_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/pad_latch_reg.rs new file mode 100644 index 0000000..c2beb88 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/pad_latch_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `PAD_LATCH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PAD_LATCH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PAD_LATCH_EN` reader - Controls the state retention of the pads. 0: latches are closed, pads retain their state. 1: latches are open, new control values have immediate effect"] +pub struct PAD_LATCH_EN_R(crate::FieldReader); +impl PAD_LATCH_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PAD_LATCH_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PAD_LATCH_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PAD_LATCH_EN` writer - Controls the state retention of the pads. 0: latches are closed, pads retain their state. 1: latches are open, new control values have immediate effect"] +pub struct PAD_LATCH_EN_W<'a> { + w: &'a mut W, +} +impl<'a> PAD_LATCH_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Controls the state retention of the pads. 0: latches are closed, pads retain their state. 1: latches are open, new control values have immediate effect"] + #[inline(always)] + pub fn pad_latch_en(&self) -> PAD_LATCH_EN_R { + PAD_LATCH_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Controls the state retention of the pads. 0: latches are closed, pads retain their state. 1: latches are open, new control values have immediate effect"] + #[inline(always)] + pub fn pad_latch_en(&mut self) -> PAD_LATCH_EN_W { + PAD_LATCH_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Control the state retention of the GPIO ports\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pad_latch_reg](index.html) module"] +pub struct PAD_LATCH_REG_SPEC; +impl crate::RegisterSpec for PAD_LATCH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pad_latch_reg::R](R) reader structure"] +impl crate::Readable for PAD_LATCH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pad_latch_reg::W](W) writer structure"] +impl crate::Writable for PAD_LATCH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PAD_LATCH_REG to value 0x01"] +impl crate::Resettable for PAD_LATCH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/power_aon_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/power_aon_ctrl_reg.rs new file mode 100644 index 0000000..3567821 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/power_aon_ctrl_reg.rs @@ -0,0 +1,506 @@ +#[doc = "Register `POWER_AON_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `POWER_AON_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FORCE_RUNNING_COMP_DIS` reader - "] +pub struct FORCE_RUNNING_COMP_DIS_R(crate::FieldReader); +impl FORCE_RUNNING_COMP_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FORCE_RUNNING_COMP_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FORCE_RUNNING_COMP_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FORCE_RUNNING_COMP_DIS` writer - "] +pub struct FORCE_RUNNING_COMP_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> FORCE_RUNNING_COMP_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u16 & 1) << 14); + self.w + } +} +#[doc = "Field `LDO_RET_TRIM` reader - VDD clamp level setting for hibernation mode"] +pub struct LDO_RET_TRIM_R(crate::FieldReader); +impl LDO_RET_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_RET_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_RET_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_RET_TRIM` writer - VDD clamp level setting for hibernation mode"] +pub struct LDO_RET_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_RET_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 10)) | ((value as u16 & 0x0f) << 10); + self.w + } +} +#[doc = "Field `CMP_VCONT_SLP_DISABLE` reader - Disable vcont comparator in SLP"] +pub struct CMP_VCONT_SLP_DISABLE_R(crate::FieldReader); +impl CMP_VCONT_SLP_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CMP_VCONT_SLP_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CMP_VCONT_SLP_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CMP_VCONT_SLP_DISABLE` writer - Disable vcont comparator in SLP"] +pub struct CMP_VCONT_SLP_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> CMP_VCONT_SLP_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `BOOST_MODE_FORCE` reader - 0x:automatic selection of boost mode 11: force boost mode 10: force buck mode"] +pub struct BOOST_MODE_FORCE_R(crate::FieldReader); +impl BOOST_MODE_FORCE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BOOST_MODE_FORCE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BOOST_MODE_FORCE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BOOST_MODE_FORCE` writer - 0x:automatic selection of boost mode 11: force boost mode 10: force buck mode"] +pub struct BOOST_MODE_FORCE_W<'a> { + w: &'a mut W, +} +impl<'a> BOOST_MODE_FORCE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 7)) | ((value as u16 & 3) << 7); + self.w + } +} +#[doc = "Field `CHARGE_VBAT_DISABLE` reader - Do not charge vbat high in boost mode"] +pub struct CHARGE_VBAT_DISABLE_R(crate::FieldReader); +impl CHARGE_VBAT_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CHARGE_VBAT_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CHARGE_VBAT_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CHARGE_VBAT_DISABLE` writer - Do not charge vbat high in boost mode"] +pub struct CHARGE_VBAT_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> CHARGE_VBAT_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `RC32K_LOW_SPEED_FORCE` reader - "] +pub struct RC32K_LOW_SPEED_FORCE_R(crate::FieldReader); +impl RC32K_LOW_SPEED_FORCE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RC32K_LOW_SPEED_FORCE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32K_LOW_SPEED_FORCE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32K_LOW_SPEED_FORCE` writer - "] +pub struct RC32K_LOW_SPEED_FORCE_W<'a> { + w: &'a mut W, +} +impl<'a> RC32K_LOW_SPEED_FORCE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `RC32K_HIGH_SPEED_FORCE` reader - "] +pub struct RC32K_HIGH_SPEED_FORCE_R(crate::FieldReader); +impl RC32K_HIGH_SPEED_FORCE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RC32K_HIGH_SPEED_FORCE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32K_HIGH_SPEED_FORCE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32K_HIGH_SPEED_FORCE` writer - "] +pub struct RC32K_HIGH_SPEED_FORCE_W<'a> { + w: &'a mut W, +} +impl<'a> RC32K_HIGH_SPEED_FORCE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `POR_VBAT_HIGH_RST_MASK` reader - Mask rst from por_vbat_high"] +pub struct POR_VBAT_HIGH_RST_MASK_R(crate::FieldReader); +impl POR_VBAT_HIGH_RST_MASK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_HIGH_RST_MASK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_HIGH_RST_MASK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_HIGH_RST_MASK` writer - Mask rst from por_vbat_high"] +pub struct POR_VBAT_HIGH_RST_MASK_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_HIGH_RST_MASK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `POR_VBAT_LOW_RST_MASK` reader - Mask rst from por_vbat_low"] +pub struct POR_VBAT_LOW_RST_MASK_R(crate::FieldReader); +impl POR_VBAT_LOW_RST_MASK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_LOW_RST_MASK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_LOW_RST_MASK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_LOW_RST_MASK` writer - Mask rst from por_vbat_low"] +pub struct POR_VBAT_LOW_RST_MASK_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_LOW_RST_MASK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `VBAT_HL_CONNECT_RES_CTRL` reader - 00: OFF 01: Forced ON 10: Active: automatic control, Sleep: forced ON 11: Automatic control"] +pub struct VBAT_HL_CONNECT_RES_CTRL_R(crate::FieldReader); +impl VBAT_HL_CONNECT_RES_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + VBAT_HL_CONNECT_RES_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for VBAT_HL_CONNECT_RES_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `VBAT_HL_CONNECT_RES_CTRL` writer - 00: OFF 01: Forced ON 10: Active: automatic control, Sleep: forced ON 11: Automatic control"] +pub struct VBAT_HL_CONNECT_RES_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> VBAT_HL_CONNECT_RES_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 14"] + #[inline(always)] + pub fn force_running_comp_dis(&self) -> FORCE_RUNNING_COMP_DIS_R { + FORCE_RUNNING_COMP_DIS_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bits 10:13 - VDD clamp level setting for hibernation mode"] + #[inline(always)] + pub fn ldo_ret_trim(&self) -> LDO_RET_TRIM_R { + LDO_RET_TRIM_R::new(((self.bits >> 10) & 0x0f) as u8) + } + #[doc = "Bit 9 - Disable vcont comparator in SLP"] + #[inline(always)] + pub fn cmp_vcont_slp_disable(&self) -> CMP_VCONT_SLP_DISABLE_R { + CMP_VCONT_SLP_DISABLE_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bits 7:8 - 0x:automatic selection of boost mode 11: force boost mode 10: force buck mode"] + #[inline(always)] + pub fn boost_mode_force(&self) -> BOOST_MODE_FORCE_R { + BOOST_MODE_FORCE_R::new(((self.bits >> 7) & 3) as u8) + } + #[doc = "Bit 6 - Do not charge vbat high in boost mode"] + #[inline(always)] + pub fn charge_vbat_disable(&self) -> CHARGE_VBAT_DISABLE_R { + CHARGE_VBAT_DISABLE_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn rc32k_low_speed_force(&self) -> RC32K_LOW_SPEED_FORCE_R { + RC32K_LOW_SPEED_FORCE_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn rc32k_high_speed_force(&self) -> RC32K_HIGH_SPEED_FORCE_R { + RC32K_HIGH_SPEED_FORCE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Mask rst from por_vbat_high"] + #[inline(always)] + pub fn por_vbat_high_rst_mask(&self) -> POR_VBAT_HIGH_RST_MASK_R { + POR_VBAT_HIGH_RST_MASK_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Mask rst from por_vbat_low"] + #[inline(always)] + pub fn por_vbat_low_rst_mask(&self) -> POR_VBAT_LOW_RST_MASK_R { + POR_VBAT_LOW_RST_MASK_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1 - 00: OFF 01: Forced ON 10: Active: automatic control, Sleep: forced ON 11: Automatic control"] + #[inline(always)] + pub fn vbat_hl_connect_res_ctrl(&self) -> VBAT_HL_CONNECT_RES_CTRL_R { + VBAT_HL_CONNECT_RES_CTRL_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 14"] + #[inline(always)] + pub fn force_running_comp_dis(&mut self) -> FORCE_RUNNING_COMP_DIS_W { + FORCE_RUNNING_COMP_DIS_W { w: self } + } + #[doc = "Bits 10:13 - VDD clamp level setting for hibernation mode"] + #[inline(always)] + pub fn ldo_ret_trim(&mut self) -> LDO_RET_TRIM_W { + LDO_RET_TRIM_W { w: self } + } + #[doc = "Bit 9 - Disable vcont comparator in SLP"] + #[inline(always)] + pub fn cmp_vcont_slp_disable(&mut self) -> CMP_VCONT_SLP_DISABLE_W { + CMP_VCONT_SLP_DISABLE_W { w: self } + } + #[doc = "Bits 7:8 - 0x:automatic selection of boost mode 11: force boost mode 10: force buck mode"] + #[inline(always)] + pub fn boost_mode_force(&mut self) -> BOOST_MODE_FORCE_W { + BOOST_MODE_FORCE_W { w: self } + } + #[doc = "Bit 6 - Do not charge vbat high in boost mode"] + #[inline(always)] + pub fn charge_vbat_disable(&mut self) -> CHARGE_VBAT_DISABLE_W { + CHARGE_VBAT_DISABLE_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn rc32k_low_speed_force(&mut self) -> RC32K_LOW_SPEED_FORCE_W { + RC32K_LOW_SPEED_FORCE_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn rc32k_high_speed_force(&mut self) -> RC32K_HIGH_SPEED_FORCE_W { + RC32K_HIGH_SPEED_FORCE_W { w: self } + } + #[doc = "Bit 3 - Mask rst from por_vbat_high"] + #[inline(always)] + pub fn por_vbat_high_rst_mask(&mut self) -> POR_VBAT_HIGH_RST_MASK_W { + POR_VBAT_HIGH_RST_MASK_W { w: self } + } + #[doc = "Bit 2 - Mask rst from por_vbat_low"] + #[inline(always)] + pub fn por_vbat_low_rst_mask(&mut self) -> POR_VBAT_LOW_RST_MASK_W { + POR_VBAT_LOW_RST_MASK_W { w: self } + } + #[doc = "Bits 0:1 - 00: OFF 01: Forced ON 10: Active: automatic control, Sleep: forced ON 11: Automatic control"] + #[inline(always)] + pub fn vbat_hl_connect_res_ctrl(&mut self) -> VBAT_HL_CONNECT_RES_CTRL_W { + VBAT_HL_CONNECT_RES_CTRL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [power_aon_ctrl_reg](index.html) module"] +pub struct POWER_AON_CTRL_REG_SPEC; +impl crate::RegisterSpec for POWER_AON_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [power_aon_ctrl_reg::R](R) reader structure"] +impl crate::Readable for POWER_AON_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [power_aon_ctrl_reg::W](W) writer structure"] +impl crate::Writable for POWER_AON_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets POWER_AON_CTRL_REG to value 0x08"] +impl crate::Resettable for POWER_AON_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x08 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/ram_lpmx_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/ram_lpmx_reg.rs new file mode 100644 index 0000000..9098035 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/ram_lpmx_reg.rs @@ -0,0 +1,107 @@ +#[doc = "Register `RAM_LPMX_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RAM_LPMX_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RAMx_LPMX` reader - RAM\\[3:1\\] +Transparent Light Sleep (TLS) Core Enable for System RAMs. Assert low to enable the TLS core feature, which will result in lower leakage current. In case VDD is below 0.81V, it is necessary to hold this pin high to maintain data retention."] +pub struct RAMX_LPMX_R(crate::FieldReader); +impl RAMX_LPMX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RAMX_LPMX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAMX_LPMX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAMx_LPMX` writer - RAM\\[3:1\\] +Transparent Light Sleep (TLS) Core Enable for System RAMs. Assert low to enable the TLS core feature, which will result in lower leakage current. In case VDD is below 0.81V, it is necessary to hold this pin high to maintain data retention."] +pub struct RAMX_LPMX_W<'a> { + w: &'a mut W, +} +impl<'a> RAMX_LPMX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u16 & 7); + self.w + } +} +impl R { + #[doc = "Bits 0:2 - RAM\\[3:1\\] +Transparent Light Sleep (TLS) Core Enable for System RAMs. Assert low to enable the TLS core feature, which will result in lower leakage current. In case VDD is below 0.81V, it is necessary to hold this pin high to maintain data retention."] + #[inline(always)] + pub fn ramx_lpmx(&self) -> RAMX_LPMX_R { + RAMX_LPMX_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 0:2 - RAM\\[3:1\\] +Transparent Light Sleep (TLS) Core Enable for System RAMs. Assert low to enable the TLS core feature, which will result in lower leakage current. In case VDD is below 0.81V, it is necessary to hold this pin high to maintain data retention."] + #[inline(always)] + pub fn ramx_lpmx(&mut self) -> RAMX_LPMX_W { + RAMX_LPMX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ram_lpmx_reg](index.html) module"] +pub struct RAM_LPMX_REG_SPEC; +impl crate::RegisterSpec for RAM_LPMX_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [ram_lpmx_reg::R](R) reader structure"] +impl crate::Readable for RAM_LPMX_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ram_lpmx_reg::W](W) writer structure"] +impl crate::Writable for RAM_LPMX_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RAM_LPMX_REG to value 0x07"] +impl crate::Resettable for RAM_LPMX_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/reset_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/reset_stat_reg.rs new file mode 100644 index 0000000..3da9b87 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/reset_stat_reg.rs @@ -0,0 +1,258 @@ +#[doc = "Register `RESET_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RESET_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WDOGRESET_STAT` reader - Indicates that a Watchdog has happened. This bit is also set with a PowerOn Reset"] +pub struct WDOGRESET_STAT_R(crate::FieldReader); +impl WDOGRESET_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WDOGRESET_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WDOGRESET_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WDOGRESET_STAT` writer - Indicates that a Watchdog has happened. This bit is also set with a PowerOn Reset"] +pub struct WDOGRESET_STAT_W<'a> { + w: &'a mut W, +} +impl<'a> WDOGRESET_STAT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `SWRESET_STAT` reader - Indicates that a SW Reset has been requested. The SW reset is requested by SYS_CTRL_REG\\[SW_RESET\\] +or SCB->AIRCR inside the ARM. This bit is also set with a PowerOn Reset"] +pub struct SWRESET_STAT_R(crate::FieldReader); +impl SWRESET_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SWRESET_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SWRESET_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SWRESET_STAT` writer - Indicates that a SW Reset has been requested. The SW reset is requested by SYS_CTRL_REG\\[SW_RESET\\] +or SCB->AIRCR inside the ARM. This bit is also set with a PowerOn Reset"] +pub struct SWRESET_STAT_W<'a> { + w: &'a mut W, +} +impl<'a> SWRESET_STAT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `HWRESET_STAT` reader - Indicates that a HW Reset has happened This bit is also set with a PowerOn Reset"] +pub struct HWRESET_STAT_R(crate::FieldReader); +impl HWRESET_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + HWRESET_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HWRESET_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HWRESET_STAT` writer - Indicates that a HW Reset has happened This bit is also set with a PowerOn Reset"] +pub struct HWRESET_STAT_W<'a> { + w: &'a mut W, +} +impl<'a> HWRESET_STAT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `PORESET_STAT` reader - Indicates that a PowerOn Reset has happened"] +pub struct PORESET_STAT_R(crate::FieldReader); +impl PORESET_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PORESET_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PORESET_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PORESET_STAT` writer - Indicates that a PowerOn Reset has happened"] +pub struct PORESET_STAT_W<'a> { + w: &'a mut W, +} +impl<'a> PORESET_STAT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 3 - Indicates that a Watchdog has happened. This bit is also set with a PowerOn Reset"] + #[inline(always)] + pub fn wdogreset_stat(&self) -> WDOGRESET_STAT_R { + WDOGRESET_STAT_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Indicates that a SW Reset has been requested. The SW reset is requested by SYS_CTRL_REG\\[SW_RESET\\] +or SCB->AIRCR inside the ARM. This bit is also set with a PowerOn Reset"] + #[inline(always)] + pub fn swreset_stat(&self) -> SWRESET_STAT_R { + SWRESET_STAT_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Indicates that a HW Reset has happened This bit is also set with a PowerOn Reset"] + #[inline(always)] + pub fn hwreset_stat(&self) -> HWRESET_STAT_R { + HWRESET_STAT_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Indicates that a PowerOn Reset has happened"] + #[inline(always)] + pub fn poreset_stat(&self) -> PORESET_STAT_R { + PORESET_STAT_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 3 - Indicates that a Watchdog has happened. This bit is also set with a PowerOn Reset"] + #[inline(always)] + pub fn wdogreset_stat(&mut self) -> WDOGRESET_STAT_W { + WDOGRESET_STAT_W { w: self } + } + #[doc = "Bit 2 - Indicates that a SW Reset has been requested. The SW reset is requested by SYS_CTRL_REG\\[SW_RESET\\] +or SCB->AIRCR inside the ARM. This bit is also set with a PowerOn Reset"] + #[inline(always)] + pub fn swreset_stat(&mut self) -> SWRESET_STAT_W { + SWRESET_STAT_W { w: self } + } + #[doc = "Bit 1 - Indicates that a HW Reset has happened This bit is also set with a PowerOn Reset"] + #[inline(always)] + pub fn hwreset_stat(&mut self) -> HWRESET_STAT_W { + HWRESET_STAT_W { w: self } + } + #[doc = "Bit 0 - Indicates that a PowerOn Reset has happened"] + #[inline(always)] + pub fn poreset_stat(&mut self) -> PORESET_STAT_W { + PORESET_STAT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Reset status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [reset_stat_reg](index.html) module"] +pub struct RESET_STAT_REG_SPEC; +impl crate::RegisterSpec for RESET_STAT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [reset_stat_reg::R](R) reader structure"] +impl crate::Readable for RESET_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [reset_stat_reg::W](W) writer structure"] +impl crate::Writable for RESET_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RESET_STAT_REG to value 0x0f"] +impl crate::Resettable for RESET_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_aon/test_vdd_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_aon/test_vdd_reg.rs new file mode 100644 index 0000000..36a54d5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_aon/test_vdd_reg.rs @@ -0,0 +1,160 @@ +#[doc = "Register `TEST_VDD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TEST_VDD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LDOS_DISABLE` reader - "] +pub struct LDOS_DISABLE_R(crate::FieldReader); +impl LDOS_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDOS_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDOS_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDOS_DISABLE` writer - "] +pub struct LDOS_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> LDOS_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `TEST_VDD` reader - "] +pub struct TEST_VDD_R(crate::FieldReader); +impl TEST_VDD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TEST_VDD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TEST_VDD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TEST_VDD` writer - "] +pub struct TEST_VDD_W<'a> { + w: &'a mut W, +} +impl<'a> TEST_VDD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1"] + #[inline(always)] + pub fn ldos_disable(&self) -> LDOS_DISABLE_R { + LDOS_DISABLE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn test_vdd(&self) -> TEST_VDD_R { + TEST_VDD_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1"] + #[inline(always)] + pub fn ldos_disable(&mut self) -> LDOS_DISABLE_W { + LDOS_DISABLE_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn test_vdd(&mut self) -> TEST_VDD_W { + TEST_VDD_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [test_vdd_reg](index.html) module"] +pub struct TEST_VDD_REG_SPEC; +impl crate::RegisterSpec for TEST_VDD_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [test_vdd_reg::R](R) reader structure"] +impl crate::Readable for TEST_VDD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [test_vdd_reg::W](W) writer structure"] +impl crate::Writable for TEST_VDD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TEST_VDD_REG to value 0"] +impl crate::Resettable for TEST_VDD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_tim.rs b/bitbox02-bt/vendor/da14531/src/crg_tim.rs new file mode 100644 index 0000000..d955041 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_tim.rs @@ -0,0 +1,11 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + _reserved0: [u8; 0x4c], + #[doc = "0x4c - Divisor for RTC 100Hz clock"] + pub clk_rtcdiv_reg: crate::Reg, +} +#[doc = "CLK_RTCDIV_REG register accessor: an alias for `Reg`"] +pub type CLK_RTCDIV_REG = crate::Reg; +#[doc = "Divisor for RTC 100Hz clock"] +pub mod clk_rtcdiv_reg; diff --git a/bitbox02-bt/vendor/da14531/src/crg_tim/clk_rtcdiv_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_tim/clk_rtcdiv_reg.rs new file mode 100644 index 0000000..c49d37a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_tim/clk_rtcdiv_reg.rs @@ -0,0 +1,281 @@ +#[doc = "Register `CLK_RTCDIV_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_RTCDIV_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_RESET_REQ` reader - Reset request for the RTC module"] +pub struct RTC_RESET_REQ_R(crate::FieldReader); +impl RTC_RESET_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_RESET_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_RESET_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_RESET_REQ` writer - Reset request for the RTC module"] +pub struct RTC_RESET_REQ_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_RESET_REQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 21)) | ((value as u32 & 1) << 21); + self.w + } +} +#[doc = "Field `RTC_DIV_ENABLE` reader - Enable for the 100 Hz generation for the RTC block"] +pub struct RTC_DIV_ENABLE_R(crate::FieldReader); +impl RTC_DIV_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_DIV_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_DIV_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_DIV_ENABLE` writer - Enable for the 100 Hz generation for the RTC block"] +pub struct RTC_DIV_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_DIV_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 20)) | ((value as u32 & 1) << 20); + self.w + } +} +#[doc = "Field `RTC_DIV_DENOM` reader - Selects the denominator for the fractional division: 0b0: 1000 0b1: 1024"] +pub struct RTC_DIV_DENOM_R(crate::FieldReader); +impl RTC_DIV_DENOM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_DIV_DENOM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_DIV_DENOM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_DIV_DENOM` writer - Selects the denominator for the fractional division: 0b0: 1000 0b1: 1024"] +pub struct RTC_DIV_DENOM_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_DIV_DENOM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `RTC_DIV_INT` reader - Integer divisor part for RTC 100Hz generation"] +pub struct RTC_DIV_INT_R(crate::FieldReader); +impl RTC_DIV_INT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RTC_DIV_INT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_DIV_INT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_DIV_INT` writer - Integer divisor part for RTC 100Hz generation"] +pub struct RTC_DIV_INT_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_DIV_INT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 10)) | ((value as u32 & 0x01ff) << 10); + self.w + } +} +#[doc = "Field `RTC_DIV_FRAC` reader - Fractional divisor part for RTC 100Hz generation. if RTC_DIV_DENOM=1, out of 1024 cycles will divide by , the rest is If RTC_DIV_DENOM=0, out of 1000 cycles will divide by , the rest is "] +pub struct RTC_DIV_FRAC_R(crate::FieldReader); +impl RTC_DIV_FRAC_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RTC_DIV_FRAC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_DIV_FRAC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_DIV_FRAC` writer - Fractional divisor part for RTC 100Hz generation. if RTC_DIV_DENOM=1, out of 1024 cycles will divide by , the rest is If RTC_DIV_DENOM=0, out of 1000 cycles will divide by , the rest is "] +pub struct RTC_DIV_FRAC_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_DIV_FRAC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bit 21 - Reset request for the RTC module"] + #[inline(always)] + pub fn rtc_reset_req(&self) -> RTC_RESET_REQ_R { + RTC_RESET_REQ_R::new(((self.bits >> 21) & 1) != 0) + } + #[doc = "Bit 20 - Enable for the 100 Hz generation for the RTC block"] + #[inline(always)] + pub fn rtc_div_enable(&self) -> RTC_DIV_ENABLE_R { + RTC_DIV_ENABLE_R::new(((self.bits >> 20) & 1) != 0) + } + #[doc = "Bit 19 - Selects the denominator for the fractional division: 0b0: 1000 0b1: 1024"] + #[inline(always)] + pub fn rtc_div_denom(&self) -> RTC_DIV_DENOM_R { + RTC_DIV_DENOM_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 10:18 - Integer divisor part for RTC 100Hz generation"] + #[inline(always)] + pub fn rtc_div_int(&self) -> RTC_DIV_INT_R { + RTC_DIV_INT_R::new(((self.bits >> 10) & 0x01ff) as u16) + } + #[doc = "Bits 0:9 - Fractional divisor part for RTC 100Hz generation. if RTC_DIV_DENOM=1, out of 1024 cycles will divide by , the rest is If RTC_DIV_DENOM=0, out of 1000 cycles will divide by , the rest is "] + #[inline(always)] + pub fn rtc_div_frac(&self) -> RTC_DIV_FRAC_R { + RTC_DIV_FRAC_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bit 21 - Reset request for the RTC module"] + #[inline(always)] + pub fn rtc_reset_req(&mut self) -> RTC_RESET_REQ_W { + RTC_RESET_REQ_W { w: self } + } + #[doc = "Bit 20 - Enable for the 100 Hz generation for the RTC block"] + #[inline(always)] + pub fn rtc_div_enable(&mut self) -> RTC_DIV_ENABLE_W { + RTC_DIV_ENABLE_W { w: self } + } + #[doc = "Bit 19 - Selects the denominator for the fractional division: 0b0: 1000 0b1: 1024"] + #[inline(always)] + pub fn rtc_div_denom(&mut self) -> RTC_DIV_DENOM_W { + RTC_DIV_DENOM_W { w: self } + } + #[doc = "Bits 10:18 - Integer divisor part for RTC 100Hz generation"] + #[inline(always)] + pub fn rtc_div_int(&mut self) -> RTC_DIV_INT_W { + RTC_DIV_INT_W { w: self } + } + #[doc = "Bits 0:9 - Fractional divisor part for RTC 100Hz generation. if RTC_DIV_DENOM=1, out of 1024 cycles will divide by , the rest is If RTC_DIV_DENOM=0, out of 1000 cycles will divide by , the rest is "] + #[inline(always)] + pub fn rtc_div_frac(&mut self) -> RTC_DIV_FRAC_W { + RTC_DIV_FRAC_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Divisor for RTC 100Hz clock\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_rtcdiv_reg](index.html) module"] +pub struct CLK_RTCDIV_REG_SPEC; +impl crate::RegisterSpec for CLK_RTCDIV_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [clk_rtcdiv_reg::R](R) reader structure"] +impl crate::Readable for CLK_RTCDIV_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_rtcdiv_reg::W](W) writer structure"] +impl crate::Writable for CLK_RTCDIV_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_RTCDIV_REG to value 0x0005_1ea8"] +impl crate::Resettable for CLK_RTCDIV_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0005_1ea8 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top.rs b/bitbox02-bt/vendor/da14531/src/crg_top.rs new file mode 100644 index 0000000..cfbe767 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top.rs @@ -0,0 +1,166 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - HCLK, PCLK, divider and clock gates"] + pub clk_amba_reg: crate::Reg, + #[doc = "0x02 - Xtal frequency trimming register"] + pub clk_freq_trim_reg: crate::Reg, + #[doc = "0x04 - Peripheral divider register"] + pub clk_per_reg: crate::Reg, + _reserved3: [u8; 0x02], + #[doc = "0x08 - Radio PLL control register"] + pub clk_radio_reg: crate::Reg, + #[doc = "0x0a - Clock control register"] + pub clk_ctrl_reg: crate::Reg, + _reserved5: [u8; 0x04], + #[doc = "0x10 - Power Management Unit control register"] + pub pmu_ctrl_reg: crate::Reg, + #[doc = "0x12 - System Control register"] + pub sys_ctrl_reg: crate::Reg, + #[doc = "0x14 - System status register"] + pub sys_stat_reg: crate::Reg, + #[doc = "0x16 - Control trimming of the XTAL32M"] + pub trim_ctrl_reg: crate::Reg, + #[doc = "0x18 - Control power state of System RAMS"] + pub ram_pwr_ctrl_reg: crate::Reg, + _reserved10: [u8; 0x06], + #[doc = "0x20 - 32 kHz RC oscillator register"] + pub clk_rc32k_reg: crate::Reg, + #[doc = "0x22 - 32 kHz XTAL oscillator register"] + pub clk_xtal32k_reg: crate::Reg, + #[doc = "0x24 - Fast RC control register"] + pub clk_rc32m_reg: crate::Reg, + #[doc = "0x26 - RCX-oscillator control register"] + pub clk_rcx_reg: crate::Reg, + #[doc = "0x28 - Bandgap trimming"] + pub bandgap_reg: crate::Reg, + #[doc = "0x2a - Status bit of analog (power management) circuits"] + pub ana_status_reg: crate::Reg, + _reserved16: [u8; 0x04], + #[doc = "0x30 - Trim values for XTAL32M"] + pub xtal32m_start_reg: crate::Reg, + #[doc = "0x32 - Read back value of current XTAL trimming"] + pub xtal32m_trstat_reg: crate::Reg, + #[doc = "0x34 - Control register for XTALRDY IRQ"] + pub xtalrdy_ctrl_reg: crate::Reg, + #[doc = "0x36 - "] + pub xtalrdy_stat_reg: crate::Reg, + #[doc = "0x38 - Control bits for XTAL32M"] + pub xtal32m_ctrl0_reg: crate::Reg, + _reserved21: [u8; 0x06], + #[doc = "0x40 - Selects a GPIO pin for POR generation"] + pub por_pin_reg: crate::Reg, + #[doc = "0x42 - Time for POR to happen"] + pub por_timer_reg: crate::Reg, + _reserved23: [u8; 0x0c], + #[doc = "0x50 - Bandgap refresh interval during sleep"] + pub pmu_sleep_reg: crate::Reg, + #[doc = "0x52 - Power management control"] + pub power_ctrl_reg: crate::Reg, + #[doc = "0x54 - Power management level and trim settings"] + pub power_level_reg: crate::Reg, +} +#[doc = "ANA_STATUS_REG register accessor: an alias for `Reg`"] +pub type ANA_STATUS_REG = crate::Reg; +#[doc = "Status bit of analog (power management) circuits"] +pub mod ana_status_reg; +#[doc = "BANDGAP_REG register accessor: an alias for `Reg`"] +pub type BANDGAP_REG = crate::Reg; +#[doc = "Bandgap trimming"] +pub mod bandgap_reg; +#[doc = "CLK_AMBA_REG register accessor: an alias for `Reg`"] +pub type CLK_AMBA_REG = crate::Reg; +#[doc = "HCLK, PCLK, divider and clock gates"] +pub mod clk_amba_reg; +#[doc = "CLK_CTRL_REG register accessor: an alias for `Reg`"] +pub type CLK_CTRL_REG = crate::Reg; +#[doc = "Clock control register"] +pub mod clk_ctrl_reg; +#[doc = "CLK_FREQ_TRIM_REG register accessor: an alias for `Reg`"] +pub type CLK_FREQ_TRIM_REG = crate::Reg; +#[doc = "Xtal frequency trimming register"] +pub mod clk_freq_trim_reg; +#[doc = "CLK_PER_REG register accessor: an alias for `Reg`"] +pub type CLK_PER_REG = crate::Reg; +#[doc = "Peripheral divider register"] +pub mod clk_per_reg; +#[doc = "CLK_RADIO_REG register accessor: an alias for `Reg`"] +pub type CLK_RADIO_REG = crate::Reg; +#[doc = "Radio PLL control register"] +pub mod clk_radio_reg; +#[doc = "CLK_RC32K_REG register accessor: an alias for `Reg`"] +pub type CLK_RC32K_REG = crate::Reg; +#[doc = "32 kHz RC oscillator register"] +pub mod clk_rc32k_reg; +#[doc = "CLK_RC32M_REG register accessor: an alias for `Reg`"] +pub type CLK_RC32M_REG = crate::Reg; +#[doc = "Fast RC control register"] +pub mod clk_rc32m_reg; +#[doc = "CLK_RCX_REG register accessor: an alias for `Reg`"] +pub type CLK_RCX_REG = crate::Reg; +#[doc = "RCX-oscillator control register"] +pub mod clk_rcx_reg; +#[doc = "CLK_XTAL32K_REG register accessor: an alias for `Reg`"] +pub type CLK_XTAL32K_REG = crate::Reg; +#[doc = "32 kHz XTAL oscillator register"] +pub mod clk_xtal32k_reg; +#[doc = "PMU_CTRL_REG register accessor: an alias for `Reg`"] +pub type PMU_CTRL_REG = crate::Reg; +#[doc = "Power Management Unit control register"] +pub mod pmu_ctrl_reg; +#[doc = "PMU_SLEEP_REG register accessor: an alias for `Reg`"] +pub type PMU_SLEEP_REG = crate::Reg; +#[doc = "Bandgap refresh interval during sleep"] +pub mod pmu_sleep_reg; +#[doc = "POR_PIN_REG register accessor: an alias for `Reg`"] +pub type POR_PIN_REG = crate::Reg; +#[doc = "Selects a GPIO pin for POR generation"] +pub mod por_pin_reg; +#[doc = "POR_TIMER_REG register accessor: an alias for `Reg`"] +pub type POR_TIMER_REG = crate::Reg; +#[doc = "Time for POR to happen"] +pub mod por_timer_reg; +#[doc = "POWER_CTRL_REG register accessor: an alias for `Reg`"] +pub type POWER_CTRL_REG = crate::Reg; +#[doc = "Power management control"] +pub mod power_ctrl_reg; +#[doc = "POWER_LEVEL_REG register accessor: an alias for `Reg`"] +pub type POWER_LEVEL_REG = crate::Reg; +#[doc = "Power management level and trim settings"] +pub mod power_level_reg; +#[doc = "RAM_PWR_CTRL_REG register accessor: an alias for `Reg`"] +pub type RAM_PWR_CTRL_REG = crate::Reg; +#[doc = "Control power state of System RAMS"] +pub mod ram_pwr_ctrl_reg; +#[doc = "SYS_CTRL_REG register accessor: an alias for `Reg`"] +pub type SYS_CTRL_REG = crate::Reg; +#[doc = "System Control register"] +pub mod sys_ctrl_reg; +#[doc = "SYS_STAT_REG register accessor: an alias for `Reg`"] +pub type SYS_STAT_REG = crate::Reg; +#[doc = "System status register"] +pub mod sys_stat_reg; +#[doc = "TRIM_CTRL_REG register accessor: an alias for `Reg`"] +pub type TRIM_CTRL_REG = crate::Reg; +#[doc = "Control trimming of the XTAL32M"] +pub mod trim_ctrl_reg; +#[doc = "XTAL32M_CTRL0_REG register accessor: an alias for `Reg`"] +pub type XTAL32M_CTRL0_REG = crate::Reg; +#[doc = "Control bits for XTAL32M"] +pub mod xtal32m_ctrl0_reg; +#[doc = "XTAL32M_START_REG register accessor: an alias for `Reg`"] +pub type XTAL32M_START_REG = crate::Reg; +#[doc = "Trim values for XTAL32M"] +pub mod xtal32m_start_reg; +#[doc = "XTAL32M_TRSTAT_REG register accessor: an alias for `Reg`"] +pub type XTAL32M_TRSTAT_REG = crate::Reg; +#[doc = "Read back value of current XTAL trimming"] +pub mod xtal32m_trstat_reg; +#[doc = "XTALRDY_CTRL_REG register accessor: an alias for `Reg`"] +pub type XTALRDY_CTRL_REG = crate::Reg; +#[doc = "Control register for XTALRDY IRQ"] +pub mod xtalrdy_ctrl_reg; +#[doc = "XTALRDY_STAT_REG register accessor: an alias for `Reg`"] +pub type XTALRDY_STAT_REG = crate::Reg; +#[doc = ""] +pub mod xtalrdy_stat_reg; diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/ana_status_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/ana_status_reg.rs new file mode 100644 index 0000000..036d40c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/ana_status_reg.rs @@ -0,0 +1,326 @@ +#[doc = "Register `ANA_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ANA_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLKLESS_WAKEUP_STAT` reader - Indicates the output of the Clockless wakeup XOR tree. If this signal is '0', the chip will wake up. Use the HIBERN_WKUP_POLARITY bit to set the value to '1' before going into hibernation mode."] +pub struct CLKLESS_WAKEUP_STAT_R(crate::FieldReader); +impl CLKLESS_WAKEUP_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLKLESS_WAKEUP_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLKLESS_WAKEUP_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FORCE_RUNNING` reader - "] +pub struct FORCE_RUNNING_R(crate::FieldReader); +impl FORCE_RUNNING_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FORCE_RUNNING_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FORCE_RUNNING_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_GPADC_OK` reader - Indicates that LDO_GPADC output is OK"] +pub struct LDO_GPADC_OK_R(crate::FieldReader); +impl LDO_GPADC_OK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_GPADC_OK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_GPADC_OK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_XTAL_OK` reader - Indicates that LDO_XTAL output is OK"] +pub struct LDO_XTAL_OK_R(crate::FieldReader); +impl LDO_XTAL_OK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_XTAL_OK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_XTAL_OK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BOOST_SELECTED` reader - 0: Buck mode detected 1: Boost mode detected"] +pub struct BOOST_SELECTED_R(crate::FieldReader); +impl BOOST_SELECTED_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BOOST_SELECTED_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BOOST_SELECTED_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_HIGH` reader - Output of VBAT_HIGH supply rail voltage monitoring circuit. 0: Voltage level on VBAT_HIGH is lower than POR VBAT_HIGH threshold VTH_L (rail not ok, will result in reset if not masked) 1: Voltage level on VBAT_HIGH is higher than POR VBAT_HIGH threshold VTH_H (rail ok, reset released)"] +pub struct POR_VBAT_HIGH_R(crate::FieldReader); +impl POR_VBAT_HIGH_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_HIGH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_HIGH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_LOW` reader - Output of VBAT_LOW supply rail voltage monitoring circuit. 0: Voltage level on VBAT_LOW is lower than POR VBAT_LOW threshold VTH_L (rail not ok, will result in reset if not masked) 1: Voltage level on VBAT_LOW is higher than POR VBAT_LOW threshold VTH_H (rail ok, reset released)"] +pub struct POR_VBAT_LOW_R(crate::FieldReader); +impl POR_VBAT_LOW_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_LOW_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_LOW_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BANDGAP_OK` reader - Indicates that BANDGAP is OK"] +pub struct BANDGAP_OK_R(crate::FieldReader); +impl BANDGAP_OK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BANDGAP_OK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BANDGAP_OK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `COMP_VBAT_HIGH_NOK` reader - Indicates that VBAT_HIGH < VBAT_LOW -50 mV"] +pub struct COMP_VBAT_HIGH_NOK_R(crate::FieldReader); +impl COMP_VBAT_HIGH_NOK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + COMP_VBAT_HIGH_NOK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for COMP_VBAT_HIGH_NOK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `COMP_VBAT_HIGH_OK` reader - Indicates that VBAT_HIGH > VBAT_LOW +50 mV"] +pub struct COMP_VBAT_HIGH_OK_R(crate::FieldReader); +impl COMP_VBAT_HIGH_OK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + COMP_VBAT_HIGH_OK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for COMP_VBAT_HIGH_OK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCDC_OK` reader - Indicates that VBAT_LOW (buck mode) or VBAT_HIGH (boost mode) is OK"] +pub struct DCDC_OK_R(crate::FieldReader); +impl DCDC_OK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DCDC_OK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCDC_OK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_LOW_OK` reader - Indicates that LDO_LOW output is OK (only valid for high current mode)"] +pub struct LDO_LOW_OK_R(crate::FieldReader); +impl LDO_LOW_OK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_LOW_OK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_LOW_OK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_CORE_OK` reader - Indicates that LDO_CORE output is OK"] +pub struct LDO_CORE_OK_R(crate::FieldReader); +impl LDO_CORE_OK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_CORE_OK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_CORE_OK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 12 - Indicates the output of the Clockless wakeup XOR tree. If this signal is '0', the chip will wake up. Use the HIBERN_WKUP_POLARITY bit to set the value to '1' before going into hibernation mode."] + #[inline(always)] + pub fn clkless_wakeup_stat(&self) -> CLKLESS_WAKEUP_STAT_R { + CLKLESS_WAKEUP_STAT_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn force_running(&self) -> FORCE_RUNNING_R { + FORCE_RUNNING_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - Indicates that LDO_GPADC output is OK"] + #[inline(always)] + pub fn ldo_gpadc_ok(&self) -> LDO_GPADC_OK_R { + LDO_GPADC_OK_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - Indicates that LDO_XTAL output is OK"] + #[inline(always)] + pub fn ldo_xtal_ok(&self) -> LDO_XTAL_OK_R { + LDO_XTAL_OK_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - 0: Buck mode detected 1: Boost mode detected"] + #[inline(always)] + pub fn boost_selected(&self) -> BOOST_SELECTED_R { + BOOST_SELECTED_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - Output of VBAT_HIGH supply rail voltage monitoring circuit. 0: Voltage level on VBAT_HIGH is lower than POR VBAT_HIGH threshold VTH_L (rail not ok, will result in reset if not masked) 1: Voltage level on VBAT_HIGH is higher than POR VBAT_HIGH threshold VTH_H (rail ok, reset released)"] + #[inline(always)] + pub fn por_vbat_high(&self) -> POR_VBAT_HIGH_R { + POR_VBAT_HIGH_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Output of VBAT_LOW supply rail voltage monitoring circuit. 0: Voltage level on VBAT_LOW is lower than POR VBAT_LOW threshold VTH_L (rail not ok, will result in reset if not masked) 1: Voltage level on VBAT_LOW is higher than POR VBAT_LOW threshold VTH_H (rail ok, reset released)"] + #[inline(always)] + pub fn por_vbat_low(&self) -> POR_VBAT_LOW_R { + POR_VBAT_LOW_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Indicates that BANDGAP is OK"] + #[inline(always)] + pub fn bandgap_ok(&self) -> BANDGAP_OK_R { + BANDGAP_OK_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Indicates that VBAT_HIGH < VBAT_LOW -50 mV"] + #[inline(always)] + pub fn comp_vbat_high_nok(&self) -> COMP_VBAT_HIGH_NOK_R { + COMP_VBAT_HIGH_NOK_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Indicates that VBAT_HIGH > VBAT_LOW +50 mV"] + #[inline(always)] + pub fn comp_vbat_high_ok(&self) -> COMP_VBAT_HIGH_OK_R { + COMP_VBAT_HIGH_OK_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Indicates that VBAT_LOW (buck mode) or VBAT_HIGH (boost mode) is OK"] + #[inline(always)] + pub fn dcdc_ok(&self) -> DCDC_OK_R { + DCDC_OK_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Indicates that LDO_LOW output is OK (only valid for high current mode)"] + #[inline(always)] + pub fn ldo_low_ok(&self) -> LDO_LOW_OK_R { + LDO_LOW_OK_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Indicates that LDO_CORE output is OK"] + #[inline(always)] + pub fn ldo_core_ok(&self) -> LDO_CORE_OK_R { + LDO_CORE_OK_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Status bit of analog (power management) circuits\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ana_status_reg](index.html) module"] +pub struct ANA_STATUS_REG_SPEC; +impl crate::RegisterSpec for ANA_STATUS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [ana_status_reg::R](R) reader structure"] +impl crate::Readable for ANA_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ana_status_reg::W](W) writer structure"] +impl crate::Writable for ANA_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ANA_STATUS_REG to value 0"] +impl crate::Resettable for ANA_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/bandgap_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/bandgap_reg.rs new file mode 100644 index 0000000..fc75a03 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/bandgap_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `BANDGAP_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BANDGAP_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BGR_ITRIM` reader - Trim setting for bandgap bias current 10000 -> -25% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +32%"] +pub struct BGR_ITRIM_R(crate::FieldReader); +impl BGR_ITRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BGR_ITRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BGR_ITRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BGR_ITRIM` writer - Trim setting for bandgap bias current 10000 -> -25% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +32%"] +pub struct BGR_ITRIM_W<'a> { + w: &'a mut W, +} +impl<'a> BGR_ITRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u16 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `BGR_TRIM` reader - Trim setting for bandgap voltage 10000 -> -6.4% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +5.8%"] +pub struct BGR_TRIM_R(crate::FieldReader); +impl BGR_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BGR_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BGR_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BGR_TRIM` writer - Trim setting for bandgap voltage 10000 -> -6.4% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +5.8%"] +pub struct BGR_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> BGR_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u16 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9 - Trim setting for bandgap bias current 10000 -> -25% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +32%"] + #[inline(always)] + pub fn bgr_itrim(&self) -> BGR_ITRIM_R { + BGR_ITRIM_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4 - Trim setting for bandgap voltage 10000 -> -6.4% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +5.8%"] + #[inline(always)] + pub fn bgr_trim(&self) -> BGR_TRIM_R { + BGR_TRIM_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9 - Trim setting for bandgap bias current 10000 -> -25% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +32%"] + #[inline(always)] + pub fn bgr_itrim(&mut self) -> BGR_ITRIM_W { + BGR_ITRIM_W { w: self } + } + #[doc = "Bits 0:4 - Trim setting for bandgap voltage 10000 -> -6.4% .... 11111 -> ~0% 00000 -> ~0% (typ) ... 01111 -> +5.8%"] + #[inline(always)] + pub fn bgr_trim(&mut self) -> BGR_TRIM_W { + BGR_TRIM_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Bandgap trimming\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bandgap_reg](index.html) module"] +pub struct BANDGAP_REG_SPEC; +impl crate::RegisterSpec for BANDGAP_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [bandgap_reg::R](R) reader structure"] +impl crate::Readable for BANDGAP_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [bandgap_reg::W](W) writer structure"] +impl crate::Writable for BANDGAP_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BANDGAP_REG to value 0"] +impl crate::Resettable for BANDGAP_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_amba_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_amba_reg.rs new file mode 100644 index 0000000..eb8affe --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_amba_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `CLK_AMBA_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_AMBA_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTP_ENABLE` reader - Clock enable for OTP controller"] +pub struct OTP_ENABLE_R(crate::FieldReader); +impl OTP_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTP_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTP_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTP_ENABLE` writer - Clock enable for OTP controller"] +pub struct OTP_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> OTP_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `PCLK_DIV` reader - APB interface clock (PCLK). Divider is cascaded with HCLK_DIV. PCLK is HCLK divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] +pub struct PCLK_DIV_R(crate::FieldReader); +impl PCLK_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PCLK_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PCLK_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PCLK_DIV` writer - APB interface clock (PCLK). Divider is cascaded with HCLK_DIV. PCLK is HCLK divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] +pub struct PCLK_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> PCLK_DIV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u16 & 3) << 4); + self.w + } +} +#[doc = "Field `HCLK_DIV` reader - AHB interface and microprocessor clock (HCLK). HCLK is source clock divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] +pub struct HCLK_DIV_R(crate::FieldReader); +impl HCLK_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + HCLK_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HCLK_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HCLK_DIV` writer - AHB interface and microprocessor clock (HCLK). HCLK is source clock divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] +pub struct HCLK_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> HCLK_DIV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 7 - Clock enable for OTP controller"] + #[inline(always)] + pub fn otp_enable(&self) -> OTP_ENABLE_R { + OTP_ENABLE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 4:5 - APB interface clock (PCLK). Divider is cascaded with HCLK_DIV. PCLK is HCLK divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] + #[inline(always)] + pub fn pclk_div(&self) -> PCLK_DIV_R { + PCLK_DIV_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bits 0:1 - AHB interface and microprocessor clock (HCLK). HCLK is source clock divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] + #[inline(always)] + pub fn hclk_div(&self) -> HCLK_DIV_R { + HCLK_DIV_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 7 - Clock enable for OTP controller"] + #[inline(always)] + pub fn otp_enable(&mut self) -> OTP_ENABLE_W { + OTP_ENABLE_W { w: self } + } + #[doc = "Bits 4:5 - APB interface clock (PCLK). Divider is cascaded with HCLK_DIV. PCLK is HCLK divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] + #[inline(always)] + pub fn pclk_div(&mut self) -> PCLK_DIV_W { + PCLK_DIV_W { w: self } + } + #[doc = "Bits 0:1 - AHB interface and microprocessor clock (HCLK). HCLK is source clock divided by: 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] + #[inline(always)] + pub fn hclk_div(&mut self) -> HCLK_DIV_W { + HCLK_DIV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "HCLK, PCLK, divider and clock gates\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_amba_reg](index.html) module"] +pub struct CLK_AMBA_REG_SPEC; +impl crate::RegisterSpec for CLK_AMBA_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_amba_reg::R](R) reader structure"] +impl crate::Readable for CLK_AMBA_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_amba_reg::W](W) writer structure"] +impl crate::Writable for CLK_AMBA_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_AMBA_REG to value 0"] +impl crate::Resettable for CLK_AMBA_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_ctrl_reg.rs new file mode 100644 index 0000000..7b7ce44 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_ctrl_reg.rs @@ -0,0 +1,251 @@ +#[doc = "Register `CLK_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RUNNING_AT_XTAL32M` reader - Indicates that the XTAL32M clock is used as clock, and may not be switched off"] +pub struct RUNNING_AT_XTAL32M_R(crate::FieldReader); +impl RUNNING_AT_XTAL32M_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RUNNING_AT_XTAL32M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RUNNING_AT_XTAL32M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RUNNING_AT_RC32M` reader - Indicates that the RC32M clock is used as clock"] +pub struct RUNNING_AT_RC32M_R(crate::FieldReader); +impl RUNNING_AT_RC32M_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RUNNING_AT_RC32M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RUNNING_AT_RC32M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RUNNING_AT_LP_CLK` reader - Indicates that either the LP_CLK is being used as system clock"] +pub struct RUNNING_AT_LP_CLK_R(crate::FieldReader); +impl RUNNING_AT_LP_CLK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RUNNING_AT_LP_CLK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RUNNING_AT_LP_CLK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LP_CLK_SEL` reader - Sets the clock source of the LowerPower clock 0x0: RC32K 0x1: RCX 0x2: XTAL32K through the oscillator with an external Crystal. 0x3: XTAL32K through an external square wave generator (set PID of P0\\[3\\] +to FUNC_GPIO) Change this setting before using this clock, and while RUNNING_AT_LP_CLK == 0."] +pub struct LP_CLK_SEL_R(crate::FieldReader); +impl LP_CLK_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LP_CLK_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LP_CLK_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LP_CLK_SEL` writer - Sets the clock source of the LowerPower clock 0x0: RC32K 0x1: RCX 0x2: XTAL32K through the oscillator with an external Crystal. 0x3: XTAL32K through an external square wave generator (set PID of P0\\[3\\] +to FUNC_GPIO) Change this setting before using this clock, and while RUNNING_AT_LP_CLK == 0."] +pub struct LP_CLK_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> LP_CLK_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 3)) | ((value as u16 & 3) << 3); + self.w + } +} +#[doc = "Field `XTAL32M_DISABLE` reader - Setting this bit instantaneously disables the 32 MHz crystal oscillator. Also, after sleep/wakeup cycle, the oscillator will not be enabled. This bit may not be set to '1'when \"RUNNING_AT_XTAL32M is '1' to prevent deadlock. After resetting this bit, wait for XTAL32M_SETTLED or XTAL32M_TRIM_READY to become '1' before switching to XTAL32M clock source."] +pub struct XTAL32M_DISABLE_R(crate::FieldReader); +impl XTAL32M_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + XTAL32M_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32M_DISABLE` writer - Setting this bit instantaneously disables the 32 MHz crystal oscillator. Also, after sleep/wakeup cycle, the oscillator will not be enabled. This bit may not be set to '1'when \"RUNNING_AT_XTAL32M is '1' to prevent deadlock. After resetting this bit, wait for XTAL32M_SETTLED or XTAL32M_TRIM_READY to become '1' before switching to XTAL32M clock source."] +pub struct XTAL32M_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32M_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `SYS_CLK_SEL` reader - Selects the clock source. 0x0: XTAL32M (check the XTAL32M_SETTLED and XTAL32M_TRIM_READY bits!!) 0x1: RC32M 0x2/0x3: LP_CLK"] +pub struct SYS_CLK_SEL_R(crate::FieldReader); +impl SYS_CLK_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SYS_CLK_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYS_CLK_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYS_CLK_SEL` writer - Selects the clock source. 0x0: XTAL32M (check the XTAL32M_SETTLED and XTAL32M_TRIM_READY bits!!) 0x1: RC32M 0x2/0x3: LP_CLK"] +pub struct SYS_CLK_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> SYS_CLK_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 7 - Indicates that the XTAL32M clock is used as clock, and may not be switched off"] + #[inline(always)] + pub fn running_at_xtal32m(&self) -> RUNNING_AT_XTAL32M_R { + RUNNING_AT_XTAL32M_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Indicates that the RC32M clock is used as clock"] + #[inline(always)] + pub fn running_at_rc32m(&self) -> RUNNING_AT_RC32M_R { + RUNNING_AT_RC32M_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Indicates that either the LP_CLK is being used as system clock"] + #[inline(always)] + pub fn running_at_lp_clk(&self) -> RUNNING_AT_LP_CLK_R { + RUNNING_AT_LP_CLK_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bits 3:4 - Sets the clock source of the LowerPower clock 0x0: RC32K 0x1: RCX 0x2: XTAL32K through the oscillator with an external Crystal. 0x3: XTAL32K through an external square wave generator (set PID of P0\\[3\\] +to FUNC_GPIO) Change this setting before using this clock, and while RUNNING_AT_LP_CLK == 0."] + #[inline(always)] + pub fn lp_clk_sel(&self) -> LP_CLK_SEL_R { + LP_CLK_SEL_R::new(((self.bits >> 3) & 3) as u8) + } + #[doc = "Bit 2 - Setting this bit instantaneously disables the 32 MHz crystal oscillator. Also, after sleep/wakeup cycle, the oscillator will not be enabled. This bit may not be set to '1'when \"RUNNING_AT_XTAL32M is '1' to prevent deadlock. After resetting this bit, wait for XTAL32M_SETTLED or XTAL32M_TRIM_READY to become '1' before switching to XTAL32M clock source."] + #[inline(always)] + pub fn xtal32m_disable(&self) -> XTAL32M_DISABLE_R { + XTAL32M_DISABLE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1 - Selects the clock source. 0x0: XTAL32M (check the XTAL32M_SETTLED and XTAL32M_TRIM_READY bits!!) 0x1: RC32M 0x2/0x3: LP_CLK"] + #[inline(always)] + pub fn sys_clk_sel(&self) -> SYS_CLK_SEL_R { + SYS_CLK_SEL_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 3:4 - Sets the clock source of the LowerPower clock 0x0: RC32K 0x1: RCX 0x2: XTAL32K through the oscillator with an external Crystal. 0x3: XTAL32K through an external square wave generator (set PID of P0\\[3\\] +to FUNC_GPIO) Change this setting before using this clock, and while RUNNING_AT_LP_CLK == 0."] + #[inline(always)] + pub fn lp_clk_sel(&mut self) -> LP_CLK_SEL_W { + LP_CLK_SEL_W { w: self } + } + #[doc = "Bit 2 - Setting this bit instantaneously disables the 32 MHz crystal oscillator. Also, after sleep/wakeup cycle, the oscillator will not be enabled. This bit may not be set to '1'when \"RUNNING_AT_XTAL32M is '1' to prevent deadlock. After resetting this bit, wait for XTAL32M_SETTLED or XTAL32M_TRIM_READY to become '1' before switching to XTAL32M clock source."] + #[inline(always)] + pub fn xtal32m_disable(&mut self) -> XTAL32M_DISABLE_W { + XTAL32M_DISABLE_W { w: self } + } + #[doc = "Bits 0:1 - Selects the clock source. 0x0: XTAL32M (check the XTAL32M_SETTLED and XTAL32M_TRIM_READY bits!!) 0x1: RC32M 0x2/0x3: LP_CLK"] + #[inline(always)] + pub fn sys_clk_sel(&mut self) -> SYS_CLK_SEL_W { + SYS_CLK_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clock control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ctrl_reg](index.html) module"] +pub struct CLK_CTRL_REG_SPEC; +impl crate::RegisterSpec for CLK_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_ctrl_reg::R](R) reader structure"] +impl crate::Readable for CLK_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_ctrl_reg::W](W) writer structure"] +impl crate::Writable for CLK_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_CTRL_REG to value 0x41"] +impl crate::Resettable for CLK_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x41 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_freq_trim_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_freq_trim_reg.rs new file mode 100644 index 0000000..1504d7b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_freq_trim_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `CLK_FREQ_TRIM_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_FREQ_TRIM_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL32M_TRIM` reader - Xtal frequency fine trimming register. 0x00: highest frequency 0xFF: lowest frequency"] +pub struct XTAL32M_TRIM_R(crate::FieldReader); +impl XTAL32M_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL32M_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32M_TRIM` writer - Xtal frequency fine trimming register. 0x00: highest frequency 0xFF: lowest frequency"] +pub struct XTAL32M_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32M_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Xtal frequency fine trimming register. 0x00: highest frequency 0xFF: lowest frequency"] + #[inline(always)] + pub fn xtal32m_trim(&self) -> XTAL32M_TRIM_R { + XTAL32M_TRIM_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Xtal frequency fine trimming register. 0x00: highest frequency 0xFF: lowest frequency"] + #[inline(always)] + pub fn xtal32m_trim(&mut self) -> XTAL32M_TRIM_W { + XTAL32M_TRIM_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Xtal frequency trimming register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_freq_trim_reg](index.html) module"] +pub struct CLK_FREQ_TRIM_REG_SPEC; +impl crate::RegisterSpec for CLK_FREQ_TRIM_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_freq_trim_reg::R](R) reader structure"] +impl crate::Readable for CLK_FREQ_TRIM_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_freq_trim_reg::W](W) writer structure"] +impl crate::Writable for CLK_FREQ_TRIM_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_FREQ_TRIM_REG to value 0"] +impl crate::Resettable for CLK_FREQ_TRIM_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_per_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_per_reg.rs new file mode 100644 index 0000000..1f888df --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_per_reg.rs @@ -0,0 +1,432 @@ +#[doc = "Register `CLK_PER_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_PER_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QUAD_ENABLE` reader - Enable the Quadrature clock"] +pub struct QUAD_ENABLE_R(crate::FieldReader); +impl QUAD_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QUAD_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QUAD_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QUAD_ENABLE` writer - Enable the Quadrature clock"] +pub struct QUAD_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> QUAD_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `SPI_ENABLE` reader - Enable SPI clock"] +pub struct SPI_ENABLE_R(crate::FieldReader); +impl SPI_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_ENABLE` writer - Enable SPI clock"] +pub struct SPI_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `UART1_ENABLE` reader - Enable UART1 clock"] +pub struct UART1_ENABLE_R(crate::FieldReader); +impl UART1_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART1_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART1_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART1_ENABLE` writer - Enable UART1 clock"] +pub struct UART1_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> UART1_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `UART2_ENABLE` reader - Enable UART2 clock"] +pub struct UART2_ENABLE_R(crate::FieldReader); +impl UART2_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART2_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART2_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART2_ENABLE` writer - Enable UART2 clock"] +pub struct UART2_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> UART2_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `I2C_ENABLE` reader - Enable I2C clock"] +pub struct I2C_ENABLE_R(crate::FieldReader); +impl I2C_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_ENABLE` writer - Enable I2C clock"] +pub struct I2C_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `WAKEUPCT_ENABLE` reader - Enable Wakeup CaptureTimer clock"] +pub struct WAKEUPCT_ENABLE_R(crate::FieldReader); +impl WAKEUPCT_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WAKEUPCT_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WAKEUPCT_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WAKEUPCT_ENABLE` writer - Enable Wakeup CaptureTimer clock"] +pub struct WAKEUPCT_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> WAKEUPCT_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `TMR_ENABLE` reader - Enable TIMER0 and TIMER2 clock"] +pub struct TMR_ENABLE_R(crate::FieldReader); +impl TMR_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TMR_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TMR_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TMR_ENABLE` writer - Enable TIMER0 and TIMER2 clock"] +pub struct TMR_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> TMR_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `TMR_DIV` reader - Division factor for TIMER0 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] +pub struct TMR_DIV_R(crate::FieldReader); +impl TMR_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TMR_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TMR_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TMR_DIV` writer - Division factor for TIMER0 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] +pub struct TMR_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> TMR_DIV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 11 - Enable the Quadrature clock"] + #[inline(always)] + pub fn quad_enable(&self) -> QUAD_ENABLE_R { + QUAD_ENABLE_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - Enable SPI clock"] + #[inline(always)] + pub fn spi_enable(&self) -> SPI_ENABLE_R { + SPI_ENABLE_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 7 - Enable UART1 clock"] + #[inline(always)] + pub fn uart1_enable(&self) -> UART1_ENABLE_R { + UART1_ENABLE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Enable UART2 clock"] + #[inline(always)] + pub fn uart2_enable(&self) -> UART2_ENABLE_R { + UART2_ENABLE_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Enable I2C clock"] + #[inline(always)] + pub fn i2c_enable(&self) -> I2C_ENABLE_R { + I2C_ENABLE_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Enable Wakeup CaptureTimer clock"] + #[inline(always)] + pub fn wakeupct_enable(&self) -> WAKEUPCT_ENABLE_R { + WAKEUPCT_ENABLE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Enable TIMER0 and TIMER2 clock"] + #[inline(always)] + pub fn tmr_enable(&self) -> TMR_ENABLE_R { + TMR_ENABLE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bits 0:1 - Division factor for TIMER0 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] + #[inline(always)] + pub fn tmr_div(&self) -> TMR_DIV_R { + TMR_DIV_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 11 - Enable the Quadrature clock"] + #[inline(always)] + pub fn quad_enable(&mut self) -> QUAD_ENABLE_W { + QUAD_ENABLE_W { w: self } + } + #[doc = "Bit 10 - Enable SPI clock"] + #[inline(always)] + pub fn spi_enable(&mut self) -> SPI_ENABLE_W { + SPI_ENABLE_W { w: self } + } + #[doc = "Bit 7 - Enable UART1 clock"] + #[inline(always)] + pub fn uart1_enable(&mut self) -> UART1_ENABLE_W { + UART1_ENABLE_W { w: self } + } + #[doc = "Bit 6 - Enable UART2 clock"] + #[inline(always)] + pub fn uart2_enable(&mut self) -> UART2_ENABLE_W { + UART2_ENABLE_W { w: self } + } + #[doc = "Bit 5 - Enable I2C clock"] + #[inline(always)] + pub fn i2c_enable(&mut self) -> I2C_ENABLE_W { + I2C_ENABLE_W { w: self } + } + #[doc = "Bit 4 - Enable Wakeup CaptureTimer clock"] + #[inline(always)] + pub fn wakeupct_enable(&mut self) -> WAKEUPCT_ENABLE_W { + WAKEUPCT_ENABLE_W { w: self } + } + #[doc = "Bit 3 - Enable TIMER0 and TIMER2 clock"] + #[inline(always)] + pub fn tmr_enable(&mut self) -> TMR_ENABLE_W { + TMR_ENABLE_W { w: self } + } + #[doc = "Bits 0:1 - Division factor for TIMER0 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8"] + #[inline(always)] + pub fn tmr_div(&mut self) -> TMR_DIV_W { + TMR_DIV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Peripheral divider register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_per_reg](index.html) module"] +pub struct CLK_PER_REG_SPEC; +impl crate::RegisterSpec for CLK_PER_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_per_reg::R](R) reader structure"] +impl crate::Readable for CLK_PER_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_per_reg::W](W) writer structure"] +impl crate::Writable for CLK_PER_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_PER_REG to value 0x0800"] +impl crate::Resettable for CLK_PER_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0800 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_radio_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_radio_reg.rs new file mode 100644 index 0000000..27f9c1a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_radio_reg.rs @@ -0,0 +1,244 @@ +#[doc = "Register `CLK_RADIO_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_RADIO_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BLE_ENABLE` reader - Enable the BLE core clocks"] +pub struct BLE_ENABLE_R(crate::FieldReader); +impl BLE_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_ENABLE` writer - Enable the BLE core clocks"] +pub struct BLE_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `BLE_LP_RESET` reader - Reset for the BLE LP timer"] +pub struct BLE_LP_RESET_R(crate::FieldReader); +impl BLE_LP_RESET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_LP_RESET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_LP_RESET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_LP_RESET` writer - Reset for the BLE LP timer"] +pub struct BLE_LP_RESET_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_LP_RESET_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `BLE_DIV` reader - Division factor for BLE core blocks 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8 The programmed frequency should not be lower than 8 MHz and not faster than the programmed CPU clock frequency. Refer also to BLE_CNTL2_REG\\[BLE_CLK_SEL\\]."] +pub struct BLE_DIV_R(crate::FieldReader); +impl BLE_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLE_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_DIV` writer - Division factor for BLE core blocks 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8 The programmed frequency should not be lower than 8 MHz and not faster than the programmed CPU clock frequency. Refer also to BLE_CNTL2_REG\\[BLE_CLK_SEL\\]."] +pub struct BLE_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_DIV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u16 & 3) << 4); + self.w + } +} +#[doc = "Field `RFCU_ENABLE` reader - Enable the RF control Unit clock"] +pub struct RFCU_ENABLE_R(crate::FieldReader); +impl RFCU_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFCU_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFCU_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFCU_ENABLE` writer - Enable the RF control Unit clock"] +pub struct RFCU_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> RFCU_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +impl R { + #[doc = "Bit 7 - Enable the BLE core clocks"] + #[inline(always)] + pub fn ble_enable(&self) -> BLE_ENABLE_R { + BLE_ENABLE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Reset for the BLE LP timer"] + #[inline(always)] + pub fn ble_lp_reset(&self) -> BLE_LP_RESET_R { + BLE_LP_RESET_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 4:5 - Division factor for BLE core blocks 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8 The programmed frequency should not be lower than 8 MHz and not faster than the programmed CPU clock frequency. Refer also to BLE_CNTL2_REG\\[BLE_CLK_SEL\\]."] + #[inline(always)] + pub fn ble_div(&self) -> BLE_DIV_R { + BLE_DIV_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bit 3 - Enable the RF control Unit clock"] + #[inline(always)] + pub fn rfcu_enable(&self) -> RFCU_ENABLE_R { + RFCU_ENABLE_R::new(((self.bits >> 3) & 1) != 0) + } +} +impl W { + #[doc = "Bit 7 - Enable the BLE core clocks"] + #[inline(always)] + pub fn ble_enable(&mut self) -> BLE_ENABLE_W { + BLE_ENABLE_W { w: self } + } + #[doc = "Bit 6 - Reset for the BLE LP timer"] + #[inline(always)] + pub fn ble_lp_reset(&mut self) -> BLE_LP_RESET_W { + BLE_LP_RESET_W { w: self } + } + #[doc = "Bits 4:5 - Division factor for BLE core blocks 0x0: divide by 1 0x1: divide by 2 0x2: divide by 4 0x3: divide by 8 The programmed frequency should not be lower than 8 MHz and not faster than the programmed CPU clock frequency. Refer also to BLE_CNTL2_REG\\[BLE_CLK_SEL\\]."] + #[inline(always)] + pub fn ble_div(&mut self) -> BLE_DIV_W { + BLE_DIV_W { w: self } + } + #[doc = "Bit 3 - Enable the RF control Unit clock"] + #[inline(always)] + pub fn rfcu_enable(&mut self) -> RFCU_ENABLE_W { + RFCU_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Radio PLL control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_radio_reg](index.html) module"] +pub struct CLK_RADIO_REG_SPEC; +impl crate::RegisterSpec for CLK_RADIO_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_radio_reg::R](R) reader structure"] +impl crate::Readable for CLK_RADIO_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_radio_reg::W](W) writer structure"] +impl crate::Writable for CLK_RADIO_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_RADIO_REG to value 0x40"] +impl crate::Resettable for CLK_RADIO_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x40 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32k_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32k_reg.rs new file mode 100644 index 0000000..5f2fc66 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32k_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `CLK_RC32K_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_RC32K_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RC32K_TRIM` reader - 0000 = lowest frequency 0111 = default 1111 = highest frequency"] +pub struct RC32K_TRIM_R(crate::FieldReader); +impl RC32K_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RC32K_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32K_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32K_TRIM` writer - 0000 = lowest frequency 0111 = default 1111 = highest frequency"] +pub struct RC32K_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> RC32K_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 1)) | ((value as u16 & 0x0f) << 1); + self.w + } +} +#[doc = "Field `RC32K_DISABLE` reader - Instantly disables the 32kHz RC oscillator Sleep cycles cannot happen with this clock disabled."] +pub struct RC32K_DISABLE_R(crate::FieldReader); +impl RC32K_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RC32K_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32K_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32K_DISABLE` writer - Instantly disables the 32kHz RC oscillator Sleep cycles cannot happen with this clock disabled."] +pub struct RC32K_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> RC32K_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 1:4 - 0000 = lowest frequency 0111 = default 1111 = highest frequency"] + #[inline(always)] + pub fn rc32k_trim(&self) -> RC32K_TRIM_R { + RC32K_TRIM_R::new(((self.bits >> 1) & 0x0f) as u8) + } + #[doc = "Bit 0 - Instantly disables the 32kHz RC oscillator Sleep cycles cannot happen with this clock disabled."] + #[inline(always)] + pub fn rc32k_disable(&self) -> RC32K_DISABLE_R { + RC32K_DISABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 1:4 - 0000 = lowest frequency 0111 = default 1111 = highest frequency"] + #[inline(always)] + pub fn rc32k_trim(&mut self) -> RC32K_TRIM_W { + RC32K_TRIM_W { w: self } + } + #[doc = "Bit 0 - Instantly disables the 32kHz RC oscillator Sleep cycles cannot happen with this clock disabled."] + #[inline(always)] + pub fn rc32k_disable(&mut self) -> RC32K_DISABLE_W { + RC32K_DISABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "32 kHz RC oscillator register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_rc32k_reg](index.html) module"] +pub struct CLK_RC32K_REG_SPEC; +impl crate::RegisterSpec for CLK_RC32K_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_rc32k_reg::R](R) reader structure"] +impl crate::Readable for CLK_RC32K_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_rc32k_reg::W](W) writer structure"] +impl crate::Writable for CLK_RC32K_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_RC32K_REG to value 0x0e"] +impl crate::Resettable for CLK_RC32K_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0e + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32m_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32m_reg.rs new file mode 100644 index 0000000..4bab7ae --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_rc32m_reg.rs @@ -0,0 +1,224 @@ +#[doc = "Register `CLK_RC32M_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_RC32M_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RC32M_COSC` reader - C-adjust of RC-oscillator A higher value of COSC results in a lower frequency"] +pub struct RC32M_COSC_R(crate::FieldReader); +impl RC32M_COSC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RC32M_COSC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32M_COSC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32M_COSC` writer - C-adjust of RC-oscillator A higher value of COSC results in a lower frequency"] +pub struct RC32M_COSC_W<'a> { + w: &'a mut W, +} +impl<'a> RC32M_COSC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 7)) | ((value as u16 & 0x0f) << 7); + self.w + } +} +#[doc = "Field `RC32M_RANGE` reader - Coarse adjust A higher value of RANGE results in a higher frequency, values 2 and 3 are equal"] +pub struct RC32M_RANGE_R(crate::FieldReader); +impl RC32M_RANGE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RC32M_RANGE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32M_RANGE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32M_RANGE` writer - Coarse adjust A higher value of RANGE results in a higher frequency, values 2 and 3 are equal"] +pub struct RC32M_RANGE_W<'a> { + w: &'a mut W, +} +impl<'a> RC32M_RANGE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 5)) | ((value as u16 & 3) << 5); + self.w + } +} +#[doc = "Field `RC32M_BIAS` reader - Bias adjustment"] +pub struct RC32M_BIAS_R(crate::FieldReader); +impl RC32M_BIAS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RC32M_BIAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32M_BIAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32M_BIAS` writer - Bias adjustment"] +pub struct RC32M_BIAS_W<'a> { + w: &'a mut W, +} +impl<'a> RC32M_BIAS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 1)) | ((value as u16 & 0x0f) << 1); + self.w + } +} +#[doc = "Field `RC32M_DISABLE` reader - Instantly disables the 32MHz RC oscillator Disabling of the oscillator during sleep happens automatically."] +pub struct RC32M_DISABLE_R(crate::FieldReader); +impl RC32M_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RC32M_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RC32M_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RC32M_DISABLE` writer - Instantly disables the 32MHz RC oscillator Disabling of the oscillator during sleep happens automatically."] +pub struct RC32M_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> RC32M_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 7:10 - C-adjust of RC-oscillator A higher value of COSC results in a lower frequency"] + #[inline(always)] + pub fn rc32m_cosc(&self) -> RC32M_COSC_R { + RC32M_COSC_R::new(((self.bits >> 7) & 0x0f) as u8) + } + #[doc = "Bits 5:6 - Coarse adjust A higher value of RANGE results in a higher frequency, values 2 and 3 are equal"] + #[inline(always)] + pub fn rc32m_range(&self) -> RC32M_RANGE_R { + RC32M_RANGE_R::new(((self.bits >> 5) & 3) as u8) + } + #[doc = "Bits 1:4 - Bias adjustment"] + #[inline(always)] + pub fn rc32m_bias(&self) -> RC32M_BIAS_R { + RC32M_BIAS_R::new(((self.bits >> 1) & 0x0f) as u8) + } + #[doc = "Bit 0 - Instantly disables the 32MHz RC oscillator Disabling of the oscillator during sleep happens automatically."] + #[inline(always)] + pub fn rc32m_disable(&self) -> RC32M_DISABLE_R { + RC32M_DISABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 7:10 - C-adjust of RC-oscillator A higher value of COSC results in a lower frequency"] + #[inline(always)] + pub fn rc32m_cosc(&mut self) -> RC32M_COSC_W { + RC32M_COSC_W { w: self } + } + #[doc = "Bits 5:6 - Coarse adjust A higher value of RANGE results in a higher frequency, values 2 and 3 are equal"] + #[inline(always)] + pub fn rc32m_range(&mut self) -> RC32M_RANGE_W { + RC32M_RANGE_W { w: self } + } + #[doc = "Bits 1:4 - Bias adjustment"] + #[inline(always)] + pub fn rc32m_bias(&mut self) -> RC32M_BIAS_W { + RC32M_BIAS_W { w: self } + } + #[doc = "Bit 0 - Instantly disables the 32MHz RC oscillator Disabling of the oscillator during sleep happens automatically."] + #[inline(always)] + pub fn rc32m_disable(&mut self) -> RC32M_DISABLE_W { + RC32M_DISABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Fast RC control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_rc32m_reg](index.html) module"] +pub struct CLK_RC32M_REG_SPEC; +impl crate::RegisterSpec for CLK_RC32M_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_rc32m_reg::R](R) reader structure"] +impl crate::Readable for CLK_RC32M_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_rc32m_reg::W](W) writer structure"] +impl crate::Writable for CLK_RC32M_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_RC32M_REG to value 0x078e"] +impl crate::Resettable for CLK_RC32M_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x078e + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_rcx_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_rcx_reg.rs new file mode 100644 index 0000000..d84eee2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_rcx_reg.rs @@ -0,0 +1,281 @@ +#[doc = "Register `CLK_RCX_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_RCX_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RCX_BIAS` reader - LDO bias current. 0x0: minimum 0xF: maximum"] +pub struct RCX_BIAS_R(crate::FieldReader); +impl RCX_BIAS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RCX_BIAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RCX_BIAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RCX_BIAS` writer - LDO bias current. 0x0: minimum 0xF: maximum"] +pub struct RCX_BIAS_W<'a> { + w: &'a mut W, +} +impl<'a> RCX_BIAS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u16 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `RCX_C0` reader - Add unit capacitance to RC-time delay."] +pub struct RCX_C0_R(crate::FieldReader); +impl RCX_C0_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RCX_C0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RCX_C0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RCX_C0` writer - Add unit capacitance to RC-time delay."] +pub struct RCX_C0_W<'a> { + w: &'a mut W, +} +impl<'a> RCX_C0_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `RCX_CADJUST` reader - Adjust capacitance part of RC-time delay. 0x00: minimum capacitance 0x1F: maximum capacitance"] +pub struct RCX_CADJUST_R(crate::FieldReader); +impl RCX_CADJUST_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RCX_CADJUST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RCX_CADJUST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RCX_CADJUST` writer - Adjust capacitance part of RC-time delay. 0x00: minimum capacitance 0x1F: maximum capacitance"] +pub struct RCX_CADJUST_W<'a> { + w: &'a mut W, +} +impl<'a> RCX_CADJUST_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 2)) | ((value as u16 & 0x1f) << 2); + self.w + } +} +#[doc = "Field `RCX_RADJUST` reader - Adjust resistance part of RC-time delay. Lower resistance increases power consumption. 0x0: maximum resistance 0x1: minimum resistance"] +pub struct RCX_RADJUST_R(crate::FieldReader); +impl RCX_RADJUST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RCX_RADJUST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RCX_RADJUST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RCX_RADJUST` writer - Adjust resistance part of RC-time delay. Lower resistance increases power consumption. 0x0: maximum resistance 0x1: minimum resistance"] +pub struct RCX_RADJUST_W<'a> { + w: &'a mut W, +} +impl<'a> RCX_RADJUST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `RCX_ENABLE` reader - Enable the RCX oscillator"] +pub struct RCX_ENABLE_R(crate::FieldReader); +impl RCX_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RCX_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RCX_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RCX_ENABLE` writer - Enable the RCX oscillator"] +pub struct RCX_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> RCX_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 8:11 - LDO bias current. 0x0: minimum 0xF: maximum"] + #[inline(always)] + pub fn rcx_bias(&self) -> RCX_BIAS_R { + RCX_BIAS_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bit 7 - Add unit capacitance to RC-time delay."] + #[inline(always)] + pub fn rcx_c0(&self) -> RCX_C0_R { + RCX_C0_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 2:6 - Adjust capacitance part of RC-time delay. 0x00: minimum capacitance 0x1F: maximum capacitance"] + #[inline(always)] + pub fn rcx_cadjust(&self) -> RCX_CADJUST_R { + RCX_CADJUST_R::new(((self.bits >> 2) & 0x1f) as u8) + } + #[doc = "Bit 1 - Adjust resistance part of RC-time delay. Lower resistance increases power consumption. 0x0: maximum resistance 0x1: minimum resistance"] + #[inline(always)] + pub fn rcx_radjust(&self) -> RCX_RADJUST_R { + RCX_RADJUST_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Enable the RCX oscillator"] + #[inline(always)] + pub fn rcx_enable(&self) -> RCX_ENABLE_R { + RCX_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 8:11 - LDO bias current. 0x0: minimum 0xF: maximum"] + #[inline(always)] + pub fn rcx_bias(&mut self) -> RCX_BIAS_W { + RCX_BIAS_W { w: self } + } + #[doc = "Bit 7 - Add unit capacitance to RC-time delay."] + #[inline(always)] + pub fn rcx_c0(&mut self) -> RCX_C0_W { + RCX_C0_W { w: self } + } + #[doc = "Bits 2:6 - Adjust capacitance part of RC-time delay. 0x00: minimum capacitance 0x1F: maximum capacitance"] + #[inline(always)] + pub fn rcx_cadjust(&mut self) -> RCX_CADJUST_W { + RCX_CADJUST_W { w: self } + } + #[doc = "Bit 1 - Adjust resistance part of RC-time delay. Lower resistance increases power consumption. 0x0: maximum resistance 0x1: minimum resistance"] + #[inline(always)] + pub fn rcx_radjust(&mut self) -> RCX_RADJUST_W { + RCX_RADJUST_W { w: self } + } + #[doc = "Bit 0 - Enable the RCX oscillator"] + #[inline(always)] + pub fn rcx_enable(&mut self) -> RCX_ENABLE_W { + RCX_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RCX-oscillator control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_rcx_reg](index.html) module"] +pub struct CLK_RCX_REG_SPEC; +impl crate::RegisterSpec for CLK_RCX_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_rcx_reg::R](R) reader structure"] +impl crate::Readable for CLK_RCX_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_rcx_reg::W](W) writer structure"] +impl crate::Writable for CLK_RCX_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_RCX_REG to value 0x0afc"] +impl crate::Resettable for CLK_RCX_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0afc + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/clk_xtal32k_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/clk_xtal32k_reg.rs new file mode 100644 index 0000000..a92a701 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/clk_xtal32k_reg.rs @@ -0,0 +1,285 @@ +#[doc = "Register `CLK_XTAL32K_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CLK_XTAL32K_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL32K_XTAL1_BIAS_DISABLE` reader - "] +pub struct XTAL32K_XTAL1_BIAS_DISABLE_R(crate::FieldReader); +impl XTAL32K_XTAL1_BIAS_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + XTAL32K_XTAL1_BIAS_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32K_XTAL1_BIAS_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32K_XTAL1_BIAS_DISABLE` writer - "] +pub struct XTAL32K_XTAL1_BIAS_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32K_XTAL1_BIAS_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `XTAL32K_DISABLE_AMPREG` reader - Setting this bit disables the amplitude regulation of the XTAL32kHz oscillator. Set this bit to '1' for an external clock to XTAL32Kp Keep this bit '0' with a crystal between XTAL32Kp and XTAL32Km"] +pub struct XTAL32K_DISABLE_AMPREG_R(crate::FieldReader); +impl XTAL32K_DISABLE_AMPREG_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + XTAL32K_DISABLE_AMPREG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32K_DISABLE_AMPREG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32K_DISABLE_AMPREG` writer - Setting this bit disables the amplitude regulation of the XTAL32kHz oscillator. Set this bit to '1' for an external clock to XTAL32Kp Keep this bit '0' with a crystal between XTAL32Kp and XTAL32Km"] +pub struct XTAL32K_DISABLE_AMPREG_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32K_DISABLE_AMPREG_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `XTAL32K_CUR` reader - Bias current for the 32kHz XTAL oscillator. 0000 is minimum, 1111 is maximum, 0011 is default. For each application there is an optimal setting for which the start-up behavior is optimal"] +pub struct XTAL32K_CUR_R(crate::FieldReader); +impl XTAL32K_CUR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL32K_CUR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32K_CUR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32K_CUR` writer - Bias current for the 32kHz XTAL oscillator. 0000 is minimum, 1111 is maximum, 0011 is default. For each application there is an optimal setting for which the start-up behavior is optimal"] +pub struct XTAL32K_CUR_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32K_CUR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 3)) | ((value as u16 & 0x0f) << 3); + self.w + } +} +#[doc = "Field `XTAL32K_RBIAS` reader - Setting for the bias resistor. 00 is maximum, 11 is minimum. Prefered setting will be provided by Dialog"] +pub struct XTAL32K_RBIAS_R(crate::FieldReader); +impl XTAL32K_RBIAS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL32K_RBIAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32K_RBIAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32K_RBIAS` writer - Setting for the bias resistor. 00 is maximum, 11 is minimum. Prefered setting will be provided by Dialog"] +pub struct XTAL32K_RBIAS_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32K_RBIAS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 1)) | ((value as u16 & 3) << 1); + self.w + } +} +#[doc = "Field `XTAL32K_ENABLE` reader - Enables the 32kHz XTAL oscillator. Also set GP_DATA_REG\\[P03_P04_FILT_DIS\\] += 1 for lowest current consumption."] +pub struct XTAL32K_ENABLE_R(crate::FieldReader); +impl XTAL32K_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + XTAL32K_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32K_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32K_ENABLE` writer - Enables the 32kHz XTAL oscillator. Also set GP_DATA_REG\\[P03_P04_FILT_DIS\\] += 1 for lowest current consumption."] +pub struct XTAL32K_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32K_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 8"] + #[inline(always)] + pub fn xtal32k_xtal1_bias_disable(&self) -> XTAL32K_XTAL1_BIAS_DISABLE_R { + XTAL32K_XTAL1_BIAS_DISABLE_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - Setting this bit disables the amplitude regulation of the XTAL32kHz oscillator. Set this bit to '1' for an external clock to XTAL32Kp Keep this bit '0' with a crystal between XTAL32Kp and XTAL32Km"] + #[inline(always)] + pub fn xtal32k_disable_ampreg(&self) -> XTAL32K_DISABLE_AMPREG_R { + XTAL32K_DISABLE_AMPREG_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 3:6 - Bias current for the 32kHz XTAL oscillator. 0000 is minimum, 1111 is maximum, 0011 is default. For each application there is an optimal setting for which the start-up behavior is optimal"] + #[inline(always)] + pub fn xtal32k_cur(&self) -> XTAL32K_CUR_R { + XTAL32K_CUR_R::new(((self.bits >> 3) & 0x0f) as u8) + } + #[doc = "Bits 1:2 - Setting for the bias resistor. 00 is maximum, 11 is minimum. Prefered setting will be provided by Dialog"] + #[inline(always)] + pub fn xtal32k_rbias(&self) -> XTAL32K_RBIAS_R { + XTAL32K_RBIAS_R::new(((self.bits >> 1) & 3) as u8) + } + #[doc = "Bit 0 - Enables the 32kHz XTAL oscillator. Also set GP_DATA_REG\\[P03_P04_FILT_DIS\\] += 1 for lowest current consumption."] + #[inline(always)] + pub fn xtal32k_enable(&self) -> XTAL32K_ENABLE_R { + XTAL32K_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 8"] + #[inline(always)] + pub fn xtal32k_xtal1_bias_disable(&mut self) -> XTAL32K_XTAL1_BIAS_DISABLE_W { + XTAL32K_XTAL1_BIAS_DISABLE_W { w: self } + } + #[doc = "Bit 7 - Setting this bit disables the amplitude regulation of the XTAL32kHz oscillator. Set this bit to '1' for an external clock to XTAL32Kp Keep this bit '0' with a crystal between XTAL32Kp and XTAL32Km"] + #[inline(always)] + pub fn xtal32k_disable_ampreg(&mut self) -> XTAL32K_DISABLE_AMPREG_W { + XTAL32K_DISABLE_AMPREG_W { w: self } + } + #[doc = "Bits 3:6 - Bias current for the 32kHz XTAL oscillator. 0000 is minimum, 1111 is maximum, 0011 is default. For each application there is an optimal setting for which the start-up behavior is optimal"] + #[inline(always)] + pub fn xtal32k_cur(&mut self) -> XTAL32K_CUR_W { + XTAL32K_CUR_W { w: self } + } + #[doc = "Bits 1:2 - Setting for the bias resistor. 00 is maximum, 11 is minimum. Prefered setting will be provided by Dialog"] + #[inline(always)] + pub fn xtal32k_rbias(&mut self) -> XTAL32K_RBIAS_W { + XTAL32K_RBIAS_W { w: self } + } + #[doc = "Bit 0 - Enables the 32kHz XTAL oscillator. Also set GP_DATA_REG\\[P03_P04_FILT_DIS\\] += 1 for lowest current consumption."] + #[inline(always)] + pub fn xtal32k_enable(&mut self) -> XTAL32K_ENABLE_W { + XTAL32K_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "32 kHz XTAL oscillator register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_xtal32k_reg](index.html) module"] +pub struct CLK_XTAL32K_REG_SPEC; +impl crate::RegisterSpec for CLK_XTAL32K_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [clk_xtal32k_reg::R](R) reader structure"] +impl crate::Readable for CLK_XTAL32K_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [clk_xtal32k_reg::W](W) writer structure"] +impl crate::Writable for CLK_XTAL32K_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CLK_XTAL32K_REG to value 0x2e"] +impl crate::Resettable for CLK_XTAL32K_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x2e + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/pmu_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/pmu_ctrl_reg.rs new file mode 100644 index 0000000..f711bac --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/pmu_ctrl_reg.rs @@ -0,0 +1,295 @@ +#[doc = "Register `PMU_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PMU_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MAP_BANDGAP_EN` reader - Enable wakeup diagnostics mapping. When set, these functions are mapped (please set direction to output) P0\\[2\\]: BANDGAP_ENABLE P0\\[1\\]: Power WOKENUP Note: P0\\[2\\] +assigned also to SWD_CLK, thus the debugger must be detached before entering into sleep mode with MAP_BANDGAP_EN=1. Refer also to SYS_STAT_REG->DBG_IS_UP."] +pub struct MAP_BANDGAP_EN_R(crate::FieldReader); +impl MAP_BANDGAP_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MAP_BANDGAP_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MAP_BANDGAP_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MAP_BANDGAP_EN` writer - Enable wakeup diagnostics mapping. When set, these functions are mapped (please set direction to output) P0\\[2\\]: BANDGAP_ENABLE P0\\[1\\]: Power WOKENUP Note: P0\\[2\\] +assigned also to SWD_CLK, thus the debugger must be detached before entering into sleep mode with MAP_BANDGAP_EN=1. Refer also to SYS_STAT_REG->DBG_IS_UP."] +pub struct MAP_BANDGAP_EN_W<'a> { + w: &'a mut W, +} +impl<'a> MAP_BANDGAP_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `OTP_COPY_DIV` reader - Sets the HCLK division during OTP mirroring"] +pub struct OTP_COPY_DIV_R(crate::FieldReader); +impl OTP_COPY_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTP_COPY_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTP_COPY_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTP_COPY_DIV` writer - Sets the HCLK division during OTP mirroring"] +pub struct OTP_COPY_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> OTP_COPY_DIV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u16 & 3) << 4); + self.w + } +} +#[doc = "Field `RADIO_SLEEP` reader - Put the digital part of the radio in powerdown"] +pub struct RADIO_SLEEP_R(crate::FieldReader); +impl RADIO_SLEEP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_SLEEP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_SLEEP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_SLEEP` writer - Put the digital part of the radio in powerdown"] +pub struct RADIO_SLEEP_W<'a> { + w: &'a mut W, +} +impl<'a> RADIO_SLEEP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `TIM_SLEEP` reader - Put PD_TIM in powerdown"] +pub struct TIM_SLEEP_R(crate::FieldReader); +impl TIM_SLEEP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIM_SLEEP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM_SLEEP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM_SLEEP` writer - Put PD_TIM in powerdown"] +pub struct TIM_SLEEP_W<'a> { + w: &'a mut W, +} +impl<'a> TIM_SLEEP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `RESET_ON_WAKEUP` reader - Perform a Hardware Reset after waking up. Booter will be started."] +pub struct RESET_ON_WAKEUP_R(crate::FieldReader); +impl RESET_ON_WAKEUP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RESET_ON_WAKEUP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_ON_WAKEUP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_ON_WAKEUP` writer - Perform a Hardware Reset after waking up. Booter will be started."] +pub struct RESET_ON_WAKEUP_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_ON_WAKEUP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 6 - Enable wakeup diagnostics mapping. When set, these functions are mapped (please set direction to output) P0\\[2\\]: BANDGAP_ENABLE P0\\[1\\]: Power WOKENUP Note: P0\\[2\\] +assigned also to SWD_CLK, thus the debugger must be detached before entering into sleep mode with MAP_BANDGAP_EN=1. Refer also to SYS_STAT_REG->DBG_IS_UP."] + #[inline(always)] + pub fn map_bandgap_en(&self) -> MAP_BANDGAP_EN_R { + MAP_BANDGAP_EN_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 4:5 - Sets the HCLK division during OTP mirroring"] + #[inline(always)] + pub fn otp_copy_div(&self) -> OTP_COPY_DIV_R { + OTP_COPY_DIV_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bit 2 - Put the digital part of the radio in powerdown"] + #[inline(always)] + pub fn radio_sleep(&self) -> RADIO_SLEEP_R { + RADIO_SLEEP_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Put PD_TIM in powerdown"] + #[inline(always)] + pub fn tim_sleep(&self) -> TIM_SLEEP_R { + TIM_SLEEP_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Perform a Hardware Reset after waking up. Booter will be started."] + #[inline(always)] + pub fn reset_on_wakeup(&self) -> RESET_ON_WAKEUP_R { + RESET_ON_WAKEUP_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 6 - Enable wakeup diagnostics mapping. When set, these functions are mapped (please set direction to output) P0\\[2\\]: BANDGAP_ENABLE P0\\[1\\]: Power WOKENUP Note: P0\\[2\\] +assigned also to SWD_CLK, thus the debugger must be detached before entering into sleep mode with MAP_BANDGAP_EN=1. Refer also to SYS_STAT_REG->DBG_IS_UP."] + #[inline(always)] + pub fn map_bandgap_en(&mut self) -> MAP_BANDGAP_EN_W { + MAP_BANDGAP_EN_W { w: self } + } + #[doc = "Bits 4:5 - Sets the HCLK division during OTP mirroring"] + #[inline(always)] + pub fn otp_copy_div(&mut self) -> OTP_COPY_DIV_W { + OTP_COPY_DIV_W { w: self } + } + #[doc = "Bit 2 - Put the digital part of the radio in powerdown"] + #[inline(always)] + pub fn radio_sleep(&mut self) -> RADIO_SLEEP_W { + RADIO_SLEEP_W { w: self } + } + #[doc = "Bit 1 - Put PD_TIM in powerdown"] + #[inline(always)] + pub fn tim_sleep(&mut self) -> TIM_SLEEP_W { + TIM_SLEEP_W { w: self } + } + #[doc = "Bit 0 - Perform a Hardware Reset after waking up. Booter will be started."] + #[inline(always)] + pub fn reset_on_wakeup(&mut self) -> RESET_ON_WAKEUP_W { + RESET_ON_WAKEUP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Power Management Unit control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pmu_ctrl_reg](index.html) module"] +pub struct PMU_CTRL_REG_SPEC; +impl crate::RegisterSpec for PMU_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pmu_ctrl_reg::R](R) reader structure"] +impl crate::Readable for PMU_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pmu_ctrl_reg::W](W) writer structure"] +impl crate::Writable for PMU_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PMU_CTRL_REG to value 0x06"] +impl crate::Resettable for PMU_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x06 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/pmu_sleep_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/pmu_sleep_reg.rs new file mode 100644 index 0000000..afe7108 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/pmu_sleep_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PMU_SLEEP_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PMU_SLEEP_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BG_REFRESH_INTERVAL` reader - Defines the refresh interval of reference voltages (bandgap activation and sampling), in units of 2ms."] +pub struct BG_REFRESH_INTERVAL_R(crate::FieldReader); +impl BG_REFRESH_INTERVAL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + BG_REFRESH_INTERVAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BG_REFRESH_INTERVAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BG_REFRESH_INTERVAL` writer - Defines the refresh interval of reference voltages (bandgap activation and sampling), in units of 2ms."] +pub struct BG_REFRESH_INTERVAL_W<'a> { + w: &'a mut W, +} +impl<'a> BG_REFRESH_INTERVAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl R { + #[doc = "Bits 0:11 - Defines the refresh interval of reference voltages (bandgap activation and sampling), in units of 2ms."] + #[inline(always)] + pub fn bg_refresh_interval(&self) -> BG_REFRESH_INTERVAL_R { + BG_REFRESH_INTERVAL_R::new((self.bits & 0x0fff) as u16) + } +} +impl W { + #[doc = "Bits 0:11 - Defines the refresh interval of reference voltages (bandgap activation and sampling), in units of 2ms."] + #[inline(always)] + pub fn bg_refresh_interval(&mut self) -> BG_REFRESH_INTERVAL_W { + BG_REFRESH_INTERVAL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Bandgap refresh interval during sleep\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pmu_sleep_reg](index.html) module"] +pub struct PMU_SLEEP_REG_SPEC; +impl crate::RegisterSpec for PMU_SLEEP_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pmu_sleep_reg::R](R) reader structure"] +impl crate::Readable for PMU_SLEEP_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pmu_sleep_reg::W](W) writer structure"] +impl crate::Writable for PMU_SLEEP_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PMU_SLEEP_REG to value 0x80"] +impl crate::Resettable for PMU_SLEEP_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x80 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/por_pin_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/por_pin_reg.rs new file mode 100644 index 0000000..46971a9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/por_pin_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `POR_PIN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `POR_PIN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `POR_PIN_POLARITY` reader - 0: Active Low 1: Active High Note: This applies only for the GPIO pin. Reset pad has a fixed polarity"] +pub struct POR_PIN_POLARITY_R(crate::FieldReader); +impl POR_PIN_POLARITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_PIN_POLARITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_PIN_POLARITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_PIN_POLARITY` writer - 0: Active Low 1: Active High Note: This applies only for the GPIO pin. Reset pad has a fixed polarity"] +pub struct POR_PIN_POLARITY_W<'a> { + w: &'a mut W, +} +impl<'a> POR_PIN_POLARITY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `POR_PIN_SELECT` reader - Selects the GPIO which is used for POR generation. 0x0: GPIO pin POReset disabled 0x1: P0_0 0x2: P0_1 ... 0xB: P0_10 0xC: P0_11 0xD - 0xF: reserved"] +pub struct POR_PIN_SELECT_R(crate::FieldReader); +impl POR_PIN_SELECT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + POR_PIN_SELECT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_PIN_SELECT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_PIN_SELECT` writer - Selects the GPIO which is used for POR generation. 0x0: GPIO pin POReset disabled 0x1: P0_0 0x2: P0_1 ... 0xB: P0_10 0xC: P0_11 0xD - 0xF: reserved"] +pub struct POR_PIN_SELECT_W<'a> { + w: &'a mut W, +} +impl<'a> POR_PIN_SELECT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 7 - 0: Active Low 1: Active High Note: This applies only for the GPIO pin. Reset pad has a fixed polarity"] + #[inline(always)] + pub fn por_pin_polarity(&self) -> POR_PIN_POLARITY_R { + POR_PIN_POLARITY_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 0:3 - Selects the GPIO which is used for POR generation. 0x0: GPIO pin POReset disabled 0x1: P0_0 0x2: P0_1 ... 0xB: P0_10 0xC: P0_11 0xD - 0xF: reserved"] + #[inline(always)] + pub fn por_pin_select(&self) -> POR_PIN_SELECT_R { + POR_PIN_SELECT_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bit 7 - 0: Active Low 1: Active High Note: This applies only for the GPIO pin. Reset pad has a fixed polarity"] + #[inline(always)] + pub fn por_pin_polarity(&mut self) -> POR_PIN_POLARITY_W { + POR_PIN_POLARITY_W { w: self } + } + #[doc = "Bits 0:3 - Selects the GPIO which is used for POR generation. 0x0: GPIO pin POReset disabled 0x1: P0_0 0x2: P0_1 ... 0xB: P0_10 0xC: P0_11 0xD - 0xF: reserved"] + #[inline(always)] + pub fn por_pin_select(&mut self) -> POR_PIN_SELECT_W { + POR_PIN_SELECT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Selects a GPIO pin for POR generation\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [por_pin_reg](index.html) module"] +pub struct POR_PIN_REG_SPEC; +impl crate::RegisterSpec for POR_PIN_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [por_pin_reg::R](R) reader structure"] +impl crate::Readable for POR_PIN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [por_pin_reg::W](W) writer structure"] +impl crate::Writable for POR_PIN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets POR_PIN_REG to value 0"] +impl crate::Resettable for POR_PIN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/por_timer_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/por_timer_reg.rs new file mode 100644 index 0000000..fc8c09f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/por_timer_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `POR_TIMER_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `POR_TIMER_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `POR_TIME` reader - Time for the POReset to happen. Formula: Time = POR_TIME x 4096 x RC32k clock period Default value: ~3 seconds When set to 0x00, the POR TIMER is disabled."] +pub struct POR_TIME_R(crate::FieldReader); +impl POR_TIME_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + POR_TIME_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_TIME_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_TIME` writer - Time for the POReset to happen. Formula: Time = POR_TIME x 4096 x RC32k clock period Default value: ~3 seconds When set to 0x00, the POR TIMER is disabled."] +pub struct POR_TIME_W<'a> { + w: &'a mut W, +} +impl<'a> POR_TIME_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x7f) | (value as u16 & 0x7f); + self.w + } +} +impl R { + #[doc = "Bits 0:6 - Time for the POReset to happen. Formula: Time = POR_TIME x 4096 x RC32k clock period Default value: ~3 seconds When set to 0x00, the POR TIMER is disabled."] + #[inline(always)] + pub fn por_time(&self) -> POR_TIME_R { + POR_TIME_R::new((self.bits & 0x7f) as u8) + } +} +impl W { + #[doc = "Bits 0:6 - Time for the POReset to happen. Formula: Time = POR_TIME x 4096 x RC32k clock period Default value: ~3 seconds When set to 0x00, the POR TIMER is disabled."] + #[inline(always)] + pub fn por_time(&mut self) -> POR_TIME_W { + POR_TIME_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Time for POR to happen\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [por_timer_reg](index.html) module"] +pub struct POR_TIMER_REG_SPEC; +impl crate::RegisterSpec for POR_TIMER_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [por_timer_reg::R](R) reader structure"] +impl crate::Readable for POR_TIMER_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [por_timer_reg::W](W) writer structure"] +impl crate::Writable for POR_TIMER_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets POR_TIMER_REG to value 0x18"] +impl crate::Resettable for POR_TIMER_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x18 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/power_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/power_ctrl_reg.rs new file mode 100644 index 0000000..9e07cb2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/power_ctrl_reg.rs @@ -0,0 +1,761 @@ +#[doc = "Register `POWER_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `POWER_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `VBAT_HL_CONNECT_MODE` reader - Sets the control mode fo the switch between VBAT_HIGH and VBAT_LOW 0: Manual (default) 1: Automatic (boost mode only)"] +pub struct VBAT_HL_CONNECT_MODE_R(crate::FieldReader); +impl VBAT_HL_CONNECT_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + VBAT_HL_CONNECT_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for VBAT_HL_CONNECT_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `VBAT_HL_CONNECT_MODE` writer - Sets the control mode fo the switch between VBAT_HIGH and VBAT_LOW 0: Manual (default) 1: Automatic (boost mode only)"] +pub struct VBAT_HL_CONNECT_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> VBAT_HL_CONNECT_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u16 & 1) << 15); + self.w + } +} +#[doc = "Field `POR_VBAT_HIGH_HYST_DIS` reader - "] +pub struct POR_VBAT_HIGH_HYST_DIS_R(crate::FieldReader); +impl POR_VBAT_HIGH_HYST_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_HIGH_HYST_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_HIGH_HYST_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_HIGH_HYST_DIS` writer - "] +pub struct POR_VBAT_HIGH_HYST_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_HIGH_HYST_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u16 & 1) << 14); + self.w + } +} +#[doc = "Field `POR_VBAT_HIGH_HYST_SEL` reader - "] +pub struct POR_VBAT_HIGH_HYST_SEL_R(crate::FieldReader); +impl POR_VBAT_HIGH_HYST_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_HIGH_HYST_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_HIGH_HYST_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_HIGH_HYST_SEL` writer - "] +pub struct POR_VBAT_HIGH_HYST_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_HIGH_HYST_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u16 & 1) << 13); + self.w + } +} +#[doc = "Field `POR_VBAT_HIGH_DISABLE` reader - Disable por_vbat_high circuit"] +pub struct POR_VBAT_HIGH_DISABLE_R(crate::FieldReader); +impl POR_VBAT_HIGH_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_HIGH_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_HIGH_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_HIGH_DISABLE` writer - Disable por_vbat_high circuit"] +pub struct POR_VBAT_HIGH_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_HIGH_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u16 & 1) << 12); + self.w + } +} +#[doc = "Field `POR_VBAT_LOW_HYST_DIS` reader - "] +pub struct POR_VBAT_LOW_HYST_DIS_R(crate::FieldReader); +impl POR_VBAT_LOW_HYST_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_LOW_HYST_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_LOW_HYST_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_LOW_HYST_DIS` writer - "] +pub struct POR_VBAT_LOW_HYST_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_LOW_HYST_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `POR_VBAT_LOW_HYST_SEL` reader - "] +pub struct POR_VBAT_LOW_HYST_SEL_R(crate::FieldReader); +impl POR_VBAT_LOW_HYST_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_LOW_HYST_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_LOW_HYST_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_LOW_HYST_SEL` writer - "] +pub struct POR_VBAT_LOW_HYST_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_LOW_HYST_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `POR_VBAT_LOW_DISABLE` reader - Disable por_vbat_low circuit"] +pub struct POR_VBAT_LOW_DISABLE_R(crate::FieldReader); +impl POR_VBAT_LOW_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + POR_VBAT_LOW_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for POR_VBAT_LOW_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `POR_VBAT_LOW_DISABLE` writer - Disable por_vbat_low circuit"] +pub struct POR_VBAT_LOW_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> POR_VBAT_LOW_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `CP_DISABLE` reader - Disables LDO_CORE charge-pump circuit"] +pub struct CP_DISABLE_R(crate::FieldReader); +impl CP_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CP_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CP_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CP_DISABLE` writer - Disables LDO_CORE charge-pump circuit"] +pub struct CP_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> CP_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `LDO_VREF_HOLD_FORCE` reader - Forces LDO references in HOLD mode"] +pub struct LDO_VREF_HOLD_FORCE_R(crate::FieldReader); +impl LDO_VREF_HOLD_FORCE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_VREF_HOLD_FORCE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_VREF_HOLD_FORCE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_VREF_HOLD_FORCE` writer - Forces LDO references in HOLD mode"] +pub struct LDO_VREF_HOLD_FORCE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_VREF_HOLD_FORCE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `LDO_LOW_CTRL_REG` reader - 00: High-current mode in active, LDO_LOW OFF in sleep 01: LDO_LOW OFF 10: Low-current mode in active, Low-current mode in sleep 11: High-current mode in active, Low-current mode in sleep"] +pub struct LDO_LOW_CTRL_REG_R(crate::FieldReader); +impl LDO_LOW_CTRL_REG_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_LOW_CTRL_REG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_LOW_CTRL_REG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_LOW_CTRL_REG` writer - 00: High-current mode in active, LDO_LOW OFF in sleep 01: LDO_LOW OFF 10: Low-current mode in active, Low-current mode in sleep 11: High-current mode in active, Low-current mode in sleep"] +pub struct LDO_LOW_CTRL_REG_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_LOW_CTRL_REG_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 5)) | ((value as u16 & 3) << 5); + self.w + } +} +#[doc = "Field `LDO_CORE_DISABLE` reader - Disables LDO_CORE"] +pub struct LDO_CORE_DISABLE_R(crate::FieldReader); +impl LDO_CORE_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_CORE_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_CORE_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_CORE_DISABLE` writer - Disables LDO_CORE"] +pub struct LDO_CORE_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_CORE_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `LDO_CORE_RET_ENABLE` reader - LDO_CORE_RETENTION 0: Disabled 1: Enabled"] +pub struct LDO_CORE_RET_ENABLE_R(crate::FieldReader); +impl LDO_CORE_RET_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_CORE_RET_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_CORE_RET_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_CORE_RET_ENABLE` writer - LDO_CORE_RETENTION 0: Disabled 1: Enabled"] +pub struct LDO_CORE_RET_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_CORE_RET_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `VBAT_HL_CONNECT` reader - Switch between VBAT_HIGH and VBAT_LOW 0: Open 1: Closed"] +pub struct VBAT_HL_CONNECT_R(crate::FieldReader); +impl VBAT_HL_CONNECT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + VBAT_HL_CONNECT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for VBAT_HL_CONNECT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `VBAT_HL_CONNECT` writer - Switch between VBAT_HIGH and VBAT_LOW 0: Open 1: Closed"] +pub struct VBAT_HL_CONNECT_W<'a> { + w: &'a mut W, +} +impl<'a> VBAT_HL_CONNECT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `CMP_VBAT_HIGH_OK_ENABLE` reader - Enable cmp_vbat_high_ok"] +pub struct CMP_VBAT_HIGH_OK_ENABLE_R(crate::FieldReader); +impl CMP_VBAT_HIGH_OK_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CMP_VBAT_HIGH_OK_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CMP_VBAT_HIGH_OK_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CMP_VBAT_HIGH_OK_ENABLE` writer - Enable cmp_vbat_high_ok"] +pub struct CMP_VBAT_HIGH_OK_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> CMP_VBAT_HIGH_OK_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `CMP_VBAT_HIGH_NOK_ENABLE` reader - Enable cmp_vbat_high_nok"] +pub struct CMP_VBAT_HIGH_NOK_ENABLE_R(crate::FieldReader); +impl CMP_VBAT_HIGH_NOK_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CMP_VBAT_HIGH_NOK_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CMP_VBAT_HIGH_NOK_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CMP_VBAT_HIGH_NOK_ENABLE` writer - Enable cmp_vbat_high_nok"] +pub struct CMP_VBAT_HIGH_NOK_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> CMP_VBAT_HIGH_NOK_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 15 - Sets the control mode fo the switch between VBAT_HIGH and VBAT_LOW 0: Manual (default) 1: Automatic (boost mode only)"] + #[inline(always)] + pub fn vbat_hl_connect_mode(&self) -> VBAT_HL_CONNECT_MODE_R { + VBAT_HL_CONNECT_MODE_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14"] + #[inline(always)] + pub fn por_vbat_high_hyst_dis(&self) -> POR_VBAT_HIGH_HYST_DIS_R { + POR_VBAT_HIGH_HYST_DIS_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn por_vbat_high_hyst_sel(&self) -> POR_VBAT_HIGH_HYST_SEL_R { + POR_VBAT_HIGH_HYST_SEL_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12 - Disable por_vbat_high circuit"] + #[inline(always)] + pub fn por_vbat_high_disable(&self) -> POR_VBAT_HIGH_DISABLE_R { + POR_VBAT_HIGH_DISABLE_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn por_vbat_low_hyst_dis(&self) -> POR_VBAT_LOW_HYST_DIS_R { + POR_VBAT_LOW_HYST_DIS_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn por_vbat_low_hyst_sel(&self) -> POR_VBAT_LOW_HYST_SEL_R { + POR_VBAT_LOW_HYST_SEL_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - Disable por_vbat_low circuit"] + #[inline(always)] + pub fn por_vbat_low_disable(&self) -> POR_VBAT_LOW_DISABLE_R { + POR_VBAT_LOW_DISABLE_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - Disables LDO_CORE charge-pump circuit"] + #[inline(always)] + pub fn cp_disable(&self) -> CP_DISABLE_R { + CP_DISABLE_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - Forces LDO references in HOLD mode"] + #[inline(always)] + pub fn ldo_vref_hold_force(&self) -> LDO_VREF_HOLD_FORCE_R { + LDO_VREF_HOLD_FORCE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 5:6 - 00: High-current mode in active, LDO_LOW OFF in sleep 01: LDO_LOW OFF 10: Low-current mode in active, Low-current mode in sleep 11: High-current mode in active, Low-current mode in sleep"] + #[inline(always)] + pub fn ldo_low_ctrl_reg(&self) -> LDO_LOW_CTRL_REG_R { + LDO_LOW_CTRL_REG_R::new(((self.bits >> 5) & 3) as u8) + } + #[doc = "Bit 4 - Disables LDO_CORE"] + #[inline(always)] + pub fn ldo_core_disable(&self) -> LDO_CORE_DISABLE_R { + LDO_CORE_DISABLE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - LDO_CORE_RETENTION 0: Disabled 1: Enabled"] + #[inline(always)] + pub fn ldo_core_ret_enable(&self) -> LDO_CORE_RET_ENABLE_R { + LDO_CORE_RET_ENABLE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Switch between VBAT_HIGH and VBAT_LOW 0: Open 1: Closed"] + #[inline(always)] + pub fn vbat_hl_connect(&self) -> VBAT_HL_CONNECT_R { + VBAT_HL_CONNECT_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Enable cmp_vbat_high_ok"] + #[inline(always)] + pub fn cmp_vbat_high_ok_enable(&self) -> CMP_VBAT_HIGH_OK_ENABLE_R { + CMP_VBAT_HIGH_OK_ENABLE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Enable cmp_vbat_high_nok"] + #[inline(always)] + pub fn cmp_vbat_high_nok_enable(&self) -> CMP_VBAT_HIGH_NOK_ENABLE_R { + CMP_VBAT_HIGH_NOK_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 15 - Sets the control mode fo the switch between VBAT_HIGH and VBAT_LOW 0: Manual (default) 1: Automatic (boost mode only)"] + #[inline(always)] + pub fn vbat_hl_connect_mode(&mut self) -> VBAT_HL_CONNECT_MODE_W { + VBAT_HL_CONNECT_MODE_W { w: self } + } + #[doc = "Bit 14"] + #[inline(always)] + pub fn por_vbat_high_hyst_dis(&mut self) -> POR_VBAT_HIGH_HYST_DIS_W { + POR_VBAT_HIGH_HYST_DIS_W { w: self } + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn por_vbat_high_hyst_sel(&mut self) -> POR_VBAT_HIGH_HYST_SEL_W { + POR_VBAT_HIGH_HYST_SEL_W { w: self } + } + #[doc = "Bit 12 - Disable por_vbat_high circuit"] + #[inline(always)] + pub fn por_vbat_high_disable(&mut self) -> POR_VBAT_HIGH_DISABLE_W { + POR_VBAT_HIGH_DISABLE_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn por_vbat_low_hyst_dis(&mut self) -> POR_VBAT_LOW_HYST_DIS_W { + POR_VBAT_LOW_HYST_DIS_W { w: self } + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn por_vbat_low_hyst_sel(&mut self) -> POR_VBAT_LOW_HYST_SEL_W { + POR_VBAT_LOW_HYST_SEL_W { w: self } + } + #[doc = "Bit 9 - Disable por_vbat_low circuit"] + #[inline(always)] + pub fn por_vbat_low_disable(&mut self) -> POR_VBAT_LOW_DISABLE_W { + POR_VBAT_LOW_DISABLE_W { w: self } + } + #[doc = "Bit 8 - Disables LDO_CORE charge-pump circuit"] + #[inline(always)] + pub fn cp_disable(&mut self) -> CP_DISABLE_W { + CP_DISABLE_W { w: self } + } + #[doc = "Bit 7 - Forces LDO references in HOLD mode"] + #[inline(always)] + pub fn ldo_vref_hold_force(&mut self) -> LDO_VREF_HOLD_FORCE_W { + LDO_VREF_HOLD_FORCE_W { w: self } + } + #[doc = "Bits 5:6 - 00: High-current mode in active, LDO_LOW OFF in sleep 01: LDO_LOW OFF 10: Low-current mode in active, Low-current mode in sleep 11: High-current mode in active, Low-current mode in sleep"] + #[inline(always)] + pub fn ldo_low_ctrl_reg(&mut self) -> LDO_LOW_CTRL_REG_W { + LDO_LOW_CTRL_REG_W { w: self } + } + #[doc = "Bit 4 - Disables LDO_CORE"] + #[inline(always)] + pub fn ldo_core_disable(&mut self) -> LDO_CORE_DISABLE_W { + LDO_CORE_DISABLE_W { w: self } + } + #[doc = "Bit 3 - LDO_CORE_RETENTION 0: Disabled 1: Enabled"] + #[inline(always)] + pub fn ldo_core_ret_enable(&mut self) -> LDO_CORE_RET_ENABLE_W { + LDO_CORE_RET_ENABLE_W { w: self } + } + #[doc = "Bit 2 - Switch between VBAT_HIGH and VBAT_LOW 0: Open 1: Closed"] + #[inline(always)] + pub fn vbat_hl_connect(&mut self) -> VBAT_HL_CONNECT_W { + VBAT_HL_CONNECT_W { w: self } + } + #[doc = "Bit 1 - Enable cmp_vbat_high_ok"] + #[inline(always)] + pub fn cmp_vbat_high_ok_enable(&mut self) -> CMP_VBAT_HIGH_OK_ENABLE_W { + CMP_VBAT_HIGH_OK_ENABLE_W { w: self } + } + #[doc = "Bit 0 - Enable cmp_vbat_high_nok"] + #[inline(always)] + pub fn cmp_vbat_high_nok_enable(&mut self) -> CMP_VBAT_HIGH_NOK_ENABLE_W { + CMP_VBAT_HIGH_NOK_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Power management control\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [power_ctrl_reg](index.html) module"] +pub struct POWER_CTRL_REG_SPEC; +impl crate::RegisterSpec for POWER_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [power_ctrl_reg::R](R) reader structure"] +impl crate::Readable for POWER_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [power_ctrl_reg::W](W) writer structure"] +impl crate::Writable for POWER_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets POWER_CTRL_REG to value 0x4000"] +impl crate::Resettable for POWER_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x4000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/power_level_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/power_level_reg.rs new file mode 100644 index 0000000..4842e12 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/power_level_reg.rs @@ -0,0 +1,298 @@ +#[doc = "Register `POWER_LEVEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `POWER_LEVEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DCDC_TRIM` reader - Delta from DCDC_LEVEL nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] +pub struct DCDC_TRIM_R(crate::FieldReader); +impl DCDC_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCDC_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCDC_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCDC_TRIM` writer - Delta from DCDC_LEVEL nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] +pub struct DCDC_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> DCDC_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 11)) | ((value as u16 & 7) << 11); + self.w + } +} +#[doc = "Field `DCDC_LEVEL` reader - 00: 1.1 V 01: 1.8 V (default) 10: 2.5 V 11: 3.0 V"] +pub struct DCDC_LEVEL_R(crate::FieldReader); +impl DCDC_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DCDC_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCDC_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCDC_LEVEL` writer - 00: 1.1 V 01: 1.8 V (default) 10: 2.5 V 11: 3.0 V"] +pub struct DCDC_LEVEL_W<'a> { + w: &'a mut W, +} +impl<'a> DCDC_LEVEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 9)) | ((value as u16 & 3) << 9); + self.w + } +} +#[doc = "Field `LDO_CORE_RET_CUR_TRIM` reader - "] +pub struct LDO_CORE_RET_CUR_TRIM_R(crate::FieldReader); +impl LDO_CORE_RET_CUR_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_CORE_RET_CUR_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_CORE_RET_CUR_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_CORE_RET_CUR_TRIM` writer - "] +pub struct LDO_CORE_RET_CUR_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_CORE_RET_CUR_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 7)) | ((value as u16 & 3) << 7); + self.w + } +} +#[doc = "Field `LDO_XTAL_TRIM` reader - Delta from 0.9 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] +pub struct LDO_XTAL_TRIM_R(crate::FieldReader); +impl LDO_XTAL_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_XTAL_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_XTAL_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_XTAL_TRIM` writer - Delta from 0.9 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] +pub struct LDO_XTAL_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_XTAL_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u16 & 7) << 4); + self.w + } +} +#[doc = "Field `LDO_LOW_TRIM` reader - Delta from 1.1 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV (coldboot)"] +pub struct LDO_LOW_TRIM_R(crate::FieldReader); +impl LDO_LOW_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_LOW_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_LOW_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_LOW_TRIM` writer - Delta from 1.1 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV (coldboot)"] +pub struct LDO_LOW_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_LOW_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 1)) | ((value as u16 & 7) << 1); + self.w + } +} +#[doc = "Field `LDO_CORE_LEVEL` reader - "] +pub struct LDO_CORE_LEVEL_R(crate::FieldReader); +impl LDO_CORE_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_CORE_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_CORE_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_CORE_LEVEL` writer - "] +pub struct LDO_CORE_LEVEL_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_CORE_LEVEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 11:13 - Delta from DCDC_LEVEL nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] + #[inline(always)] + pub fn dcdc_trim(&self) -> DCDC_TRIM_R { + DCDC_TRIM_R::new(((self.bits >> 11) & 7) as u8) + } + #[doc = "Bits 9:10 - 00: 1.1 V 01: 1.8 V (default) 10: 2.5 V 11: 3.0 V"] + #[inline(always)] + pub fn dcdc_level(&self) -> DCDC_LEVEL_R { + DCDC_LEVEL_R::new(((self.bits >> 9) & 3) as u8) + } + #[doc = "Bits 7:8"] + #[inline(always)] + pub fn ldo_core_ret_cur_trim(&self) -> LDO_CORE_RET_CUR_TRIM_R { + LDO_CORE_RET_CUR_TRIM_R::new(((self.bits >> 7) & 3) as u8) + } + #[doc = "Bits 4:6 - Delta from 0.9 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] + #[inline(always)] + pub fn ldo_xtal_trim(&self) -> LDO_XTAL_TRIM_R { + LDO_XTAL_TRIM_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bits 1:3 - Delta from 1.1 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV (coldboot)"] + #[inline(always)] + pub fn ldo_low_trim(&self) -> LDO_LOW_TRIM_R { + LDO_LOW_TRIM_R::new(((self.bits >> 1) & 7) as u8) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ldo_core_level(&self) -> LDO_CORE_LEVEL_R { + LDO_CORE_LEVEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 11:13 - Delta from DCDC_LEVEL nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] + #[inline(always)] + pub fn dcdc_trim(&mut self) -> DCDC_TRIM_W { + DCDC_TRIM_W { w: self } + } + #[doc = "Bits 9:10 - 00: 1.1 V 01: 1.8 V (default) 10: 2.5 V 11: 3.0 V"] + #[inline(always)] + pub fn dcdc_level(&mut self) -> DCDC_LEVEL_W { + DCDC_LEVEL_W { w: self } + } + #[doc = "Bits 7:8"] + #[inline(always)] + pub fn ldo_core_ret_cur_trim(&mut self) -> LDO_CORE_RET_CUR_TRIM_W { + LDO_CORE_RET_CUR_TRIM_W { w: self } + } + #[doc = "Bits 4:6 - Delta from 0.9 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV"] + #[inline(always)] + pub fn ldo_xtal_trim(&mut self) -> LDO_XTAL_TRIM_W { + LDO_XTAL_TRIM_W { w: self } + } + #[doc = "Bits 1:3 - Delta from 1.1 V nominal value 000: -75 mV 001: -50 mV 010: -25 mV 011: 0 (default) 100: +25 mV 101: +50 mV 110: +75 mV 111: +100 mV (coldboot)"] + #[inline(always)] + pub fn ldo_low_trim(&mut self) -> LDO_LOW_TRIM_W { + LDO_LOW_TRIM_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn ldo_core_level(&mut self) -> LDO_CORE_LEVEL_W { + LDO_CORE_LEVEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Power management level and trim settings\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [power_level_reg](index.html) module"] +pub struct POWER_LEVEL_REG_SPEC; +impl crate::RegisterSpec for POWER_LEVEL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [power_level_reg::R](R) reader structure"] +impl crate::Readable for POWER_LEVEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [power_level_reg::W](W) writer structure"] +impl crate::Writable for POWER_LEVEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets POWER_LEVEL_REG to value 0x1a3e"] +impl crate::Resettable for POWER_LEVEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x1a3e + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/ram_pwr_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/ram_pwr_ctrl_reg.rs new file mode 100644 index 0000000..cbe5520 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/ram_pwr_ctrl_reg.rs @@ -0,0 +1,177 @@ +#[doc = "Register `RAM_PWR_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RAM_PWR_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RAM3_PWR_CTRL` reader - See description of RAM1_PWR_CTRL."] +pub struct RAM3_PWR_CTRL_R(crate::FieldReader); +impl RAM3_PWR_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RAM3_PWR_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAM3_PWR_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM3_PWR_CTRL` writer - See description of RAM1_PWR_CTRL."] +pub struct RAM3_PWR_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> RAM3_PWR_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u16 & 3) << 4); + self.w + } +} +#[doc = "Field `RAM2_PWR_CTRL` reader - See description of RAM1_PWR_CTRL."] +pub struct RAM2_PWR_CTRL_R(crate::FieldReader); +impl RAM2_PWR_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RAM2_PWR_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAM2_PWR_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM2_PWR_CTRL` writer - See description of RAM1_PWR_CTRL."] +pub struct RAM2_PWR_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> RAM2_PWR_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 2)) | ((value as u16 & 3) << 2); + self.w + } +} +#[doc = "Field `RAM1_PWR_CTRL` reader - Power state control of the individual RAMs. May only change when the memory isn't accessed. When in Active or Sleep mode: 0x0: Normal operation 0x1: Normal operation 0x2: Retained (no access possible) 0x3: Off (memory content corrupted) When in Extended Sleep, Deep Sleep or Hibernation mode 0x0: Retained 0x1: Off (memory content corrupted) 0x2: Retained 0x3: Off (memory content corrupted)"] +pub struct RAM1_PWR_CTRL_R(crate::FieldReader); +impl RAM1_PWR_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RAM1_PWR_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAM1_PWR_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM1_PWR_CTRL` writer - Power state control of the individual RAMs. May only change when the memory isn't accessed. When in Active or Sleep mode: 0x0: Normal operation 0x1: Normal operation 0x2: Retained (no access possible) 0x3: Off (memory content corrupted) When in Extended Sleep, Deep Sleep or Hibernation mode 0x0: Retained 0x1: Off (memory content corrupted) 0x2: Retained 0x3: Off (memory content corrupted)"] +pub struct RAM1_PWR_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> RAM1_PWR_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bits 4:5 - See description of RAM1_PWR_CTRL."] + #[inline(always)] + pub fn ram3_pwr_ctrl(&self) -> RAM3_PWR_CTRL_R { + RAM3_PWR_CTRL_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bits 2:3 - See description of RAM1_PWR_CTRL."] + #[inline(always)] + pub fn ram2_pwr_ctrl(&self) -> RAM2_PWR_CTRL_R { + RAM2_PWR_CTRL_R::new(((self.bits >> 2) & 3) as u8) + } + #[doc = "Bits 0:1 - Power state control of the individual RAMs. May only change when the memory isn't accessed. When in Active or Sleep mode: 0x0: Normal operation 0x1: Normal operation 0x2: Retained (no access possible) 0x3: Off (memory content corrupted) When in Extended Sleep, Deep Sleep or Hibernation mode 0x0: Retained 0x1: Off (memory content corrupted) 0x2: Retained 0x3: Off (memory content corrupted)"] + #[inline(always)] + pub fn ram1_pwr_ctrl(&self) -> RAM1_PWR_CTRL_R { + RAM1_PWR_CTRL_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 4:5 - See description of RAM1_PWR_CTRL."] + #[inline(always)] + pub fn ram3_pwr_ctrl(&mut self) -> RAM3_PWR_CTRL_W { + RAM3_PWR_CTRL_W { w: self } + } + #[doc = "Bits 2:3 - See description of RAM1_PWR_CTRL."] + #[inline(always)] + pub fn ram2_pwr_ctrl(&mut self) -> RAM2_PWR_CTRL_W { + RAM2_PWR_CTRL_W { w: self } + } + #[doc = "Bits 0:1 - Power state control of the individual RAMs. May only change when the memory isn't accessed. When in Active or Sleep mode: 0x0: Normal operation 0x1: Normal operation 0x2: Retained (no access possible) 0x3: Off (memory content corrupted) When in Extended Sleep, Deep Sleep or Hibernation mode 0x0: Retained 0x1: Off (memory content corrupted) 0x2: Retained 0x3: Off (memory content corrupted)"] + #[inline(always)] + pub fn ram1_pwr_ctrl(&mut self) -> RAM1_PWR_CTRL_W { + RAM1_PWR_CTRL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Control power state of System RAMS\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ram_pwr_ctrl_reg](index.html) module"] +pub struct RAM_PWR_CTRL_REG_SPEC; +impl crate::RegisterSpec for RAM_PWR_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [ram_pwr_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RAM_PWR_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ram_pwr_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RAM_PWR_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RAM_PWR_CTRL_REG to value 0"] +impl crate::Resettable for RAM_PWR_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/sys_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/sys_ctrl_reg.rs new file mode 100644 index 0000000..716ece2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/sys_ctrl_reg.rs @@ -0,0 +1,363 @@ +#[doc = "Register `SYS_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SYS_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SW_RESET` writer - Writing a '1' to this bit will reset the device, except for: SYS_CTRL_REG CLK_FREQ_TRIM_REG ..."] +pub struct SW_RESET_W<'a> { + w: &'a mut W, +} +impl<'a> SW_RESET_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u16 & 1) << 15); + self.w + } +} +#[doc = "Field `TIMEOUT_DISABLE` reader - Disables timeout in Power statemachine. By default, the statemachine continues if after 2 ms the blocks are not started up. This can be read back from ANA_STATUS_REG."] +pub struct TIMEOUT_DISABLE_R(crate::FieldReader); +impl TIMEOUT_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMEOUT_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMEOUT_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMEOUT_DISABLE` writer - Disables timeout in Power statemachine. By default, the statemachine continues if after 2 ms the blocks are not started up. This can be read back from ANA_STATUS_REG."] +pub struct TIMEOUT_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> TIMEOUT_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `DEBUGGER_ENABLE` reader - Enable the debugger. This bit is set by the booter according to the OTP header. If not set, the SWDIO and SW_CLK can be used as gpio ports. 0x0: no debugger enabled. 0x1: SW_CLK = P0\\[2\\], SW_DIO=P0\\[5\\] +0x2: SW_CLK = P0\\[2\\], SW_DIO=P0\\[1\\] +0x3: SW_CLK = P0\\[2\\], SW_DIO=P0\\[10\\]"] +pub struct DEBUGGER_ENABLE_R(crate::FieldReader); +impl DEBUGGER_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEBUGGER_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEBUGGER_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEBUGGER_ENABLE` writer - Enable the debugger. This bit is set by the booter according to the OTP header. If not set, the SWDIO and SW_CLK can be used as gpio ports. 0x0: no debugger enabled. 0x1: SW_CLK = P0\\[2\\], SW_DIO=P0\\[5\\] +0x2: SW_CLK = P0\\[2\\], SW_DIO=P0\\[1\\] +0x3: SW_CLK = P0\\[2\\], SW_DIO=P0\\[10\\]"] +pub struct DEBUGGER_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> DEBUGGER_ENABLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 7)) | ((value as u16 & 3) << 7); + self.w + } +} +#[doc = "Field `OTPC_RESET_REQ` reader - Reset request for the OTP controller."] +pub struct OTPC_RESET_REQ_R(crate::FieldReader); +impl OTPC_RESET_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTPC_RESET_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_RESET_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_RESET_REQ` writer - Reset request for the OTP controller."] +pub struct OTPC_RESET_REQ_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_RESET_REQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `OTP_COPY` reader - Enables OTP to SysRAM copy action after waking up PD_SYS"] +pub struct OTP_COPY_R(crate::FieldReader); +impl OTP_COPY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTP_COPY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTP_COPY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTP_COPY` writer - Enables OTP to SysRAM copy action after waking up PD_SYS"] +pub struct OTP_COPY_W<'a> { + w: &'a mut W, +} +impl<'a> OTP_COPY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `DEV_PHASE` reader - Sets the development phase mode. If this bit is set, in combination with the OTP_COPY bit, the OTP DMA will emulate the OTP mirroring to System RAM. No actual writing to RAM is done, but the exact same amount of time is spend as if the mirroring would take place. This is to mimic the behavior as if the System Code is already in OTP, and the mirroring takes place after waking up, but the (development) code still resides in an external source. If this bit is set to '0' and OTP_COPY='1', then the OTP DMA will actually do the OTP mirroring at wakeup."] +pub struct DEV_PHASE_R(crate::FieldReader); +impl DEV_PHASE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEV_PHASE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEV_PHASE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEV_PHASE` writer - Sets the development phase mode. If this bit is set, in combination with the OTP_COPY bit, the OTP DMA will emulate the OTP mirroring to System RAM. No actual writing to RAM is done, but the exact same amount of time is spend as if the mirroring would take place. This is to mimic the behavior as if the System Code is already in OTP, and the mirroring takes place after waking up, but the (development) code still resides in an external source. If this bit is set to '0' and OTP_COPY='1', then the OTP DMA will actually do the OTP mirroring at wakeup."] +pub struct DEV_PHASE_W<'a> { + w: &'a mut W, +} +impl<'a> DEV_PHASE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `REMAP_ADR0` reader - Controls which memory is located at address 0x0000 for execution. 0x0: ROM 0x1: OTP 0x2: RAM (SysRAM1) 0x3: RAM (SysRAM3, 28 kBytes offset) This bitfield only takes affect after a Software Reset."] +pub struct REMAP_ADR0_R(crate::FieldReader); +impl REMAP_ADR0_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + REMAP_ADR0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for REMAP_ADR0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `REMAP_ADR0` writer - Controls which memory is located at address 0x0000 for execution. 0x0: ROM 0x1: OTP 0x2: RAM (SysRAM1) 0x3: RAM (SysRAM3, 28 kBytes offset) This bitfield only takes affect after a Software Reset."] +pub struct REMAP_ADR0_W<'a> { + w: &'a mut W, +} +impl<'a> REMAP_ADR0_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 10 - Disables timeout in Power statemachine. By default, the statemachine continues if after 2 ms the blocks are not started up. This can be read back from ANA_STATUS_REG."] + #[inline(always)] + pub fn timeout_disable(&self) -> TIMEOUT_DISABLE_R { + TIMEOUT_DISABLE_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bits 7:8 - Enable the debugger. This bit is set by the booter according to the OTP header. If not set, the SWDIO and SW_CLK can be used as gpio ports. 0x0: no debugger enabled. 0x1: SW_CLK = P0\\[2\\], SW_DIO=P0\\[5\\] +0x2: SW_CLK = P0\\[2\\], SW_DIO=P0\\[1\\] +0x3: SW_CLK = P0\\[2\\], SW_DIO=P0\\[10\\]"] + #[inline(always)] + pub fn debugger_enable(&self) -> DEBUGGER_ENABLE_R { + DEBUGGER_ENABLE_R::new(((self.bits >> 7) & 3) as u8) + } + #[doc = "Bit 6 - Reset request for the OTP controller."] + #[inline(always)] + pub fn otpc_reset_req(&self) -> OTPC_RESET_REQ_R { + OTPC_RESET_REQ_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 4 - Enables OTP to SysRAM copy action after waking up PD_SYS"] + #[inline(always)] + pub fn otp_copy(&self) -> OTP_COPY_R { + OTP_COPY_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 2 - Sets the development phase mode. If this bit is set, in combination with the OTP_COPY bit, the OTP DMA will emulate the OTP mirroring to System RAM. No actual writing to RAM is done, but the exact same amount of time is spend as if the mirroring would take place. This is to mimic the behavior as if the System Code is already in OTP, and the mirroring takes place after waking up, but the (development) code still resides in an external source. If this bit is set to '0' and OTP_COPY='1', then the OTP DMA will actually do the OTP mirroring at wakeup."] + #[inline(always)] + pub fn dev_phase(&self) -> DEV_PHASE_R { + DEV_PHASE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1 - Controls which memory is located at address 0x0000 for execution. 0x0: ROM 0x1: OTP 0x2: RAM (SysRAM1) 0x3: RAM (SysRAM3, 28 kBytes offset) This bitfield only takes affect after a Software Reset."] + #[inline(always)] + pub fn remap_adr0(&self) -> REMAP_ADR0_R { + REMAP_ADR0_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 15 - Writing a '1' to this bit will reset the device, except for: SYS_CTRL_REG CLK_FREQ_TRIM_REG ..."] + #[inline(always)] + pub fn sw_reset(&mut self) -> SW_RESET_W { + SW_RESET_W { w: self } + } + #[doc = "Bit 10 - Disables timeout in Power statemachine. By default, the statemachine continues if after 2 ms the blocks are not started up. This can be read back from ANA_STATUS_REG."] + #[inline(always)] + pub fn timeout_disable(&mut self) -> TIMEOUT_DISABLE_W { + TIMEOUT_DISABLE_W { w: self } + } + #[doc = "Bits 7:8 - Enable the debugger. This bit is set by the booter according to the OTP header. If not set, the SWDIO and SW_CLK can be used as gpio ports. 0x0: no debugger enabled. 0x1: SW_CLK = P0\\[2\\], SW_DIO=P0\\[5\\] +0x2: SW_CLK = P0\\[2\\], SW_DIO=P0\\[1\\] +0x3: SW_CLK = P0\\[2\\], SW_DIO=P0\\[10\\]"] + #[inline(always)] + pub fn debugger_enable(&mut self) -> DEBUGGER_ENABLE_W { + DEBUGGER_ENABLE_W { w: self } + } + #[doc = "Bit 6 - Reset request for the OTP controller."] + #[inline(always)] + pub fn otpc_reset_req(&mut self) -> OTPC_RESET_REQ_W { + OTPC_RESET_REQ_W { w: self } + } + #[doc = "Bit 4 - Enables OTP to SysRAM copy action after waking up PD_SYS"] + #[inline(always)] + pub fn otp_copy(&mut self) -> OTP_COPY_W { + OTP_COPY_W { w: self } + } + #[doc = "Bit 2 - Sets the development phase mode. If this bit is set, in combination with the OTP_COPY bit, the OTP DMA will emulate the OTP mirroring to System RAM. No actual writing to RAM is done, but the exact same amount of time is spend as if the mirroring would take place. This is to mimic the behavior as if the System Code is already in OTP, and the mirroring takes place after waking up, but the (development) code still resides in an external source. If this bit is set to '0' and OTP_COPY='1', then the OTP DMA will actually do the OTP mirroring at wakeup."] + #[inline(always)] + pub fn dev_phase(&mut self) -> DEV_PHASE_W { + DEV_PHASE_W { w: self } + } + #[doc = "Bits 0:1 - Controls which memory is located at address 0x0000 for execution. 0x0: ROM 0x1: OTP 0x2: RAM (SysRAM1) 0x3: RAM (SysRAM3, 28 kBytes offset) This bitfield only takes affect after a Software Reset."] + #[inline(always)] + pub fn remap_adr0(&mut self) -> REMAP_ADR0_W { + REMAP_ADR0_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "System Control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sys_ctrl_reg](index.html) module"] +pub struct SYS_CTRL_REG_SPEC; +impl crate::RegisterSpec for SYS_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [sys_ctrl_reg::R](R) reader structure"] +impl crate::Readable for SYS_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [sys_ctrl_reg::W](W) writer structure"] +impl crate::Writable for SYS_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SYS_CTRL_REG to value 0x20"] +impl crate::Resettable for SYS_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x20 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/sys_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/sys_stat_reg.rs new file mode 100644 index 0000000..df27524 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/sys_stat_reg.rs @@ -0,0 +1,206 @@ +#[doc = "Register `SYS_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SYS_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL32M_SETTLED` reader - Indicates that XTAL32M has had its settle time, as defined by TRIM_CTRL_REG\\[XTAL_SETTLE_N\\]"] +pub struct XTAL32M_SETTLED_R(crate::FieldReader); +impl XTAL32M_SETTLED_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + XTAL32M_SETTLED_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_SETTLED_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32M_TRIM_READY` reader - Indicates that XTAL trimming mechanism is ready, i.e. the trimming equals CLK_FREQ_TRIM_REG."] +pub struct XTAL32M_TRIM_READY_R(crate::FieldReader); +impl XTAL32M_TRIM_READY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + XTAL32M_TRIM_READY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_TRIM_READY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DBG_IS_UP` reader - Indicates that the SW debugger is attached and in connection with the ARM."] +pub struct DBG_IS_UP_R(crate::FieldReader); +impl DBG_IS_UP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DBG_IS_UP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DBG_IS_UP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM_IS_UP` reader - Indicates that PD_TIM is functional"] +pub struct TIM_IS_UP_R(crate::FieldReader); +impl TIM_IS_UP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIM_IS_UP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM_IS_UP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM_IS_DOWN` reader - Indicates that PD_TIM is in power down"] +pub struct TIM_IS_DOWN_R(crate::FieldReader); +impl TIM_IS_DOWN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIM_IS_DOWN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM_IS_DOWN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAD_IS_UP` reader - Indicates that PD_RAD is functional"] +pub struct RAD_IS_UP_R(crate::FieldReader); +impl RAD_IS_UP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RAD_IS_UP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAD_IS_UP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAD_IS_DOWN` reader - Indicates that PD_RAD is in power down"] +pub struct RAD_IS_DOWN_R(crate::FieldReader); +impl RAD_IS_DOWN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RAD_IS_DOWN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAD_IS_DOWN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 7 - Indicates that XTAL32M has had its settle time, as defined by TRIM_CTRL_REG\\[XTAL_SETTLE_N\\]"] + #[inline(always)] + pub fn xtal32m_settled(&self) -> XTAL32M_SETTLED_R { + XTAL32M_SETTLED_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Indicates that XTAL trimming mechanism is ready, i.e. the trimming equals CLK_FREQ_TRIM_REG."] + #[inline(always)] + pub fn xtal32m_trim_ready(&self) -> XTAL32M_TRIM_READY_R { + XTAL32M_TRIM_READY_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 4 - Indicates that the SW debugger is attached and in connection with the ARM."] + #[inline(always)] + pub fn dbg_is_up(&self) -> DBG_IS_UP_R { + DBG_IS_UP_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Indicates that PD_TIM is functional"] + #[inline(always)] + pub fn tim_is_up(&self) -> TIM_IS_UP_R { + TIM_IS_UP_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Indicates that PD_TIM is in power down"] + #[inline(always)] + pub fn tim_is_down(&self) -> TIM_IS_DOWN_R { + TIM_IS_DOWN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Indicates that PD_RAD is functional"] + #[inline(always)] + pub fn rad_is_up(&self) -> RAD_IS_UP_R { + RAD_IS_UP_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Indicates that PD_RAD is in power down"] + #[inline(always)] + pub fn rad_is_down(&self) -> RAD_IS_DOWN_R { + RAD_IS_DOWN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "System status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sys_stat_reg](index.html) module"] +pub struct SYS_STAT_REG_SPEC; +impl crate::RegisterSpec for SYS_STAT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [sys_stat_reg::R](R) reader structure"] +impl crate::Readable for SYS_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [sys_stat_reg::W](W) writer structure"] +impl crate::Writable for SYS_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SYS_STAT_REG to value 0x45"] +impl crate::Resettable for SYS_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x45 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/trim_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/trim_ctrl_reg.rs new file mode 100644 index 0000000..1194199 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/trim_ctrl_reg.rs @@ -0,0 +1,193 @@ +#[doc = "Register `TRIM_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TRIM_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL_SETTLE_N` reader - Designates that the XTAL can be safely used as the CPU clock. When XTAL_CLK_CNT reases this value, the signal XTAL32M_SETTLED bit in the SYS_STAT_REG will be set. Counts in steps of 64 xtal clock-cycles."] +pub struct XTAL_SETTLE_N_R(crate::FieldReader); +impl XTAL_SETTLE_N_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL_SETTLE_N_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL_SETTLE_N_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL_SETTLE_N` writer - Designates that the XTAL can be safely used as the CPU clock. When XTAL_CLK_CNT reases this value, the signal XTAL32M_SETTLED bit in the SYS_STAT_REG will be set. Counts in steps of 64 xtal clock-cycles."] +pub struct XTAL_SETTLE_N_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL_SETTLE_N_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 8)) | ((value as u16 & 0x3f) << 8); + self.w + } +} +#[doc = "Field `XTAL_TRIM_SELECT` reader - Select which source controls the XTAL trimming 0b00: xtal counter. Starts XTAL32M_START_REG\\[XTAL32M_START\\] +after COUNT_N * 32 xtal pulses trim is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b01: xtal OK filter. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\], when xtal amplitude is ramping is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b10: statically forced off. Only uses CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b11: xtal OK filter, 2 stage. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\] +switches to CLK_FREQ_TRIM_REG\\[XTAL32M_RAMP\\] +after timeout (32us), and switches to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\] +when xtal amplitude is ramping up."] +pub struct XTAL_TRIM_SELECT_R(crate::FieldReader); +impl XTAL_TRIM_SELECT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL_TRIM_SELECT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL_TRIM_SELECT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL_TRIM_SELECT` writer - Select which source controls the XTAL trimming 0b00: xtal counter. Starts XTAL32M_START_REG\\[XTAL32M_START\\] +after COUNT_N * 32 xtal pulses trim is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b01: xtal OK filter. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\], when xtal amplitude is ramping is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b10: statically forced off. Only uses CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b11: xtal OK filter, 2 stage. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\] +switches to CLK_FREQ_TRIM_REG\\[XTAL32M_RAMP\\] +after timeout (32us), and switches to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\] +when xtal amplitude is ramping up."] +pub struct XTAL_TRIM_SELECT_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL_TRIM_SELECT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 6)) | ((value as u16 & 3) << 6); + self.w + } +} +#[doc = "Field `XTAL_COUNT_N` reader - Defines the number of XTAL cycles to be counted, before the xtal trimming is applied, in steps of 64 cycles. 0x01: 64 0x02: 128 0x3f: 4032"] +pub struct XTAL_COUNT_N_R(crate::FieldReader); +impl XTAL_COUNT_N_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL_COUNT_N_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL_COUNT_N_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL_COUNT_N` writer - Defines the number of XTAL cycles to be counted, before the xtal trimming is applied, in steps of 64 cycles. 0x01: 64 0x02: 128 0x3f: 4032"] +pub struct XTAL_COUNT_N_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL_COUNT_N_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u16 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bits 8:13 - Designates that the XTAL can be safely used as the CPU clock. When XTAL_CLK_CNT reases this value, the signal XTAL32M_SETTLED bit in the SYS_STAT_REG will be set. Counts in steps of 64 xtal clock-cycles."] + #[inline(always)] + pub fn xtal_settle_n(&self) -> XTAL_SETTLE_N_R { + XTAL_SETTLE_N_R::new(((self.bits >> 8) & 0x3f) as u8) + } + #[doc = "Bits 6:7 - Select which source controls the XTAL trimming 0b00: xtal counter. Starts XTAL32M_START_REG\\[XTAL32M_START\\] +after COUNT_N * 32 xtal pulses trim is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b01: xtal OK filter. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\], when xtal amplitude is ramping is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b10: statically forced off. Only uses CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b11: xtal OK filter, 2 stage. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\] +switches to CLK_FREQ_TRIM_REG\\[XTAL32M_RAMP\\] +after timeout (32us), and switches to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\] +when xtal amplitude is ramping up."] + #[inline(always)] + pub fn xtal_trim_select(&self) -> XTAL_TRIM_SELECT_R { + XTAL_TRIM_SELECT_R::new(((self.bits >> 6) & 3) as u8) + } + #[doc = "Bits 0:5 - Defines the number of XTAL cycles to be counted, before the xtal trimming is applied, in steps of 64 cycles. 0x01: 64 0x02: 128 0x3f: 4032"] + #[inline(always)] + pub fn xtal_count_n(&self) -> XTAL_COUNT_N_R { + XTAL_COUNT_N_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bits 8:13 - Designates that the XTAL can be safely used as the CPU clock. When XTAL_CLK_CNT reases this value, the signal XTAL32M_SETTLED bit in the SYS_STAT_REG will be set. Counts in steps of 64 xtal clock-cycles."] + #[inline(always)] + pub fn xtal_settle_n(&mut self) -> XTAL_SETTLE_N_W { + XTAL_SETTLE_N_W { w: self } + } + #[doc = "Bits 6:7 - Select which source controls the XTAL trimming 0b00: xtal counter. Starts XTAL32M_START_REG\\[XTAL32M_START\\] +after COUNT_N * 32 xtal pulses trim is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b01: xtal OK filter. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\], when xtal amplitude is ramping is changed to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b10: statically forced off. Only uses CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\]. 0b11: xtal OK filter, 2 stage. Starts with CLK_FREQ_TRIM_REG\\[XTAL32M_START\\] +switches to CLK_FREQ_TRIM_REG\\[XTAL32M_RAMP\\] +after timeout (32us), and switches to CLK_FREQ_TRIM_REG\\[XTAL32M_TRIM\\] +when xtal amplitude is ramping up."] + #[inline(always)] + pub fn xtal_trim_select(&mut self) -> XTAL_TRIM_SELECT_W { + XTAL_TRIM_SELECT_W { w: self } + } + #[doc = "Bits 0:5 - Defines the number of XTAL cycles to be counted, before the xtal trimming is applied, in steps of 64 cycles. 0x01: 64 0x02: 128 0x3f: 4032"] + #[inline(always)] + pub fn xtal_count_n(&mut self) -> XTAL_COUNT_N_W { + XTAL_COUNT_N_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Control trimming of the XTAL32M\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [trim_ctrl_reg](index.html) module"] +pub struct TRIM_CTRL_REG_SPEC; +impl crate::RegisterSpec for TRIM_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [trim_ctrl_reg::R](R) reader structure"] +impl crate::Readable for TRIM_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [trim_ctrl_reg::W](W) writer structure"] +impl crate::Writable for TRIM_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TRIM_CTRL_REG to value 0x3f22"] +impl crate::Resettable for TRIM_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x3f22 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_ctrl0_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_ctrl0_reg.rs new file mode 100644 index 0000000..611f7fe --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_ctrl0_reg.rs @@ -0,0 +1,271 @@ +#[doc = "Register `XTAL32M_CTRL0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `XTAL32M_CTRL0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL32M_SPARE` reader - "] +pub struct XTAL32M_SPARE_R(crate::FieldReader); +impl XTAL32M_SPARE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL32M_SPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_SPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32M_SPARE` writer - "] +pub struct XTAL32M_SPARE_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32M_SPARE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u16 & 3) << 8); + self.w + } +} +#[doc = "Field `CORE_AMPL_TRIM` reader - Core amplitude trimming"] +pub struct CORE_AMPL_TRIM_R(crate::FieldReader); +impl CORE_AMPL_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CORE_AMPL_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_AMPL_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_AMPL_TRIM` writer - Core amplitude trimming"] +pub struct CORE_AMPL_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_AMPL_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 5)) | ((value as u16 & 7) << 5); + self.w + } +} +#[doc = "Field `CORE_CUR_SET` reader - Core current trim setting"] +pub struct CORE_CUR_SET_R(crate::FieldReader); +impl CORE_CUR_SET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CORE_CUR_SET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_CUR_SET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_CUR_SET` writer - Core current trim setting"] +pub struct CORE_CUR_SET_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_CUR_SET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 2)) | ((value as u16 & 7) << 2); + self.w + } +} +#[doc = "Field `CORE_AMPL_REG_NULLBIAS` reader - Keep bias in ampl detector alive, even when there is a large drive"] +pub struct CORE_AMPL_REG_NULLBIAS_R(crate::FieldReader); +impl CORE_AMPL_REG_NULLBIAS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CORE_AMPL_REG_NULLBIAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_AMPL_REG_NULLBIAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_AMPL_REG_NULLBIAS` writer - Keep bias in ampl detector alive, even when there is a large drive"] +pub struct CORE_AMPL_REG_NULLBIAS_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_AMPL_REG_NULLBIAS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `DCBLOCK_ENABLE` reader - Enable dcblock/high pass filter circuit"] +pub struct DCBLOCK_ENABLE_R(crate::FieldReader); +impl DCBLOCK_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DCBLOCK_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCBLOCK_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCBLOCK_ENABLE` writer - Enable dcblock/high pass filter circuit"] +pub struct DCBLOCK_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> DCBLOCK_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn xtal32m_spare(&self) -> XTAL32M_SPARE_R { + XTAL32M_SPARE_R::new(((self.bits >> 8) & 3) as u8) + } + #[doc = "Bits 5:7 - Core amplitude trimming"] + #[inline(always)] + pub fn core_ampl_trim(&self) -> CORE_AMPL_TRIM_R { + CORE_AMPL_TRIM_R::new(((self.bits >> 5) & 7) as u8) + } + #[doc = "Bits 2:4 - Core current trim setting"] + #[inline(always)] + pub fn core_cur_set(&self) -> CORE_CUR_SET_R { + CORE_CUR_SET_R::new(((self.bits >> 2) & 7) as u8) + } + #[doc = "Bit 1 - Keep bias in ampl detector alive, even when there is a large drive"] + #[inline(always)] + pub fn core_ampl_reg_nullbias(&self) -> CORE_AMPL_REG_NULLBIAS_R { + CORE_AMPL_REG_NULLBIAS_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Enable dcblock/high pass filter circuit"] + #[inline(always)] + pub fn dcblock_enable(&self) -> DCBLOCK_ENABLE_R { + DCBLOCK_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn xtal32m_spare(&mut self) -> XTAL32M_SPARE_W { + XTAL32M_SPARE_W { w: self } + } + #[doc = "Bits 5:7 - Core amplitude trimming"] + #[inline(always)] + pub fn core_ampl_trim(&mut self) -> CORE_AMPL_TRIM_W { + CORE_AMPL_TRIM_W { w: self } + } + #[doc = "Bits 2:4 - Core current trim setting"] + #[inline(always)] + pub fn core_cur_set(&mut self) -> CORE_CUR_SET_W { + CORE_CUR_SET_W { w: self } + } + #[doc = "Bit 1 - Keep bias in ampl detector alive, even when there is a large drive"] + #[inline(always)] + pub fn core_ampl_reg_nullbias(&mut self) -> CORE_AMPL_REG_NULLBIAS_W { + CORE_AMPL_REG_NULLBIAS_W { w: self } + } + #[doc = "Bit 0 - Enable dcblock/high pass filter circuit"] + #[inline(always)] + pub fn dcblock_enable(&mut self) -> DCBLOCK_ENABLE_W { + DCBLOCK_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Control bits for XTAL32M\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtal32m_ctrl0_reg](index.html) module"] +pub struct XTAL32M_CTRL0_REG_SPEC; +impl crate::RegisterSpec for XTAL32M_CTRL0_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [xtal32m_ctrl0_reg::R](R) reader structure"] +impl crate::Readable for XTAL32M_CTRL0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [xtal32m_ctrl0_reg::W](W) writer structure"] +impl crate::Writable for XTAL32M_CTRL0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets XTAL32M_CTRL0_REG to value 0x15"] +impl crate::Resettable for XTAL32M_CTRL0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x15 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_start_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_start_reg.rs new file mode 100644 index 0000000..e409f7c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_start_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `XTAL32M_START_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `XTAL32M_START_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL32M_RAMP` reader - Xtal frequency trimming register. 0x00 : highest frequency 0xFF :lowest frequency"] +pub struct XTAL32M_RAMP_R(crate::FieldReader); +impl XTAL32M_RAMP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL32M_RAMP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_RAMP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32M_RAMP` writer - Xtal frequency trimming register. 0x00 : highest frequency 0xFF :lowest frequency"] +pub struct XTAL32M_RAMP_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32M_RAMP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u16 & 0xff) << 8); + self.w + } +} +#[doc = "Field `XTAL32M_START` reader - Xtal frequency trimming register. 0x0 = highest frequency 0xF = lowest frequency."] +pub struct XTAL32M_START_R(crate::FieldReader); +impl XTAL32M_START_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL32M_START_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_START_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32M_START` writer - Xtal frequency trimming register. 0x0 = highest frequency 0xF = lowest frequency."] +pub struct XTAL32M_START_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32M_START_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15 - Xtal frequency trimming register. 0x00 : highest frequency 0xFF :lowest frequency"] + #[inline(always)] + pub fn xtal32m_ramp(&self) -> XTAL32M_RAMP_R { + XTAL32M_RAMP_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7 - Xtal frequency trimming register. 0x0 = highest frequency 0xF = lowest frequency."] + #[inline(always)] + pub fn xtal32m_start(&self) -> XTAL32M_START_R { + XTAL32M_START_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15 - Xtal frequency trimming register. 0x00 : highest frequency 0xFF :lowest frequency"] + #[inline(always)] + pub fn xtal32m_ramp(&mut self) -> XTAL32M_RAMP_W { + XTAL32M_RAMP_W { w: self } + } + #[doc = "Bits 0:7 - Xtal frequency trimming register. 0x0 = highest frequency 0xF = lowest frequency."] + #[inline(always)] + pub fn xtal32m_start(&mut self) -> XTAL32M_START_W { + XTAL32M_START_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Trim values for XTAL32M\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtal32m_start_reg](index.html) module"] +pub struct XTAL32M_START_REG_SPEC; +impl crate::RegisterSpec for XTAL32M_START_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [xtal32m_start_reg::R](R) reader structure"] +impl crate::Readable for XTAL32M_START_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [xtal32m_start_reg::W](W) writer structure"] +impl crate::Writable for XTAL32M_START_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets XTAL32M_START_REG to value 0xaa"] +impl crate::Resettable for XTAL32M_START_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0xaa + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_trstat_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_trstat_reg.rs new file mode 100644 index 0000000..360cc51 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/xtal32m_trstat_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `XTAL32M_TRSTAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `XTAL32M_TRSTAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTAL32M_TRSTAT` reader - Reads value of the current XTAL trimming"] +pub struct XTAL32M_TRSTAT_R(crate::FieldReader); +impl XTAL32M_TRSTAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTAL32M_TRSTAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_TRSTAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7 - Reads value of the current XTAL trimming"] + #[inline(always)] + pub fn xtal32m_trstat(&self) -> XTAL32M_TRSTAT_R { + XTAL32M_TRSTAT_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Read back value of current XTAL trimming\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtal32m_trstat_reg](index.html) module"] +pub struct XTAL32M_TRSTAT_REG_SPEC; +impl crate::RegisterSpec for XTAL32M_TRSTAT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [xtal32m_trstat_reg::R](R) reader structure"] +impl crate::Readable for XTAL32M_TRSTAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [xtal32m_trstat_reg::W](W) writer structure"] +impl crate::Writable for XTAL32M_TRSTAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets XTAL32M_TRSTAT_REG to value 0"] +impl crate::Resettable for XTAL32M_TRSTAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_ctrl_reg.rs new file mode 100644 index 0000000..94f2154 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_ctrl_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `XTALRDY_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `XTALRDY_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTALRDY_CNT` reader - Number of 32kHz cycles between the crystal is enabled, and the XTALRDY_IRQ is fired. 0x00: no interrupt"] +pub struct XTALRDY_CNT_R(crate::FieldReader); +impl XTALRDY_CNT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTALRDY_CNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTALRDY_CNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTALRDY_CNT` writer - Number of 32kHz cycles between the crystal is enabled, and the XTALRDY_IRQ is fired. 0x00: no interrupt"] +pub struct XTALRDY_CNT_W<'a> { + w: &'a mut W, +} +impl<'a> XTALRDY_CNT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Number of 32kHz cycles between the crystal is enabled, and the XTALRDY_IRQ is fired. 0x00: no interrupt"] + #[inline(always)] + pub fn xtalrdy_cnt(&self) -> XTALRDY_CNT_R { + XTALRDY_CNT_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Number of 32kHz cycles between the crystal is enabled, and the XTALRDY_IRQ is fired. 0x00: no interrupt"] + #[inline(always)] + pub fn xtalrdy_cnt(&mut self) -> XTALRDY_CNT_W { + XTALRDY_CNT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Control register for XTALRDY IRQ\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtalrdy_ctrl_reg](index.html) module"] +pub struct XTALRDY_CTRL_REG_SPEC; +impl crate::RegisterSpec for XTALRDY_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [xtalrdy_ctrl_reg::R](R) reader structure"] +impl crate::Readable for XTALRDY_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [xtalrdy_ctrl_reg::W](W) writer structure"] +impl crate::Writable for XTALRDY_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets XTALRDY_CTRL_REG to value 0"] +impl crate::Resettable for XTALRDY_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_stat_reg.rs new file mode 100644 index 0000000..399494f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/crg_top/xtalrdy_stat_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `XTALRDY_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `XTALRDY_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `XTALRDY_STAT` reader - "] +pub struct XTALRDY_STAT_R(crate::FieldReader); +impl XTALRDY_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + XTALRDY_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTALRDY_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn xtalrdy_stat(&self) -> XTALRDY_STAT_R { + XTALRDY_STAT_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtalrdy_stat_reg](index.html) module"] +pub struct XTALRDY_STAT_REG_SPEC; +impl crate::RegisterSpec for XTALRDY_STAT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [xtalrdy_stat_reg::R](R) reader structure"] +impl crate::Readable for XTALRDY_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [xtalrdy_stat_reg::W](W) writer structure"] +impl crate::Writable for XTALRDY_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets XTALRDY_STAT_REG to value 0"] +impl crate::Resettable for XTALRDY_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/generic.rs b/bitbox02-bt/vendor/da14531/src/generic.rs new file mode 100644 index 0000000..7615964 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/generic.rs @@ -0,0 +1,260 @@ +use core::marker; +#[doc = " Raw register type"] +pub trait RegisterSpec { + #[doc = " Raw register type (`u8`, `u16`, `u32`, ...)."] + type Ux: Copy; +} +#[doc = " Trait implemented by readable registers to enable the `read` method."] +#[doc = ""] +#[doc = " Registers marked with `Writable` can be also `modify`'ed."] +pub trait Readable: RegisterSpec { + #[doc = " Result from a call to `read` and argument to `modify`."] + type Reader: From> + core::ops::Deref>; +} +#[doc = " Trait implemented by writeable registers."] +#[doc = ""] +#[doc = " This enables the `write`, `write_with_zero` and `reset` methods."] +#[doc = ""] +#[doc = " Registers marked with `Readable` can be also `modify`'ed."] +pub trait Writable: RegisterSpec { + #[doc = " Writer type argument to `write`, et al."] + type Writer: From> + core::ops::DerefMut>; +} +#[doc = " Reset value of the register."] +#[doc = ""] +#[doc = " This value is the initial value for the `write` method. It can also be directly written to the"] +#[doc = " register by using the `reset` method."] +pub trait Resettable: RegisterSpec { + #[doc = " Reset value of the register."] + fn reset_value() -> Self::Ux; +} +#[doc = " This structure provides volatile access to registers."] +#[repr(transparent)] +pub struct Reg { + register: vcell::VolatileCell, + _marker: marker::PhantomData, +} +unsafe impl Send for Reg where REG::Ux: Send {} +impl Reg { + #[doc = " Returns the underlying memory address of register."] + #[doc = ""] + #[doc = " ```ignore"] + #[doc = " let reg_ptr = periph.reg.as_ptr();"] + #[doc = " ```"] + #[inline(always)] + pub fn as_ptr(&self) -> *mut REG::Ux { + self.register.as_ptr() + } +} +impl Reg { + #[doc = " Reads the contents of a `Readable` register."] + #[doc = ""] + #[doc = " You can read the raw contents of a register by using `bits`:"] + #[doc = " ```ignore"] + #[doc = " let bits = periph.reg.read().bits();"] + #[doc = " ```"] + #[doc = " or get the content of a particular field of a register:"] + #[doc = " ```ignore"] + #[doc = " let reader = periph.reg.read();"] + #[doc = " let bits = reader.field1().bits();"] + #[doc = " let flag = reader.field2().bit_is_set();"] + #[doc = " ```"] + #[inline(always)] + pub fn read(&self) -> REG::Reader { + REG::Reader::from(R { + bits: self.register.get(), + _reg: marker::PhantomData, + }) + } +} +impl Reg { + #[doc = " Writes the reset value to `Writable` register."] + #[doc = ""] + #[doc = " Resets the register to its initial state."] + #[inline(always)] + pub fn reset(&self) { + self.register.set(REG::reset_value()) + } + #[doc = " Writes bits to a `Writable` register."] + #[doc = ""] + #[doc = " You can write raw bits into a register:"] + #[doc = " ```ignore"] + #[doc = " periph.reg.write(|w| unsafe { w.bits(rawbits) });"] + #[doc = " ```"] + #[doc = " or write only the fields you need:"] + #[doc = " ```ignore"] + #[doc = " periph.reg.write(|w| w"] + #[doc = " .field1().bits(newfield1bits)"] + #[doc = " .field2().set_bit()"] + #[doc = " .field3().variant(VARIANT)"] + #[doc = " );"] + #[doc = " ```"] + #[doc = " In the latter case, other fields will be set to their reset value."] + #[inline(always)] + pub fn write(&self, f: F) + where + F: FnOnce(&mut REG::Writer) -> &mut W, + { + self.register.set( + f(&mut REG::Writer::from(W { + bits: REG::reset_value(), + _reg: marker::PhantomData, + })) + .bits, + ); + } +} +impl Reg +where + REG::Ux: Default, +{ + #[doc = " Writes 0 to a `Writable` register."] + #[doc = ""] + #[doc = " Similar to `write`, but unused bits will contain 0."] + #[inline(always)] + pub unsafe fn write_with_zero(&self, f: F) + where + F: FnOnce(&mut REG::Writer) -> &mut W, + { + self.register.set( + (*f(&mut REG::Writer::from(W { + bits: REG::Ux::default(), + _reg: marker::PhantomData, + }))) + .bits, + ); + } +} +impl Reg { + #[doc = " Modifies the contents of the register by reading and then writing it."] + #[doc = ""] + #[doc = " E.g. to do a read-modify-write sequence to change parts of a register:"] + #[doc = " ```ignore"] + #[doc = " periph.reg.modify(|r, w| unsafe { w.bits("] + #[doc = " r.bits() | 3"] + #[doc = " ) });"] + #[doc = " ```"] + #[doc = " or"] + #[doc = " ```ignore"] + #[doc = " periph.reg.modify(|_, w| w"] + #[doc = " .field1().bits(newfield1bits)"] + #[doc = " .field2().set_bit()"] + #[doc = " .field3().variant(VARIANT)"] + #[doc = " );"] + #[doc = " ```"] + #[doc = " Other fields will have the value they had before the call to `modify`."] + #[inline(always)] + pub fn modify(&self, f: F) + where + for<'w> F: FnOnce(®::Reader, &'w mut REG::Writer) -> &'w mut W, + { + let bits = self.register.get(); + self.register.set( + f( + ®::Reader::from(R { + bits, + _reg: marker::PhantomData, + }), + &mut REG::Writer::from(W { + bits, + _reg: marker::PhantomData, + }), + ) + .bits, + ); + } +} +#[doc = " Register reader."] +#[doc = ""] +#[doc = " Result of the `read` methods of registers. Also used as a closure argument in the `modify`"] +#[doc = " method."] +pub struct R { + pub(crate) bits: REG::Ux, + _reg: marker::PhantomData, +} +impl R { + #[doc = " Reads raw bits from register."] + #[inline(always)] + pub fn bits(&self) -> REG::Ux { + self.bits + } +} +impl PartialEq for R +where + REG::Ux: PartialEq, + FI: Copy + Into, +{ + #[inline(always)] + fn eq(&self, other: &FI) -> bool { + self.bits.eq(&(*other).into()) + } +} +#[doc = " Register writer."] +#[doc = ""] +#[doc = " Used as an argument to the closures in the `write` and `modify` methods of the register."] +pub struct W { + #[doc = "Writable bits"] + pub(crate) bits: REG::Ux, + _reg: marker::PhantomData, +} +impl W { + #[doc = " Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: REG::Ux) -> &mut Self { + self.bits = bits; + self + } +} +#[doc = " Field reader."] +#[doc = ""] +#[doc = " Result of the `read` methods of fields."] +pub struct FieldReader { + pub(crate) bits: U, + _reg: marker::PhantomData, +} +impl FieldReader +where + U: Copy, +{ + #[doc = " Creates a new instance of the reader."] + #[allow(unused)] + #[inline(always)] + pub(crate) fn new(bits: U) -> Self { + Self { + bits, + _reg: marker::PhantomData, + } + } + #[doc = " Reads raw bits from field."] + #[inline(always)] + pub fn bits(&self) -> U { + self.bits + } +} +impl PartialEq for FieldReader +where + U: PartialEq, + FI: Copy + Into, +{ + #[inline(always)] + fn eq(&self, other: &FI) -> bool { + self.bits.eq(&(*other).into()) + } +} +impl FieldReader { + #[doc = " Value of the field as raw bits."] + #[inline(always)] + pub fn bit(&self) -> bool { + self.bits + } + #[doc = " Returns `true` if the bit is clear (0)."] + #[inline(always)] + pub fn bit_is_clear(&self) -> bool { + !self.bit() + } + #[doc = " Returns `true` if the bit is set (1)."] + #[inline(always)] + pub fn bit_is_set(&self) -> bool { + self.bit() + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc.rs b/bitbox02-bt/vendor/da14531/src/gpadc.rs new file mode 100644 index 0000000..53e5226 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc.rs @@ -0,0 +1,72 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - General Purpose ADC Control Register"] + pub gp_adc_ctrl_reg: crate::Reg, + #[doc = "0x02 - General Purpose ADC Second Control Register"] + pub gp_adc_ctrl2_reg: crate::Reg, + #[doc = "0x04 - General Purpose ADC Third Control Register"] + pub gp_adc_ctrl3_reg: crate::Reg, + #[doc = "0x06 - General Purpose ADC Input Selection Register"] + pub gp_adc_sel_reg: crate::Reg, + _reserved4: [u8; 0x01], + #[doc = "0x08 - General Purpose ADC Positive Offset Register"] + pub gp_adc_offp_reg: crate::Reg, + #[doc = "0x0a - General Purpose ADC Negative Offset Register"] + pub gp_adc_offn_reg: crate::Reg, + #[doc = "0x0c - General Purpose ADC Trim Register"] + pub gp_adc_trim_reg: crate::Reg, + #[doc = "0x0e - General Purpose ADC Clear Interrupt Register"] + pub gp_adc_clear_int_reg: crate::Reg, + #[doc = "0x10 - General Purpose ADC Result Register"] + pub gp_adc_result_reg: crate::Reg, + _reserved9: [u8; 0x0a], + #[doc = "0x1c - "] + pub gp_adc_param_dif_reg: crate::Reg, + #[doc = "0x1e - "] + pub gp_adc_param_se_reg: crate::Reg, +} +#[doc = "GP_ADC_CLEAR_INT_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_CLEAR_INT_REG = crate::Reg; +#[doc = "General Purpose ADC Clear Interrupt Register"] +pub mod gp_adc_clear_int_reg; +#[doc = "GP_ADC_CTRL2_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_CTRL2_REG = crate::Reg; +#[doc = "General Purpose ADC Second Control Register"] +pub mod gp_adc_ctrl2_reg; +#[doc = "GP_ADC_CTRL3_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_CTRL3_REG = crate::Reg; +#[doc = "General Purpose ADC Third Control Register"] +pub mod gp_adc_ctrl3_reg; +#[doc = "GP_ADC_CTRL_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_CTRL_REG = crate::Reg; +#[doc = "General Purpose ADC Control Register"] +pub mod gp_adc_ctrl_reg; +#[doc = "GP_ADC_OFFN_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_OFFN_REG = crate::Reg; +#[doc = "General Purpose ADC Negative Offset Register"] +pub mod gp_adc_offn_reg; +#[doc = "GP_ADC_OFFP_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_OFFP_REG = crate::Reg; +#[doc = "General Purpose ADC Positive Offset Register"] +pub mod gp_adc_offp_reg; +#[doc = "GP_ADC_SEL_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_SEL_REG = crate::Reg; +#[doc = "General Purpose ADC Input Selection Register"] +pub mod gp_adc_sel_reg; +#[doc = "GP_ADC_PARAM_DIF_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_PARAM_DIF_REG = crate::Reg; +#[doc = ""] +pub mod gp_adc_param_dif_reg; +#[doc = "GP_ADC_PARAM_SE_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_PARAM_SE_REG = crate::Reg; +#[doc = ""] +pub mod gp_adc_param_se_reg; +#[doc = "GP_ADC_RESULT_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_RESULT_REG = crate::Reg; +#[doc = "General Purpose ADC Result Register"] +pub mod gp_adc_result_reg; +#[doc = "GP_ADC_TRIM_REG register accessor: an alias for `Reg`"] +pub type GP_ADC_TRIM_REG = crate::Reg; +#[doc = "General Purpose ADC Trim Register"] +pub mod gp_adc_trim_reg; diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_clear_int_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_clear_int_reg.rs new file mode 100644 index 0000000..28d146b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_clear_int_reg.rs @@ -0,0 +1,81 @@ +#[doc = "Register `GP_ADC_CLEAR_INT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_CLEAR_INT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_CLR_INT` writer - Writing any value to this register will clear the ADC_INT interrupt. Reading returns 0."] +pub struct GP_ADC_CLR_INT_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_CLR_INT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl W { + #[doc = "Bits 0:15 - Writing any value to this register will clear the ADC_INT interrupt. Reading returns 0."] + #[inline(always)] + pub fn gp_adc_clr_int(&mut self) -> GP_ADC_CLR_INT_W { + GP_ADC_CLR_INT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Clear Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_clear_int_reg](index.html) module"] +pub struct GP_ADC_CLEAR_INT_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_CLEAR_INT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_clear_int_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_CLEAR_INT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_clear_int_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_CLEAR_INT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_CLEAR_INT_REG to value 0"] +impl crate::Resettable for GP_ADC_CLEAR_INT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl2_reg.rs new file mode 100644 index 0000000..c8a5802 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl2_reg.rs @@ -0,0 +1,345 @@ +#[doc = "Register `GP_ADC_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_STORE_DEL` reader - 0: Data is stored after handshake synchronisation 1: Data is stored 2 ADC_CLK cycles after internal start trigger 7: Data is stored 8 ADC_CLK cycles after internal start trigger"] +pub struct GP_ADC_STORE_DEL_R(crate::FieldReader); +impl GP_ADC_STORE_DEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_STORE_DEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_STORE_DEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_STORE_DEL` writer - 0: Data is stored after handshake synchronisation 1: Data is stored 2 ADC_CLK cycles after internal start trigger 7: Data is stored 8 ADC_CLK cycles after internal start trigger"] +pub struct GP_ADC_STORE_DEL_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_STORE_DEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 13)) | ((value as u16 & 7) << 13); + self.w + } +} +#[doc = "Field `GP_ADC_SMPL_TIME` reader - 0: The sample time (switch is closed) is two ADC_CLK cycles 1: The sample time is 1*8 ADC_CLK cycles 2: The sample time is 2*8 ADC_CLK cycles 15: The sample time is 15*8 ADC_CLK cycles"] +pub struct GP_ADC_SMPL_TIME_R(crate::FieldReader); +impl GP_ADC_SMPL_TIME_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_SMPL_TIME_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_SMPL_TIME_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_SMPL_TIME` writer - 0: The sample time (switch is closed) is two ADC_CLK cycles 1: The sample time is 1*8 ADC_CLK cycles 2: The sample time is 2*8 ADC_CLK cycles 15: The sample time is 15*8 ADC_CLK cycles"] +pub struct GP_ADC_SMPL_TIME_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_SMPL_TIME_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 9)) | ((value as u16 & 0x0f) << 9); + self.w + } +} +#[doc = "Field `GP_ADC_CONV_NRS` reader - 0: 1 sample is taken or 2 in case ADC_CHOP is active. 1: 2 samples are taken. 2: 4 samples are taken. 7: 128 samples are taken."] +pub struct GP_ADC_CONV_NRS_R(crate::FieldReader); +impl GP_ADC_CONV_NRS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_CONV_NRS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_CONV_NRS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_CONV_NRS` writer - 0: 1 sample is taken or 2 in case ADC_CHOP is active. 1: 2 samples are taken. 2: 4 samples are taken. 7: 128 samples are taken."] +pub struct GP_ADC_CONV_NRS_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_CONV_NRS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 6)) | ((value as u16 & 7) << 6); + self.w + } +} +#[doc = "Field `GP_ADC_OFFS_SH_CM` reader - Common mode adjust for offset shifter. Input range is CM +/- 450mV. 0: CM = 1.25V (Input range 0.80 - 1.70) 1: CM = 1.30V (Input range 0.85 - 1.75) (default) 2: CM = 1.35V (Input range 0.90 - 1.80) 3: CM = 1.40V (input range 0.95 - 1.85)"] +pub struct GP_ADC_OFFS_SH_CM_R(crate::FieldReader); +impl GP_ADC_OFFS_SH_CM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_OFFS_SH_CM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_OFFS_SH_CM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_OFFS_SH_CM` writer - Common mode adjust for offset shifter. Input range is CM +/- 450mV. 0: CM = 1.25V (Input range 0.80 - 1.70) 1: CM = 1.30V (Input range 0.85 - 1.75) (default) 2: CM = 1.35V (Input range 0.90 - 1.80) 3: CM = 1.40V (input range 0.95 - 1.85)"] +pub struct GP_ADC_OFFS_SH_CM_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_OFFS_SH_CM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u16 & 3) << 4); + self.w + } +} +#[doc = "Field `GP_ADC_OFFS_SH_EN` reader - 0: Disable input shifter 1: Enable input shifter (900mV - 1800mV shifted to 0mV - 900mV)"] +pub struct GP_ADC_OFFS_SH_EN_R(crate::FieldReader); +impl GP_ADC_OFFS_SH_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_OFFS_SH_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_OFFS_SH_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_OFFS_SH_EN` writer - 0: Disable input shifter 1: Enable input shifter (900mV - 1800mV shifted to 0mV - 900mV)"] +pub struct GP_ADC_OFFS_SH_EN_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_OFFS_SH_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `GP_ADC_I20U` reader - 1: Adds 20uA constant load current at the ADC LDO to minimize ripple on the reference voltage of the ADC."] +pub struct GP_ADC_I20U_R(crate::FieldReader); +impl GP_ADC_I20U_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_I20U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_I20U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_I20U` writer - 1: Adds 20uA constant load current at the ADC LDO to minimize ripple on the reference voltage of the ADC."] +pub struct GP_ADC_I20U_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_I20U_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `GP_ADC_ATTN` reader - 0: No attenuator (input voltages up to 0.9V allowed) 1: Enabling 2x attenuator (input voltages up to 1.8V allowed) 2: Enabling 3x attenuator (input voltages up to 2.7V allowed) 3: Enabling 4x attenuator (input voltages up to 3.6V allowed) Enabling the attenuator requires a longer sampling time."] +pub struct GP_ADC_ATTN_R(crate::FieldReader); +impl GP_ADC_ATTN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_ATTN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_ATTN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_ATTN` writer - 0: No attenuator (input voltages up to 0.9V allowed) 1: Enabling 2x attenuator (input voltages up to 1.8V allowed) 2: Enabling 3x attenuator (input voltages up to 2.7V allowed) 3: Enabling 4x attenuator (input voltages up to 3.6V allowed) Enabling the attenuator requires a longer sampling time."] +pub struct GP_ADC_ATTN_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_ATTN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bits 13:15 - 0: Data is stored after handshake synchronisation 1: Data is stored 2 ADC_CLK cycles after internal start trigger 7: Data is stored 8 ADC_CLK cycles after internal start trigger"] + #[inline(always)] + pub fn gp_adc_store_del(&self) -> GP_ADC_STORE_DEL_R { + GP_ADC_STORE_DEL_R::new(((self.bits >> 13) & 7) as u8) + } + #[doc = "Bits 9:12 - 0: The sample time (switch is closed) is two ADC_CLK cycles 1: The sample time is 1*8 ADC_CLK cycles 2: The sample time is 2*8 ADC_CLK cycles 15: The sample time is 15*8 ADC_CLK cycles"] + #[inline(always)] + pub fn gp_adc_smpl_time(&self) -> GP_ADC_SMPL_TIME_R { + GP_ADC_SMPL_TIME_R::new(((self.bits >> 9) & 0x0f) as u8) + } + #[doc = "Bits 6:8 - 0: 1 sample is taken or 2 in case ADC_CHOP is active. 1: 2 samples are taken. 2: 4 samples are taken. 7: 128 samples are taken."] + #[inline(always)] + pub fn gp_adc_conv_nrs(&self) -> GP_ADC_CONV_NRS_R { + GP_ADC_CONV_NRS_R::new(((self.bits >> 6) & 7) as u8) + } + #[doc = "Bits 4:5 - Common mode adjust for offset shifter. Input range is CM +/- 450mV. 0: CM = 1.25V (Input range 0.80 - 1.70) 1: CM = 1.30V (Input range 0.85 - 1.75) (default) 2: CM = 1.35V (Input range 0.90 - 1.80) 3: CM = 1.40V (input range 0.95 - 1.85)"] + #[inline(always)] + pub fn gp_adc_offs_sh_cm(&self) -> GP_ADC_OFFS_SH_CM_R { + GP_ADC_OFFS_SH_CM_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bit 3 - 0: Disable input shifter 1: Enable input shifter (900mV - 1800mV shifted to 0mV - 900mV)"] + #[inline(always)] + pub fn gp_adc_offs_sh_en(&self) -> GP_ADC_OFFS_SH_EN_R { + GP_ADC_OFFS_SH_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - 1: Adds 20uA constant load current at the ADC LDO to minimize ripple on the reference voltage of the ADC."] + #[inline(always)] + pub fn gp_adc_i20u(&self) -> GP_ADC_I20U_R { + GP_ADC_I20U_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1 - 0: No attenuator (input voltages up to 0.9V allowed) 1: Enabling 2x attenuator (input voltages up to 1.8V allowed) 2: Enabling 3x attenuator (input voltages up to 2.7V allowed) 3: Enabling 4x attenuator (input voltages up to 3.6V allowed) Enabling the attenuator requires a longer sampling time."] + #[inline(always)] + pub fn gp_adc_attn(&self) -> GP_ADC_ATTN_R { + GP_ADC_ATTN_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 13:15 - 0: Data is stored after handshake synchronisation 1: Data is stored 2 ADC_CLK cycles after internal start trigger 7: Data is stored 8 ADC_CLK cycles after internal start trigger"] + #[inline(always)] + pub fn gp_adc_store_del(&mut self) -> GP_ADC_STORE_DEL_W { + GP_ADC_STORE_DEL_W { w: self } + } + #[doc = "Bits 9:12 - 0: The sample time (switch is closed) is two ADC_CLK cycles 1: The sample time is 1*8 ADC_CLK cycles 2: The sample time is 2*8 ADC_CLK cycles 15: The sample time is 15*8 ADC_CLK cycles"] + #[inline(always)] + pub fn gp_adc_smpl_time(&mut self) -> GP_ADC_SMPL_TIME_W { + GP_ADC_SMPL_TIME_W { w: self } + } + #[doc = "Bits 6:8 - 0: 1 sample is taken or 2 in case ADC_CHOP is active. 1: 2 samples are taken. 2: 4 samples are taken. 7: 128 samples are taken."] + #[inline(always)] + pub fn gp_adc_conv_nrs(&mut self) -> GP_ADC_CONV_NRS_W { + GP_ADC_CONV_NRS_W { w: self } + } + #[doc = "Bits 4:5 - Common mode adjust for offset shifter. Input range is CM +/- 450mV. 0: CM = 1.25V (Input range 0.80 - 1.70) 1: CM = 1.30V (Input range 0.85 - 1.75) (default) 2: CM = 1.35V (Input range 0.90 - 1.80) 3: CM = 1.40V (input range 0.95 - 1.85)"] + #[inline(always)] + pub fn gp_adc_offs_sh_cm(&mut self) -> GP_ADC_OFFS_SH_CM_W { + GP_ADC_OFFS_SH_CM_W { w: self } + } + #[doc = "Bit 3 - 0: Disable input shifter 1: Enable input shifter (900mV - 1800mV shifted to 0mV - 900mV)"] + #[inline(always)] + pub fn gp_adc_offs_sh_en(&mut self) -> GP_ADC_OFFS_SH_EN_W { + GP_ADC_OFFS_SH_EN_W { w: self } + } + #[doc = "Bit 2 - 1: Adds 20uA constant load current at the ADC LDO to minimize ripple on the reference voltage of the ADC."] + #[inline(always)] + pub fn gp_adc_i20u(&mut self) -> GP_ADC_I20U_W { + GP_ADC_I20U_W { w: self } + } + #[doc = "Bits 0:1 - 0: No attenuator (input voltages up to 0.9V allowed) 1: Enabling 2x attenuator (input voltages up to 1.8V allowed) 2: Enabling 3x attenuator (input voltages up to 2.7V allowed) 3: Enabling 4x attenuator (input voltages up to 3.6V allowed) Enabling the attenuator requires a longer sampling time."] + #[inline(always)] + pub fn gp_adc_attn(&mut self) -> GP_ADC_ATTN_W { + GP_ADC_ATTN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Second Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_ctrl2_reg](index.html) module"] +pub struct GP_ADC_CTRL2_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_CTRL2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_CTRL2_REG to value 0x0210"] +impl crate::Resettable for GP_ADC_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0210 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl3_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl3_reg.rs new file mode 100644 index 0000000..8ed86c4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl3_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `GP_ADC_CTRL3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_CTRL3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_INTERVAL` reader - Defines the interval between two ADC conversions in case GP_ADC_CONT is set. 0: No extra delay between two conversions. 1: 1.024 ms interval between two conversions. 2: 2.048 ms interval between two conversions. 255: 261.12 ms interval between two conversions."] +pub struct GP_ADC_INTERVAL_R(crate::FieldReader); +impl GP_ADC_INTERVAL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_INTERVAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_INTERVAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_INTERVAL` writer - Defines the interval between two ADC conversions in case GP_ADC_CONT is set. 0: No extra delay between two conversions. 1: 1.024 ms interval between two conversions. 2: 2.048 ms interval between two conversions. 255: 261.12 ms interval between two conversions."] +pub struct GP_ADC_INTERVAL_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_INTERVAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u16 & 0xff) << 8); + self.w + } +} +#[doc = "Field `GP_ADC_EN_DEL` reader - Defines the delay for enabling the ADC after enabling the LDO. 0: Not allowed 1: 4x ADC_CLK period. n: n*4x ADC_CLK period."] +pub struct GP_ADC_EN_DEL_R(crate::FieldReader); +impl GP_ADC_EN_DEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_EN_DEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_EN_DEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_EN_DEL` writer - Defines the delay for enabling the ADC after enabling the LDO. 0: Not allowed 1: 4x ADC_CLK period. n: n*4x ADC_CLK period."] +pub struct GP_ADC_EN_DEL_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_EN_DEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15 - Defines the interval between two ADC conversions in case GP_ADC_CONT is set. 0: No extra delay between two conversions. 1: 1.024 ms interval between two conversions. 2: 2.048 ms interval between two conversions. 255: 261.12 ms interval between two conversions."] + #[inline(always)] + pub fn gp_adc_interval(&self) -> GP_ADC_INTERVAL_R { + GP_ADC_INTERVAL_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7 - Defines the delay for enabling the ADC after enabling the LDO. 0: Not allowed 1: 4x ADC_CLK period. n: n*4x ADC_CLK period."] + #[inline(always)] + pub fn gp_adc_en_del(&self) -> GP_ADC_EN_DEL_R { + GP_ADC_EN_DEL_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15 - Defines the interval between two ADC conversions in case GP_ADC_CONT is set. 0: No extra delay between two conversions. 1: 1.024 ms interval between two conversions. 2: 2.048 ms interval between two conversions. 255: 261.12 ms interval between two conversions."] + #[inline(always)] + pub fn gp_adc_interval(&mut self) -> GP_ADC_INTERVAL_W { + GP_ADC_INTERVAL_W { w: self } + } + #[doc = "Bits 0:7 - Defines the delay for enabling the ADC after enabling the LDO. 0: Not allowed 1: 4x ADC_CLK period. n: n*4x ADC_CLK period."] + #[inline(always)] + pub fn gp_adc_en_del(&mut self) -> GP_ADC_EN_DEL_W { + GP_ADC_EN_DEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Third Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_ctrl3_reg](index.html) module"] +pub struct GP_ADC_CTRL3_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_CTRL3_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_ctrl3_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_CTRL3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_ctrl3_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_CTRL3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_CTRL3_REG to value 0x40"] +impl crate::Resettable for GP_ADC_CTRL3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x40 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl_reg.rs new file mode 100644 index 0000000..89643b3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_ctrl_reg.rs @@ -0,0 +1,650 @@ +#[doc = "Register `GP_ADC_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DIE_TEMP_EN` reader - Enables the die-temperature sensor. Output can be measured on GPADC input 4."] +pub struct DIE_TEMP_EN_R(crate::FieldReader); +impl DIE_TEMP_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIE_TEMP_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIE_TEMP_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIE_TEMP_EN` writer - Enables the die-temperature sensor. Output can be measured on GPADC input 4."] +pub struct DIE_TEMP_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DIE_TEMP_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u16 & 1) << 12); + self.w + } +} +#[doc = "Field `GP_ADC_OFFS_SH_GAIN_SEL` reader - "] +pub struct GP_ADC_OFFS_SH_GAIN_SEL_R(crate::FieldReader); +impl GP_ADC_OFFS_SH_GAIN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_OFFS_SH_GAIN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_OFFS_SH_GAIN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_OFFS_SH_GAIN_SEL` writer - "] +pub struct GP_ADC_OFFS_SH_GAIN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_OFFS_SH_GAIN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `GP_ADC_LDO_HOLD` reader - 0: GPADC LDO tracking bandgap reference 1: GPADC LDO hold sampled bandgap reference"] +pub struct GP_ADC_LDO_HOLD_R(crate::FieldReader); +impl GP_ADC_LDO_HOLD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_LDO_HOLD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_LDO_HOLD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_LDO_HOLD` writer - 0: GPADC LDO tracking bandgap reference 1: GPADC LDO hold sampled bandgap reference"] +pub struct GP_ADC_LDO_HOLD_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_LDO_HOLD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `GP_ADC_CHOP` reader - 0: Chopper mode off 1: Chopper mode enabled. Takes two samples with opposite GP_ADC_SIGN to cancel the internal offset voltage of the ADC; Highly recommended for DC-measurements."] +pub struct GP_ADC_CHOP_R(crate::FieldReader); +impl GP_ADC_CHOP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_CHOP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_CHOP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_CHOP` writer - 0: Chopper mode off 1: Chopper mode enabled. Takes two samples with opposite GP_ADC_SIGN to cancel the internal offset voltage of the ADC; Highly recommended for DC-measurements."] +pub struct GP_ADC_CHOP_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_CHOP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `GP_ADC_SIGN` reader - 0: Default 1: Conversion with opposite sign at input and output to cancel out the internal offset of the ADC and low-frequency"] +pub struct GP_ADC_SIGN_R(crate::FieldReader); +impl GP_ADC_SIGN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_SIGN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_SIGN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_SIGN` writer - 0: Default 1: Conversion with opposite sign at input and output to cancel out the internal offset of the ADC and low-frequency"] +pub struct GP_ADC_SIGN_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_SIGN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `GP_ADC_MUTE` reader - 0: Normal operation 1: Mute ADC input. Takes sample at mid-scale (to dertermine the internal offset and/or noise of the ADC with regards to VDD_REF which is also sampled by the ADC)."] +pub struct GP_ADC_MUTE_R(crate::FieldReader); +impl GP_ADC_MUTE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_MUTE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_MUTE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_MUTE` writer - 0: Normal operation 1: Mute ADC input. Takes sample at mid-scale (to dertermine the internal offset and/or noise of the ADC with regards to VDD_REF which is also sampled by the ADC)."] +pub struct GP_ADC_MUTE_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_MUTE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `GP_ADC_SE` reader - 0: Differential mode 1: Single ended mode"] +pub struct GP_ADC_SE_R(crate::FieldReader); +impl GP_ADC_SE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_SE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_SE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_SE` writer - 0: Differential mode 1: Single ended mode"] +pub struct GP_ADC_SE_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_SE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `GP_ADC_MINT` reader - 0: Disable (mask) GP_ADC_INT. 1: Enable GP_ADC_INT to ICU."] +pub struct GP_ADC_MINT_R(crate::FieldReader); +impl GP_ADC_MINT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_MINT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_MINT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_MINT` writer - 0: Disable (mask) GP_ADC_INT. 1: Enable GP_ADC_INT to ICU."] +pub struct GP_ADC_MINT_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_MINT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `GP_ADC_INT` reader - 1: AD conversion ready and has generated an interrupt. Must be cleared by writing any value to GP_ADC_CLEAR_INT_REG."] +pub struct GP_ADC_INT_R(crate::FieldReader); +impl GP_ADC_INT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_INT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_INT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_DMA_EN` reader - 0: DMA functionality disabled 1: DMA functionality enabled"] +pub struct GP_ADC_DMA_EN_R(crate::FieldReader); +impl GP_ADC_DMA_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_DMA_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_DMA_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_DMA_EN` writer - 0: DMA functionality disabled 1: DMA functionality enabled"] +pub struct GP_ADC_DMA_EN_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_DMA_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `GP_ADC_CONT` reader - 0: Manual ADC mode, a single result will be generated after setting the GP_ADC_START bit. 1: Continuous ADC mode, new ADC results will be constantly stored in GP_ADC_RESULT_REG. Still GP_ADC_START has to be set to start the execution. The time between conversions is configurable with GP_ADC_INTERVAL."] +pub struct GP_ADC_CONT_R(crate::FieldReader); +impl GP_ADC_CONT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_CONT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_CONT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_CONT` writer - 0: Manual ADC mode, a single result will be generated after setting the GP_ADC_START bit. 1: Continuous ADC mode, new ADC results will be constantly stored in GP_ADC_RESULT_REG. Still GP_ADC_START has to be set to start the execution. The time between conversions is configurable with GP_ADC_INTERVAL."] +pub struct GP_ADC_CONT_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_CONT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `GP_ADC_START` reader - 0: ADC conversion ready. 1: If a 1 is written, the ADC starts a conversion. After the conversion this bit will be set to 0 and the GP_ADC_INT bit will be set. It is not allowed to write this bit while it is not (yet) zero."] +pub struct GP_ADC_START_R(crate::FieldReader); +impl GP_ADC_START_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_START_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_START_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_START` writer - 0: ADC conversion ready. 1: If a 1 is written, the ADC starts a conversion. After the conversion this bit will be set to 0 and the GP_ADC_INT bit will be set. It is not allowed to write this bit while it is not (yet) zero."] +pub struct GP_ADC_START_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_START_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `GP_ADC_EN` reader - 0: LDO is off and ADC is disabled.. 1: LDO is turned on and afterwards the ADC is enabled."] +pub struct GP_ADC_EN_R(crate::FieldReader); +impl GP_ADC_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GP_ADC_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_EN` writer - 0: LDO is off and ADC is disabled.. 1: LDO is turned on and afterwards the ADC is enabled."] +pub struct GP_ADC_EN_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 12 - Enables the die-temperature sensor. Output can be measured on GPADC input 4."] + #[inline(always)] + pub fn die_temp_en(&self) -> DIE_TEMP_EN_R { + DIE_TEMP_EN_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn gp_adc_offs_sh_gain_sel(&self) -> GP_ADC_OFFS_SH_GAIN_SEL_R { + GP_ADC_OFFS_SH_GAIN_SEL_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - 0: GPADC LDO tracking bandgap reference 1: GPADC LDO hold sampled bandgap reference"] + #[inline(always)] + pub fn gp_adc_ldo_hold(&self) -> GP_ADC_LDO_HOLD_R { + GP_ADC_LDO_HOLD_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - 0: Chopper mode off 1: Chopper mode enabled. Takes two samples with opposite GP_ADC_SIGN to cancel the internal offset voltage of the ADC; Highly recommended for DC-measurements."] + #[inline(always)] + pub fn gp_adc_chop(&self) -> GP_ADC_CHOP_R { + GP_ADC_CHOP_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - 0: Default 1: Conversion with opposite sign at input and output to cancel out the internal offset of the ADC and low-frequency"] + #[inline(always)] + pub fn gp_adc_sign(&self) -> GP_ADC_SIGN_R { + GP_ADC_SIGN_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - 0: Normal operation 1: Mute ADC input. Takes sample at mid-scale (to dertermine the internal offset and/or noise of the ADC with regards to VDD_REF which is also sampled by the ADC)."] + #[inline(always)] + pub fn gp_adc_mute(&self) -> GP_ADC_MUTE_R { + GP_ADC_MUTE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - 0: Differential mode 1: Single ended mode"] + #[inline(always)] + pub fn gp_adc_se(&self) -> GP_ADC_SE_R { + GP_ADC_SE_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - 0: Disable (mask) GP_ADC_INT. 1: Enable GP_ADC_INT to ICU."] + #[inline(always)] + pub fn gp_adc_mint(&self) -> GP_ADC_MINT_R { + GP_ADC_MINT_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - 1: AD conversion ready and has generated an interrupt. Must be cleared by writing any value to GP_ADC_CLEAR_INT_REG."] + #[inline(always)] + pub fn gp_adc_int(&self) -> GP_ADC_INT_R { + GP_ADC_INT_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - 0: DMA functionality disabled 1: DMA functionality enabled"] + #[inline(always)] + pub fn gp_adc_dma_en(&self) -> GP_ADC_DMA_EN_R { + GP_ADC_DMA_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - 0: Manual ADC mode, a single result will be generated after setting the GP_ADC_START bit. 1: Continuous ADC mode, new ADC results will be constantly stored in GP_ADC_RESULT_REG. Still GP_ADC_START has to be set to start the execution. The time between conversions is configurable with GP_ADC_INTERVAL."] + #[inline(always)] + pub fn gp_adc_cont(&self) -> GP_ADC_CONT_R { + GP_ADC_CONT_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - 0: ADC conversion ready. 1: If a 1 is written, the ADC starts a conversion. After the conversion this bit will be set to 0 and the GP_ADC_INT bit will be set. It is not allowed to write this bit while it is not (yet) zero."] + #[inline(always)] + pub fn gp_adc_start(&self) -> GP_ADC_START_R { + GP_ADC_START_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 0: LDO is off and ADC is disabled.. 1: LDO is turned on and afterwards the ADC is enabled."] + #[inline(always)] + pub fn gp_adc_en(&self) -> GP_ADC_EN_R { + GP_ADC_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 12 - Enables the die-temperature sensor. Output can be measured on GPADC input 4."] + #[inline(always)] + pub fn die_temp_en(&mut self) -> DIE_TEMP_EN_W { + DIE_TEMP_EN_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn gp_adc_offs_sh_gain_sel(&mut self) -> GP_ADC_OFFS_SH_GAIN_SEL_W { + GP_ADC_OFFS_SH_GAIN_SEL_W { w: self } + } + #[doc = "Bit 10 - 0: GPADC LDO tracking bandgap reference 1: GPADC LDO hold sampled bandgap reference"] + #[inline(always)] + pub fn gp_adc_ldo_hold(&mut self) -> GP_ADC_LDO_HOLD_W { + GP_ADC_LDO_HOLD_W { w: self } + } + #[doc = "Bit 9 - 0: Chopper mode off 1: Chopper mode enabled. Takes two samples with opposite GP_ADC_SIGN to cancel the internal offset voltage of the ADC; Highly recommended for DC-measurements."] + #[inline(always)] + pub fn gp_adc_chop(&mut self) -> GP_ADC_CHOP_W { + GP_ADC_CHOP_W { w: self } + } + #[doc = "Bit 8 - 0: Default 1: Conversion with opposite sign at input and output to cancel out the internal offset of the ADC and low-frequency"] + #[inline(always)] + pub fn gp_adc_sign(&mut self) -> GP_ADC_SIGN_W { + GP_ADC_SIGN_W { w: self } + } + #[doc = "Bit 7 - 0: Normal operation 1: Mute ADC input. Takes sample at mid-scale (to dertermine the internal offset and/or noise of the ADC with regards to VDD_REF which is also sampled by the ADC)."] + #[inline(always)] + pub fn gp_adc_mute(&mut self) -> GP_ADC_MUTE_W { + GP_ADC_MUTE_W { w: self } + } + #[doc = "Bit 6 - 0: Differential mode 1: Single ended mode"] + #[inline(always)] + pub fn gp_adc_se(&mut self) -> GP_ADC_SE_W { + GP_ADC_SE_W { w: self } + } + #[doc = "Bit 5 - 0: Disable (mask) GP_ADC_INT. 1: Enable GP_ADC_INT to ICU."] + #[inline(always)] + pub fn gp_adc_mint(&mut self) -> GP_ADC_MINT_W { + GP_ADC_MINT_W { w: self } + } + #[doc = "Bit 3 - 0: DMA functionality disabled 1: DMA functionality enabled"] + #[inline(always)] + pub fn gp_adc_dma_en(&mut self) -> GP_ADC_DMA_EN_W { + GP_ADC_DMA_EN_W { w: self } + } + #[doc = "Bit 2 - 0: Manual ADC mode, a single result will be generated after setting the GP_ADC_START bit. 1: Continuous ADC mode, new ADC results will be constantly stored in GP_ADC_RESULT_REG. Still GP_ADC_START has to be set to start the execution. The time between conversions is configurable with GP_ADC_INTERVAL."] + #[inline(always)] + pub fn gp_adc_cont(&mut self) -> GP_ADC_CONT_W { + GP_ADC_CONT_W { w: self } + } + #[doc = "Bit 1 - 0: ADC conversion ready. 1: If a 1 is written, the ADC starts a conversion. After the conversion this bit will be set to 0 and the GP_ADC_INT bit will be set. It is not allowed to write this bit while it is not (yet) zero."] + #[inline(always)] + pub fn gp_adc_start(&mut self) -> GP_ADC_START_W { + GP_ADC_START_W { w: self } + } + #[doc = "Bit 0 - 0: LDO is off and ADC is disabled.. 1: LDO is turned on and afterwards the ADC is enabled."] + #[inline(always)] + pub fn gp_adc_en(&mut self) -> GP_ADC_EN_W { + GP_ADC_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_ctrl_reg](index.html) module"] +pub struct GP_ADC_CTRL_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_ctrl_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_ctrl_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_CTRL_REG to value 0"] +impl crate::Resettable for GP_ADC_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offn_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offn_reg.rs new file mode 100644 index 0000000..e50937e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offn_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `GP_ADC_OFFN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_OFFN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_OFFN` reader - Offset adjust of 'negative' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=1 OR GP_ADC_CHOP=1\")"] +pub struct GP_ADC_OFFN_R(crate::FieldReader); +impl GP_ADC_OFFN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + GP_ADC_OFFN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_OFFN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_OFFN` writer - Offset adjust of 'negative' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=1 OR GP_ADC_CHOP=1\")"] +pub struct GP_ADC_OFFN_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_OFFN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u16 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 0:9 - Offset adjust of 'negative' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=1 OR GP_ADC_CHOP=1\")"] + #[inline(always)] + pub fn gp_adc_offn(&self) -> GP_ADC_OFFN_R { + GP_ADC_OFFN_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 0:9 - Offset adjust of 'negative' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=1 OR GP_ADC_CHOP=1\")"] + #[inline(always)] + pub fn gp_adc_offn(&mut self) -> GP_ADC_OFFN_W { + GP_ADC_OFFN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Negative Offset Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_offn_reg](index.html) module"] +pub struct GP_ADC_OFFN_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_OFFN_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_offn_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_OFFN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_offn_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_OFFN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_OFFN_REG to value 0x0200"] +impl crate::Resettable for GP_ADC_OFFN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0200 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offp_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offp_reg.rs new file mode 100644 index 0000000..6cfc9da --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_offp_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `GP_ADC_OFFP_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_OFFP_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_OFFP` reader - Offset adjust of 'positive' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=0 OR GP_ADC_CHOP=1\")"] +pub struct GP_ADC_OFFP_R(crate::FieldReader); +impl GP_ADC_OFFP_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + GP_ADC_OFFP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_OFFP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_OFFP` writer - Offset adjust of 'positive' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=0 OR GP_ADC_CHOP=1\")"] +pub struct GP_ADC_OFFP_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_OFFP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u16 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 0:9 - Offset adjust of 'positive' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=0 OR GP_ADC_CHOP=1\")"] + #[inline(always)] + pub fn gp_adc_offp(&self) -> GP_ADC_OFFP_R { + GP_ADC_OFFP_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 0:9 - Offset adjust of 'positive' array of ADC-network (effective if \"GP_ADC_SE=0\", or \"GP_ADC_SE=1 AND GP_ADC_SIGN=0 OR GP_ADC_CHOP=1\")"] + #[inline(always)] + pub fn gp_adc_offp(&mut self) -> GP_ADC_OFFP_W { + GP_ADC_OFFP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Positive Offset Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_offp_reg](index.html) module"] +pub struct GP_ADC_OFFP_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_OFFP_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_offp_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_OFFP_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_offp_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_OFFP_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_OFFP_REG to value 0x0200"] +impl crate::Resettable for GP_ADC_OFFP_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0200 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_dif_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_dif_reg.rs new file mode 100644 index 0000000..626f604 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_dif_reg.rs @@ -0,0 +1,64 @@ +#[doc = "Register `GP_ADC_PARAM_DIF_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_PARAM_DIF_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_param_dif_reg](index.html) module"] +pub struct GP_ADC_PARAM_DIF_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_PARAM_DIF_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_param_dif_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_PARAM_DIF_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_param_dif_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_PARAM_DIF_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_PARAM_DIF_REG to value 0"] +impl crate::Resettable for GP_ADC_PARAM_DIF_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_se_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_se_reg.rs new file mode 100644 index 0000000..6de9e4c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_param_se_reg.rs @@ -0,0 +1,64 @@ +#[doc = "Register `GP_ADC_PARAM_SE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_PARAM_SE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_param_se_reg](index.html) module"] +pub struct GP_ADC_PARAM_SE_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_PARAM_SE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_param_se_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_PARAM_SE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_param_se_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_PARAM_SE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_PARAM_SE_REG to value 0"] +impl crate::Resettable for GP_ADC_PARAM_SE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_result_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_result_reg.rs new file mode 100644 index 0000000..95f67b4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_result_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `GP_ADC_RESULT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_RESULT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_VAL` reader - Returns the 10 up to 16 bits linear value of the last AD conversion. The upper 10 bits are always valid, the lower 6 bits are only valid in case oversampling has been applied. Two samples results in one extra bit and 64 samples results in six extra bits."] +pub struct GP_ADC_VAL_R(crate::FieldReader); +impl GP_ADC_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + GP_ADC_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Returns the 10 up to 16 bits linear value of the last AD conversion. The upper 10 bits are always valid, the lower 6 bits are only valid in case oversampling has been applied. Two samples results in one extra bit and 64 samples results in six extra bits."] + #[inline(always)] + pub fn gp_adc_val(&self) -> GP_ADC_VAL_R { + GP_ADC_VAL_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Result Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_result_reg](index.html) module"] +pub struct GP_ADC_RESULT_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_RESULT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_result_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_RESULT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_result_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_RESULT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_RESULT_REG to value 0"] +impl crate::Resettable for GP_ADC_RESULT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_sel_reg.rs new file mode 100644 index 0000000..0f2596f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_sel_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `GP_ADC_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_SEL_P` reader - ADC positive input selection. 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) 4: Temperature Sensor 5: VBAT_HIGH 6: VBAT_LOW 7: VDDD"] +pub struct GP_ADC_SEL_P_R(crate::FieldReader); +impl GP_ADC_SEL_P_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_SEL_P_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_SEL_P_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_SEL_P` writer - ADC positive input selection. 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) 4: Temperature Sensor 5: VBAT_HIGH 6: VBAT_LOW 7: VDDD"] +pub struct GP_ADC_SEL_P_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_SEL_P_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u8 & 7) << 4); + self.w + } +} +#[doc = "Field `GP_ADC_SEL_N` reader - ADC negative input selection. Differential only (GP_ADC_SE=0). 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) All other combinations are reserved."] +pub struct GP_ADC_SEL_N_R(crate::FieldReader); +impl GP_ADC_SEL_N_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_SEL_N_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_SEL_N_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_SEL_N` writer - ADC negative input selection. Differential only (GP_ADC_SE=0). 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) All other combinations are reserved."] +pub struct GP_ADC_SEL_N_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_SEL_N_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u8 & 7); + self.w + } +} +impl R { + #[doc = "Bits 4:6 - ADC positive input selection. 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) 4: Temperature Sensor 5: VBAT_HIGH 6: VBAT_LOW 7: VDDD"] + #[inline(always)] + pub fn gp_adc_sel_p(&self) -> GP_ADC_SEL_P_R { + GP_ADC_SEL_P_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bits 0:2 - ADC negative input selection. Differential only (GP_ADC_SE=0). 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) All other combinations are reserved."] + #[inline(always)] + pub fn gp_adc_sel_n(&self) -> GP_ADC_SEL_N_R { + GP_ADC_SEL_N_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 4:6 - ADC positive input selection. 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) 4: Temperature Sensor 5: VBAT_HIGH 6: VBAT_LOW 7: VDDD"] + #[inline(always)] + pub fn gp_adc_sel_p(&mut self) -> GP_ADC_SEL_P_W { + GP_ADC_SEL_P_W { w: self } + } + #[doc = "Bits 0:2 - ADC negative input selection. Differential only (GP_ADC_SE=0). 0: ADC0 (P0\\[1\\]) 1: ADC1 (P0\\[2\\]) 2: ADC2 (P0\\[6\\]) 3: ADC3 (P0\\[7\\]) All other combinations are reserved."] + #[inline(always)] + pub fn gp_adc_sel_n(&mut self) -> GP_ADC_SEL_N_W { + GP_ADC_SEL_N_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Input Selection Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_sel_reg](index.html) module"] +pub struct GP_ADC_SEL_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_SEL_REG_SPEC { + type Ux = u8; +} +#[doc = "`read()` method returns [gp_adc_sel_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_sel_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_SEL_REG to value 0"] +impl crate::Resettable for GP_ADC_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_trim_reg.rs b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_trim_reg.rs new file mode 100644 index 0000000..45a5552 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpadc/gp_adc_trim_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `GP_ADC_TRIM_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_ADC_TRIM_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GP_ADC_LDO_LEVEL` reader - GPADC LDO level 0: 825mV 1: 850mV 2: 875mV 3: 900mV (reset) 4: 925mV (default) 5: 950mV 6: 975mV 7:1000mV"] +pub struct GP_ADC_LDO_LEVEL_R(crate::FieldReader); +impl GP_ADC_LDO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_LDO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_LDO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_LDO_LEVEL` writer - GPADC LDO level 0: 825mV 1: 850mV 2: 875mV 3: 900mV (reset) 4: 925mV (default) 5: 950mV 6: 975mV 7:1000mV"] +pub struct GP_ADC_LDO_LEVEL_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_LDO_LEVEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u16 & 7) << 4); + self.w + } +} +#[doc = "Field `GP_ADC_OFFS_SH_VREF` reader - Offset Shifter common-mode reference fine trimming: 2mV/LSB Default = mid-scale at 1000"] +pub struct GP_ADC_OFFS_SH_VREF_R(crate::FieldReader); +impl GP_ADC_OFFS_SH_VREF_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + GP_ADC_OFFS_SH_VREF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GP_ADC_OFFS_SH_VREF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GP_ADC_OFFS_SH_VREF` writer - Offset Shifter common-mode reference fine trimming: 2mV/LSB Default = mid-scale at 1000"] +pub struct GP_ADC_OFFS_SH_VREF_W<'a> { + w: &'a mut W, +} +impl<'a> GP_ADC_OFFS_SH_VREF_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 4:6 - GPADC LDO level 0: 825mV 1: 850mV 2: 875mV 3: 900mV (reset) 4: 925mV (default) 5: 950mV 6: 975mV 7:1000mV"] + #[inline(always)] + pub fn gp_adc_ldo_level(&self) -> GP_ADC_LDO_LEVEL_R { + GP_ADC_LDO_LEVEL_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bits 0:3 - Offset Shifter common-mode reference fine trimming: 2mV/LSB Default = mid-scale at 1000"] + #[inline(always)] + pub fn gp_adc_offs_sh_vref(&self) -> GP_ADC_OFFS_SH_VREF_R { + GP_ADC_OFFS_SH_VREF_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 4:6 - GPADC LDO level 0: 825mV 1: 850mV 2: 875mV 3: 900mV (reset) 4: 925mV (default) 5: 950mV 6: 975mV 7:1000mV"] + #[inline(always)] + pub fn gp_adc_ldo_level(&mut self) -> GP_ADC_LDO_LEVEL_W { + GP_ADC_LDO_LEVEL_W { w: self } + } + #[doc = "Bits 0:3 - Offset Shifter common-mode reference fine trimming: 2mV/LSB Default = mid-scale at 1000"] + #[inline(always)] + pub fn gp_adc_offs_sh_vref(&mut self) -> GP_ADC_OFFS_SH_VREF_W { + GP_ADC_OFFS_SH_VREF_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General Purpose ADC Trim Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_adc_trim_reg](index.html) module"] +pub struct GP_ADC_TRIM_REG_SPEC; +impl crate::RegisterSpec for GP_ADC_TRIM_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_adc_trim_reg::R](R) reader structure"] +impl crate::Readable for GP_ADC_TRIM_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_adc_trim_reg::W](W) writer structure"] +impl crate::Writable for GP_ADC_TRIM_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_ADC_TRIM_REG to value 0x38"] +impl crate::Resettable for GP_ADC_TRIM_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x38 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio.rs b/bitbox02-bt/vendor/da14531/src/gpio.rs new file mode 100644 index 0000000..cf56a80 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio.rs @@ -0,0 +1,95 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - P0 Data input/output Register"] + pub p0_data_reg: crate::Reg, + #[doc = "0x02 - P0 Set port pins Register"] + pub p0_set_data_reg: crate::Reg, + #[doc = "0x04 - P0 Reset port pins Register"] + pub p0_reset_data_reg: crate::Reg, + #[doc = "0x06..0x1e - Configuration of GPIO pins"] + pub p0_mode_reg: [crate::Reg; 12], + #[doc = "0x1e - Pad driving strength control Register"] + pub pad_weak_ctrl_reg: crate::Reg, + #[doc = "0x20 - "] + pub scan_observe_reg: crate::Reg, + _reserved6: [u8; 0x0e], + #[doc = "0x30 - "] + pub test_ctrl_reg: crate::Reg, + #[doc = "0x32 - "] + pub test_ctrl2_reg: crate::Reg, + #[doc = "0x34 - "] + pub test_ctrl3_reg: crate::Reg, + #[doc = "0x36 - "] + pub test_ctrl4_reg: crate::Reg, + #[doc = "0x38 - "] + pub xtal32m_testctrl0_reg: crate::Reg, + #[doc = "0x3a - "] + pub xtal32m_testctrl1_reg: crate::Reg, + #[doc = "0x3c - "] + pub bist_ctrl_reg: crate::Reg, + #[doc = "0x3e - "] + pub rombist_resultl_reg: crate::Reg, + #[doc = "0x40 - "] + pub rombist_resulth_reg: crate::Reg, +} +#[doc = "BIST_CTRL_REG register accessor: an alias for `Reg`"] +pub type BIST_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod bist_ctrl_reg; +#[doc = "P0_MODE_REG register accessor: an alias for `Reg`"] +pub type P0_MODE_REG = crate::Reg; +#[doc = "Configuration of GPIO pins"] +pub mod p0_mode_reg; +#[doc = "P0_DATA_REG register accessor: an alias for `Reg`"] +pub type P0_DATA_REG = crate::Reg; +#[doc = "P0 Data input/output Register"] +pub mod p0_data_reg; +#[doc = "P0_RESET_DATA_REG register accessor: an alias for `Reg`"] +pub type P0_RESET_DATA_REG = crate::Reg; +#[doc = "P0 Reset port pins Register"] +pub mod p0_reset_data_reg; +#[doc = "P0_SET_DATA_REG register accessor: an alias for `Reg`"] +pub type P0_SET_DATA_REG = crate::Reg; +#[doc = "P0 Set port pins Register"] +pub mod p0_set_data_reg; +#[doc = "PAD_WEAK_CTRL_REG register accessor: an alias for `Reg`"] +pub type PAD_WEAK_CTRL_REG = crate::Reg; +#[doc = "Pad driving strength control Register"] +pub mod pad_weak_ctrl_reg; +#[doc = "ROMBIST_RESULTH_REG register accessor: an alias for `Reg`"] +pub type ROMBIST_RESULTH_REG = crate::Reg; +#[doc = ""] +pub mod rombist_resulth_reg; +#[doc = "ROMBIST_RESULTL_REG register accessor: an alias for `Reg`"] +pub type ROMBIST_RESULTL_REG = crate::Reg; +#[doc = ""] +pub mod rombist_resultl_reg; +#[doc = "SCAN_OBSERVE_REG register accessor: an alias for `Reg`"] +pub type SCAN_OBSERVE_REG = crate::Reg; +#[doc = ""] +pub mod scan_observe_reg; +#[doc = "TEST_CTRL2_REG register accessor: an alias for `Reg`"] +pub type TEST_CTRL2_REG = crate::Reg; +#[doc = ""] +pub mod test_ctrl2_reg; +#[doc = "TEST_CTRL3_REG register accessor: an alias for `Reg`"] +pub type TEST_CTRL3_REG = crate::Reg; +#[doc = ""] +pub mod test_ctrl3_reg; +#[doc = "TEST_CTRL4_REG register accessor: an alias for `Reg`"] +pub type TEST_CTRL4_REG = crate::Reg; +#[doc = ""] +pub mod test_ctrl4_reg; +#[doc = "TEST_CTRL_REG register accessor: an alias for `Reg`"] +pub type TEST_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod test_ctrl_reg; +#[doc = "XTAL32M_TESTCTRL0_REG register accessor: an alias for `Reg`"] +pub type XTAL32M_TESTCTRL0_REG = crate::Reg; +#[doc = ""] +pub mod xtal32m_testctrl0_reg; +#[doc = "XTAL32M_TESTCTRL1_REG register accessor: an alias for `Reg`"] +pub type XTAL32M_TESTCTRL1_REG = crate::Reg; +#[doc = ""] +pub mod xtal32m_testctrl1_reg; diff --git a/bitbox02-bt/vendor/da14531/src/gpio/bist_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/bist_ctrl_reg.rs new file mode 100644 index 0000000..6265010 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/bist_ctrl_reg.rs @@ -0,0 +1,381 @@ +#[doc = "Register `BIST_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BIST_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SYSRAM3_BIST_ENABLE` reader - "] +pub struct SYSRAM3_BIST_ENABLE_R(crate::FieldReader); +impl SYSRAM3_BIST_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SYSRAM3_BIST_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYSRAM3_BIST_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYSRAM3_BIST_ENABLE` writer - "] +pub struct SYSRAM3_BIST_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> SYSRAM3_BIST_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u16 & 1) << 14); + self.w + } +} +#[doc = "Field `RAM_BIST_PATTERN` reader - "] +pub struct RAM_BIST_PATTERN_R(crate::FieldReader); +impl RAM_BIST_PATTERN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RAM_BIST_PATTERN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAM_BIST_PATTERN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM_BIST_PATTERN` writer - "] +pub struct RAM_BIST_PATTERN_W<'a> { + w: &'a mut W, +} +impl<'a> RAM_BIST_PATTERN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 12)) | ((value as u16 & 3) << 12); + self.w + } +} +#[doc = "Field `SYSRAM12_BIST_BUSY` reader - "] +pub struct SYSRAM12_BIST_BUSY_R(crate::FieldReader); +impl SYSRAM12_BIST_BUSY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SYSRAM12_BIST_BUSY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYSRAM12_BIST_BUSY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYSRAM12_BIST_FAIL` reader - "] +pub struct SYSRAM12_BIST_FAIL_R(crate::FieldReader); +impl SYSRAM12_BIST_FAIL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SYSRAM12_BIST_FAIL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYSRAM12_BIST_FAIL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYSRAM3_BIST_BUSY` reader - "] +pub struct SYSRAM3_BIST_BUSY_R(crate::FieldReader); +impl SYSRAM3_BIST_BUSY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SYSRAM3_BIST_BUSY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYSRAM3_BIST_BUSY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYSRAM3_BIST_FAIL` reader - "] +pub struct SYSRAM3_BIST_FAIL_R(crate::FieldReader); +impl SYSRAM3_BIST_FAIL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SYSRAM3_BIST_FAIL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYSRAM3_BIST_FAIL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ROM_BIST_BUSY` reader - "] +pub struct ROM_BIST_BUSY_R(crate::FieldReader); +impl ROM_BIST_BUSY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ROM_BIST_BUSY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ROM_BIST_BUSY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYSRAM12_BIST_ENABLE` reader - "] +pub struct SYSRAM12_BIST_ENABLE_R(crate::FieldReader); +impl SYSRAM12_BIST_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SYSRAM12_BIST_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SYSRAM12_BIST_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SYSRAM12_BIST_ENABLE` writer - "] +pub struct SYSRAM12_BIST_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> SYSRAM12_BIST_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `ROMBIST_ENABLE` reader - "] +pub struct ROMBIST_ENABLE_R(crate::FieldReader); +impl ROMBIST_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ROMBIST_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ROMBIST_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ROMBIST_ENABLE` writer - "] +pub struct ROMBIST_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> ROMBIST_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `RAM_BIST_CONFIG` reader - "] +pub struct RAM_BIST_CONFIG_R(crate::FieldReader); +impl RAM_BIST_CONFIG_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RAM_BIST_CONFIG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAM_BIST_CONFIG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM_BIST_CONFIG` writer - "] +pub struct RAM_BIST_CONFIG_W<'a> { + w: &'a mut W, +} +impl<'a> RAM_BIST_CONFIG_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 14"] + #[inline(always)] + pub fn sysram3_bist_enable(&self) -> SYSRAM3_BIST_ENABLE_R { + SYSRAM3_BIST_ENABLE_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bits 12:13"] + #[inline(always)] + pub fn ram_bist_pattern(&self) -> RAM_BIST_PATTERN_R { + RAM_BIST_PATTERN_R::new(((self.bits >> 12) & 3) as u8) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn sysram12_bist_busy(&self) -> SYSRAM12_BIST_BUSY_R { + SYSRAM12_BIST_BUSY_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn sysram12_bist_fail(&self) -> SYSRAM12_BIST_FAIL_R { + SYSRAM12_BIST_FAIL_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn sysram3_bist_busy(&self) -> SYSRAM3_BIST_BUSY_R { + SYSRAM3_BIST_BUSY_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn sysram3_bist_fail(&self) -> SYSRAM3_BIST_FAIL_R { + SYSRAM3_BIST_FAIL_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn rom_bist_busy(&self) -> ROM_BIST_BUSY_R { + ROM_BIST_BUSY_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn sysram12_bist_enable(&self) -> SYSRAM12_BIST_ENABLE_R { + SYSRAM12_BIST_ENABLE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rombist_enable(&self) -> ROMBIST_ENABLE_R { + ROMBIST_ENABLE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn ram_bist_config(&self) -> RAM_BIST_CONFIG_R { + RAM_BIST_CONFIG_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 14"] + #[inline(always)] + pub fn sysram3_bist_enable(&mut self) -> SYSRAM3_BIST_ENABLE_W { + SYSRAM3_BIST_ENABLE_W { w: self } + } + #[doc = "Bits 12:13"] + #[inline(always)] + pub fn ram_bist_pattern(&mut self) -> RAM_BIST_PATTERN_W { + RAM_BIST_PATTERN_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn sysram12_bist_enable(&mut self) -> SYSRAM12_BIST_ENABLE_W { + SYSRAM12_BIST_ENABLE_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rombist_enable(&mut self) -> ROMBIST_ENABLE_W { + ROMBIST_ENABLE_W { w: self } + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn ram_bist_config(&mut self) -> RAM_BIST_CONFIG_W { + RAM_BIST_CONFIG_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bist_ctrl_reg](index.html) module"] +pub struct BIST_CTRL_REG_SPEC; +impl crate::RegisterSpec for BIST_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [bist_ctrl_reg::R](R) reader structure"] +impl crate::Readable for BIST_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [bist_ctrl_reg::W](W) writer structure"] +impl crate::Writable for BIST_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BIST_CTRL_REG to value 0x0480"] +impl crate::Resettable for BIST_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0480 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/p0_data_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/p0_data_reg.rs new file mode 100644 index 0000000..42e1677 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/p0_data_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `P0_DATA_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `P0_DATA_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `P0_DATA` reader - Sets P0 output register when written ; Returns the value of P0 port when read"] +pub struct P0_DATA_R(crate::FieldReader); +impl P0_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + P0_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for P0_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `P0_DATA` writer - Sets P0 output register when written ; Returns the value of P0 port when read"] +pub struct P0_DATA_W<'a> { + w: &'a mut W, +} +impl<'a> P0_DATA_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl R { + #[doc = "Bits 0:11 - Sets P0 output register when written ; Returns the value of P0 port when read"] + #[inline(always)] + pub fn p0_data(&self) -> P0_DATA_R { + P0_DATA_R::new((self.bits & 0x0fff) as u16) + } +} +impl W { + #[doc = "Bits 0:11 - Sets P0 output register when written ; Returns the value of P0 port when read"] + #[inline(always)] + pub fn p0_data(&mut self) -> P0_DATA_W { + P0_DATA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "P0 Data input/output Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [p0_data_reg](index.html) module"] +pub struct P0_DATA_REG_SPEC; +impl crate::RegisterSpec for P0_DATA_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [p0_data_reg::R](R) reader structure"] +impl crate::Readable for P0_DATA_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [p0_data_reg::W](W) writer structure"] +impl crate::Writable for P0_DATA_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets P0_DATA_REG to value 0"] +impl crate::Resettable for P0_DATA_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/p0_mode_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/p0_mode_reg.rs new file mode 100644 index 0000000..44f0642 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/p0_mode_reg.rs @@ -0,0 +1,145 @@ +#[doc = "Register `P0_MODE_REG[%s]` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `P0_MODE_REG[%s]` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PUPD` reader - 00 = Input, no resistors selected 01 = Input, pull-up selected 10 = Input, pull-down selected 11 = Output, no resistors selected In ADC mode, these bits are don't care"] +pub struct PUPD_R(crate::FieldReader); +impl PUPD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PUPD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PUPD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PUPD` writer - 00 = Input, no resistors selected 01 = Input, pull-up selected 10 = Input, pull-down selected 11 = Output, no resistors selected In ADC mode, these bits are don't care"] +pub struct PUPD_W<'a> { + w: &'a mut W, +} +impl<'a> PUPD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u16 & 3) << 8); + self.w + } +} +#[doc = "Field `PID` reader - Function of port 0 = GPIO (pin direction determined by \"PUPD\" field) 1 = UART1_RX 2 = UART1_TX 3 = UART2_RX 4 = UART2_TX 5 = SYS_CLK 6 = LP_CLK 7 = Reserved 8 = Reserved 9 = I2C_SCL 10 = I2C_SDA 11 = PWM5 12 = PWM6 13 = PWM7 14 = Reserved 15 = ADC (only for P0_1, P0_2, P0_6 and P0_7) 16 = PWM0 17 = PWM1 18 = BLE_DIAG (signals mapped to P0\\[3:0\\] +are also mapped to P0\\[11:8\\]) 19 = UART1_CTSN 20 = UART1_RTSN 21 = Reserved 22 = Reserved 23 = PWM2 24 = PWM3 25 = PWM4 26 = SPI_DI 27 = SPI_DO 28 = SPI_CLK 29 = SPI_CSN0 30 = SPI_CSN1 31 = Reserved Note: When a certain input function (like SPI_DI) is selected on more than 1 pins, the pin of the lowest index has the highest priority."] +pub struct PID_R(crate::FieldReader); +impl PID_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PID_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PID_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PID` writer - Function of port 0 = GPIO (pin direction determined by \"PUPD\" field) 1 = UART1_RX 2 = UART1_TX 3 = UART2_RX 4 = UART2_TX 5 = SYS_CLK 6 = LP_CLK 7 = Reserved 8 = Reserved 9 = I2C_SCL 10 = I2C_SDA 11 = PWM5 12 = PWM6 13 = PWM7 14 = Reserved 15 = ADC (only for P0_1, P0_2, P0_6 and P0_7) 16 = PWM0 17 = PWM1 18 = BLE_DIAG (signals mapped to P0\\[3:0\\] +are also mapped to P0\\[11:8\\]) 19 = UART1_CTSN 20 = UART1_RTSN 21 = Reserved 22 = Reserved 23 = PWM2 24 = PWM3 25 = PWM4 26 = SPI_DI 27 = SPI_DO 28 = SPI_CLK 29 = SPI_CSN0 30 = SPI_CSN1 31 = Reserved Note: When a certain input function (like SPI_DI) is selected on more than 1 pins, the pin of the lowest index has the highest priority."] +pub struct PID_W<'a> { + w: &'a mut W, +} +impl<'a> PID_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u16 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 8:9 - 00 = Input, no resistors selected 01 = Input, pull-up selected 10 = Input, pull-down selected 11 = Output, no resistors selected In ADC mode, these bits are don't care"] + #[inline(always)] + pub fn pupd(&self) -> PUPD_R { + PUPD_R::new(((self.bits >> 8) & 3) as u8) + } + #[doc = "Bits 0:4 - Function of port 0 = GPIO (pin direction determined by \"PUPD\" field) 1 = UART1_RX 2 = UART1_TX 3 = UART2_RX 4 = UART2_TX 5 = SYS_CLK 6 = LP_CLK 7 = Reserved 8 = Reserved 9 = I2C_SCL 10 = I2C_SDA 11 = PWM5 12 = PWM6 13 = PWM7 14 = Reserved 15 = ADC (only for P0_1, P0_2, P0_6 and P0_7) 16 = PWM0 17 = PWM1 18 = BLE_DIAG (signals mapped to P0\\[3:0\\] +are also mapped to P0\\[11:8\\]) 19 = UART1_CTSN 20 = UART1_RTSN 21 = Reserved 22 = Reserved 23 = PWM2 24 = PWM3 25 = PWM4 26 = SPI_DI 27 = SPI_DO 28 = SPI_CLK 29 = SPI_CSN0 30 = SPI_CSN1 31 = Reserved Note: When a certain input function (like SPI_DI) is selected on more than 1 pins, the pin of the lowest index has the highest priority."] + #[inline(always)] + pub fn pid(&self) -> PID_R { + PID_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 8:9 - 00 = Input, no resistors selected 01 = Input, pull-up selected 10 = Input, pull-down selected 11 = Output, no resistors selected In ADC mode, these bits are don't care"] + #[inline(always)] + pub fn pupd(&mut self) -> PUPD_W { + PUPD_W { w: self } + } + #[doc = "Bits 0:4 - Function of port 0 = GPIO (pin direction determined by \"PUPD\" field) 1 = UART1_RX 2 = UART1_TX 3 = UART2_RX 4 = UART2_TX 5 = SYS_CLK 6 = LP_CLK 7 = Reserved 8 = Reserved 9 = I2C_SCL 10 = I2C_SDA 11 = PWM5 12 = PWM6 13 = PWM7 14 = Reserved 15 = ADC (only for P0_1, P0_2, P0_6 and P0_7) 16 = PWM0 17 = PWM1 18 = BLE_DIAG (signals mapped to P0\\[3:0\\] +are also mapped to P0\\[11:8\\]) 19 = UART1_CTSN 20 = UART1_RTSN 21 = Reserved 22 = Reserved 23 = PWM2 24 = PWM3 25 = PWM4 26 = SPI_DI 27 = SPI_DO 28 = SPI_CLK 29 = SPI_CSN0 30 = SPI_CSN1 31 = Reserved Note: When a certain input function (like SPI_DI) is selected on more than 1 pins, the pin of the lowest index has the highest priority."] + #[inline(always)] + pub fn pid(&mut self) -> PID_W { + PID_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Configuration of GPIO pins\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [p0_mode_reg](index.html) module"] +pub struct P0_MODE_REG_SPEC; +impl crate::RegisterSpec for P0_MODE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [p0_mode_reg::R](R) reader structure"] +impl crate::Readable for P0_MODE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [p0_mode_reg::W](W) writer structure"] +impl crate::Writable for P0_MODE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets P0_MODE_REG[%s] +to value 0x0200"] +impl crate::Resettable for P0_MODE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0200 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/p0_reset_data_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/p0_reset_data_reg.rs new file mode 100644 index 0000000..1900b12 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/p0_reset_data_reg.rs @@ -0,0 +1,85 @@ +#[doc = "Register `P0_RESET_DATA_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `P0_RESET_DATA_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `P0_RESET` writer - Writing a 1 to P0\\[x\\] +sets P0\\[x\\] +to 0. Writing 0 is discarded, reading returns 0."] +pub struct P0_RESET_W<'a> { + w: &'a mut W, +} +impl<'a> P0_RESET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl W { + #[doc = "Bits 0:11 - Writing a 1 to P0\\[x\\] +sets P0\\[x\\] +to 0. Writing 0 is discarded, reading returns 0."] + #[inline(always)] + pub fn p0_reset(&mut self) -> P0_RESET_W { + P0_RESET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "P0 Reset port pins Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [p0_reset_data_reg](index.html) module"] +pub struct P0_RESET_DATA_REG_SPEC; +impl crate::RegisterSpec for P0_RESET_DATA_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [p0_reset_data_reg::R](R) reader structure"] +impl crate::Readable for P0_RESET_DATA_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [p0_reset_data_reg::W](W) writer structure"] +impl crate::Writable for P0_RESET_DATA_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets P0_RESET_DATA_REG to value 0"] +impl crate::Resettable for P0_RESET_DATA_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/p0_set_data_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/p0_set_data_reg.rs new file mode 100644 index 0000000..d5634f6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/p0_set_data_reg.rs @@ -0,0 +1,85 @@ +#[doc = "Register `P0_SET_DATA_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `P0_SET_DATA_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `P0_SET` writer - Writing a 1 to P0\\[x\\] +sets P0\\[x\\] +to 1. Writing 0 is discarded, reading returns 0"] +pub struct P0_SET_W<'a> { + w: &'a mut W, +} +impl<'a> P0_SET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl W { + #[doc = "Bits 0:11 - Writing a 1 to P0\\[x\\] +sets P0\\[x\\] +to 1. Writing 0 is discarded, reading returns 0"] + #[inline(always)] + pub fn p0_set(&mut self) -> P0_SET_W { + P0_SET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "P0 Set port pins Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [p0_set_data_reg](index.html) module"] +pub struct P0_SET_DATA_REG_SPEC; +impl crate::RegisterSpec for P0_SET_DATA_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [p0_set_data_reg::R](R) reader structure"] +impl crate::Readable for P0_SET_DATA_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [p0_set_data_reg::W](W) writer structure"] +impl crate::Writable for P0_SET_DATA_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets P0_SET_DATA_REG to value 0"] +impl crate::Resettable for P0_SET_DATA_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/pad_weak_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/pad_weak_ctrl_reg.rs new file mode 100644 index 0000000..c421631 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/pad_weak_ctrl_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PAD_WEAK_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PAD_WEAK_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PAD_LOW_DRV` reader - 0 = Normal operation 1 = Reduces the driving strength of P0_x pad. Bit x controls the driving strength of P0_x, x=0, 1,..., 11."] +pub struct PAD_LOW_DRV_R(crate::FieldReader); +impl PAD_LOW_DRV_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + PAD_LOW_DRV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PAD_LOW_DRV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PAD_LOW_DRV` writer - 0 = Normal operation 1 = Reduces the driving strength of P0_x pad. Bit x controls the driving strength of P0_x, x=0, 1,..., 11."] +pub struct PAD_LOW_DRV_W<'a> { + w: &'a mut W, +} +impl<'a> PAD_LOW_DRV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl R { + #[doc = "Bits 0:11 - 0 = Normal operation 1 = Reduces the driving strength of P0_x pad. Bit x controls the driving strength of P0_x, x=0, 1,..., 11."] + #[inline(always)] + pub fn pad_low_drv(&self) -> PAD_LOW_DRV_R { + PAD_LOW_DRV_R::new((self.bits & 0x0fff) as u16) + } +} +impl W { + #[doc = "Bits 0:11 - 0 = Normal operation 1 = Reduces the driving strength of P0_x pad. Bit x controls the driving strength of P0_x, x=0, 1,..., 11."] + #[inline(always)] + pub fn pad_low_drv(&mut self) -> PAD_LOW_DRV_W { + PAD_LOW_DRV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Pad driving strength control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pad_weak_ctrl_reg](index.html) module"] +pub struct PAD_WEAK_CTRL_REG_SPEC; +impl crate::RegisterSpec for PAD_WEAK_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pad_weak_ctrl_reg::R](R) reader structure"] +impl crate::Readable for PAD_WEAK_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pad_weak_ctrl_reg::W](W) writer structure"] +impl crate::Writable for PAD_WEAK_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PAD_WEAK_CTRL_REG to value 0"] +impl crate::Resettable for PAD_WEAK_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/rombist_resulth_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/rombist_resulth_reg.rs new file mode 100644 index 0000000..12ee68d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/rombist_resulth_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `ROMBIST_RESULTH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ROMBIST_RESULTH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ROMBIST_RESULTH` reader - "] +pub struct ROMBIST_RESULTH_R(crate::FieldReader); +impl ROMBIST_RESULTH_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ROMBIST_RESULTH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ROMBIST_RESULTH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn rombist_resulth(&self) -> ROMBIST_RESULTH_R { + ROMBIST_RESULTH_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rombist_resulth_reg](index.html) module"] +pub struct ROMBIST_RESULTH_REG_SPEC; +impl crate::RegisterSpec for ROMBIST_RESULTH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rombist_resulth_reg::R](R) reader structure"] +impl crate::Readable for ROMBIST_RESULTH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rombist_resulth_reg::W](W) writer structure"] +impl crate::Writable for ROMBIST_RESULTH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ROMBIST_RESULTH_REG to value 0"] +impl crate::Resettable for ROMBIST_RESULTH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/rombist_resultl_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/rombist_resultl_reg.rs new file mode 100644 index 0000000..77d548d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/rombist_resultl_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `ROMBIST_RESULTL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `ROMBIST_RESULTL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ROMBIST_RESULTL` reader - "] +pub struct ROMBIST_RESULTL_R(crate::FieldReader); +impl ROMBIST_RESULTL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ROMBIST_RESULTL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ROMBIST_RESULTL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn rombist_resultl(&self) -> ROMBIST_RESULTL_R { + ROMBIST_RESULTL_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rombist_resultl_reg](index.html) module"] +pub struct ROMBIST_RESULTL_REG_SPEC; +impl crate::RegisterSpec for ROMBIST_RESULTL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rombist_resultl_reg::R](R) reader structure"] +impl crate::Readable for ROMBIST_RESULTL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rombist_resultl_reg::W](W) writer structure"] +impl crate::Writable for ROMBIST_RESULTL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets ROMBIST_RESULTL_REG to value 0"] +impl crate::Resettable for ROMBIST_RESULTL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/scan_observe_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/scan_observe_reg.rs new file mode 100644 index 0000000..0081611 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/scan_observe_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `SCAN_OBSERVE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SCAN_OBSERVE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SCAN_FEEDBACK_MUX` reader - "] +pub struct SCAN_FEEDBACK_MUX_R(crate::FieldReader); +impl SCAN_FEEDBACK_MUX_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + SCAN_FEEDBACK_MUX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SCAN_FEEDBACK_MUX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn scan_feedback_mux(&self) -> SCAN_FEEDBACK_MUX_R { + SCAN_FEEDBACK_MUX_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [scan_observe_reg](index.html) module"] +pub struct SCAN_OBSERVE_REG_SPEC; +impl crate::RegisterSpec for SCAN_OBSERVE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [scan_observe_reg::R](R) reader structure"] +impl crate::Readable for SCAN_OBSERVE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [scan_observe_reg::W](W) writer structure"] +impl crate::Writable for SCAN_OBSERVE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SCAN_OBSERVE_REG to value 0"] +impl crate::Resettable for SCAN_OBSERVE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl2_reg.rs new file mode 100644 index 0000000..1ab646c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl2_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `TEST_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TEST_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ANA_TEST_OUT_PARAM` reader - "] +pub struct ANA_TEST_OUT_PARAM_R(crate::FieldReader); +impl ANA_TEST_OUT_PARAM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ANA_TEST_OUT_PARAM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ANA_TEST_OUT_PARAM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ANA_TEST_OUT_PARAM` writer - "] +pub struct ANA_TEST_OUT_PARAM_W<'a> { + w: &'a mut W, +} +impl<'a> ANA_TEST_OUT_PARAM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 12)) | ((value as u16 & 0x0f) << 12); + self.w + } +} +#[doc = "Field `ANA_TEST_OUT_TO_PIN` reader - "] +pub struct ANA_TEST_OUT_TO_PIN_R(crate::FieldReader); +impl ANA_TEST_OUT_TO_PIN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ANA_TEST_OUT_TO_PIN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ANA_TEST_OUT_TO_PIN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ANA_TEST_OUT_TO_PIN` writer - "] +pub struct ANA_TEST_OUT_TO_PIN_W<'a> { + w: &'a mut W, +} +impl<'a> ANA_TEST_OUT_TO_PIN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `ANA_TEST_OUT_SEL` reader - "] +pub struct ANA_TEST_OUT_SEL_R(crate::FieldReader); +impl ANA_TEST_OUT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ANA_TEST_OUT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ANA_TEST_OUT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ANA_TEST_OUT_SEL` writer - "] +pub struct ANA_TEST_OUT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> ANA_TEST_OUT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u16 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 12:15"] + #[inline(always)] + pub fn ana_test_out_param(&self) -> ANA_TEST_OUT_PARAM_R { + ANA_TEST_OUT_PARAM_R::new(((self.bits >> 12) & 0x0f) as u8) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn ana_test_out_to_pin(&self) -> ANA_TEST_OUT_TO_PIN_R { + ANA_TEST_OUT_TO_PIN_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bits 0:9"] + #[inline(always)] + pub fn ana_test_out_sel(&self) -> ANA_TEST_OUT_SEL_R { + ANA_TEST_OUT_SEL_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 12:15"] + #[inline(always)] + pub fn ana_test_out_param(&mut self) -> ANA_TEST_OUT_PARAM_W { + ANA_TEST_OUT_PARAM_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn ana_test_out_to_pin(&mut self) -> ANA_TEST_OUT_TO_PIN_W { + ANA_TEST_OUT_TO_PIN_W { w: self } + } + #[doc = "Bits 0:9"] + #[inline(always)] + pub fn ana_test_out_sel(&mut self) -> ANA_TEST_OUT_SEL_W { + ANA_TEST_OUT_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [test_ctrl2_reg](index.html) module"] +pub struct TEST_CTRL2_REG_SPEC; +impl crate::RegisterSpec for TEST_CTRL2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [test_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for TEST_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [test_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for TEST_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TEST_CTRL2_REG to value 0"] +impl crate::Resettable for TEST_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl3_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl3_reg.rs new file mode 100644 index 0000000..e0b4ad3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl3_reg.rs @@ -0,0 +1,234 @@ +#[doc = "Register `TEST_CTRL3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TEST_CTRL3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RF_TEST_OUT_TO_PIN` reader - "] +pub struct RF_TEST_OUT_TO_PIN_R(crate::FieldReader); +impl RF_TEST_OUT_TO_PIN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_TEST_OUT_TO_PIN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_TEST_OUT_TO_PIN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_TEST_OUT_TO_PIN` writer - "] +pub struct RF_TEST_OUT_TO_PIN_W<'a> { + w: &'a mut W, +} +impl<'a> RF_TEST_OUT_TO_PIN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u16 & 1) << 13); + self.w + } +} +#[doc = "Field `RF_TEST_OUT_PARAM` reader - "] +pub struct RF_TEST_OUT_PARAM_R(crate::FieldReader); +impl RF_TEST_OUT_PARAM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_TEST_OUT_PARAM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_TEST_OUT_PARAM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_TEST_OUT_PARAM` writer - "] +pub struct RF_TEST_OUT_PARAM_W<'a> { + w: &'a mut W, +} +impl<'a> RF_TEST_OUT_PARAM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 7)) | ((value as u16 & 0x3f) << 7); + self.w + } +} +#[doc = "Field `ENABLE_RFPT` reader - "] +pub struct ENABLE_RFPT_R(crate::FieldReader); +impl ENABLE_RFPT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ENABLE_RFPT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ENABLE_RFPT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ENABLE_RFPT` writer - "] +pub struct ENABLE_RFPT_W<'a> { + w: &'a mut W, +} +impl<'a> ENABLE_RFPT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `RF_TEST_OUT_SEL` reader - "] +pub struct RF_TEST_OUT_SEL_R(crate::FieldReader); +impl RF_TEST_OUT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_TEST_OUT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_TEST_OUT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_TEST_OUT_SEL` writer - "] +pub struct RF_TEST_OUT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_TEST_OUT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u16 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bit 13"] + #[inline(always)] + pub fn rf_test_out_to_pin(&self) -> RF_TEST_OUT_TO_PIN_R { + RF_TEST_OUT_TO_PIN_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bits 7:12"] + #[inline(always)] + pub fn rf_test_out_param(&self) -> RF_TEST_OUT_PARAM_R { + RF_TEST_OUT_PARAM_R::new(((self.bits >> 7) & 0x3f) as u8) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn enable_rfpt(&self) -> ENABLE_RFPT_R { + ENABLE_RFPT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 0:5"] + #[inline(always)] + pub fn rf_test_out_sel(&self) -> RF_TEST_OUT_SEL_R { + RF_TEST_OUT_SEL_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bit 13"] + #[inline(always)] + pub fn rf_test_out_to_pin(&mut self) -> RF_TEST_OUT_TO_PIN_W { + RF_TEST_OUT_TO_PIN_W { w: self } + } + #[doc = "Bits 7:12"] + #[inline(always)] + pub fn rf_test_out_param(&mut self) -> RF_TEST_OUT_PARAM_W { + RF_TEST_OUT_PARAM_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn enable_rfpt(&mut self) -> ENABLE_RFPT_W { + ENABLE_RFPT_W { w: self } + } + #[doc = "Bits 0:5"] + #[inline(always)] + pub fn rf_test_out_sel(&mut self) -> RF_TEST_OUT_SEL_W { + RF_TEST_OUT_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [test_ctrl3_reg](index.html) module"] +pub struct TEST_CTRL3_REG_SPEC; +impl crate::RegisterSpec for TEST_CTRL3_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [test_ctrl3_reg::R](R) reader structure"] +impl crate::Readable for TEST_CTRL3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [test_ctrl3_reg::W](W) writer structure"] +impl crate::Writable for TEST_CTRL3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TEST_CTRL3_REG to value 0"] +impl crate::Resettable for TEST_CTRL3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl4_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl4_reg.rs new file mode 100644 index 0000000..1c9b3dc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl4_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `TEST_CTRL4_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TEST_CTRL4_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RF_TEST_IN_TO_PIN` reader - "] +pub struct RF_TEST_IN_TO_PIN_R(crate::FieldReader); +impl RF_TEST_IN_TO_PIN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_TEST_IN_TO_PIN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_TEST_IN_TO_PIN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_TEST_IN_TO_PIN` writer - "] +pub struct RF_TEST_IN_TO_PIN_W<'a> { + w: &'a mut W, +} +impl<'a> RF_TEST_IN_TO_PIN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u16 & 1) << 13); + self.w + } +} +#[doc = "Field `RF_TEST_IN_PARAM` reader - "] +pub struct RF_TEST_IN_PARAM_R(crate::FieldReader); +impl RF_TEST_IN_PARAM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_TEST_IN_PARAM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_TEST_IN_PARAM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_TEST_IN_PARAM` writer - "] +pub struct RF_TEST_IN_PARAM_W<'a> { + w: &'a mut W, +} +impl<'a> RF_TEST_IN_PARAM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 8)) | ((value as u16 & 0x1f) << 8); + self.w + } +} +#[doc = "Field `RF_TEST_IN_SEL` reader - "] +pub struct RF_TEST_IN_SEL_R(crate::FieldReader); +impl RF_TEST_IN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_TEST_IN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_TEST_IN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_TEST_IN_SEL` writer - "] +pub struct RF_TEST_IN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_TEST_IN_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 13"] + #[inline(always)] + pub fn rf_test_in_to_pin(&self) -> RF_TEST_IN_TO_PIN_R { + RF_TEST_IN_TO_PIN_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bits 8:12"] + #[inline(always)] + pub fn rf_test_in_param(&self) -> RF_TEST_IN_PARAM_R { + RF_TEST_IN_PARAM_R::new(((self.bits >> 8) & 0x1f) as u8) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rf_test_in_sel(&self) -> RF_TEST_IN_SEL_R { + RF_TEST_IN_SEL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bit 13"] + #[inline(always)] + pub fn rf_test_in_to_pin(&mut self) -> RF_TEST_IN_TO_PIN_W { + RF_TEST_IN_TO_PIN_W { w: self } + } + #[doc = "Bits 8:12"] + #[inline(always)] + pub fn rf_test_in_param(&mut self) -> RF_TEST_IN_PARAM_W { + RF_TEST_IN_PARAM_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rf_test_in_sel(&mut self) -> RF_TEST_IN_SEL_W { + RF_TEST_IN_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [test_ctrl4_reg](index.html) module"] +pub struct TEST_CTRL4_REG_SPEC; +impl crate::RegisterSpec for TEST_CTRL4_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [test_ctrl4_reg::R](R) reader structure"] +impl crate::Readable for TEST_CTRL4_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [test_ctrl4_reg::W](W) writer structure"] +impl crate::Writable for TEST_CTRL4_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TEST_CTRL4_REG to value 0"] +impl crate::Resettable for TEST_CTRL4_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl_reg.rs new file mode 100644 index 0000000..4cf43a4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/test_ctrl_reg.rs @@ -0,0 +1,479 @@ +#[doc = "Register `TEST_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TEST_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_SCAN_COMP_EN` reader - "] +pub struct ADPLL_SCAN_COMP_EN_R(crate::FieldReader); +impl ADPLL_SCAN_COMP_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLL_SCAN_COMP_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_SCAN_COMP_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_SCAN_COMP_EN` writer - "] +pub struct ADPLL_SCAN_COMP_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_SCAN_COMP_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u16 & 1) << 12); + self.w + } +} +#[doc = "Field `ADPLL_SCAN_TEST_EN` reader - "] +pub struct ADPLL_SCAN_TEST_EN_R(crate::FieldReader); +impl ADPLL_SCAN_TEST_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLL_SCAN_TEST_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_SCAN_TEST_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_SCAN_TEST_EN` writer - "] +pub struct ADPLL_SCAN_TEST_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_SCAN_TEST_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `CP_CAP_BIAS_TRIM` reader - "] +pub struct CP_CAP_BIAS_TRIM_R(crate::FieldReader); +impl CP_CAP_BIAS_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CP_CAP_BIAS_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CP_CAP_BIAS_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CP_CAP_BIAS_TRIM` writer - "] +pub struct CP_CAP_BIAS_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> CP_CAP_BIAS_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 9)) | ((value as u16 & 3) << 9); + self.w + } +} +#[doc = "Field `LDO_CORE_DUMMY_LOAD_ENABLE` reader - "] +pub struct LDO_CORE_DUMMY_LOAD_ENABLE_R(crate::FieldReader); +impl LDO_CORE_DUMMY_LOAD_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_CORE_DUMMY_LOAD_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_CORE_DUMMY_LOAD_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_CORE_DUMMY_LOAD_ENABLE` writer - "] +pub struct LDO_CORE_DUMMY_LOAD_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_CORE_DUMMY_LOAD_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `LDO_CORE_CAP_BYPASS` reader - "] +pub struct LDO_CORE_CAP_BYPASS_R(crate::FieldReader); +impl LDO_CORE_CAP_BYPASS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_CORE_CAP_BYPASS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_CORE_CAP_BYPASS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_CORE_CAP_BYPASS` writer - "] +pub struct LDO_CORE_CAP_BYPASS_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_CORE_CAP_BYPASS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `XTAL32M_CAP_TEST_EN` reader - "] +pub struct XTAL32M_CAP_TEST_EN_R(crate::FieldReader); +impl XTAL32M_CAP_TEST_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + XTAL32M_CAP_TEST_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for XTAL32M_CAP_TEST_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `XTAL32M_CAP_TEST_EN` writer - "] +pub struct XTAL32M_CAP_TEST_EN_W<'a> { + w: &'a mut W, +} +impl<'a> XTAL32M_CAP_TEST_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `SHOW_DCDC` reader - "] +pub struct SHOW_DCDC_R(crate::FieldReader); +impl SHOW_DCDC_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SHOW_DCDC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SHOW_DCDC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SHOW_DCDC` writer - "] +pub struct SHOW_DCDC_W<'a> { + w: &'a mut W, +} +impl<'a> SHOW_DCDC_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `SHOW_POWER` reader - "] +pub struct SHOW_POWER_R(crate::FieldReader); +impl SHOW_POWER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SHOW_POWER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SHOW_POWER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SHOW_POWER` writer - "] +pub struct SHOW_POWER_W<'a> { + w: &'a mut W, +} +impl<'a> SHOW_POWER_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `SHOW_CLOCKS` reader - "] +pub struct SHOW_CLOCKS_R(crate::FieldReader); +impl SHOW_CLOCKS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SHOW_CLOCKS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SHOW_CLOCKS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SHOW_CLOCKS` writer - "] +pub struct SHOW_CLOCKS_W<'a> { + w: &'a mut W, +} +impl<'a> SHOW_CLOCKS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 12"] + #[inline(always)] + pub fn adpll_scan_comp_en(&self) -> ADPLL_SCAN_COMP_EN_R { + ADPLL_SCAN_COMP_EN_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn adpll_scan_test_en(&self) -> ADPLL_SCAN_TEST_EN_R { + ADPLL_SCAN_TEST_EN_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bits 9:10"] + #[inline(always)] + pub fn cp_cap_bias_trim(&self) -> CP_CAP_BIAS_TRIM_R { + CP_CAP_BIAS_TRIM_R::new(((self.bits >> 9) & 3) as u8) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ldo_core_dummy_load_enable(&self) -> LDO_CORE_DUMMY_LOAD_ENABLE_R { + LDO_CORE_DUMMY_LOAD_ENABLE_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ldo_core_cap_bypass(&self) -> LDO_CORE_CAP_BYPASS_R { + LDO_CORE_CAP_BYPASS_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn xtal32m_cap_test_en(&self) -> XTAL32M_CAP_TEST_EN_R { + XTAL32M_CAP_TEST_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn show_dcdc(&self) -> SHOW_DCDC_R { + SHOW_DCDC_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn show_power(&self) -> SHOW_POWER_R { + SHOW_POWER_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn show_clocks(&self) -> SHOW_CLOCKS_R { + SHOW_CLOCKS_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 12"] + #[inline(always)] + pub fn adpll_scan_comp_en(&mut self) -> ADPLL_SCAN_COMP_EN_W { + ADPLL_SCAN_COMP_EN_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn adpll_scan_test_en(&mut self) -> ADPLL_SCAN_TEST_EN_W { + ADPLL_SCAN_TEST_EN_W { w: self } + } + #[doc = "Bits 9:10"] + #[inline(always)] + pub fn cp_cap_bias_trim(&mut self) -> CP_CAP_BIAS_TRIM_W { + CP_CAP_BIAS_TRIM_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ldo_core_dummy_load_enable(&mut self) -> LDO_CORE_DUMMY_LOAD_ENABLE_W { + LDO_CORE_DUMMY_LOAD_ENABLE_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ldo_core_cap_bypass(&mut self) -> LDO_CORE_CAP_BYPASS_W { + LDO_CORE_CAP_BYPASS_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn xtal32m_cap_test_en(&mut self) -> XTAL32M_CAP_TEST_EN_W { + XTAL32M_CAP_TEST_EN_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn show_dcdc(&mut self) -> SHOW_DCDC_W { + SHOW_DCDC_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn show_power(&mut self) -> SHOW_POWER_W { + SHOW_POWER_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn show_clocks(&mut self) -> SHOW_CLOCKS_W { + SHOW_CLOCKS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [test_ctrl_reg](index.html) module"] +pub struct TEST_CTRL_REG_SPEC; +impl crate::RegisterSpec for TEST_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [test_ctrl_reg::R](R) reader structure"] +impl crate::Readable for TEST_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [test_ctrl_reg::W](W) writer structure"] +impl crate::Writable for TEST_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TEST_CTRL_REG to value 0"] +impl crate::Resettable for TEST_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl0_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl0_reg.rs new file mode 100644 index 0000000..d4be393 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl0_reg.rs @@ -0,0 +1,600 @@ +#[doc = "Register `XTAL32M_TESTCTRL0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `XTAL32M_TESTCTRL0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BIAS_SAH_HOLD_OVERRIDE` reader - "] +pub struct BIAS_SAH_HOLD_OVERRIDE_R(crate::FieldReader); +impl BIAS_SAH_HOLD_OVERRIDE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BIAS_SAH_HOLD_OVERRIDE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BIAS_SAH_HOLD_OVERRIDE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BIAS_SAH_HOLD_OVERRIDE` writer - "] +pub struct BIAS_SAH_HOLD_OVERRIDE_W<'a> { + w: &'a mut W, +} +impl<'a> BIAS_SAH_HOLD_OVERRIDE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 14)) | ((value as u16 & 3) << 14); + self.w + } +} +#[doc = "Field `CORE_FREQ_TRIM_SW2_AMP` reader - "] +pub struct CORE_FREQ_TRIM_SW2_AMP_R(crate::FieldReader); +impl CORE_FREQ_TRIM_SW2_AMP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CORE_FREQ_TRIM_SW2_AMP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_FREQ_TRIM_SW2_AMP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_FREQ_TRIM_SW2_AMP` writer - "] +pub struct CORE_FREQ_TRIM_SW2_AMP_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_FREQ_TRIM_SW2_AMP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 11)) | ((value as u16 & 7) << 11); + self.w + } +} +#[doc = "Field `CORE_GM_CURRENT` reader - "] +pub struct CORE_GM_CURRENT_R(crate::FieldReader); +impl CORE_GM_CURRENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CORE_GM_CURRENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_GM_CURRENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_GM_CURRENT` writer - "] +pub struct CORE_GM_CURRENT_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_GM_CURRENT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `CORE_HOLD_AMP_REG_OVERRIDE` reader - "] +pub struct CORE_HOLD_AMP_REG_OVERRIDE_R(crate::FieldReader); +impl CORE_HOLD_AMP_REG_OVERRIDE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CORE_HOLD_AMP_REG_OVERRIDE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_HOLD_AMP_REG_OVERRIDE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_HOLD_AMP_REG_OVERRIDE` writer - "] +pub struct CORE_HOLD_AMP_REG_OVERRIDE_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_HOLD_AMP_REG_OVERRIDE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u16 & 3) << 8); + self.w + } +} +#[doc = "Field `CORE_I2V_TO_TESTBUS` reader - "] +pub struct CORE_I2V_TO_TESTBUS_R(crate::FieldReader); +impl CORE_I2V_TO_TESTBUS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CORE_I2V_TO_TESTBUS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_I2V_TO_TESTBUS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_I2V_TO_TESTBUS` writer - "] +pub struct CORE_I2V_TO_TESTBUS_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_I2V_TO_TESTBUS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `CORE_I2V_TO_TESTBUS_10X` reader - "] +pub struct CORE_I2V_TO_TESTBUS_10X_R(crate::FieldReader); +impl CORE_I2V_TO_TESTBUS_10X_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CORE_I2V_TO_TESTBUS_10X_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_I2V_TO_TESTBUS_10X_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_I2V_TO_TESTBUS_10X` writer - "] +pub struct CORE_I2V_TO_TESTBUS_10X_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_I2V_TO_TESTBUS_10X_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `CORE_MAX_CURRENT` reader - "] +pub struct CORE_MAX_CURRENT_R(crate::FieldReader); +impl CORE_MAX_CURRENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CORE_MAX_CURRENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_MAX_CURRENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_MAX_CURRENT` writer - "] +pub struct CORE_MAX_CURRENT_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_MAX_CURRENT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `CORE_XTAL_DISCHARGE` reader - "] +pub struct CORE_XTAL_DISCHARGE_R(crate::FieldReader); +impl CORE_XTAL_DISCHARGE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CORE_XTAL_DISCHARGE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CORE_XTAL_DISCHARGE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CORE_XTAL_DISCHARGE` writer - "] +pub struct CORE_XTAL_DISCHARGE_W<'a> { + w: &'a mut W, +} +impl<'a> CORE_XTAL_DISCHARGE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `DCBLOCK_LV_MODE` reader - "] +pub struct DCBLOCK_LV_MODE_R(crate::FieldReader); +impl DCBLOCK_LV_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DCBLOCK_LV_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DCBLOCK_LV_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DCBLOCK_LV_MODE` writer - "] +pub struct DCBLOCK_LV_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> DCBLOCK_LV_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `DIFFBUF_BYPASS` reader - "] +pub struct DIFFBUF_BYPASS_R(crate::FieldReader); +impl DIFFBUF_BYPASS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIFFBUF_BYPASS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIFFBUF_BYPASS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIFFBUF_BYPASS` writer - "] +pub struct DIFFBUF_BYPASS_W<'a> { + w: &'a mut W, +} +impl<'a> DIFFBUF_BYPASS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `OSC_TRIM_OPEN_DISABLE` reader - "] +pub struct OSC_TRIM_OPEN_DISABLE_R(crate::FieldReader); +impl OSC_TRIM_OPEN_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OSC_TRIM_OPEN_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OSC_TRIM_OPEN_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OSC_TRIM_OPEN_DISABLE` writer - "] +pub struct OSC_TRIM_OPEN_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> OSC_TRIM_OPEN_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `SPIKE_FLT_DISABLE` reader - "] +pub struct SPIKE_FLT_DISABLE_R(crate::FieldReader); +impl SPIKE_FLT_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPIKE_FLT_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPIKE_FLT_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPIKE_FLT_DISABLE` writer - "] +pub struct SPIKE_FLT_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> SPIKE_FLT_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 14:15"] + #[inline(always)] + pub fn bias_sah_hold_override(&self) -> BIAS_SAH_HOLD_OVERRIDE_R { + BIAS_SAH_HOLD_OVERRIDE_R::new(((self.bits >> 14) & 3) as u8) + } + #[doc = "Bits 11:13"] + #[inline(always)] + pub fn core_freq_trim_sw2_amp(&self) -> CORE_FREQ_TRIM_SW2_AMP_R { + CORE_FREQ_TRIM_SW2_AMP_R::new(((self.bits >> 11) & 7) as u8) + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn core_gm_current(&self) -> CORE_GM_CURRENT_R { + CORE_GM_CURRENT_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn core_hold_amp_reg_override(&self) -> CORE_HOLD_AMP_REG_OVERRIDE_R { + CORE_HOLD_AMP_REG_OVERRIDE_R::new(((self.bits >> 8) & 3) as u8) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn core_i2v_to_testbus(&self) -> CORE_I2V_TO_TESTBUS_R { + CORE_I2V_TO_TESTBUS_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn core_i2v_to_testbus_10x(&self) -> CORE_I2V_TO_TESTBUS_10X_R { + CORE_I2V_TO_TESTBUS_10X_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn core_max_current(&self) -> CORE_MAX_CURRENT_R { + CORE_MAX_CURRENT_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn core_xtal_discharge(&self) -> CORE_XTAL_DISCHARGE_R { + CORE_XTAL_DISCHARGE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn dcblock_lv_mode(&self) -> DCBLOCK_LV_MODE_R { + DCBLOCK_LV_MODE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn diffbuf_bypass(&self) -> DIFFBUF_BYPASS_R { + DIFFBUF_BYPASS_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn osc_trim_open_disable(&self) -> OSC_TRIM_OPEN_DISABLE_R { + OSC_TRIM_OPEN_DISABLE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn spike_flt_disable(&self) -> SPIKE_FLT_DISABLE_R { + SPIKE_FLT_DISABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 14:15"] + #[inline(always)] + pub fn bias_sah_hold_override(&mut self) -> BIAS_SAH_HOLD_OVERRIDE_W { + BIAS_SAH_HOLD_OVERRIDE_W { w: self } + } + #[doc = "Bits 11:13"] + #[inline(always)] + pub fn core_freq_trim_sw2_amp(&mut self) -> CORE_FREQ_TRIM_SW2_AMP_W { + CORE_FREQ_TRIM_SW2_AMP_W { w: self } + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn core_gm_current(&mut self) -> CORE_GM_CURRENT_W { + CORE_GM_CURRENT_W { w: self } + } + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn core_hold_amp_reg_override(&mut self) -> CORE_HOLD_AMP_REG_OVERRIDE_W { + CORE_HOLD_AMP_REG_OVERRIDE_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn core_i2v_to_testbus(&mut self) -> CORE_I2V_TO_TESTBUS_W { + CORE_I2V_TO_TESTBUS_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn core_i2v_to_testbus_10x(&mut self) -> CORE_I2V_TO_TESTBUS_10X_W { + CORE_I2V_TO_TESTBUS_10X_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn core_max_current(&mut self) -> CORE_MAX_CURRENT_W { + CORE_MAX_CURRENT_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn core_xtal_discharge(&mut self) -> CORE_XTAL_DISCHARGE_W { + CORE_XTAL_DISCHARGE_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn dcblock_lv_mode(&mut self) -> DCBLOCK_LV_MODE_W { + DCBLOCK_LV_MODE_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn diffbuf_bypass(&mut self) -> DIFFBUF_BYPASS_W { + DIFFBUF_BYPASS_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn osc_trim_open_disable(&mut self) -> OSC_TRIM_OPEN_DISABLE_W { + OSC_TRIM_OPEN_DISABLE_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn spike_flt_disable(&mut self) -> SPIKE_FLT_DISABLE_W { + SPIKE_FLT_DISABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtal32m_testctrl0_reg](index.html) module"] +pub struct XTAL32M_TESTCTRL0_REG_SPEC; +impl crate::RegisterSpec for XTAL32M_TESTCTRL0_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [xtal32m_testctrl0_reg::R](R) reader structure"] +impl crate::Readable for XTAL32M_TESTCTRL0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [xtal32m_testctrl0_reg::W](W) writer structure"] +impl crate::Writable for XTAL32M_TESTCTRL0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets XTAL32M_TESTCTRL0_REG to value 0x3400"] +impl crate::Resettable for XTAL32M_TESTCTRL0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x3400 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl1_reg.rs new file mode 100644 index 0000000..feaa8e4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpio/xtal32m_testctrl1_reg.rs @@ -0,0 +1,489 @@ +#[doc = "Register `XTAL32M_TESTCTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `XTAL32M_TESTCTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OSC_TRIM_CAP_BIAS` reader - "] +pub struct OSC_TRIM_CAP_BIAS_R(crate::FieldReader); +impl OSC_TRIM_CAP_BIAS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OSC_TRIM_CAP_BIAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OSC_TRIM_CAP_BIAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OSC_TRIM_CAP_BIAS` writer - "] +pub struct OSC_TRIM_CAP_BIAS_W<'a> { + w: &'a mut W, +} +impl<'a> OSC_TRIM_CAP_BIAS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `RFCLK_SEL_ADPLL_ADC_TO_GPIO` reader - "] +pub struct RFCLK_SEL_ADPLL_ADC_TO_GPIO_R(crate::FieldReader); +impl RFCLK_SEL_ADPLL_ADC_TO_GPIO_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFCLK_SEL_ADPLL_ADC_TO_GPIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFCLK_SEL_ADPLL_ADC_TO_GPIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFCLK_SEL_ADPLL_ADC_TO_GPIO` writer - "] +pub struct RFCLK_SEL_ADPLL_ADC_TO_GPIO_W<'a> { + w: &'a mut W, +} +impl<'a> RFCLK_SEL_ADPLL_ADC_TO_GPIO_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `RFCLK_ADC_TO_GPIO` reader - "] +pub struct RFCLK_ADC_TO_GPIO_R(crate::FieldReader); +impl RFCLK_ADC_TO_GPIO_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFCLK_ADC_TO_GPIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFCLK_ADC_TO_GPIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFCLK_ADC_TO_GPIO` writer - "] +pub struct RFCLK_ADC_TO_GPIO_W<'a> { + w: &'a mut W, +} +impl<'a> RFCLK_ADC_TO_GPIO_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `RFCLK_ADPLL_TO_GPIO` reader - "] +pub struct RFCLK_ADPLL_TO_GPIO_R(crate::FieldReader); +impl RFCLK_ADPLL_TO_GPIO_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFCLK_ADPLL_TO_GPIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFCLK_ADPLL_TO_GPIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFCLK_ADPLL_TO_GPIO` writer - "] +pub struct RFCLK_ADPLL_TO_GPIO_W<'a> { + w: &'a mut W, +} +impl<'a> RFCLK_ADPLL_TO_GPIO_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `PROG_VREF_SEL` reader - "] +pub struct PROG_VREF_SEL_R(crate::FieldReader); +impl PROG_VREF_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PROG_VREF_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PROG_VREF_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PROG_VREF_SEL` writer - "] +pub struct PROG_VREF_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> PROG_VREF_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `VARICAP_TEST_SEL_XTAL` reader - "] +pub struct VARICAP_TEST_SEL_XTAL_R(crate::FieldReader); +impl VARICAP_TEST_SEL_XTAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + VARICAP_TEST_SEL_XTAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for VARICAP_TEST_SEL_XTAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `VARICAP_TEST_SEL_XTAL` writer - "] +pub struct VARICAP_TEST_SEL_XTAL_W<'a> { + w: &'a mut W, +} +impl<'a> VARICAP_TEST_SEL_XTAL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `VARICAP_TEST_ENABLE` reader - "] +pub struct VARICAP_TEST_ENABLE_R(crate::FieldReader); +impl VARICAP_TEST_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + VARICAP_TEST_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for VARICAP_TEST_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `VARICAP_TEST_ENABLE` writer - "] +pub struct VARICAP_TEST_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> VARICAP_TEST_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `LDO_VREF_HOLD_OVERRIDE` reader - "] +pub struct LDO_VREF_HOLD_OVERRIDE_R(crate::FieldReader); +impl LDO_VREF_HOLD_OVERRIDE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_VREF_HOLD_OVERRIDE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_VREF_HOLD_OVERRIDE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_VREF_HOLD_OVERRIDE` writer - "] +pub struct LDO_VREF_HOLD_OVERRIDE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_VREF_HOLD_OVERRIDE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `DISABLE_TM_CLK` reader - "] +pub struct DISABLE_TM_CLK_R(crate::FieldReader); +impl DISABLE_TM_CLK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DISABLE_TM_CLK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DISABLE_TM_CLK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DISABLE_TM_CLK` writer - "] +pub struct DISABLE_TM_CLK_W<'a> { + w: &'a mut W, +} +impl<'a> DISABLE_TM_CLK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 8"] + #[inline(always)] + pub fn osc_trim_cap_bias(&self) -> OSC_TRIM_CAP_BIAS_R { + OSC_TRIM_CAP_BIAS_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn rfclk_sel_adpll_adc_to_gpio(&self) -> RFCLK_SEL_ADPLL_ADC_TO_GPIO_R { + RFCLK_SEL_ADPLL_ADC_TO_GPIO_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn rfclk_adc_to_gpio(&self) -> RFCLK_ADC_TO_GPIO_R { + RFCLK_ADC_TO_GPIO_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn rfclk_adpll_to_gpio(&self) -> RFCLK_ADPLL_TO_GPIO_R { + RFCLK_ADPLL_TO_GPIO_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn prog_vref_sel(&self) -> PROG_VREF_SEL_R { + PROG_VREF_SEL_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn varicap_test_sel_xtal(&self) -> VARICAP_TEST_SEL_XTAL_R { + VARICAP_TEST_SEL_XTAL_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn varicap_test_enable(&self) -> VARICAP_TEST_ENABLE_R { + VARICAP_TEST_ENABLE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn ldo_vref_hold_override(&self) -> LDO_VREF_HOLD_OVERRIDE_R { + LDO_VREF_HOLD_OVERRIDE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn disable_tm_clk(&self) -> DISABLE_TM_CLK_R { + DISABLE_TM_CLK_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 8"] + #[inline(always)] + pub fn osc_trim_cap_bias(&mut self) -> OSC_TRIM_CAP_BIAS_W { + OSC_TRIM_CAP_BIAS_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn rfclk_sel_adpll_adc_to_gpio(&mut self) -> RFCLK_SEL_ADPLL_ADC_TO_GPIO_W { + RFCLK_SEL_ADPLL_ADC_TO_GPIO_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn rfclk_adc_to_gpio(&mut self) -> RFCLK_ADC_TO_GPIO_W { + RFCLK_ADC_TO_GPIO_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn rfclk_adpll_to_gpio(&mut self) -> RFCLK_ADPLL_TO_GPIO_W { + RFCLK_ADPLL_TO_GPIO_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn prog_vref_sel(&mut self) -> PROG_VREF_SEL_W { + PROG_VREF_SEL_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn varicap_test_sel_xtal(&mut self) -> VARICAP_TEST_SEL_XTAL_W { + VARICAP_TEST_SEL_XTAL_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn varicap_test_enable(&mut self) -> VARICAP_TEST_ENABLE_W { + VARICAP_TEST_ENABLE_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn ldo_vref_hold_override(&mut self) -> LDO_VREF_HOLD_OVERRIDE_W { + LDO_VREF_HOLD_OVERRIDE_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn disable_tm_clk(&mut self) -> DISABLE_TM_CLK_W { + DISABLE_TM_CLK_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtal32m_testctrl1_reg](index.html) module"] +pub struct XTAL32M_TESTCTRL1_REG_SPEC; +impl crate::RegisterSpec for XTAL32M_TESTCTRL1_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [xtal32m_testctrl1_reg::R](R) reader structure"] +impl crate::Readable for XTAL32M_TESTCTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [xtal32m_testctrl1_reg::W](W) writer structure"] +impl crate::Writable for XTAL32M_TESTCTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets XTAL32M_TESTCTRL1_REG to value 0"] +impl crate::Resettable for XTAL32M_TESTCTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpreg.rs b/bitbox02-bt/vendor/da14531/src/gpreg.rs new file mode 100644 index 0000000..6ccb057 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg.rs @@ -0,0 +1,46 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Controls freezing of various timers/counters."] + pub set_freeze_reg: crate::Reg, + #[doc = "0x02 - Controls unfreezing of various timers/counters."] + pub reset_freeze_reg: crate::Reg, + #[doc = "0x04 - Various debug information register."] + pub debug_reg: crate::Reg, + #[doc = "0x06 - General purpose system status register."] + pub gp_status_reg: crate::Reg, + #[doc = "0x08 - General purpose system control register."] + pub gp_control_reg: crate::Reg, + #[doc = "0x0a - BLE FINECNT sampled value while in deep sleep state."] + pub ble_timer_reg: crate::Reg, + #[doc = "0x0c - "] + pub mem_ctrl_reg: crate::Reg, +} +#[doc = "BLE_TIMER_REG register accessor: an alias for `Reg`"] +pub type BLE_TIMER_REG = crate::Reg; +#[doc = "BLE FINECNT sampled value while in deep sleep state."] +pub mod ble_timer_reg; +#[doc = "DEBUG_REG register accessor: an alias for `Reg`"] +pub type DEBUG_REG = crate::Reg; +#[doc = "Various debug information register."] +pub mod debug_reg; +#[doc = "GP_CONTROL_REG register accessor: an alias for `Reg`"] +pub type GP_CONTROL_REG = crate::Reg; +#[doc = "General purpose system control register."] +pub mod gp_control_reg; +#[doc = "GP_STATUS_REG register accessor: an alias for `Reg`"] +pub type GP_STATUS_REG = crate::Reg; +#[doc = "General purpose system status register."] +pub mod gp_status_reg; +#[doc = "MEM_CTRL_REG register accessor: an alias for `Reg`"] +pub type MEM_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod mem_ctrl_reg; +#[doc = "RESET_FREEZE_REG register accessor: an alias for `Reg`"] +pub type RESET_FREEZE_REG = crate::Reg; +#[doc = "Controls unfreezing of various timers/counters."] +pub mod reset_freeze_reg; +#[doc = "SET_FREEZE_REG register accessor: an alias for `Reg`"] +pub type SET_FREEZE_REG = crate::Reg; +#[doc = "Controls freezing of various timers/counters."] +pub mod set_freeze_reg; diff --git a/bitbox02-bt/vendor/da14531/src/gpreg/ble_timer_reg.rs b/bitbox02-bt/vendor/da14531/src/gpreg/ble_timer_reg.rs new file mode 100644 index 0000000..e67b42e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg/ble_timer_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `BLE_TIMER_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `BLE_TIMER_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BLE_TIMER_DATA` reader - Operation depends on GP_CONTROL_REG->BLE_TIMER_DATA_CTRL. If BLE_TIMER_DATA_CTRL = 0 then: This register is located at the Always On Power Domain and it holds the automatically sampled value of the BLE FINECNT timer The HW automatically samples the value into this register during the sequence of \"BLE Sleep On\" and restores automatically the value during the BLE Wake up sequence. The Software may read and modify the value while the BLE is in Sleep state. While the BLE is awake, the value of the register has no meaning, while changing the value by writing another one will have no effect in the operation of the BLE core. There is a constraint when the SW performs an write-read sequence where it has to inject a one cycle delay in between (e.g. write-NOP-read) in order to read back the correct value. If BLE_TIMER_DATA_CTRL is non 0 then write operations have the same effect as when BLE_TIMER_DATA_CTRL=0, while for read operations: BLE_TIMER_DATA_CTRL= 1: then reading BLE_TIMER_REG returns \"deepsldur\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 2: then reading BLE_TIMER_REG returns \"deepsltime_samp\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 3: then reading BLE_TIMER_REG returns \"{deep_sleep_stat_monitor, deepsltime_samp\\[18:10\\]}. ."] +pub struct BLE_TIMER_DATA_R(crate::FieldReader); +impl BLE_TIMER_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + BLE_TIMER_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_TIMER_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_TIMER_DATA` writer - Operation depends on GP_CONTROL_REG->BLE_TIMER_DATA_CTRL. If BLE_TIMER_DATA_CTRL = 0 then: This register is located at the Always On Power Domain and it holds the automatically sampled value of the BLE FINECNT timer The HW automatically samples the value into this register during the sequence of \"BLE Sleep On\" and restores automatically the value during the BLE Wake up sequence. The Software may read and modify the value while the BLE is in Sleep state. While the BLE is awake, the value of the register has no meaning, while changing the value by writing another one will have no effect in the operation of the BLE core. There is a constraint when the SW performs an write-read sequence where it has to inject a one cycle delay in between (e.g. write-NOP-read) in order to read back the correct value. If BLE_TIMER_DATA_CTRL is non 0 then write operations have the same effect as when BLE_TIMER_DATA_CTRL=0, while for read operations: BLE_TIMER_DATA_CTRL= 1: then reading BLE_TIMER_REG returns \"deepsldur\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 2: then reading BLE_TIMER_REG returns \"deepsltime_samp\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 3: then reading BLE_TIMER_REG returns \"{deep_sleep_stat_monitor, deepsltime_samp\\[18:10\\]}. ."] +pub struct BLE_TIMER_DATA_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_TIMER_DATA_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u16 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 0:9 - Operation depends on GP_CONTROL_REG->BLE_TIMER_DATA_CTRL. If BLE_TIMER_DATA_CTRL = 0 then: This register is located at the Always On Power Domain and it holds the automatically sampled value of the BLE FINECNT timer The HW automatically samples the value into this register during the sequence of \"BLE Sleep On\" and restores automatically the value during the BLE Wake up sequence. The Software may read and modify the value while the BLE is in Sleep state. While the BLE is awake, the value of the register has no meaning, while changing the value by writing another one will have no effect in the operation of the BLE core. There is a constraint when the SW performs an write-read sequence where it has to inject a one cycle delay in between (e.g. write-NOP-read) in order to read back the correct value. If BLE_TIMER_DATA_CTRL is non 0 then write operations have the same effect as when BLE_TIMER_DATA_CTRL=0, while for read operations: BLE_TIMER_DATA_CTRL= 1: then reading BLE_TIMER_REG returns \"deepsldur\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 2: then reading BLE_TIMER_REG returns \"deepsltime_samp\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 3: then reading BLE_TIMER_REG returns \"{deep_sleep_stat_monitor, deepsltime_samp\\[18:10\\]}. ."] + #[inline(always)] + pub fn ble_timer_data(&self) -> BLE_TIMER_DATA_R { + BLE_TIMER_DATA_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 0:9 - Operation depends on GP_CONTROL_REG->BLE_TIMER_DATA_CTRL. If BLE_TIMER_DATA_CTRL = 0 then: This register is located at the Always On Power Domain and it holds the automatically sampled value of the BLE FINECNT timer The HW automatically samples the value into this register during the sequence of \"BLE Sleep On\" and restores automatically the value during the BLE Wake up sequence. The Software may read and modify the value while the BLE is in Sleep state. While the BLE is awake, the value of the register has no meaning, while changing the value by writing another one will have no effect in the operation of the BLE core. There is a constraint when the SW performs an write-read sequence where it has to inject a one cycle delay in between (e.g. write-NOP-read) in order to read back the correct value. If BLE_TIMER_DATA_CTRL is non 0 then write operations have the same effect as when BLE_TIMER_DATA_CTRL=0, while for read operations: BLE_TIMER_DATA_CTRL= 1: then reading BLE_TIMER_REG returns \"deepsldur\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 2: then reading BLE_TIMER_REG returns \"deepsltime_samp\\[9:0\\]\". BLE_TIMER_DATA_CTRL= 3: then reading BLE_TIMER_REG returns \"{deep_sleep_stat_monitor, deepsltime_samp\\[18:10\\]}. ."] + #[inline(always)] + pub fn ble_timer_data(&mut self) -> BLE_TIMER_DATA_W { + BLE_TIMER_DATA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "BLE FINECNT sampled value while in deep sleep state.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ble_timer_reg](index.html) module"] +pub struct BLE_TIMER_REG_SPEC; +impl crate::RegisterSpec for BLE_TIMER_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [ble_timer_reg::R](R) reader structure"] +impl crate::Readable for BLE_TIMER_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ble_timer_reg::W](W) writer structure"] +impl crate::Writable for BLE_TIMER_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets BLE_TIMER_REG to value 0"] +impl crate::Resettable for BLE_TIMER_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpreg/debug_reg.rs b/bitbox02-bt/vendor/da14531/src/gpreg/debug_reg.rs new file mode 100644 index 0000000..ece0d4d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg/debug_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `DEBUG_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `DEBUG_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DEBUGS_FREEZE_EN` reader - Default '1', freezing of the on-chip timers is enabled when the Cortex-M0Plus is halted in DEBUG State. If '0', freezing of the on-chip timers is depending on FREEZE_REG when the Cortex-M0Plus is halted in DEBUG State except the watchdog timer. The watchdog timer is always frozen when the Cortex-M0Plus is halted in DEBUG State."] +pub struct DEBUGS_FREEZE_EN_R(crate::FieldReader); +impl DEBUGS_FREEZE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEBUGS_FREEZE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEBUGS_FREEZE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEBUGS_FREEZE_EN` writer - Default '1', freezing of the on-chip timers is enabled when the Cortex-M0Plus is halted in DEBUG State. If '0', freezing of the on-chip timers is depending on FREEZE_REG when the Cortex-M0Plus is halted in DEBUG State except the watchdog timer. The watchdog timer is always frozen when the Cortex-M0Plus is halted in DEBUG State."] +pub struct DEBUGS_FREEZE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> DEBUGS_FREEZE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Default '1', freezing of the on-chip timers is enabled when the Cortex-M0Plus is halted in DEBUG State. If '0', freezing of the on-chip timers is depending on FREEZE_REG when the Cortex-M0Plus is halted in DEBUG State except the watchdog timer. The watchdog timer is always frozen when the Cortex-M0Plus is halted in DEBUG State."] + #[inline(always)] + pub fn debugs_freeze_en(&self) -> DEBUGS_FREEZE_EN_R { + DEBUGS_FREEZE_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Default '1', freezing of the on-chip timers is enabled when the Cortex-M0Plus is halted in DEBUG State. If '0', freezing of the on-chip timers is depending on FREEZE_REG when the Cortex-M0Plus is halted in DEBUG State except the watchdog timer. The watchdog timer is always frozen when the Cortex-M0Plus is halted in DEBUG State."] + #[inline(always)] + pub fn debugs_freeze_en(&mut self) -> DEBUGS_FREEZE_EN_W { + DEBUGS_FREEZE_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Various debug information register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [debug_reg](index.html) module"] +pub struct DEBUG_REG_SPEC; +impl crate::RegisterSpec for DEBUG_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [debug_reg::R](R) reader structure"] +impl crate::Readable for DEBUG_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [debug_reg::W](W) writer structure"] +impl crate::Writable for DEBUG_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets DEBUG_REG to value 0x01"] +impl crate::Resettable for DEBUG_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpreg/gp_control_reg.rs b/bitbox02-bt/vendor/da14531/src/gpreg/gp_control_reg.rs new file mode 100644 index 0000000..03fa196 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg/gp_control_reg.rs @@ -0,0 +1,217 @@ +#[doc = "Register `GP_CONTROL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_CONTROL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `BLE_TIMER_DATA_CTRL` reader - Refer to BLE_TIMER_REG."] +pub struct BLE_TIMER_DATA_CTRL_R(crate::FieldReader); +impl BLE_TIMER_DATA_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + BLE_TIMER_DATA_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_TIMER_DATA_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_TIMER_DATA_CTRL` writer - Refer to BLE_TIMER_REG."] +pub struct BLE_TIMER_DATA_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_TIMER_DATA_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 5)) | ((value as u16 & 3) << 5); + self.w + } +} +#[doc = "Field `CPU_DMA_BUS_PRIO` reader - Controls the CPU DMA system bus priority: If '0', the CPU has highest priority. If '1', the DMA has highest priority."] +pub struct CPU_DMA_BUS_PRIO_R(crate::FieldReader); +impl CPU_DMA_BUS_PRIO_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CPU_DMA_BUS_PRIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CPU_DMA_BUS_PRIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CPU_DMA_BUS_PRIO` writer - Controls the CPU DMA system bus priority: If '0', the CPU has highest priority. If '1', the DMA has highest priority."] +pub struct CPU_DMA_BUS_PRIO_W<'a> { + w: &'a mut W, +} +impl<'a> CPU_DMA_BUS_PRIO_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `BLE_WAKEUP_LP_IRQ` reader - The current value of the BLE_WAKEUP_LP_IRQ interrupt request."] +pub struct BLE_WAKEUP_LP_IRQ_R(crate::FieldReader); +impl BLE_WAKEUP_LP_IRQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_WAKEUP_LP_IRQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_WAKEUP_LP_IRQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_WAKEUP_REQ` reader - If '1', the BLE wakes up. Must be kept high at least for 1 low power clock period. If the BLE is in deep sleep state, then by setting this bit it will cause the wakeup LP IRQ to be asserted with a delay of 3 to 4 low power cycles."] +pub struct BLE_WAKEUP_REQ_R(crate::FieldReader); +impl BLE_WAKEUP_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + BLE_WAKEUP_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for BLE_WAKEUP_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `BLE_WAKEUP_REQ` writer - If '1', the BLE wakes up. Must be kept high at least for 1 low power clock period. If the BLE is in deep sleep state, then by setting this bit it will cause the wakeup LP IRQ to be asserted with a delay of 3 to 4 low power cycles."] +pub struct BLE_WAKEUP_REQ_W<'a> { + w: &'a mut W, +} +impl<'a> BLE_WAKEUP_REQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 5:6 - Refer to BLE_TIMER_REG."] + #[inline(always)] + pub fn ble_timer_data_ctrl(&self) -> BLE_TIMER_DATA_CTRL_R { + BLE_TIMER_DATA_CTRL_R::new(((self.bits >> 5) & 3) as u8) + } + #[doc = "Bit 4 - Controls the CPU DMA system bus priority: If '0', the CPU has highest priority. If '1', the DMA has highest priority."] + #[inline(always)] + pub fn cpu_dma_bus_prio(&self) -> CPU_DMA_BUS_PRIO_R { + CPU_DMA_BUS_PRIO_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 2 - The current value of the BLE_WAKEUP_LP_IRQ interrupt request."] + #[inline(always)] + pub fn ble_wakeup_lp_irq(&self) -> BLE_WAKEUP_LP_IRQ_R { + BLE_WAKEUP_LP_IRQ_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 0 - If '1', the BLE wakes up. Must be kept high at least for 1 low power clock period. If the BLE is in deep sleep state, then by setting this bit it will cause the wakeup LP IRQ to be asserted with a delay of 3 to 4 low power cycles."] + #[inline(always)] + pub fn ble_wakeup_req(&self) -> BLE_WAKEUP_REQ_R { + BLE_WAKEUP_REQ_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 5:6 - Refer to BLE_TIMER_REG."] + #[inline(always)] + pub fn ble_timer_data_ctrl(&mut self) -> BLE_TIMER_DATA_CTRL_W { + BLE_TIMER_DATA_CTRL_W { w: self } + } + #[doc = "Bit 4 - Controls the CPU DMA system bus priority: If '0', the CPU has highest priority. If '1', the DMA has highest priority."] + #[inline(always)] + pub fn cpu_dma_bus_prio(&mut self) -> CPU_DMA_BUS_PRIO_W { + CPU_DMA_BUS_PRIO_W { w: self } + } + #[doc = "Bit 0 - If '1', the BLE wakes up. Must be kept high at least for 1 low power clock period. If the BLE is in deep sleep state, then by setting this bit it will cause the wakeup LP IRQ to be asserted with a delay of 3 to 4 low power cycles."] + #[inline(always)] + pub fn ble_wakeup_req(&mut self) -> BLE_WAKEUP_REQ_W { + BLE_WAKEUP_REQ_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General purpose system control register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_control_reg](index.html) module"] +pub struct GP_CONTROL_REG_SPEC; +impl crate::RegisterSpec for GP_CONTROL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_control_reg::R](R) reader structure"] +impl crate::Readable for GP_CONTROL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_control_reg::W](W) writer structure"] +impl crate::Writable for GP_CONTROL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_CONTROL_REG to value 0"] +impl crate::Resettable for GP_CONTROL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpreg/gp_status_reg.rs b/bitbox02-bt/vendor/da14531/src/gpreg/gp_status_reg.rs new file mode 100644 index 0000000..42e4c85 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg/gp_status_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `GP_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GP_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CAL_PHASE` reader - If '1', it designates that the chip is in Calibration Phase i.e. the OTP has been initially programmed but no Calibration has occured."] +pub struct CAL_PHASE_R(crate::FieldReader); +impl CAL_PHASE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CAL_PHASE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CAL_PHASE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CAL_PHASE` writer - If '1', it designates that the chip is in Calibration Phase i.e. the OTP has been initially programmed but no Calibration has occured."] +pub struct CAL_PHASE_W<'a> { + w: &'a mut W, +} +impl<'a> CAL_PHASE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - If '1', it designates that the chip is in Calibration Phase i.e. the OTP has been initially programmed but no Calibration has occured."] + #[inline(always)] + pub fn cal_phase(&self) -> CAL_PHASE_R { + CAL_PHASE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - If '1', it designates that the chip is in Calibration Phase i.e. the OTP has been initially programmed but no Calibration has occured."] + #[inline(always)] + pub fn cal_phase(&mut self) -> CAL_PHASE_W { + CAL_PHASE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "General purpose system status register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gp_status_reg](index.html) module"] +pub struct GP_STATUS_REG_SPEC; +impl crate::RegisterSpec for GP_STATUS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gp_status_reg::R](R) reader structure"] +impl crate::Readable for GP_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gp_status_reg::W](W) writer structure"] +impl crate::Writable for GP_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GP_STATUS_REG to value 0"] +impl crate::Resettable for GP_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpreg/mem_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/gpreg/mem_ctrl_reg.rs new file mode 100644 index 0000000..7156147 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg/mem_ctrl_reg.rs @@ -0,0 +1,314 @@ +#[doc = "Register `MEM_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MEM_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ARB2_AHB2_WR_BUFF` reader - "] +pub struct ARB2_AHB2_WR_BUFF_R(crate::FieldReader); +impl ARB2_AHB2_WR_BUFF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ARB2_AHB2_WR_BUFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ARB2_AHB2_WR_BUFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ARB2_AHB_WR_BUFF` reader - "] +pub struct ARB2_AHB_WR_BUFF_R(crate::FieldReader); +impl ARB2_AHB_WR_BUFF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ARB2_AHB_WR_BUFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ARB2_AHB_WR_BUFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ARB1_AHB2_WR_BUFF` reader - "] +pub struct ARB1_AHB2_WR_BUFF_R(crate::FieldReader); +impl ARB1_AHB2_WR_BUFF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ARB1_AHB2_WR_BUFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ARB1_AHB2_WR_BUFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ARB1_AHB_WR_BUFF` reader - "] +pub struct ARB1_AHB_WR_BUFF_R(crate::FieldReader); +impl ARB1_AHB_WR_BUFF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ARB1_AHB_WR_BUFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ARB1_AHB_WR_BUFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM_MARGIN` reader - "] +pub struct RAM_MARGIN_R(crate::FieldReader); +impl RAM_MARGIN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RAM_MARGIN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAM_MARGIN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM_MARGIN` writer - "] +pub struct RAM_MARGIN_W<'a> { + w: &'a mut W, +} +impl<'a> RAM_MARGIN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 6)) | ((value as u16 & 3) << 6); + self.w + } +} +#[doc = "Field `RAM_DST` reader - "] +pub struct RAM_DST_R(crate::FieldReader); +impl RAM_DST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RAM_DST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RAM_DST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RAM_DST` writer - "] +pub struct RAM_DST_W<'a> { + w: &'a mut W, +} +impl<'a> RAM_DST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `ROM_MARGIN_EN` reader - "] +pub struct ROM_MARGIN_EN_R(crate::FieldReader); +impl ROM_MARGIN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ROM_MARGIN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ROM_MARGIN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ROM_MARGIN_EN` writer - "] +pub struct ROM_MARGIN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ROM_MARGIN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `ROM_MARGIN_CTRL` reader - "] +pub struct ROM_MARGIN_CTRL_R(crate::FieldReader); +impl ROM_MARGIN_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ROM_MARGIN_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ROM_MARGIN_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ROM_MARGIN_CTRL` writer - "] +pub struct ROM_MARGIN_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> ROM_MARGIN_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 11"] + #[inline(always)] + pub fn arb2_ahb2_wr_buff(&self) -> ARB2_AHB2_WR_BUFF_R { + ARB2_AHB2_WR_BUFF_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn arb2_ahb_wr_buff(&self) -> ARB2_AHB_WR_BUFF_R { + ARB2_AHB_WR_BUFF_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn arb1_ahb2_wr_buff(&self) -> ARB1_AHB2_WR_BUFF_R { + ARB1_AHB2_WR_BUFF_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn arb1_ahb_wr_buff(&self) -> ARB1_AHB_WR_BUFF_R { + ARB1_AHB_WR_BUFF_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 6:7"] + #[inline(always)] + pub fn ram_margin(&self) -> RAM_MARGIN_R { + RAM_MARGIN_R::new(((self.bits >> 6) & 3) as u8) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ram_dst(&self) -> RAM_DST_R { + RAM_DST_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn rom_margin_en(&self) -> ROM_MARGIN_EN_R { + ROM_MARGIN_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rom_margin_ctrl(&self) -> ROM_MARGIN_CTRL_R { + ROM_MARGIN_CTRL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 6:7"] + #[inline(always)] + pub fn ram_margin(&mut self) -> RAM_MARGIN_W { + RAM_MARGIN_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ram_dst(&mut self) -> RAM_DST_W { + RAM_DST_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn rom_margin_en(&mut self) -> ROM_MARGIN_EN_W { + ROM_MARGIN_EN_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rom_margin_ctrl(&mut self) -> ROM_MARGIN_CTRL_W { + ROM_MARGIN_CTRL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mem_ctrl_reg](index.html) module"] +pub struct MEM_CTRL_REG_SPEC; +impl crate::RegisterSpec for MEM_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mem_ctrl_reg::R](R) reader structure"] +impl crate::Readable for MEM_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mem_ctrl_reg::W](W) writer structure"] +impl crate::Writable for MEM_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MEM_CTRL_REG to value 0x80"] +impl crate::Resettable for MEM_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x80 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpreg/reset_freeze_reg.rs b/bitbox02-bt/vendor/da14531/src/gpreg/reset_freeze_reg.rs new file mode 100644 index 0000000..47a3b60 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg/reset_freeze_reg.rs @@ -0,0 +1,301 @@ +#[doc = "Register `RESET_FREEZE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RESET_FREEZE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FRZ_DMA` reader - If '1', the DMA continues, '0' is discarded."] +pub struct FRZ_DMA_R(crate::FieldReader); +impl FRZ_DMA_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_DMA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_DMA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_DMA` writer - If '1', the DMA continues, '0' is discarded."] +pub struct FRZ_DMA_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_DMA_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `FRZ_WDOG` reader - If '1', the watchdog timer continues, '0' is discarded."] +pub struct FRZ_WDOG_R(crate::FieldReader); +impl FRZ_WDOG_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_WDOG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_WDOG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_WDOG` writer - If '1', the watchdog timer continues, '0' is discarded."] +pub struct FRZ_WDOG_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_WDOG_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `FRZ_BLETIM` reader - If '1', the the BLE master clock continues, '0' is discarded."] +pub struct FRZ_BLETIM_R(crate::FieldReader); +impl FRZ_BLETIM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_BLETIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_BLETIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_BLETIM` writer - If '1', the the BLE master clock continues, '0' is discarded."] +pub struct FRZ_BLETIM_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_BLETIM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `FRZ_SWTIM` reader - If '1', the SW Timer (TIMER0) continues, '0' is discarded."] +pub struct FRZ_SWTIM_R(crate::FieldReader); +impl FRZ_SWTIM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_SWTIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_SWTIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_SWTIM` writer - If '1', the SW Timer (TIMER0) continues, '0' is discarded."] +pub struct FRZ_SWTIM_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_SWTIM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `FRZ_WKUPTIM` reader - If '1', the Wake Up Timer continues, '0' is discarded."] +pub struct FRZ_WKUPTIM_R(crate::FieldReader); +impl FRZ_WKUPTIM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_WKUPTIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_WKUPTIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_WKUPTIM` writer - If '1', the Wake Up Timer continues, '0' is discarded."] +pub struct FRZ_WKUPTIM_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_WKUPTIM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 4 - If '1', the DMA continues, '0' is discarded."] + #[inline(always)] + pub fn frz_dma(&self) -> FRZ_DMA_R { + FRZ_DMA_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - If '1', the watchdog timer continues, '0' is discarded."] + #[inline(always)] + pub fn frz_wdog(&self) -> FRZ_WDOG_R { + FRZ_WDOG_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - If '1', the the BLE master clock continues, '0' is discarded."] + #[inline(always)] + pub fn frz_bletim(&self) -> FRZ_BLETIM_R { + FRZ_BLETIM_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - If '1', the SW Timer (TIMER0) continues, '0' is discarded."] + #[inline(always)] + pub fn frz_swtim(&self) -> FRZ_SWTIM_R { + FRZ_SWTIM_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - If '1', the Wake Up Timer continues, '0' is discarded."] + #[inline(always)] + pub fn frz_wkuptim(&self) -> FRZ_WKUPTIM_R { + FRZ_WKUPTIM_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 4 - If '1', the DMA continues, '0' is discarded."] + #[inline(always)] + pub fn frz_dma(&mut self) -> FRZ_DMA_W { + FRZ_DMA_W { w: self } + } + #[doc = "Bit 3 - If '1', the watchdog timer continues, '0' is discarded."] + #[inline(always)] + pub fn frz_wdog(&mut self) -> FRZ_WDOG_W { + FRZ_WDOG_W { w: self } + } + #[doc = "Bit 2 - If '1', the the BLE master clock continues, '0' is discarded."] + #[inline(always)] + pub fn frz_bletim(&mut self) -> FRZ_BLETIM_W { + FRZ_BLETIM_W { w: self } + } + #[doc = "Bit 1 - If '1', the SW Timer (TIMER0) continues, '0' is discarded."] + #[inline(always)] + pub fn frz_swtim(&mut self) -> FRZ_SWTIM_W { + FRZ_SWTIM_W { w: self } + } + #[doc = "Bit 0 - If '1', the Wake Up Timer continues, '0' is discarded."] + #[inline(always)] + pub fn frz_wkuptim(&mut self) -> FRZ_WKUPTIM_W { + FRZ_WKUPTIM_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Controls unfreezing of various timers/counters.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [reset_freeze_reg](index.html) module"] +pub struct RESET_FREEZE_REG_SPEC; +impl crate::RegisterSpec for RESET_FREEZE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [reset_freeze_reg::R](R) reader structure"] +impl crate::Readable for RESET_FREEZE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [reset_freeze_reg::W](W) writer structure"] +impl crate::Writable for RESET_FREEZE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RESET_FREEZE_REG to value 0"] +impl crate::Resettable for RESET_FREEZE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/gpreg/set_freeze_reg.rs b/bitbox02-bt/vendor/da14531/src/gpreg/set_freeze_reg.rs new file mode 100644 index 0000000..cba63e8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/gpreg/set_freeze_reg.rs @@ -0,0 +1,305 @@ +#[doc = "Register `SET_FREEZE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SET_FREEZE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `FRZ_DMA` reader - If '1', the DMA is frozen, '0' is discarded."] +pub struct FRZ_DMA_R(crate::FieldReader); +impl FRZ_DMA_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_DMA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_DMA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_DMA` writer - If '1', the DMA is frozen, '0' is discarded."] +pub struct FRZ_DMA_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_DMA_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `FRZ_WDOG` reader - If '1', the watchdog timer is frozen, '0' is discarded. WATCHDOG_CTRL_REG\\[NMI_RST\\] +must be '0' to allow the freeze function."] +pub struct FRZ_WDOG_R(crate::FieldReader); +impl FRZ_WDOG_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_WDOG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_WDOG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_WDOG` writer - If '1', the watchdog timer is frozen, '0' is discarded. WATCHDOG_CTRL_REG\\[NMI_RST\\] +must be '0' to allow the freeze function."] +pub struct FRZ_WDOG_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_WDOG_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `FRZ_BLETIM` reader - If '1', the BLE master clock is frozen, '0' is discarded."] +pub struct FRZ_BLETIM_R(crate::FieldReader); +impl FRZ_BLETIM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_BLETIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_BLETIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_BLETIM` writer - If '1', the BLE master clock is frozen, '0' is discarded."] +pub struct FRZ_BLETIM_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_BLETIM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `FRZ_SWTIM` reader - If '1', the SW Timer (TIMER0) is frozen, '0' is discarded."] +pub struct FRZ_SWTIM_R(crate::FieldReader); +impl FRZ_SWTIM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_SWTIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_SWTIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_SWTIM` writer - If '1', the SW Timer (TIMER0) is frozen, '0' is discarded."] +pub struct FRZ_SWTIM_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_SWTIM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `FRZ_WKUPTIM` reader - If '1', the Wake Up Timer is frozen, '0' is discarded."] +pub struct FRZ_WKUPTIM_R(crate::FieldReader); +impl FRZ_WKUPTIM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + FRZ_WKUPTIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for FRZ_WKUPTIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `FRZ_WKUPTIM` writer - If '1', the Wake Up Timer is frozen, '0' is discarded."] +pub struct FRZ_WKUPTIM_W<'a> { + w: &'a mut W, +} +impl<'a> FRZ_WKUPTIM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 4 - If '1', the DMA is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_dma(&self) -> FRZ_DMA_R { + FRZ_DMA_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - If '1', the watchdog timer is frozen, '0' is discarded. WATCHDOG_CTRL_REG\\[NMI_RST\\] +must be '0' to allow the freeze function."] + #[inline(always)] + pub fn frz_wdog(&self) -> FRZ_WDOG_R { + FRZ_WDOG_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - If '1', the BLE master clock is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_bletim(&self) -> FRZ_BLETIM_R { + FRZ_BLETIM_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - If '1', the SW Timer (TIMER0) is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_swtim(&self) -> FRZ_SWTIM_R { + FRZ_SWTIM_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - If '1', the Wake Up Timer is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_wkuptim(&self) -> FRZ_WKUPTIM_R { + FRZ_WKUPTIM_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 4 - If '1', the DMA is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_dma(&mut self) -> FRZ_DMA_W { + FRZ_DMA_W { w: self } + } + #[doc = "Bit 3 - If '1', the watchdog timer is frozen, '0' is discarded. WATCHDOG_CTRL_REG\\[NMI_RST\\] +must be '0' to allow the freeze function."] + #[inline(always)] + pub fn frz_wdog(&mut self) -> FRZ_WDOG_W { + FRZ_WDOG_W { w: self } + } + #[doc = "Bit 2 - If '1', the BLE master clock is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_bletim(&mut self) -> FRZ_BLETIM_W { + FRZ_BLETIM_W { w: self } + } + #[doc = "Bit 1 - If '1', the SW Timer (TIMER0) is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_swtim(&mut self) -> FRZ_SWTIM_W { + FRZ_SWTIM_W { w: self } + } + #[doc = "Bit 0 - If '1', the Wake Up Timer is frozen, '0' is discarded."] + #[inline(always)] + pub fn frz_wkuptim(&mut self) -> FRZ_WKUPTIM_W { + FRZ_WKUPTIM_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Controls freezing of various timers/counters.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [set_freeze_reg](index.html) module"] +pub struct SET_FREEZE_REG_SPEC; +impl crate::RegisterSpec for SET_FREEZE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [set_freeze_reg::R](R) reader structure"] +impl crate::Readable for SET_FREEZE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [set_freeze_reg::W](W) writer structure"] +impl crate::Writable for SET_FREEZE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SET_FREEZE_REG to value 0"] +impl crate::Resettable for SET_FREEZE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c.rs b/bitbox02-bt/vendor/da14531/src/i2c.rs new file mode 100644 index 0000000..8ade0aa --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c.rs @@ -0,0 +1,301 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - I2C Control Register"] + pub i2c_con_reg: crate::Reg, + _reserved1: [u8; 0x02], + #[doc = "0x04 - I2C Target Address Register"] + pub i2c_tar_reg: crate::Reg, + _reserved2: [u8; 0x02], + #[doc = "0x08 - I2C Slave Address Register"] + pub i2c_sar_reg: crate::Reg, + _reserved3: [u8; 0x06], + #[doc = "0x10 - I2C Rx/Tx Data Buffer and Command Register"] + pub i2c_data_cmd_reg: crate::Reg, + _reserved4: [u8; 0x02], + #[doc = "0x14 - Standard Speed I2C Clock SCL High Count Register"] + pub i2c_ss_scl_hcnt_reg: crate::Reg, + _reserved5: [u8; 0x02], + #[doc = "0x18 - Standard Speed I2C Clock SCL Low Count Register"] + pub i2c_ss_scl_lcnt_reg: crate::Reg, + _reserved6: [u8; 0x02], + #[doc = "0x1c - Fast Speed I2C Clock SCL High Count Register"] + pub i2c_fs_scl_hcnt_reg: crate::Reg, + _reserved7: [u8; 0x02], + #[doc = "0x20 - Fast Speed I2C Clock SCL Low Count Register"] + pub i2c_fs_scl_lcnt_reg: crate::Reg, + _reserved8: [u8; 0x0a], + #[doc = "0x2c - I2C Interrupt Status Register"] + pub i2c_intr_stat_reg: crate::Reg, + _reserved9: [u8; 0x02], + #[doc = "0x30 - I2C Interrupt Mask Register"] + pub i2c_intr_mask_reg: crate::Reg, + _reserved10: [u8; 0x02], + #[doc = "0x34 - I2C Raw Interrupt Status Register"] + pub i2c_raw_intr_stat_reg: crate::Reg, + _reserved11: [u8; 0x02], + #[doc = "0x38 - I2C Receive FIFO Threshold Register"] + pub i2c_rx_tl_reg: crate::Reg, + _reserved12: [u8; 0x02], + #[doc = "0x3c - I2C Transmit FIFO Threshold Register"] + pub i2c_tx_tl_reg: crate::Reg, + _reserved13: [u8; 0x02], + #[doc = "0x40 - Clear Combined and Individual Interrupt Register"] + pub i2c_clr_intr_reg: crate::Reg, + _reserved14: [u8; 0x02], + #[doc = "0x44 - Clear RX_UNDER Interrupt Register"] + pub i2c_clr_rx_under_reg: crate::Reg, + _reserved15: [u8; 0x02], + #[doc = "0x48 - Clear RX_OVER Interrupt Register"] + pub i2c_clr_rx_over_reg: crate::Reg, + _reserved16: [u8; 0x02], + #[doc = "0x4c - Clear TX_OVER Interrupt Register"] + pub i2c_clr_tx_over_reg: crate::Reg, + _reserved17: [u8; 0x02], + #[doc = "0x50 - Clear RD_REQ Interrupt Register"] + pub i2c_clr_rd_req_reg: crate::Reg, + _reserved18: [u8; 0x02], + #[doc = "0x54 - Clear TX_ABRT Interrupt Register"] + pub i2c_clr_tx_abrt_reg: crate::Reg, + _reserved19: [u8; 0x02], + #[doc = "0x58 - Clear RX_DONE Interrupt Register"] + pub i2c_clr_rx_done_reg: crate::Reg, + _reserved20: [u8; 0x02], + #[doc = "0x5c - Clear ACTIVITY Interrupt Register"] + pub i2c_clr_activity_reg: crate::Reg, + _reserved21: [u8; 0x02], + #[doc = "0x60 - Clear STOP_DET Interrupt Register"] + pub i2c_clr_stop_det_reg: crate::Reg, + _reserved22: [u8; 0x02], + #[doc = "0x64 - Clear START_DET Interrupt Register"] + pub i2c_clr_start_det_reg: crate::Reg, + _reserved23: [u8; 0x02], + #[doc = "0x68 - Clear GEN_CALL Interrupt Register"] + pub i2c_clr_gen_call_reg: crate::Reg, + _reserved24: [u8; 0x02], + #[doc = "0x6c - I2C Enable Register"] + pub i2c_enable_reg: crate::Reg, + _reserved25: [u8; 0x02], + #[doc = "0x70 - I2C Status Register"] + pub i2c_status_reg: crate::Reg, + _reserved26: [u8; 0x02], + #[doc = "0x74 - I2C Transmit FIFO Level Register"] + pub i2c_txflr_reg: crate::Reg, + _reserved27: [u8; 0x02], + #[doc = "0x78 - I2C Receive FIFO Level Register"] + pub i2c_rxflr_reg: crate::Reg, + _reserved28: [u8; 0x02], + #[doc = "0x7c - I2C SDA Hold Time Length Register"] + pub i2c_sda_hold_reg: crate::Reg, + _reserved29: [u8; 0x02], + #[doc = "0x80 - I2C Transmit Abort Source Register"] + pub i2c_tx_abrt_source_reg: crate::Reg, + _reserved30: [u8; 0x06], + #[doc = "0x88 - DMA Control Register"] + pub i2c_dma_cr_reg: crate::Reg, + _reserved31: [u8; 0x02], + #[doc = "0x8c - DMA Transmit Data Level Register"] + pub i2c_dma_tdlr_reg: crate::Reg, + _reserved32: [u8; 0x02], + #[doc = "0x90 - I2C Receive Data Level Register"] + pub i2c_dma_rdlr_reg: crate::Reg, + _reserved33: [u8; 0x02], + #[doc = "0x94 - I2C SDA Setup Register"] + pub i2c_sda_setup_reg: crate::Reg, + _reserved34: [u8; 0x02], + #[doc = "0x98 - I2C ACK General Call Register"] + pub i2c_ack_general_call_reg: + crate::Reg, + _reserved35: [u8; 0x02], + #[doc = "0x9c - I2C Enable Status Register"] + pub i2c_enable_status_reg: crate::Reg, + _reserved36: [u8; 0x02], + #[doc = "0xa0 - I2C SS and FS spike suppression limit Size"] + pub i2c_ic_fs_spklen_reg: crate::Reg, + _reserved37: [u8; 0x52], + #[doc = "0xf4 - "] + pub i2c_comp_param1_reg: crate::Reg, + #[doc = "0xf6 - "] + pub i2c_comp_param2_reg: crate::Reg, + #[doc = "0xf8 - "] + pub i2c_comp_version_reg: crate::Reg, + #[doc = "0xfa - "] + pub i2c_comp2_version: crate::Reg, + #[doc = "0xfc - "] + pub i2c_comp_type_reg: crate::Reg, + #[doc = "0xfe - "] + pub i2c_comp_type2_reg: crate::Reg, +} +#[doc = "I2C_ACK_GENERAL_CALL_REG register accessor: an alias for `Reg`"] +pub type I2C_ACK_GENERAL_CALL_REG = + crate::Reg; +#[doc = "I2C ACK General Call Register"] +pub mod i2c_ack_general_call_reg; +#[doc = "I2C_CLR_ACTIVITY_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_ACTIVITY_REG = crate::Reg; +#[doc = "Clear ACTIVITY Interrupt Register"] +pub mod i2c_clr_activity_reg; +#[doc = "I2C_CLR_GEN_CALL_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_GEN_CALL_REG = crate::Reg; +#[doc = "Clear GEN_CALL Interrupt Register"] +pub mod i2c_clr_gen_call_reg; +#[doc = "I2C_CLR_INTR_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_INTR_REG = crate::Reg; +#[doc = "Clear Combined and Individual Interrupt Register"] +pub mod i2c_clr_intr_reg; +#[doc = "I2C_CLR_RD_REQ_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_RD_REQ_REG = crate::Reg; +#[doc = "Clear RD_REQ Interrupt Register"] +pub mod i2c_clr_rd_req_reg; +#[doc = "I2C_CLR_RX_DONE_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_RX_DONE_REG = crate::Reg; +#[doc = "Clear RX_DONE Interrupt Register"] +pub mod i2c_clr_rx_done_reg; +#[doc = "I2C_CLR_RX_OVER_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_RX_OVER_REG = crate::Reg; +#[doc = "Clear RX_OVER Interrupt Register"] +pub mod i2c_clr_rx_over_reg; +#[doc = "I2C_CLR_RX_UNDER_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_RX_UNDER_REG = crate::Reg; +#[doc = "Clear RX_UNDER Interrupt Register"] +pub mod i2c_clr_rx_under_reg; +#[doc = "I2C_CLR_START_DET_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_START_DET_REG = crate::Reg; +#[doc = "Clear START_DET Interrupt Register"] +pub mod i2c_clr_start_det_reg; +#[doc = "I2C_CLR_STOP_DET_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_STOP_DET_REG = crate::Reg; +#[doc = "Clear STOP_DET Interrupt Register"] +pub mod i2c_clr_stop_det_reg; +#[doc = "I2C_CLR_TX_ABRT_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_TX_ABRT_REG = crate::Reg; +#[doc = "Clear TX_ABRT Interrupt Register"] +pub mod i2c_clr_tx_abrt_reg; +#[doc = "I2C_CLR_TX_OVER_REG register accessor: an alias for `Reg`"] +pub type I2C_CLR_TX_OVER_REG = crate::Reg; +#[doc = "Clear TX_OVER Interrupt Register"] +pub mod i2c_clr_tx_over_reg; +#[doc = "I2C_COMP2_VERSION register accessor: an alias for `Reg`"] +pub type I2C_COMP2_VERSION = crate::Reg; +#[doc = ""] +pub mod i2c_comp2_version; +#[doc = "I2C_COMP_PARAM1_REG register accessor: an alias for `Reg`"] +pub type I2C_COMP_PARAM1_REG = crate::Reg; +#[doc = ""] +pub mod i2c_comp_param1_reg; +#[doc = "I2C_COMP_PARAM2_REG register accessor: an alias for `Reg`"] +pub type I2C_COMP_PARAM2_REG = crate::Reg; +#[doc = ""] +pub mod i2c_comp_param2_reg; +#[doc = "I2C_COMP_TYPE2_REG register accessor: an alias for `Reg`"] +pub type I2C_COMP_TYPE2_REG = crate::Reg; +#[doc = ""] +pub mod i2c_comp_type2_reg; +#[doc = "I2C_COMP_TYPE_REG register accessor: an alias for `Reg`"] +pub type I2C_COMP_TYPE_REG = crate::Reg; +#[doc = ""] +pub mod i2c_comp_type_reg; +#[doc = "I2C_COMP_VERSION_REG register accessor: an alias for `Reg`"] +pub type I2C_COMP_VERSION_REG = crate::Reg; +#[doc = ""] +pub mod i2c_comp_version_reg; +#[doc = "I2C_CON_REG register accessor: an alias for `Reg`"] +pub type I2C_CON_REG = crate::Reg; +#[doc = "I2C Control Register"] +pub mod i2c_con_reg; +#[doc = "I2C_DATA_CMD_REG register accessor: an alias for `Reg`"] +pub type I2C_DATA_CMD_REG = crate::Reg; +#[doc = "I2C Rx/Tx Data Buffer and Command Register"] +pub mod i2c_data_cmd_reg; +#[doc = "I2C_DMA_CR_REG register accessor: an alias for `Reg`"] +pub type I2C_DMA_CR_REG = crate::Reg; +#[doc = "DMA Control Register"] +pub mod i2c_dma_cr_reg; +#[doc = "I2C_DMA_RDLR_REG register accessor: an alias for `Reg`"] +pub type I2C_DMA_RDLR_REG = crate::Reg; +#[doc = "I2C Receive Data Level Register"] +pub mod i2c_dma_rdlr_reg; +#[doc = "I2C_DMA_TDLR_REG register accessor: an alias for `Reg`"] +pub type I2C_DMA_TDLR_REG = crate::Reg; +#[doc = "DMA Transmit Data Level Register"] +pub mod i2c_dma_tdlr_reg; +#[doc = "I2C_ENABLE_REG register accessor: an alias for `Reg`"] +pub type I2C_ENABLE_REG = crate::Reg; +#[doc = "I2C Enable Register"] +pub mod i2c_enable_reg; +#[doc = "I2C_ENABLE_STATUS_REG register accessor: an alias for `Reg`"] +pub type I2C_ENABLE_STATUS_REG = crate::Reg; +#[doc = "I2C Enable Status Register"] +pub mod i2c_enable_status_reg; +#[doc = "I2C_FS_SCL_HCNT_REG register accessor: an alias for `Reg`"] +pub type I2C_FS_SCL_HCNT_REG = crate::Reg; +#[doc = "Fast Speed I2C Clock SCL High Count Register"] +pub mod i2c_fs_scl_hcnt_reg; +#[doc = "I2C_FS_SCL_LCNT_REG register accessor: an alias for `Reg`"] +pub type I2C_FS_SCL_LCNT_REG = crate::Reg; +#[doc = "Fast Speed I2C Clock SCL Low Count Register"] +pub mod i2c_fs_scl_lcnt_reg; +#[doc = "I2C_IC_FS_SPKLEN_REG register accessor: an alias for `Reg`"] +pub type I2C_IC_FS_SPKLEN_REG = crate::Reg; +#[doc = "I2C SS and FS spike suppression limit Size"] +pub mod i2c_ic_fs_spklen_reg; +#[doc = "I2C_INTR_MASK_REG register accessor: an alias for `Reg`"] +pub type I2C_INTR_MASK_REG = crate::Reg; +#[doc = "I2C Interrupt Mask Register"] +pub mod i2c_intr_mask_reg; +#[doc = "I2C_INTR_STAT_REG register accessor: an alias for `Reg`"] +pub type I2C_INTR_STAT_REG = crate::Reg; +#[doc = "I2C Interrupt Status Register"] +pub mod i2c_intr_stat_reg; +#[doc = "I2C_RAW_INTR_STAT_REG register accessor: an alias for `Reg`"] +pub type I2C_RAW_INTR_STAT_REG = crate::Reg; +#[doc = "I2C Raw Interrupt Status Register"] +pub mod i2c_raw_intr_stat_reg; +#[doc = "I2C_RXFLR_REG register accessor: an alias for `Reg`"] +pub type I2C_RXFLR_REG = crate::Reg; +#[doc = "I2C Receive FIFO Level Register"] +pub mod i2c_rxflr_reg; +#[doc = "I2C_RX_TL_REG register accessor: an alias for `Reg`"] +pub type I2C_RX_TL_REG = crate::Reg; +#[doc = "I2C Receive FIFO Threshold Register"] +pub mod i2c_rx_tl_reg; +#[doc = "I2C_SAR_REG register accessor: an alias for `Reg`"] +pub type I2C_SAR_REG = crate::Reg; +#[doc = "I2C Slave Address Register"] +pub mod i2c_sar_reg; +#[doc = "I2C_SDA_HOLD_REG register accessor: an alias for `Reg`"] +pub type I2C_SDA_HOLD_REG = crate::Reg; +#[doc = "I2C SDA Hold Time Length Register"] +pub mod i2c_sda_hold_reg; +#[doc = "I2C_SDA_SETUP_REG register accessor: an alias for `Reg`"] +pub type I2C_SDA_SETUP_REG = crate::Reg; +#[doc = "I2C SDA Setup Register"] +pub mod i2c_sda_setup_reg; +#[doc = "I2C_SS_SCL_HCNT_REG register accessor: an alias for `Reg`"] +pub type I2C_SS_SCL_HCNT_REG = crate::Reg; +#[doc = "Standard Speed I2C Clock SCL High Count Register"] +pub mod i2c_ss_scl_hcnt_reg; +#[doc = "I2C_SS_SCL_LCNT_REG register accessor: an alias for `Reg`"] +pub type I2C_SS_SCL_LCNT_REG = crate::Reg; +#[doc = "Standard Speed I2C Clock SCL Low Count Register"] +pub mod i2c_ss_scl_lcnt_reg; +#[doc = "I2C_STATUS_REG register accessor: an alias for `Reg`"] +pub type I2C_STATUS_REG = crate::Reg; +#[doc = "I2C Status Register"] +pub mod i2c_status_reg; +#[doc = "I2C_TAR_REG register accessor: an alias for `Reg`"] +pub type I2C_TAR_REG = crate::Reg; +#[doc = "I2C Target Address Register"] +pub mod i2c_tar_reg; +#[doc = "I2C_TXFLR_REG register accessor: an alias for `Reg`"] +pub type I2C_TXFLR_REG = crate::Reg; +#[doc = "I2C Transmit FIFO Level Register"] +pub mod i2c_txflr_reg; +#[doc = "I2C_TX_ABRT_SOURCE_REG register accessor: an alias for `Reg`"] +pub type I2C_TX_ABRT_SOURCE_REG = crate::Reg; +#[doc = "I2C Transmit Abort Source Register"] +pub mod i2c_tx_abrt_source_reg; +#[doc = "I2C_TX_TL_REG register accessor: an alias for `Reg`"] +pub type I2C_TX_TL_REG = crate::Reg; +#[doc = "I2C Transmit FIFO Threshold Register"] +pub mod i2c_tx_tl_reg; diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_ack_general_call_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ack_general_call_reg.rs new file mode 100644 index 0000000..d6f5b5c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ack_general_call_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `I2C_ACK_GENERAL_CALL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_ACK_GENERAL_CALL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ACK_GEN_CALL` reader - ACK General Call. When set to 1, I2C Ctrl responds with a ACK (by asserting ic_data_oe) when it receives a General Call. When set to 0, the controller does not generate General Call interrupts."] +pub struct ACK_GEN_CALL_R(crate::FieldReader); +impl ACK_GEN_CALL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ACK_GEN_CALL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ACK_GEN_CALL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ACK_GEN_CALL` writer - ACK General Call. When set to 1, I2C Ctrl responds with a ACK (by asserting ic_data_oe) when it receives a General Call. When set to 0, the controller does not generate General Call interrupts."] +pub struct ACK_GEN_CALL_W<'a> { + w: &'a mut W, +} +impl<'a> ACK_GEN_CALL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - ACK General Call. When set to 1, I2C Ctrl responds with a ACK (by asserting ic_data_oe) when it receives a General Call. When set to 0, the controller does not generate General Call interrupts."] + #[inline(always)] + pub fn ack_gen_call(&self) -> ACK_GEN_CALL_R { + ACK_GEN_CALL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - ACK General Call. When set to 1, I2C Ctrl responds with a ACK (by asserting ic_data_oe) when it receives a General Call. When set to 0, the controller does not generate General Call interrupts."] + #[inline(always)] + pub fn ack_gen_call(&mut self) -> ACK_GEN_CALL_W { + ACK_GEN_CALL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C ACK General Call Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_ack_general_call_reg](index.html) module"] +pub struct I2C_ACK_GENERAL_CALL_REG_SPEC; +impl crate::RegisterSpec for I2C_ACK_GENERAL_CALL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_ack_general_call_reg::R](R) reader structure"] +impl crate::Readable for I2C_ACK_GENERAL_CALL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_ack_general_call_reg::W](W) writer structure"] +impl crate::Writable for I2C_ACK_GENERAL_CALL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_ACK_GENERAL_CALL_REG to value 0"] +impl crate::Resettable for I2C_ACK_GENERAL_CALL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_activity_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_activity_reg.rs new file mode 100644 index 0000000..1a4e6cb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_activity_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_ACTIVITY_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_ACTIVITY_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_ACTIVITY` reader - Reading this register clears the ACTIVITY interrupt if the I2C is not active anymore. If the I2C module is still active on the bus, the ACTIVITY interrupt bit continues to be set. It is automatically cleared by hardware if the module is disabled and if there is no further activity on the bus. The value read from this register to get status of the ACTIVITY interrupt (bit 8) of the IC_RAW_INTR_STAT register"] +pub struct CLR_ACTIVITY_R(crate::FieldReader); +impl CLR_ACTIVITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_ACTIVITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_ACTIVITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Reading this register clears the ACTIVITY interrupt if the I2C is not active anymore. If the I2C module is still active on the bus, the ACTIVITY interrupt bit continues to be set. It is automatically cleared by hardware if the module is disabled and if there is no further activity on the bus. The value read from this register to get status of the ACTIVITY interrupt (bit 8) of the IC_RAW_INTR_STAT register"] + #[inline(always)] + pub fn clr_activity(&self) -> CLR_ACTIVITY_R { + CLR_ACTIVITY_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear ACTIVITY Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_activity_reg](index.html) module"] +pub struct I2C_CLR_ACTIVITY_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_ACTIVITY_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_activity_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_ACTIVITY_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_activity_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_ACTIVITY_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_ACTIVITY_REG to value 0"] +impl crate::Resettable for I2C_CLR_ACTIVITY_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_gen_call_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_gen_call_reg.rs new file mode 100644 index 0000000..a35c2ec --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_gen_call_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_GEN_CALL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_GEN_CALL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_GEN_CALL` reader - Read this register to clear the GEN_CALL interrupt (bit 11) of I2C_RAW_INTR_STAT register."] +pub struct CLR_GEN_CALL_R(crate::FieldReader); +impl CLR_GEN_CALL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_GEN_CALL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_GEN_CALL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the GEN_CALL interrupt (bit 11) of I2C_RAW_INTR_STAT register."] + #[inline(always)] + pub fn clr_gen_call(&self) -> CLR_GEN_CALL_R { + CLR_GEN_CALL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear GEN_CALL Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_gen_call_reg](index.html) module"] +pub struct I2C_CLR_GEN_CALL_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_GEN_CALL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_gen_call_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_GEN_CALL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_gen_call_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_GEN_CALL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_GEN_CALL_REG to value 0"] +impl crate::Resettable for I2C_CLR_GEN_CALL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_intr_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_intr_reg.rs new file mode 100644 index 0000000..b1364cf --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_intr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_INTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_INTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_INTR` reader - Read this register to clear the combined interrupt, all individual interrupts, and the I2C_TX_ABRT_SOURCE register. This bit does not clear hardware clearable interrupts but software clearable interrupts. Refer to Bit 9 of the I2C_TX_ABRT_SOURCE register for an exception to clearing I2C_TX_ABRT_SOURCE"] +pub struct CLR_INTR_R(crate::FieldReader); +impl CLR_INTR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_INTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_INTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the combined interrupt, all individual interrupts, and the I2C_TX_ABRT_SOURCE register. This bit does not clear hardware clearable interrupts but software clearable interrupts. Refer to Bit 9 of the I2C_TX_ABRT_SOURCE register for an exception to clearing I2C_TX_ABRT_SOURCE"] + #[inline(always)] + pub fn clr_intr(&self) -> CLR_INTR_R { + CLR_INTR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear Combined and Individual Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_intr_reg](index.html) module"] +pub struct I2C_CLR_INTR_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_INTR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_intr_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_INTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_intr_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_INTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_INTR_REG to value 0"] +impl crate::Resettable for I2C_CLR_INTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rd_req_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rd_req_reg.rs new file mode 100644 index 0000000..cb9cb86 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rd_req_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_RD_REQ_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_RD_REQ_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_RD_REQ` reader - Read this register to clear the RD_REQ interrupt (bit 5) of the I2C_RAW_INTR_STAT register."] +pub struct CLR_RD_REQ_R(crate::FieldReader); +impl CLR_RD_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_RD_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_RD_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the RD_REQ interrupt (bit 5) of the I2C_RAW_INTR_STAT register."] + #[inline(always)] + pub fn clr_rd_req(&self) -> CLR_RD_REQ_R { + CLR_RD_REQ_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear RD_REQ Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_rd_req_reg](index.html) module"] +pub struct I2C_CLR_RD_REQ_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_RD_REQ_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_rd_req_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_RD_REQ_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_rd_req_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_RD_REQ_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_RD_REQ_REG to value 0"] +impl crate::Resettable for I2C_CLR_RD_REQ_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_done_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_done_reg.rs new file mode 100644 index 0000000..2112680 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_done_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_RX_DONE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_RX_DONE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_RX_DONE` reader - Read this register to clear the RX_DONE interrupt (bit 7) of the I2C_RAW_INTR_STAT register."] +pub struct CLR_RX_DONE_R(crate::FieldReader); +impl CLR_RX_DONE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_RX_DONE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_RX_DONE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the RX_DONE interrupt (bit 7) of the I2C_RAW_INTR_STAT register."] + #[inline(always)] + pub fn clr_rx_done(&self) -> CLR_RX_DONE_R { + CLR_RX_DONE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear RX_DONE Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_rx_done_reg](index.html) module"] +pub struct I2C_CLR_RX_DONE_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_RX_DONE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_rx_done_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_RX_DONE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_rx_done_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_RX_DONE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_RX_DONE_REG to value 0"] +impl crate::Resettable for I2C_CLR_RX_DONE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_over_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_over_reg.rs new file mode 100644 index 0000000..a811957 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_over_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_RX_OVER_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_RX_OVER_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_RX_OVER` reader - Read this register to clear the RX_OVER interrupt (bit 1) of the I2C_RAW_INTR_STAT register."] +pub struct CLR_RX_OVER_R(crate::FieldReader); +impl CLR_RX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_RX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_RX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the RX_OVER interrupt (bit 1) of the I2C_RAW_INTR_STAT register."] + #[inline(always)] + pub fn clr_rx_over(&self) -> CLR_RX_OVER_R { + CLR_RX_OVER_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear RX_OVER Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_rx_over_reg](index.html) module"] +pub struct I2C_CLR_RX_OVER_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_RX_OVER_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_rx_over_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_RX_OVER_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_rx_over_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_RX_OVER_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_RX_OVER_REG to value 0"] +impl crate::Resettable for I2C_CLR_RX_OVER_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_under_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_under_reg.rs new file mode 100644 index 0000000..754b16c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_rx_under_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_RX_UNDER_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_RX_UNDER_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_RX_UNDER` reader - Read this register to clear the RX_UNDER interrupt (bit 0) of the I2C_RAW_INTR_STAT register."] +pub struct CLR_RX_UNDER_R(crate::FieldReader); +impl CLR_RX_UNDER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_RX_UNDER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_RX_UNDER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the RX_UNDER interrupt (bit 0) of the I2C_RAW_INTR_STAT register."] + #[inline(always)] + pub fn clr_rx_under(&self) -> CLR_RX_UNDER_R { + CLR_RX_UNDER_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear RX_UNDER Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_rx_under_reg](index.html) module"] +pub struct I2C_CLR_RX_UNDER_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_RX_UNDER_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_rx_under_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_RX_UNDER_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_rx_under_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_RX_UNDER_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_RX_UNDER_REG to value 0"] +impl crate::Resettable for I2C_CLR_RX_UNDER_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_start_det_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_start_det_reg.rs new file mode 100644 index 0000000..77332fb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_start_det_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_START_DET_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_START_DET_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_START_DET` reader - Read this register to clear the START_DET interrupt (bit 10) of the IC_RAW_INTR_STAT register."] +pub struct CLR_START_DET_R(crate::FieldReader); +impl CLR_START_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_START_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_START_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the START_DET interrupt (bit 10) of the IC_RAW_INTR_STAT register."] + #[inline(always)] + pub fn clr_start_det(&self) -> CLR_START_DET_R { + CLR_START_DET_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear START_DET Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_start_det_reg](index.html) module"] +pub struct I2C_CLR_START_DET_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_START_DET_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_start_det_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_START_DET_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_start_det_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_START_DET_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_START_DET_REG to value 0"] +impl crate::Resettable for I2C_CLR_START_DET_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_stop_det_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_stop_det_reg.rs new file mode 100644 index 0000000..00da82f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_stop_det_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_STOP_DET_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_STOP_DET_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_STOP_DET` reader - Read this register to clear the STOP_DET interrupt (bit 9) of the IC_RAW_INTR_STAT register. Reset value: 0x0"] +pub struct CLR_STOP_DET_R(crate::FieldReader); +impl CLR_STOP_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_STOP_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_STOP_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the STOP_DET interrupt (bit 9) of the IC_RAW_INTR_STAT register. Reset value: 0x0"] + #[inline(always)] + pub fn clr_stop_det(&self) -> CLR_STOP_DET_R { + CLR_STOP_DET_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear STOP_DET Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_stop_det_reg](index.html) module"] +pub struct I2C_CLR_STOP_DET_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_STOP_DET_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_stop_det_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_STOP_DET_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_stop_det_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_STOP_DET_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_STOP_DET_REG to value 0"] +impl crate::Resettable for I2C_CLR_STOP_DET_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_abrt_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_abrt_reg.rs new file mode 100644 index 0000000..631e7f2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_abrt_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_TX_ABRT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_TX_ABRT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_TX_ABRT` reader - Read this register to clear the TX_ABRT interrupt (bit 6) of the IC_RAW_INTR_STAT register, and the I2C_TX_ABRT_SOURCE register. This also releases the TX FIFO from the flushed/reset state, allowing more writes to the TX FIFO. Refer to Bit 9 of the I2C_TX_ABRT_SOURCE register for an exception to clearing IC_TX_ABRT_SOURCE."] +pub struct CLR_TX_ABRT_R(crate::FieldReader); +impl CLR_TX_ABRT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_TX_ABRT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_TX_ABRT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the TX_ABRT interrupt (bit 6) of the IC_RAW_INTR_STAT register, and the I2C_TX_ABRT_SOURCE register. This also releases the TX FIFO from the flushed/reset state, allowing more writes to the TX FIFO. Refer to Bit 9 of the I2C_TX_ABRT_SOURCE register for an exception to clearing IC_TX_ABRT_SOURCE."] + #[inline(always)] + pub fn clr_tx_abrt(&self) -> CLR_TX_ABRT_R { + CLR_TX_ABRT_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear TX_ABRT Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_tx_abrt_reg](index.html) module"] +pub struct I2C_CLR_TX_ABRT_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_TX_ABRT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_tx_abrt_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_TX_ABRT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_tx_abrt_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_TX_ABRT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_TX_ABRT_REG to value 0"] +impl crate::Resettable for I2C_CLR_TX_ABRT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_over_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_over_reg.rs new file mode 100644 index 0000000..c27ad51 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_clr_tx_over_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_CLR_TX_OVER_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CLR_TX_OVER_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CLR_TX_OVER` reader - Read this register to clear the TX_OVER interrupt (bit 3) of the I2C_RAW_INTR_STAT register."] +pub struct CLR_TX_OVER_R(crate::FieldReader); +impl CLR_TX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLR_TX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLR_TX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Read this register to clear the TX_OVER interrupt (bit 3) of the I2C_RAW_INTR_STAT register."] + #[inline(always)] + pub fn clr_tx_over(&self) -> CLR_TX_OVER_R { + CLR_TX_OVER_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear TX_OVER Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_clr_tx_over_reg](index.html) module"] +pub struct I2C_CLR_TX_OVER_REG_SPEC; +impl crate::RegisterSpec for I2C_CLR_TX_OVER_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_clr_tx_over_reg::R](R) reader structure"] +impl crate::Readable for I2C_CLR_TX_OVER_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_clr_tx_over_reg::W](W) writer structure"] +impl crate::Writable for I2C_CLR_TX_OVER_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CLR_TX_OVER_REG to value 0"] +impl crate::Resettable for I2C_CLR_TX_OVER_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp2_version.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp2_version.rs new file mode 100644 index 0000000..be1a203 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp2_version.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_COMP2_VERSION` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_COMP2_VERSION` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_COMP2_VERSION` reader - "] +pub struct IC_COMP2_VERSION_R(crate::FieldReader); +impl IC_COMP2_VERSION_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_COMP2_VERSION_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_COMP2_VERSION_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn ic_comp2_version(&self) -> IC_COMP2_VERSION_R { + IC_COMP2_VERSION_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_comp2_version](index.html) module"] +pub struct I2C_COMP2_VERSION_SPEC; +impl crate::RegisterSpec for I2C_COMP2_VERSION_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_comp2_version::R](R) reader structure"] +impl crate::Readable for I2C_COMP2_VERSION_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_comp2_version::W](W) writer structure"] +impl crate::Writable for I2C_COMP2_VERSION_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_COMP2_VERSION to value 0x3132"] +impl crate::Resettable for I2C_COMP2_VERSION_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x3132 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param1_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param1_reg.rs new file mode 100644 index 0000000..03631f1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param1_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_COMP_PARAM1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_COMP_PARAM1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_COMP_PARAM1` reader - "] +pub struct IC_COMP_PARAM1_R(crate::FieldReader); +impl IC_COMP_PARAM1_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_COMP_PARAM1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_COMP_PARAM1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn ic_comp_param1(&self) -> IC_COMP_PARAM1_R { + IC_COMP_PARAM1_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_comp_param1_reg](index.html) module"] +pub struct I2C_COMP_PARAM1_REG_SPEC; +impl crate::RegisterSpec for I2C_COMP_PARAM1_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_comp_param1_reg::R](R) reader structure"] +impl crate::Readable for I2C_COMP_PARAM1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_comp_param1_reg::W](W) writer structure"] +impl crate::Writable for I2C_COMP_PARAM1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_COMP_PARAM1_REG to value 0"] +impl crate::Resettable for I2C_COMP_PARAM1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param2_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param2_reg.rs new file mode 100644 index 0000000..a2f49d7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_param2_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_COMP_PARAM2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_COMP_PARAM2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_COMP_PARAM2` reader - "] +pub struct IC_COMP_PARAM2_R(crate::FieldReader); +impl IC_COMP_PARAM2_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_COMP_PARAM2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_COMP_PARAM2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn ic_comp_param2(&self) -> IC_COMP_PARAM2_R { + IC_COMP_PARAM2_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_comp_param2_reg](index.html) module"] +pub struct I2C_COMP_PARAM2_REG_SPEC; +impl crate::RegisterSpec for I2C_COMP_PARAM2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_comp_param2_reg::R](R) reader structure"] +impl crate::Readable for I2C_COMP_PARAM2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_comp_param2_reg::W](W) writer structure"] +impl crate::Writable for I2C_COMP_PARAM2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_COMP_PARAM2_REG to value 0"] +impl crate::Resettable for I2C_COMP_PARAM2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type2_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type2_reg.rs new file mode 100644 index 0000000..65fe2a7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type2_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_COMP_TYPE2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_COMP_TYPE2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_COMP2_TYPE` reader - "] +pub struct IC_COMP2_TYPE_R(crate::FieldReader); +impl IC_COMP2_TYPE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_COMP2_TYPE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_COMP2_TYPE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn ic_comp2_type(&self) -> IC_COMP2_TYPE_R { + IC_COMP2_TYPE_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_comp_type2_reg](index.html) module"] +pub struct I2C_COMP_TYPE2_REG_SPEC; +impl crate::RegisterSpec for I2C_COMP_TYPE2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_comp_type2_reg::R](R) reader structure"] +impl crate::Readable for I2C_COMP_TYPE2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_comp_type2_reg::W](W) writer structure"] +impl crate::Writable for I2C_COMP_TYPE2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_COMP_TYPE2_REG to value 0x4457"] +impl crate::Resettable for I2C_COMP_TYPE2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x4457 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type_reg.rs new file mode 100644 index 0000000..b664c55 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_type_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_COMP_TYPE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_COMP_TYPE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_COMP_TYPE` reader - "] +pub struct IC_COMP_TYPE_R(crate::FieldReader); +impl IC_COMP_TYPE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_COMP_TYPE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_COMP_TYPE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn ic_comp_type(&self) -> IC_COMP_TYPE_R { + IC_COMP_TYPE_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_comp_type_reg](index.html) module"] +pub struct I2C_COMP_TYPE_REG_SPEC; +impl crate::RegisterSpec for I2C_COMP_TYPE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_comp_type_reg::R](R) reader structure"] +impl crate::Readable for I2C_COMP_TYPE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_comp_type_reg::W](W) writer structure"] +impl crate::Writable for I2C_COMP_TYPE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_COMP_TYPE_REG to value 0x0140"] +impl crate::Resettable for I2C_COMP_TYPE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0140 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_version_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_version_reg.rs new file mode 100644 index 0000000..83f03af --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_comp_version_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_COMP_VERSION_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_COMP_VERSION_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_COMP_VERSION` reader - "] +pub struct IC_COMP_VERSION_R(crate::FieldReader); +impl IC_COMP_VERSION_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_COMP_VERSION_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_COMP_VERSION_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn ic_comp_version(&self) -> IC_COMP_VERSION_R { + IC_COMP_VERSION_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_comp_version_reg](index.html) module"] +pub struct I2C_COMP_VERSION_REG_SPEC; +impl crate::RegisterSpec for I2C_COMP_VERSION_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_comp_version_reg::R](R) reader structure"] +impl crate::Readable for I2C_COMP_VERSION_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_comp_version_reg::W](W) writer structure"] +impl crate::Writable for I2C_COMP_VERSION_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_COMP_VERSION_REG to value 0x302a"] +impl crate::Resettable for I2C_COMP_VERSION_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x302a + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_con_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_con_reg.rs new file mode 100644 index 0000000..3010b40 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_con_reg.rs @@ -0,0 +1,338 @@ +#[doc = "Register `I2C_CON_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_CON_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `I2C_SLAVE_DISABLE` reader - Slave enabled or disabled after reset is applied, which means software does not have to configure the slave. 0=slave is enabled 1=slave is disabled Software should ensure that if this bit is written with '0', then bit 0 should also be written with a '0'."] +pub struct I2C_SLAVE_DISABLE_R(crate::FieldReader); +impl I2C_SLAVE_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_SLAVE_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_SLAVE_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_SLAVE_DISABLE` writer - Slave enabled or disabled after reset is applied, which means software does not have to configure the slave. 0=slave is enabled 1=slave is disabled Software should ensure that if this bit is written with '0', then bit 0 should also be written with a '0'."] +pub struct I2C_SLAVE_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_SLAVE_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `I2C_RESTART_EN` reader - Determines whether RESTART conditions may be sent when acting as a master 0= disable 1=enable"] +pub struct I2C_RESTART_EN_R(crate::FieldReader); +impl I2C_RESTART_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_RESTART_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_RESTART_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_RESTART_EN` writer - Determines whether RESTART conditions may be sent when acting as a master 0= disable 1=enable"] +pub struct I2C_RESTART_EN_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_RESTART_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `I2C_10BITADDR_MASTER` reader - Controls whether the controller starts its transfers in 7- or 10-bit addressing mode when acting as a master. 0= 7-bit addressing 1= 10-bit addressing"] +pub struct I2C_10BITADDR_MASTER_R(crate::FieldReader); +impl I2C_10BITADDR_MASTER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_10BITADDR_MASTER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_10BITADDR_MASTER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_10BITADDR_MASTER` writer - Controls whether the controller starts its transfers in 7- or 10-bit addressing mode when acting as a master. 0= 7-bit addressing 1= 10-bit addressing"] +pub struct I2C_10BITADDR_MASTER_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_10BITADDR_MASTER_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `I2C_10BITADDR_SLAVE` reader - When acting as a slave, this bit controls whether the controller responds to 7- or 10-bit addresses. 0= 7-bit addressing 1= 10-bit addressing"] +pub struct I2C_10BITADDR_SLAVE_R(crate::FieldReader); +impl I2C_10BITADDR_SLAVE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_10BITADDR_SLAVE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_10BITADDR_SLAVE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_10BITADDR_SLAVE` writer - When acting as a slave, this bit controls whether the controller responds to 7- or 10-bit addresses. 0= 7-bit addressing 1= 10-bit addressing"] +pub struct I2C_10BITADDR_SLAVE_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_10BITADDR_SLAVE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `I2C_SPEED` reader - These bits control at which speed the controller operates. 1= standard mode (100 kbit/s) 2= fast mode (400 kbit/s) Note: The actuall speed depends on the pcb traces capacitance as well as on the values of the external pull-up resistorts. For an exact speed match, trimming might be required, by adjusting the values of I2C_SS_SCL_HCNT_REG, I2C_SS_SCL_LCNT_REG, I2C_FS_SCL_HCNT_REG, I2C_FS_SCL_LCNT_REG registers. The reset values of those registers were calculated with the assumption of 4.3kOhms external pull-up resistors."] +pub struct I2C_SPEED_R(crate::FieldReader); +impl I2C_SPEED_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + I2C_SPEED_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_SPEED_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_SPEED` writer - These bits control at which speed the controller operates. 1= standard mode (100 kbit/s) 2= fast mode (400 kbit/s) Note: The actuall speed depends on the pcb traces capacitance as well as on the values of the external pull-up resistorts. For an exact speed match, trimming might be required, by adjusting the values of I2C_SS_SCL_HCNT_REG, I2C_SS_SCL_LCNT_REG, I2C_FS_SCL_HCNT_REG, I2C_FS_SCL_LCNT_REG registers. The reset values of those registers were calculated with the assumption of 4.3kOhms external pull-up resistors."] +pub struct I2C_SPEED_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_SPEED_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 1)) | ((value as u16 & 3) << 1); + self.w + } +} +#[doc = "Field `I2C_MASTER_MODE` reader - This bit controls whether the controller master is enabled. 0= master disabled 1= master enabled Software should ensure that if this bit is written with '1' then bit 6 should also be written with a '1'."] +pub struct I2C_MASTER_MODE_R(crate::FieldReader); +impl I2C_MASTER_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_MASTER_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_MASTER_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_MASTER_MODE` writer - This bit controls whether the controller master is enabled. 0= master disabled 1= master enabled Software should ensure that if this bit is written with '1' then bit 6 should also be written with a '1'."] +pub struct I2C_MASTER_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_MASTER_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 6 - Slave enabled or disabled after reset is applied, which means software does not have to configure the slave. 0=slave is enabled 1=slave is disabled Software should ensure that if this bit is written with '0', then bit 0 should also be written with a '0'."] + #[inline(always)] + pub fn i2c_slave_disable(&self) -> I2C_SLAVE_DISABLE_R { + I2C_SLAVE_DISABLE_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Determines whether RESTART conditions may be sent when acting as a master 0= disable 1=enable"] + #[inline(always)] + pub fn i2c_restart_en(&self) -> I2C_RESTART_EN_R { + I2C_RESTART_EN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Controls whether the controller starts its transfers in 7- or 10-bit addressing mode when acting as a master. 0= 7-bit addressing 1= 10-bit addressing"] + #[inline(always)] + pub fn i2c_10bitaddr_master(&self) -> I2C_10BITADDR_MASTER_R { + I2C_10BITADDR_MASTER_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - When acting as a slave, this bit controls whether the controller responds to 7- or 10-bit addresses. 0= 7-bit addressing 1= 10-bit addressing"] + #[inline(always)] + pub fn i2c_10bitaddr_slave(&self) -> I2C_10BITADDR_SLAVE_R { + I2C_10BITADDR_SLAVE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bits 1:2 - These bits control at which speed the controller operates. 1= standard mode (100 kbit/s) 2= fast mode (400 kbit/s) Note: The actuall speed depends on the pcb traces capacitance as well as on the values of the external pull-up resistorts. For an exact speed match, trimming might be required, by adjusting the values of I2C_SS_SCL_HCNT_REG, I2C_SS_SCL_LCNT_REG, I2C_FS_SCL_HCNT_REG, I2C_FS_SCL_LCNT_REG registers. The reset values of those registers were calculated with the assumption of 4.3kOhms external pull-up resistors."] + #[inline(always)] + pub fn i2c_speed(&self) -> I2C_SPEED_R { + I2C_SPEED_R::new(((self.bits >> 1) & 3) as u8) + } + #[doc = "Bit 0 - This bit controls whether the controller master is enabled. 0= master disabled 1= master enabled Software should ensure that if this bit is written with '1' then bit 6 should also be written with a '1'."] + #[inline(always)] + pub fn i2c_master_mode(&self) -> I2C_MASTER_MODE_R { + I2C_MASTER_MODE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 6 - Slave enabled or disabled after reset is applied, which means software does not have to configure the slave. 0=slave is enabled 1=slave is disabled Software should ensure that if this bit is written with '0', then bit 0 should also be written with a '0'."] + #[inline(always)] + pub fn i2c_slave_disable(&mut self) -> I2C_SLAVE_DISABLE_W { + I2C_SLAVE_DISABLE_W { w: self } + } + #[doc = "Bit 5 - Determines whether RESTART conditions may be sent when acting as a master 0= disable 1=enable"] + #[inline(always)] + pub fn i2c_restart_en(&mut self) -> I2C_RESTART_EN_W { + I2C_RESTART_EN_W { w: self } + } + #[doc = "Bit 4 - Controls whether the controller starts its transfers in 7- or 10-bit addressing mode when acting as a master. 0= 7-bit addressing 1= 10-bit addressing"] + #[inline(always)] + pub fn i2c_10bitaddr_master(&mut self) -> I2C_10BITADDR_MASTER_W { + I2C_10BITADDR_MASTER_W { w: self } + } + #[doc = "Bit 3 - When acting as a slave, this bit controls whether the controller responds to 7- or 10-bit addresses. 0= 7-bit addressing 1= 10-bit addressing"] + #[inline(always)] + pub fn i2c_10bitaddr_slave(&mut self) -> I2C_10BITADDR_SLAVE_W { + I2C_10BITADDR_SLAVE_W { w: self } + } + #[doc = "Bits 1:2 - These bits control at which speed the controller operates. 1= standard mode (100 kbit/s) 2= fast mode (400 kbit/s) Note: The actuall speed depends on the pcb traces capacitance as well as on the values of the external pull-up resistorts. For an exact speed match, trimming might be required, by adjusting the values of I2C_SS_SCL_HCNT_REG, I2C_SS_SCL_LCNT_REG, I2C_FS_SCL_HCNT_REG, I2C_FS_SCL_LCNT_REG registers. The reset values of those registers were calculated with the assumption of 4.3kOhms external pull-up resistors."] + #[inline(always)] + pub fn i2c_speed(&mut self) -> I2C_SPEED_W { + I2C_SPEED_W { w: self } + } + #[doc = "Bit 0 - This bit controls whether the controller master is enabled. 0= master disabled 1= master enabled Software should ensure that if this bit is written with '1' then bit 6 should also be written with a '1'."] + #[inline(always)] + pub fn i2c_master_mode(&mut self) -> I2C_MASTER_MODE_W { + I2C_MASTER_MODE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_con_reg](index.html) module"] +pub struct I2C_CON_REG_SPEC; +impl crate::RegisterSpec for I2C_CON_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_con_reg::R](R) reader structure"] +impl crate::Readable for I2C_CON_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_con_reg::W](W) writer structure"] +impl crate::Writable for I2C_CON_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_CON_REG to value 0x7d"] +impl crate::Resettable for I2C_CON_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7d + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_data_cmd_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_data_cmd_reg.rs new file mode 100644 index 0000000..541302d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_data_cmd_reg.rs @@ -0,0 +1,244 @@ +#[doc = "Register `I2C_DATA_CMD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_DATA_CMD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `I2C_RESTART` reader - This bit controls whether a RESTART is issued before the byte is sent or received. If IC_RESTART_EN is 1, a RESTART is issued before the data is sent/received (according to the value of CMD), regardless of whether or not the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. If IC_RESTART_EN is 1, a RESTART is issued only if the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. Reset value: 0x0"] +pub struct I2C_RESTART_R(crate::FieldReader); +impl I2C_RESTART_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_RESTART_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_RESTART_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_RESTART` writer - This bit controls whether a RESTART is issued before the byte is sent or received. If IC_RESTART_EN is 1, a RESTART is issued before the data is sent/received (according to the value of CMD), regardless of whether or not the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. If IC_RESTART_EN is 1, a RESTART is issued only if the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. Reset value: 0x0"] +pub struct I2C_RESTART_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_RESTART_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `I2C_STOP` reader - This bit controls whether a STOP is issued after the byte is sent or received. STOP is issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master immediately tries to start a new transfer by issuing a START and arbitrating for the bus. STOP is not issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master continues the current transfer by sending/receiving data bytes according to the value of the CMD bit. If the Tx FIFO is empty, the master holds the SCL line low and stalls the bus until a new command is available in the Tx FIFO. Reset value: 0x0"] +pub struct I2C_STOP_R(crate::FieldReader); +impl I2C_STOP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_STOP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_STOP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_STOP` writer - This bit controls whether a STOP is issued after the byte is sent or received. STOP is issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master immediately tries to start a new transfer by issuing a START and arbitrating for the bus. STOP is not issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master continues the current transfer by sending/receiving data bytes according to the value of the CMD bit. If the Tx FIFO is empty, the master holds the SCL line low and stalls the bus until a new command is available in the Tx FIFO. Reset value: 0x0"] +pub struct I2C_STOP_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_STOP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `I2C_CMD` reader - This bit controls whether a read or a write is performed. This bit does not control the direction when the I2C Ctrl acts as a slave. It controls only the direction when it acts as a master. 1 = Read 0 = Write When a command is entered in the TX FIFO, this bit distinguishes the write and read commands. In slave-receiver mode, this bit is a \"don't care\" because writes to this register are not required. In slave-transmitter mode, a \"0\" indicates that CPU data is to be transmitted and as DAT or IC_DATA_CMD\\[7:0\\]. When programming this bit, you should remember the following: attempting to perform a read operation after a General Call command has been sent results in a TX_ABRT interrupt (bit 6 of the I2C_RAW_INTR_STAT_REG), unless bit 11 (SPECIAL) in the I2C_TAR register has been cleared. If a \"1\" is written to this bit after receiving a RD_REQ interrupt, then a TX_ABRT interrupt occurs. NOTE: It is possible that while attempting a master I2C read transfer on the controller, a RD_REQ interrupt may have occurred simultaneously due to a remote I2C master addressing the controller. In this type of scenario, it ignores the I2C_DATA_CMD write, generates a TX_ABRT interrupt, and waits to service the RD_REQ interrupt"] +pub struct I2C_CMD_R(crate::FieldReader); +impl I2C_CMD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_CMD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_CMD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_CMD` writer - This bit controls whether a read or a write is performed. This bit does not control the direction when the I2C Ctrl acts as a slave. It controls only the direction when it acts as a master. 1 = Read 0 = Write When a command is entered in the TX FIFO, this bit distinguishes the write and read commands. In slave-receiver mode, this bit is a \"don't care\" because writes to this register are not required. In slave-transmitter mode, a \"0\" indicates that CPU data is to be transmitted and as DAT or IC_DATA_CMD\\[7:0\\]. When programming this bit, you should remember the following: attempting to perform a read operation after a General Call command has been sent results in a TX_ABRT interrupt (bit 6 of the I2C_RAW_INTR_STAT_REG), unless bit 11 (SPECIAL) in the I2C_TAR register has been cleared. If a \"1\" is written to this bit after receiving a RD_REQ interrupt, then a TX_ABRT interrupt occurs. NOTE: It is possible that while attempting a master I2C read transfer on the controller, a RD_REQ interrupt may have occurred simultaneously due to a remote I2C master addressing the controller. In this type of scenario, it ignores the I2C_DATA_CMD write, generates a TX_ABRT interrupt, and waits to service the RD_REQ interrupt"] +pub struct I2C_CMD_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_CMD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `DAT` reader - This register contains the data to be transmitted or received on the I2C bus. If you are writing to this register and want to perform a read, bits 7:0 (DAT) are ignored by the controller. However, when you read this register, these bits return the value of data received on the controller's interface."] +pub struct DAT_R(crate::FieldReader); +impl DAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DAT` writer - This register contains the data to be transmitted or received on the I2C bus. If you are writing to this register and want to perform a read, bits 7:0 (DAT) are ignored by the controller. However, when you read this register, these bits return the value of data received on the controller's interface."] +pub struct DAT_W<'a> { + w: &'a mut W, +} +impl<'a> DAT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bit 10 - This bit controls whether a RESTART is issued before the byte is sent or received. If IC_RESTART_EN is 1, a RESTART is issued before the data is sent/received (according to the value of CMD), regardless of whether or not the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. If IC_RESTART_EN is 1, a RESTART is issued only if the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. Reset value: 0x0"] + #[inline(always)] + pub fn i2c_restart(&self) -> I2C_RESTART_R { + I2C_RESTART_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - This bit controls whether a STOP is issued after the byte is sent or received. STOP is issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master immediately tries to start a new transfer by issuing a START and arbitrating for the bus. STOP is not issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master continues the current transfer by sending/receiving data bytes according to the value of the CMD bit. If the Tx FIFO is empty, the master holds the SCL line low and stalls the bus until a new command is available in the Tx FIFO. Reset value: 0x0"] + #[inline(always)] + pub fn i2c_stop(&self) -> I2C_STOP_R { + I2C_STOP_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - This bit controls whether a read or a write is performed. This bit does not control the direction when the I2C Ctrl acts as a slave. It controls only the direction when it acts as a master. 1 = Read 0 = Write When a command is entered in the TX FIFO, this bit distinguishes the write and read commands. In slave-receiver mode, this bit is a \"don't care\" because writes to this register are not required. In slave-transmitter mode, a \"0\" indicates that CPU data is to be transmitted and as DAT or IC_DATA_CMD\\[7:0\\]. When programming this bit, you should remember the following: attempting to perform a read operation after a General Call command has been sent results in a TX_ABRT interrupt (bit 6 of the I2C_RAW_INTR_STAT_REG), unless bit 11 (SPECIAL) in the I2C_TAR register has been cleared. If a \"1\" is written to this bit after receiving a RD_REQ interrupt, then a TX_ABRT interrupt occurs. NOTE: It is possible that while attempting a master I2C read transfer on the controller, a RD_REQ interrupt may have occurred simultaneously due to a remote I2C master addressing the controller. In this type of scenario, it ignores the I2C_DATA_CMD write, generates a TX_ABRT interrupt, and waits to service the RD_REQ interrupt"] + #[inline(always)] + pub fn i2c_cmd(&self) -> I2C_CMD_R { + I2C_CMD_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 0:7 - This register contains the data to be transmitted or received on the I2C bus. If you are writing to this register and want to perform a read, bits 7:0 (DAT) are ignored by the controller. However, when you read this register, these bits return the value of data received on the controller's interface."] + #[inline(always)] + pub fn dat(&self) -> DAT_R { + DAT_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bit 10 - This bit controls whether a RESTART is issued before the byte is sent or received. If IC_RESTART_EN is 1, a RESTART is issued before the data is sent/received (according to the value of CMD), regardless of whether or not the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. If IC_RESTART_EN is 1, a RESTART is issued only if the transfer direction is changing from the previous command; if IC_RESTART_EN is 0, a STOP followed by a START is issued instead. Reset value: 0x0"] + #[inline(always)] + pub fn i2c_restart(&mut self) -> I2C_RESTART_W { + I2C_RESTART_W { w: self } + } + #[doc = "Bit 9 - This bit controls whether a STOP is issued after the byte is sent or received. STOP is issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master immediately tries to start a new transfer by issuing a START and arbitrating for the bus. STOP is not issued after this byte, regardless of whether or not the Tx FIFO is empty. If the Tx FIFO is not empty, the master continues the current transfer by sending/receiving data bytes according to the value of the CMD bit. If the Tx FIFO is empty, the master holds the SCL line low and stalls the bus until a new command is available in the Tx FIFO. Reset value: 0x0"] + #[inline(always)] + pub fn i2c_stop(&mut self) -> I2C_STOP_W { + I2C_STOP_W { w: self } + } + #[doc = "Bit 8 - This bit controls whether a read or a write is performed. This bit does not control the direction when the I2C Ctrl acts as a slave. It controls only the direction when it acts as a master. 1 = Read 0 = Write When a command is entered in the TX FIFO, this bit distinguishes the write and read commands. In slave-receiver mode, this bit is a \"don't care\" because writes to this register are not required. In slave-transmitter mode, a \"0\" indicates that CPU data is to be transmitted and as DAT or IC_DATA_CMD\\[7:0\\]. When programming this bit, you should remember the following: attempting to perform a read operation after a General Call command has been sent results in a TX_ABRT interrupt (bit 6 of the I2C_RAW_INTR_STAT_REG), unless bit 11 (SPECIAL) in the I2C_TAR register has been cleared. If a \"1\" is written to this bit after receiving a RD_REQ interrupt, then a TX_ABRT interrupt occurs. NOTE: It is possible that while attempting a master I2C read transfer on the controller, a RD_REQ interrupt may have occurred simultaneously due to a remote I2C master addressing the controller. In this type of scenario, it ignores the I2C_DATA_CMD write, generates a TX_ABRT interrupt, and waits to service the RD_REQ interrupt"] + #[inline(always)] + pub fn i2c_cmd(&mut self) -> I2C_CMD_W { + I2C_CMD_W { w: self } + } + #[doc = "Bits 0:7 - This register contains the data to be transmitted or received on the I2C bus. If you are writing to this register and want to perform a read, bits 7:0 (DAT) are ignored by the controller. However, when you read this register, these bits return the value of data received on the controller's interface."] + #[inline(always)] + pub fn dat(&mut self) -> DAT_W { + DAT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Rx/Tx Data Buffer and Command Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_data_cmd_reg](index.html) module"] +pub struct I2C_DATA_CMD_REG_SPEC; +impl crate::RegisterSpec for I2C_DATA_CMD_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_data_cmd_reg::R](R) reader structure"] +impl crate::Readable for I2C_DATA_CMD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_data_cmd_reg::W](W) writer structure"] +impl crate::Writable for I2C_DATA_CMD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_DATA_CMD_REG to value 0"] +impl crate::Resettable for I2C_DATA_CMD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_cr_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_cr_reg.rs new file mode 100644 index 0000000..0216bfe --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_cr_reg.rs @@ -0,0 +1,160 @@ +#[doc = "Register `I2C_DMA_CR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_DMA_CR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TDMAE` reader - Transmit DMA Enable. //This bit enables/disables the transmit FIFO DMA channel. 0 = Transmit DMA disabled 1 = Transmit DMA enabled"] +pub struct TDMAE_R(crate::FieldReader); +impl TDMAE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TDMAE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TDMAE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TDMAE` writer - Transmit DMA Enable. //This bit enables/disables the transmit FIFO DMA channel. 0 = Transmit DMA disabled 1 = Transmit DMA enabled"] +pub struct TDMAE_W<'a> { + w: &'a mut W, +} +impl<'a> TDMAE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `RDMAE` reader - Receive DMA Enable. This bit enables/disables the receive FIFO DMA channel. 0 = Receive DMA disabled 1 = Receive DMA enabled"] +pub struct RDMAE_R(crate::FieldReader); +impl RDMAE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RDMAE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RDMAE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RDMAE` writer - Receive DMA Enable. This bit enables/disables the receive FIFO DMA channel. 0 = Receive DMA disabled 1 = Receive DMA enabled"] +pub struct RDMAE_W<'a> { + w: &'a mut W, +} +impl<'a> RDMAE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1 - Transmit DMA Enable. //This bit enables/disables the transmit FIFO DMA channel. 0 = Transmit DMA disabled 1 = Transmit DMA enabled"] + #[inline(always)] + pub fn tdmae(&self) -> TDMAE_R { + TDMAE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Receive DMA Enable. This bit enables/disables the receive FIFO DMA channel. 0 = Receive DMA disabled 1 = Receive DMA enabled"] + #[inline(always)] + pub fn rdmae(&self) -> RDMAE_R { + RDMAE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1 - Transmit DMA Enable. //This bit enables/disables the transmit FIFO DMA channel. 0 = Transmit DMA disabled 1 = Transmit DMA enabled"] + #[inline(always)] + pub fn tdmae(&mut self) -> TDMAE_W { + TDMAE_W { w: self } + } + #[doc = "Bit 0 - Receive DMA Enable. This bit enables/disables the receive FIFO DMA channel. 0 = Receive DMA disabled 1 = Receive DMA enabled"] + #[inline(always)] + pub fn rdmae(&mut self) -> RDMAE_W { + RDMAE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "DMA Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_dma_cr_reg](index.html) module"] +pub struct I2C_DMA_CR_REG_SPEC; +impl crate::RegisterSpec for I2C_DMA_CR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_dma_cr_reg::R](R) reader structure"] +impl crate::Readable for I2C_DMA_CR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_dma_cr_reg::W](W) writer structure"] +impl crate::Writable for I2C_DMA_CR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_DMA_CR_REG to value 0"] +impl crate::Resettable for I2C_DMA_CR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_rdlr_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_rdlr_reg.rs new file mode 100644 index 0000000..5b45219 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_rdlr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_DMA_RDLR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_DMA_RDLR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DMARDL` reader - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO."] +pub struct DMARDL_R(crate::FieldReader); +impl DMARDL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DMARDL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DMARDL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DMARDL` writer - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO."] +pub struct DMARDL_W<'a> { + w: &'a mut W, +} +impl<'a> DMARDL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u16 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 0:4 - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO."] + #[inline(always)] + pub fn dmardl(&self) -> DMARDL_R { + DMARDL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 0:4 - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO."] + #[inline(always)] + pub fn dmardl(&mut self) -> DMARDL_W { + DMARDL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Receive Data Level Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_dma_rdlr_reg](index.html) module"] +pub struct I2C_DMA_RDLR_REG_SPEC; +impl crate::RegisterSpec for I2C_DMA_RDLR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_dma_rdlr_reg::R](R) reader structure"] +impl crate::Readable for I2C_DMA_RDLR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_dma_rdlr_reg::W](W) writer structure"] +impl crate::Writable for I2C_DMA_RDLR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_DMA_RDLR_REG to value 0"] +impl crate::Resettable for I2C_DMA_RDLR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_tdlr_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_tdlr_reg.rs new file mode 100644 index 0000000..c809c52 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_dma_tdlr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_DMA_TDLR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_DMA_TDLR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DMATDL` reader - Transmit Data Level. This bit field controls the level at which a DMA request is made by the transmit logic. It is equal to the watermark level; that is, the dma_tx_req signal is generated when the number of valid data entries in the transmit FIFO is equal to or below this field value, and TDMAE = 1."] +pub struct DMATDL_R(crate::FieldReader); +impl DMATDL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DMATDL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DMATDL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DMATDL` writer - Transmit Data Level. This bit field controls the level at which a DMA request is made by the transmit logic. It is equal to the watermark level; that is, the dma_tx_req signal is generated when the number of valid data entries in the transmit FIFO is equal to or below this field value, and TDMAE = 1."] +pub struct DMATDL_W<'a> { + w: &'a mut W, +} +impl<'a> DMATDL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u16 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 0:4 - Transmit Data Level. This bit field controls the level at which a DMA request is made by the transmit logic. It is equal to the watermark level; that is, the dma_tx_req signal is generated when the number of valid data entries in the transmit FIFO is equal to or below this field value, and TDMAE = 1."] + #[inline(always)] + pub fn dmatdl(&self) -> DMATDL_R { + DMATDL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 0:4 - Transmit Data Level. This bit field controls the level at which a DMA request is made by the transmit logic. It is equal to the watermark level; that is, the dma_tx_req signal is generated when the number of valid data entries in the transmit FIFO is equal to or below this field value, and TDMAE = 1."] + #[inline(always)] + pub fn dmatdl(&mut self) -> DMATDL_W { + DMATDL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "DMA Transmit Data Level Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_dma_tdlr_reg](index.html) module"] +pub struct I2C_DMA_TDLR_REG_SPEC; +impl crate::RegisterSpec for I2C_DMA_TDLR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_dma_tdlr_reg::R](R) reader structure"] +impl crate::Readable for I2C_DMA_TDLR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_dma_tdlr_reg::W](W) writer structure"] +impl crate::Writable for I2C_DMA_TDLR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_DMA_TDLR_REG to value 0"] +impl crate::Resettable for I2C_DMA_TDLR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_reg.rs new file mode 100644 index 0000000..bbba4ed --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_reg.rs @@ -0,0 +1,160 @@ +#[doc = "Register `I2C_ENABLE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_ENABLE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `I2C_ABORT` reader - 0= ABORT not initiated or ABORT done 1= ABORT operation in progress The software can abort the I2C transfer in master mode by setting this bit. The software can set this bit only when ENABLE is already set; otherwise, the controller ignores any write to ABORT bit. The software cannot clear the ABORT bit once set. In response to an ABORT, the controller issues a STOP and flushes the Tx FIFO after completing the current transfer, then sets the TX_ABORT interrupt after the abort operation. The ABORT bit is cleared automatically after the abort operation."] +pub struct I2C_ABORT_R(crate::FieldReader); +impl I2C_ABORT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_ABORT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_ABORT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_ABORT` writer - 0= ABORT not initiated or ABORT done 1= ABORT operation in progress The software can abort the I2C transfer in master mode by setting this bit. The software can set this bit only when ENABLE is already set; otherwise, the controller ignores any write to ABORT bit. The software cannot clear the ABORT bit once set. In response to an ABORT, the controller issues a STOP and flushes the Tx FIFO after completing the current transfer, then sets the TX_ABORT interrupt after the abort operation. The ABORT bit is cleared automatically after the abort operation."] +pub struct I2C_ABORT_W<'a> { + w: &'a mut W, +} +impl<'a> I2C_ABORT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `CTRL_ENABLE` reader - Controls whether the controller is enabled. 0: Disables the controller (TX and RX FIFOs are held in an erased state) 1: Enables the controller Software can disable the controller while it is active. However, it is important that care be taken to ensure that the controller is disabled properly. When the controller is disabled, the following occurs: * The TX FIFO and RX FIFO get flushed. * Status bits in the IC_INTR_STAT register are still active until the controller goes into IDLE state. If the module is transmitting, it stops as well as deletes the contents of the transmit buffer after the current transfer is complete. If the module is receiving, the controller stops the current transfer at the end of the current byte and does not acknowledge the transfer. There is a two ic_clk delay when enabling or disabling the controller"] +pub struct CTRL_ENABLE_R(crate::FieldReader); +impl CTRL_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CTRL_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CTRL_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CTRL_ENABLE` writer - Controls whether the controller is enabled. 0: Disables the controller (TX and RX FIFOs are held in an erased state) 1: Enables the controller Software can disable the controller while it is active. However, it is important that care be taken to ensure that the controller is disabled properly. When the controller is disabled, the following occurs: * The TX FIFO and RX FIFO get flushed. * Status bits in the IC_INTR_STAT register are still active until the controller goes into IDLE state. If the module is transmitting, it stops as well as deletes the contents of the transmit buffer after the current transfer is complete. If the module is receiving, the controller stops the current transfer at the end of the current byte and does not acknowledge the transfer. There is a two ic_clk delay when enabling or disabling the controller"] +pub struct CTRL_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> CTRL_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1 - 0= ABORT not initiated or ABORT done 1= ABORT operation in progress The software can abort the I2C transfer in master mode by setting this bit. The software can set this bit only when ENABLE is already set; otherwise, the controller ignores any write to ABORT bit. The software cannot clear the ABORT bit once set. In response to an ABORT, the controller issues a STOP and flushes the Tx FIFO after completing the current transfer, then sets the TX_ABORT interrupt after the abort operation. The ABORT bit is cleared automatically after the abort operation."] + #[inline(always)] + pub fn i2c_abort(&self) -> I2C_ABORT_R { + I2C_ABORT_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Controls whether the controller is enabled. 0: Disables the controller (TX and RX FIFOs are held in an erased state) 1: Enables the controller Software can disable the controller while it is active. However, it is important that care be taken to ensure that the controller is disabled properly. When the controller is disabled, the following occurs: * The TX FIFO and RX FIFO get flushed. * Status bits in the IC_INTR_STAT register are still active until the controller goes into IDLE state. If the module is transmitting, it stops as well as deletes the contents of the transmit buffer after the current transfer is complete. If the module is receiving, the controller stops the current transfer at the end of the current byte and does not acknowledge the transfer. There is a two ic_clk delay when enabling or disabling the controller"] + #[inline(always)] + pub fn ctrl_enable(&self) -> CTRL_ENABLE_R { + CTRL_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1 - 0= ABORT not initiated or ABORT done 1= ABORT operation in progress The software can abort the I2C transfer in master mode by setting this bit. The software can set this bit only when ENABLE is already set; otherwise, the controller ignores any write to ABORT bit. The software cannot clear the ABORT bit once set. In response to an ABORT, the controller issues a STOP and flushes the Tx FIFO after completing the current transfer, then sets the TX_ABORT interrupt after the abort operation. The ABORT bit is cleared automatically after the abort operation."] + #[inline(always)] + pub fn i2c_abort(&mut self) -> I2C_ABORT_W { + I2C_ABORT_W { w: self } + } + #[doc = "Bit 0 - Controls whether the controller is enabled. 0: Disables the controller (TX and RX FIFOs are held in an erased state) 1: Enables the controller Software can disable the controller while it is active. However, it is important that care be taken to ensure that the controller is disabled properly. When the controller is disabled, the following occurs: * The TX FIFO and RX FIFO get flushed. * Status bits in the IC_INTR_STAT register are still active until the controller goes into IDLE state. If the module is transmitting, it stops as well as deletes the contents of the transmit buffer after the current transfer is complete. If the module is receiving, the controller stops the current transfer at the end of the current byte and does not acknowledge the transfer. There is a two ic_clk delay when enabling or disabling the controller"] + #[inline(always)] + pub fn ctrl_enable(&mut self) -> CTRL_ENABLE_W { + CTRL_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_enable_reg](index.html) module"] +pub struct I2C_ENABLE_REG_SPEC; +impl crate::RegisterSpec for I2C_ENABLE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_enable_reg::R](R) reader structure"] +impl crate::Readable for I2C_ENABLE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_enable_reg::W](W) writer structure"] +impl crate::Writable for I2C_ENABLE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_ENABLE_REG to value 0"] +impl crate::Resettable for I2C_ENABLE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_status_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_status_reg.rs new file mode 100644 index 0000000..7b81bab --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_enable_status_reg.rs @@ -0,0 +1,126 @@ +#[doc = "Register `I2C_ENABLE_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_ENABLE_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SLV_RX_DATA_LOST` reader - Slave Received Data Lost. This bit indicates if a Slave-Receiver operation has been aborted with at least one data byte received from an I2C transfer due to the setting of IC_ENABLE from 1 to 0. When read as 1, the controller is deemed to have been actively engaged in an aborted I2C transfer (with matching address) and the data phase of the I2C transfer has been entered, even though a data byte has been responded with a NACK. NOTE: If the remote I2C master terminates the transfer with a STOP condition before the controller has a chance to NACK a transfer, and IC_ENABLE has been set to 0, then this bit is also set to 1. When read as 0, the controller is deemed to have been disabled without being actively involved in the data phase of a Slave-Receiver transfer. NOTE: The CPU can safely read this bit when IC_EN (bit 0) is read as 0."] +pub struct SLV_RX_DATA_LOST_R(crate::FieldReader); +impl SLV_RX_DATA_LOST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SLV_RX_DATA_LOST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SLV_RX_DATA_LOST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SLV_DISABLED_WHILE_BUSY` reader - Slave Disabled While Busy (Transmit, Receive). This bit indicates if a potential or active Slave operation has been aborted due to the setting of the IC_ENABLE register from 1 to 0. This bit is set when the CPU writes a 0 to the IC_ENABLE register while: (a) I2C Ctrl is receiving the address byte of the Slave-Transmitter operation from a remote master; OR, (b) address and data bytes of the Slave-Receiver operation from a remote master. When read as 1, the controller is deemed to have forced a NACK during any part of an I2C transfer, irrespective of whether the I2C address matches the slave address set in I2C Ctrl (IC_SAR register) OR if the transfer is completed before IC_ENABLE is set to 0 but has not taken effect. NOTE: If the remote I2C master terminates the transfer with a STOP condition before the the controller has a chance to NACK a transfer, and IC_ENABLE has been set to 0, then this bit will also be set to 1. When read as 0, the controller is deemed to have been disabled when there is master activity, or when the I2C bus is idle. NOTE: The CPU can safely read this bit when IC_EN (bit 0) is read as 0."] +pub struct SLV_DISABLED_WHILE_BUSY_R(crate::FieldReader); +impl SLV_DISABLED_WHILE_BUSY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SLV_DISABLED_WHILE_BUSY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SLV_DISABLED_WHILE_BUSY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_EN` reader - ic_en Status. This bit always reflects the value driven on the output port ic_en. When read as 1, the controller is deemed to be in an enabled state. When read as 0, the controller is deemed completely inactive. NOTE: The CPU can safely read this bit anytime. When this bit is read as 0, the CPU can safely read SLV_RX_DATA_LOST (bit 2) and SLV_DISABLED_WHILE_BUSY (bit 1)."] +pub struct IC_EN_R(crate::FieldReader); +impl IC_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + IC_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 2 - Slave Received Data Lost. This bit indicates if a Slave-Receiver operation has been aborted with at least one data byte received from an I2C transfer due to the setting of IC_ENABLE from 1 to 0. When read as 1, the controller is deemed to have been actively engaged in an aborted I2C transfer (with matching address) and the data phase of the I2C transfer has been entered, even though a data byte has been responded with a NACK. NOTE: If the remote I2C master terminates the transfer with a STOP condition before the controller has a chance to NACK a transfer, and IC_ENABLE has been set to 0, then this bit is also set to 1. When read as 0, the controller is deemed to have been disabled without being actively involved in the data phase of a Slave-Receiver transfer. NOTE: The CPU can safely read this bit when IC_EN (bit 0) is read as 0."] + #[inline(always)] + pub fn slv_rx_data_lost(&self) -> SLV_RX_DATA_LOST_R { + SLV_RX_DATA_LOST_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Slave Disabled While Busy (Transmit, Receive). This bit indicates if a potential or active Slave operation has been aborted due to the setting of the IC_ENABLE register from 1 to 0. This bit is set when the CPU writes a 0 to the IC_ENABLE register while: (a) I2C Ctrl is receiving the address byte of the Slave-Transmitter operation from a remote master; OR, (b) address and data bytes of the Slave-Receiver operation from a remote master. When read as 1, the controller is deemed to have forced a NACK during any part of an I2C transfer, irrespective of whether the I2C address matches the slave address set in I2C Ctrl (IC_SAR register) OR if the transfer is completed before IC_ENABLE is set to 0 but has not taken effect. NOTE: If the remote I2C master terminates the transfer with a STOP condition before the the controller has a chance to NACK a transfer, and IC_ENABLE has been set to 0, then this bit will also be set to 1. When read as 0, the controller is deemed to have been disabled when there is master activity, or when the I2C bus is idle. NOTE: The CPU can safely read this bit when IC_EN (bit 0) is read as 0."] + #[inline(always)] + pub fn slv_disabled_while_busy(&self) -> SLV_DISABLED_WHILE_BUSY_R { + SLV_DISABLED_WHILE_BUSY_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - ic_en Status. This bit always reflects the value driven on the output port ic_en. When read as 1, the controller is deemed to be in an enabled state. When read as 0, the controller is deemed completely inactive. NOTE: The CPU can safely read this bit anytime. When this bit is read as 0, the CPU can safely read SLV_RX_DATA_LOST (bit 2) and SLV_DISABLED_WHILE_BUSY (bit 1)."] + #[inline(always)] + pub fn ic_en(&self) -> IC_EN_R { + IC_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Enable Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_enable_status_reg](index.html) module"] +pub struct I2C_ENABLE_STATUS_REG_SPEC; +impl crate::RegisterSpec for I2C_ENABLE_STATUS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_enable_status_reg::R](R) reader structure"] +impl crate::Readable for I2C_ENABLE_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_enable_status_reg::W](W) writer structure"] +impl crate::Writable for I2C_ENABLE_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_ENABLE_STATUS_REG to value 0"] +impl crate::Resettable for I2C_ENABLE_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_hcnt_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_hcnt_reg.rs new file mode 100644 index 0000000..7db5508 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_hcnt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_FS_SCL_HCNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_FS_SCL_HCNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_FS_SCL_HCNT` reader - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set."] +pub struct IC_FS_SCL_HCNT_R(crate::FieldReader); +impl IC_FS_SCL_HCNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_FS_SCL_HCNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_FS_SCL_HCNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_FS_SCL_HCNT` writer - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set."] +pub struct IC_FS_SCL_HCNT_W<'a> { + w: &'a mut W, +} +impl<'a> IC_FS_SCL_HCNT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set."] + #[inline(always)] + pub fn ic_fs_scl_hcnt(&self) -> IC_FS_SCL_HCNT_R { + IC_FS_SCL_HCNT_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set."] + #[inline(always)] + pub fn ic_fs_scl_hcnt(&mut self) -> IC_FS_SCL_HCNT_W { + IC_FS_SCL_HCNT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Fast Speed I2C Clock SCL High Count Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_fs_scl_hcnt_reg](index.html) module"] +pub struct I2C_FS_SCL_HCNT_REG_SPEC; +impl crate::RegisterSpec for I2C_FS_SCL_HCNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_fs_scl_hcnt_reg::R](R) reader structure"] +impl crate::Readable for I2C_FS_SCL_HCNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_fs_scl_hcnt_reg::W](W) writer structure"] +impl crate::Writable for I2C_FS_SCL_HCNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_FS_SCL_HCNT_REG to value 0x08"] +impl crate::Resettable for I2C_FS_SCL_HCNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x08 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_lcnt_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_lcnt_reg.rs new file mode 100644 index 0000000..f3c2290 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_fs_scl_lcnt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_FS_SCL_LCNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_FS_SCL_LCNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_FS_SCL_LCNT` reader - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted results in 8 being set. For designs with APB_DATA_WIDTH = 8 the order of programming is important to ensure the correct operation of the controller. The lower byte must be programmed first. Then the upper byte is programmed."] +pub struct IC_FS_SCL_LCNT_R(crate::FieldReader); +impl IC_FS_SCL_LCNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_FS_SCL_LCNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_FS_SCL_LCNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_FS_SCL_LCNT` writer - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted results in 8 being set. For designs with APB_DATA_WIDTH = 8 the order of programming is important to ensure the correct operation of the controller. The lower byte must be programmed first. Then the upper byte is programmed."] +pub struct IC_FS_SCL_LCNT_W<'a> { + w: &'a mut W, +} +impl<'a> IC_FS_SCL_LCNT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted results in 8 being set. For designs with APB_DATA_WIDTH = 8 the order of programming is important to ensure the correct operation of the controller. The lower byte must be programmed first. Then the upper byte is programmed."] + #[inline(always)] + pub fn ic_fs_scl_lcnt(&self) -> IC_FS_SCL_LCNT_R { + IC_FS_SCL_LCNT_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low-period count for fast speed. It is used in high-speed mode to send the Master Code and START BYTE or General CALL. This register can be written only when the I2C interface is disabled, which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted results in 8 being set. For designs with APB_DATA_WIDTH = 8 the order of programming is important to ensure the correct operation of the controller. The lower byte must be programmed first. Then the upper byte is programmed."] + #[inline(always)] + pub fn ic_fs_scl_lcnt(&mut self) -> IC_FS_SCL_LCNT_W { + IC_FS_SCL_LCNT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Fast Speed I2C Clock SCL Low Count Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_fs_scl_lcnt_reg](index.html) module"] +pub struct I2C_FS_SCL_LCNT_REG_SPEC; +impl crate::RegisterSpec for I2C_FS_SCL_LCNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_fs_scl_lcnt_reg::R](R) reader structure"] +impl crate::Readable for I2C_FS_SCL_LCNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_fs_scl_lcnt_reg::W](W) writer structure"] +impl crate::Writable for I2C_FS_SCL_LCNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_FS_SCL_LCNT_REG to value 0x17"] +impl crate::Resettable for I2C_FS_SCL_LCNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x17 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_ic_fs_spklen_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ic_fs_spklen_reg.rs new file mode 100644 index 0000000..e04cdc9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ic_fs_spklen_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_IC_FS_SPKLEN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_IC_FS_SPKLEN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_FS_SPKLEN` reader - This register must be set before any I2C bus transaction can take place to ensure stable operation. This register sets the duration, measured in ic_clk cycles, of the longest spike in the SCL or SDA lines that will be filtered out by the spike suppression logic. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 1; hardware prevents values less than this being written, and if attempted results in 1 being set."] +pub struct IC_FS_SPKLEN_R(crate::FieldReader); +impl IC_FS_SPKLEN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IC_FS_SPKLEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_FS_SPKLEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_FS_SPKLEN` writer - This register must be set before any I2C bus transaction can take place to ensure stable operation. This register sets the duration, measured in ic_clk cycles, of the longest spike in the SCL or SDA lines that will be filtered out by the spike suppression logic. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 1; hardware prevents values less than this being written, and if attempted results in 1 being set."] +pub struct IC_FS_SPKLEN_W<'a> { + w: &'a mut W, +} +impl<'a> IC_FS_SPKLEN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - This register must be set before any I2C bus transaction can take place to ensure stable operation. This register sets the duration, measured in ic_clk cycles, of the longest spike in the SCL or SDA lines that will be filtered out by the spike suppression logic. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 1; hardware prevents values less than this being written, and if attempted results in 1 being set."] + #[inline(always)] + pub fn ic_fs_spklen(&self) -> IC_FS_SPKLEN_R { + IC_FS_SPKLEN_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - This register must be set before any I2C bus transaction can take place to ensure stable operation. This register sets the duration, measured in ic_clk cycles, of the longest spike in the SCL or SDA lines that will be filtered out by the spike suppression logic. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 1; hardware prevents values less than this being written, and if attempted results in 1 being set."] + #[inline(always)] + pub fn ic_fs_spklen(&mut self) -> IC_FS_SPKLEN_W { + IC_FS_SPKLEN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C SS and FS spike suppression limit Size\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_ic_fs_spklen_reg](index.html) module"] +pub struct I2C_IC_FS_SPKLEN_REG_SPEC; +impl crate::RegisterSpec for I2C_IC_FS_SPKLEN_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_ic_fs_spklen_reg::R](R) reader structure"] +impl crate::Readable for I2C_IC_FS_SPKLEN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_ic_fs_spklen_reg::W](W) writer structure"] +impl crate::Writable for I2C_IC_FS_SPKLEN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_IC_FS_SPKLEN_REG to value 0x01"] +impl crate::Resettable for I2C_IC_FS_SPKLEN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_mask_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_mask_reg.rs new file mode 100644 index 0000000..c3e2ca6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_mask_reg.rs @@ -0,0 +1,630 @@ +#[doc = "Register `I2C_INTR_MASK_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_INTR_MASK_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `M_GEN_CALL` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_GEN_CALL_R(crate::FieldReader); +impl M_GEN_CALL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_GEN_CALL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_GEN_CALL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_GEN_CALL` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_GEN_CALL_W<'a> { + w: &'a mut W, +} +impl<'a> M_GEN_CALL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `M_START_DET` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_START_DET_R(crate::FieldReader); +impl M_START_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_START_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_START_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_START_DET` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_START_DET_W<'a> { + w: &'a mut W, +} +impl<'a> M_START_DET_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `M_STOP_DET` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_STOP_DET_R(crate::FieldReader); +impl M_STOP_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_STOP_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_STOP_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_STOP_DET` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_STOP_DET_W<'a> { + w: &'a mut W, +} +impl<'a> M_STOP_DET_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `M_ACTIVITY` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_ACTIVITY_R(crate::FieldReader); +impl M_ACTIVITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_ACTIVITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_ACTIVITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_ACTIVITY` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_ACTIVITY_W<'a> { + w: &'a mut W, +} +impl<'a> M_ACTIVITY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `M_RX_DONE` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_DONE_R(crate::FieldReader); +impl M_RX_DONE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_RX_DONE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_RX_DONE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_RX_DONE` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_DONE_W<'a> { + w: &'a mut W, +} +impl<'a> M_RX_DONE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `M_TX_ABRT` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_TX_ABRT_R(crate::FieldReader); +impl M_TX_ABRT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_TX_ABRT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_TX_ABRT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_TX_ABRT` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_TX_ABRT_W<'a> { + w: &'a mut W, +} +impl<'a> M_TX_ABRT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `M_RD_REQ` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RD_REQ_R(crate::FieldReader); +impl M_RD_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_RD_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_RD_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_RD_REQ` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RD_REQ_W<'a> { + w: &'a mut W, +} +impl<'a> M_RD_REQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `M_TX_EMPTY` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_TX_EMPTY_R(crate::FieldReader); +impl M_TX_EMPTY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_TX_EMPTY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_TX_EMPTY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_TX_EMPTY` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_TX_EMPTY_W<'a> { + w: &'a mut W, +} +impl<'a> M_TX_EMPTY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `M_TX_OVER` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_TX_OVER_R(crate::FieldReader); +impl M_TX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_TX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_TX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_TX_OVER` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_TX_OVER_W<'a> { + w: &'a mut W, +} +impl<'a> M_TX_OVER_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `M_RX_FULL` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_FULL_R(crate::FieldReader); +impl M_RX_FULL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_RX_FULL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_RX_FULL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_RX_FULL` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_FULL_W<'a> { + w: &'a mut W, +} +impl<'a> M_RX_FULL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `M_RX_OVER` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_OVER_R(crate::FieldReader); +impl M_RX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_RX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_RX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_RX_OVER` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_OVER_W<'a> { + w: &'a mut W, +} +impl<'a> M_RX_OVER_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `M_RX_UNDER` reader - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_UNDER_R(crate::FieldReader); +impl M_RX_UNDER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + M_RX_UNDER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for M_RX_UNDER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `M_RX_UNDER` writer - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] +pub struct M_RX_UNDER_W<'a> { + w: &'a mut W, +} +impl<'a> M_RX_UNDER_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 11 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_gen_call(&self) -> M_GEN_CALL_R { + M_GEN_CALL_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_start_det(&self) -> M_START_DET_R { + M_START_DET_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_stop_det(&self) -> M_STOP_DET_R { + M_STOP_DET_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_activity(&self) -> M_ACTIVITY_R { + M_ACTIVITY_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_done(&self) -> M_RX_DONE_R { + M_RX_DONE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_tx_abrt(&self) -> M_TX_ABRT_R { + M_TX_ABRT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rd_req(&self) -> M_RD_REQ_R { + M_RD_REQ_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_tx_empty(&self) -> M_TX_EMPTY_R { + M_TX_EMPTY_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_tx_over(&self) -> M_TX_OVER_R { + M_TX_OVER_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_full(&self) -> M_RX_FULL_R { + M_RX_FULL_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_over(&self) -> M_RX_OVER_R { + M_RX_OVER_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_under(&self) -> M_RX_UNDER_R { + M_RX_UNDER_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 11 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_gen_call(&mut self) -> M_GEN_CALL_W { + M_GEN_CALL_W { w: self } + } + #[doc = "Bit 10 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_start_det(&mut self) -> M_START_DET_W { + M_START_DET_W { w: self } + } + #[doc = "Bit 9 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_stop_det(&mut self) -> M_STOP_DET_W { + M_STOP_DET_W { w: self } + } + #[doc = "Bit 8 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_activity(&mut self) -> M_ACTIVITY_W { + M_ACTIVITY_W { w: self } + } + #[doc = "Bit 7 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_done(&mut self) -> M_RX_DONE_W { + M_RX_DONE_W { w: self } + } + #[doc = "Bit 6 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_tx_abrt(&mut self) -> M_TX_ABRT_W { + M_TX_ABRT_W { w: self } + } + #[doc = "Bit 5 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rd_req(&mut self) -> M_RD_REQ_W { + M_RD_REQ_W { w: self } + } + #[doc = "Bit 4 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_tx_empty(&mut self) -> M_TX_EMPTY_W { + M_TX_EMPTY_W { w: self } + } + #[doc = "Bit 3 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_tx_over(&mut self) -> M_TX_OVER_W { + M_TX_OVER_W { w: self } + } + #[doc = "Bit 2 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_full(&mut self) -> M_RX_FULL_W { + M_RX_FULL_W { w: self } + } + #[doc = "Bit 1 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_over(&mut self) -> M_RX_OVER_W { + M_RX_OVER_W { w: self } + } + #[doc = "Bit 0 - These bits mask their corresponding interrupt status bits in the I2C_INTR_STAT register."] + #[inline(always)] + pub fn m_rx_under(&mut self) -> M_RX_UNDER_W { + M_RX_UNDER_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_intr_mask_reg](index.html) module"] +pub struct I2C_INTR_MASK_REG_SPEC; +impl crate::RegisterSpec for I2C_INTR_MASK_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_intr_mask_reg::R](R) reader structure"] +impl crate::Readable for I2C_INTR_MASK_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_intr_mask_reg::W](W) writer structure"] +impl crate::Writable for I2C_INTR_MASK_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_INTR_MASK_REG to value 0x08ff"] +impl crate::Resettable for I2C_INTR_MASK_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x08ff + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_stat_reg.rs new file mode 100644 index 0000000..0503a41 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_intr_stat_reg.rs @@ -0,0 +1,306 @@ +#[doc = "Register `I2C_INTR_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_INTR_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `R_GEN_CALL` reader - Set only when a General Call address is received and it is acknowledged. It stays set until it is cleared either by disabling controller or when the CPU reads bit 0 of the I2C_CLR_GEN_CALL register. The controller stores the received data in the Rx buffer."] +pub struct R_GEN_CALL_R(crate::FieldReader); +impl R_GEN_CALL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_GEN_CALL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_GEN_CALL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_START_DET` reader - Indicates whether a START or RESTART condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] +pub struct R_START_DET_R(crate::FieldReader); +impl R_START_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_START_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_START_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_STOP_DET` reader - Indicates whether a STOP condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] +pub struct R_STOP_DET_R(crate::FieldReader); +impl R_STOP_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_STOP_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_STOP_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_ACTIVITY` reader - This bit captures I2C Ctrl activity and stays set until it is cleared. There are four ways to clear it: => Disabling the I2C Ctrl => Reading the IC_CLR_ACTIVITY register => Reading the IC_CLR_INTR register => System reset Once this bit is set, it stays set unless one of the four methods is used to clear it. Even if the controller module is idle, this bit remains set until cleared, indicating that there was activity on the bus."] +pub struct R_ACTIVITY_R(crate::FieldReader); +impl R_ACTIVITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_ACTIVITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_ACTIVITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_RX_DONE` reader - When the controller is acting as a slave-transmitter, this bit is set to 1 if the master does not acknowledge a transmitted byte. This occurs on the last byte of the transmission, indicating that the transmission is done."] +pub struct R_RX_DONE_R(crate::FieldReader); +impl R_RX_DONE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_RX_DONE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_RX_DONE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_TX_ABRT` reader - This bit indicates if the controller, as an I2C transmitter, is unable to complete the intended actions on the contents of the transmit FIFO. This situation can occur both as an I2C master or an I2C slave, and is referred to as a \"transmit abort\". When this bit is set to 1, the I2C_TX_ABRT_SOURCE register indicates the reason why the transmit abort takes places. NOTE: The controller flushes/resets/empties the TX FIFO whenever this bit is set. The TX FIFO remains in this flushed state until the register I2C_CLR_TX_ABRT is read. Once this read is performed, the TX FIFO is then ready to accept more data bytes from the APB interface."] +pub struct R_TX_ABRT_R(crate::FieldReader); +impl R_TX_ABRT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_TX_ABRT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_TX_ABRT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_RD_REQ` reader - This bit is set to 1 when the controller is acting as a slave and another I2C master is attempting to read data from the controller. The controller holds the I2C bus in a wait state (SCL=0) until this interrupt is serviced, which means that the slave has been addressed by a remote master that is asking for data to be transferred. The processor must respond to this interrupt and then write the requested data to the I2C_DATA_CMD register. This bit is set to 0 just after the processor reads the I2C_CLR_RD_REQ register"] +pub struct R_RD_REQ_R(crate::FieldReader); +impl R_RD_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_RD_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_RD_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_TX_EMPTY` reader - This bit is set to 1 when the transmit buffer is at or below the threshold value set in the I2C_TX_TL register. It is automatically cleared by hardware when the buffer level goes above the threshold. When the IC_ENABLE bit 0 is 0, the TX FIFO is flushed and held in reset. There the TX FIFO looks like it has no data within it, so this bit is set to 1, provided there is activity in the master or slave state machines. When there is no longer activity, then with ic_en=0, this bit is set to 0."] +pub struct R_TX_EMPTY_R(crate::FieldReader); +impl R_TX_EMPTY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_TX_EMPTY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_TX_EMPTY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_TX_OVER` reader - Set during transmit if the transmit buffer is filled to 32 and the processor attempts to issue another I2C command by writing to the IC_DATA_CMD register. When the module is disabled, this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared"] +pub struct R_TX_OVER_R(crate::FieldReader); +impl R_TX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_TX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_TX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_RX_FULL` reader - Set when the receive buffer reaches or goes above the RX_TL threshold in the I2C_RX_TL register. It is automatically cleared by hardware when buffer level goes below the threshold. If the module is disabled (I2C_ENABLE\\[0\\]=0), the RX FIFO is flushed and held in reset; therefore the RX FIFO is not full. So this bit is cleared once the I2C_ENABLE bit 0 is programmed with a 0, regardless of the activity that continues."] +pub struct R_RX_FULL_R(crate::FieldReader); +impl R_RX_FULL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_RX_FULL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_RX_FULL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_RX_OVER` reader - Set if the receive buffer is completely filled to 32 and an additional byte is received from an external I2C device. The controller acknowledges this, but any data bytes received after the FIFO is full are lost. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] +pub struct R_RX_OVER_R(crate::FieldReader); +impl R_RX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_RX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_RX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `R_RX_UNDER` reader - Set if the processor attempts to read the receive buffer when it is empty by reading from the IC_DATA_CMD register. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] +pub struct R_RX_UNDER_R(crate::FieldReader); +impl R_RX_UNDER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + R_RX_UNDER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for R_RX_UNDER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 11 - Set only when a General Call address is received and it is acknowledged. It stays set until it is cleared either by disabling controller or when the CPU reads bit 0 of the I2C_CLR_GEN_CALL register. The controller stores the received data in the Rx buffer."] + #[inline(always)] + pub fn r_gen_call(&self) -> R_GEN_CALL_R { + R_GEN_CALL_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - Indicates whether a START or RESTART condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] + #[inline(always)] + pub fn r_start_det(&self) -> R_START_DET_R { + R_START_DET_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - Indicates whether a STOP condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] + #[inline(always)] + pub fn r_stop_det(&self) -> R_STOP_DET_R { + R_STOP_DET_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - This bit captures I2C Ctrl activity and stays set until it is cleared. There are four ways to clear it: => Disabling the I2C Ctrl => Reading the IC_CLR_ACTIVITY register => Reading the IC_CLR_INTR register => System reset Once this bit is set, it stays set unless one of the four methods is used to clear it. Even if the controller module is idle, this bit remains set until cleared, indicating that there was activity on the bus."] + #[inline(always)] + pub fn r_activity(&self) -> R_ACTIVITY_R { + R_ACTIVITY_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - When the controller is acting as a slave-transmitter, this bit is set to 1 if the master does not acknowledge a transmitted byte. This occurs on the last byte of the transmission, indicating that the transmission is done."] + #[inline(always)] + pub fn r_rx_done(&self) -> R_RX_DONE_R { + R_RX_DONE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - This bit indicates if the controller, as an I2C transmitter, is unable to complete the intended actions on the contents of the transmit FIFO. This situation can occur both as an I2C master or an I2C slave, and is referred to as a \"transmit abort\". When this bit is set to 1, the I2C_TX_ABRT_SOURCE register indicates the reason why the transmit abort takes places. NOTE: The controller flushes/resets/empties the TX FIFO whenever this bit is set. The TX FIFO remains in this flushed state until the register I2C_CLR_TX_ABRT is read. Once this read is performed, the TX FIFO is then ready to accept more data bytes from the APB interface."] + #[inline(always)] + pub fn r_tx_abrt(&self) -> R_TX_ABRT_R { + R_TX_ABRT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - This bit is set to 1 when the controller is acting as a slave and another I2C master is attempting to read data from the controller. The controller holds the I2C bus in a wait state (SCL=0) until this interrupt is serviced, which means that the slave has been addressed by a remote master that is asking for data to be transferred. The processor must respond to this interrupt and then write the requested data to the I2C_DATA_CMD register. This bit is set to 0 just after the processor reads the I2C_CLR_RD_REQ register"] + #[inline(always)] + pub fn r_rd_req(&self) -> R_RD_REQ_R { + R_RD_REQ_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - This bit is set to 1 when the transmit buffer is at or below the threshold value set in the I2C_TX_TL register. It is automatically cleared by hardware when the buffer level goes above the threshold. When the IC_ENABLE bit 0 is 0, the TX FIFO is flushed and held in reset. There the TX FIFO looks like it has no data within it, so this bit is set to 1, provided there is activity in the master or slave state machines. When there is no longer activity, then with ic_en=0, this bit is set to 0."] + #[inline(always)] + pub fn r_tx_empty(&self) -> R_TX_EMPTY_R { + R_TX_EMPTY_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Set during transmit if the transmit buffer is filled to 32 and the processor attempts to issue another I2C command by writing to the IC_DATA_CMD register. When the module is disabled, this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared"] + #[inline(always)] + pub fn r_tx_over(&self) -> R_TX_OVER_R { + R_TX_OVER_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Set when the receive buffer reaches or goes above the RX_TL threshold in the I2C_RX_TL register. It is automatically cleared by hardware when buffer level goes below the threshold. If the module is disabled (I2C_ENABLE\\[0\\]=0), the RX FIFO is flushed and held in reset; therefore the RX FIFO is not full. So this bit is cleared once the I2C_ENABLE bit 0 is programmed with a 0, regardless of the activity that continues."] + #[inline(always)] + pub fn r_rx_full(&self) -> R_RX_FULL_R { + R_RX_FULL_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Set if the receive buffer is completely filled to 32 and an additional byte is received from an external I2C device. The controller acknowledges this, but any data bytes received after the FIFO is full are lost. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] + #[inline(always)] + pub fn r_rx_over(&self) -> R_RX_OVER_R { + R_RX_OVER_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Set if the processor attempts to read the receive buffer when it is empty by reading from the IC_DATA_CMD register. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] + #[inline(always)] + pub fn r_rx_under(&self) -> R_RX_UNDER_R { + R_RX_UNDER_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Interrupt Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_intr_stat_reg](index.html) module"] +pub struct I2C_INTR_STAT_REG_SPEC; +impl crate::RegisterSpec for I2C_INTR_STAT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_intr_stat_reg::R](R) reader structure"] +impl crate::Readable for I2C_INTR_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_intr_stat_reg::W](W) writer structure"] +impl crate::Writable for I2C_INTR_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_INTR_STAT_REG to value 0"] +impl crate::Resettable for I2C_INTR_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_raw_intr_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_raw_intr_stat_reg.rs new file mode 100644 index 0000000..cc53048 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_raw_intr_stat_reg.rs @@ -0,0 +1,306 @@ +#[doc = "Register `I2C_RAW_INTR_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_RAW_INTR_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `GEN_CALL` reader - Set only when a General Call address is received and it is acknowledged. It stays set until it is cleared either by disabling controller or when the CPU reads bit 0 of the I2C_CLR_GEN_CALL register. I2C Ctrl stores the received data in the Rx buffer."] +pub struct GEN_CALL_R(crate::FieldReader); +impl GEN_CALL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GEN_CALL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GEN_CALL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `START_DET` reader - Indicates whether a START or RESTART condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] +pub struct START_DET_R(crate::FieldReader); +impl START_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + START_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for START_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `STOP_DET` reader - Indicates whether a STOP condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] +pub struct STOP_DET_R(crate::FieldReader); +impl STOP_DET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + STOP_DET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for STOP_DET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ACTIVITY` reader - This bit captures I2C Ctrl activity and stays set until it is cleared. There are four ways to clear it: => Disabling the I2C Ctrl => Reading the IC_CLR_ACTIVITY register => Reading the IC_CLR_INTR register => System reset Once this bit is set, it stays set unless one of the four methods is used to clear it. Even if the controller module is idle, this bit remains set until cleared, indicating that there was activity on the bus."] +pub struct ACTIVITY_R(crate::FieldReader); +impl ACTIVITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ACTIVITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ACTIVITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RX_DONE` reader - When the controller is acting as a slave-transmitter, this bit is set to 1 if the master does not acknowledge a transmitted byte. This occurs on the last byte of the transmission, indicating that the transmission is done."] +pub struct RX_DONE_R(crate::FieldReader); +impl RX_DONE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RX_DONE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RX_DONE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TX_ABRT` reader - This bit indicates if the controller, as an I2C transmitter, is unable to complete the intended actions on the contents of the transmit FIFO. This situation can occur both as an I2C master or an I2C slave, and is referred to as a \"transmit abort\". When this bit is set to 1, the I2C_TX_ABRT_SOURCE register indicates the reason why the transmit abort takes places. NOTE: The controller flushes/resets/empties the TX FIFO whenever this bit is set. The TX FIFO remains in this flushed state until the register I2C_CLR_TX_ABRT is read. Once this read is performed, the TX FIFO is then ready to accept more data bytes from the APB interface."] +pub struct TX_ABRT_R(crate::FieldReader); +impl TX_ABRT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TX_ABRT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TX_ABRT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RD_REQ` reader - This bit is set to 1 when I2C Ctrl is acting as a slave and another I2C master is attempting to read data from the controller. The controller holds the I2C bus in a wait state (SCL=0) until this interrupt is serviced, which means that the slave has been addressed by a remote master that is asking for data to be transferred. The processor must respond to this interrupt and then write the requested data to the I2C_DATA_CMD register. This bit is set to 0 just after the processor reads the I2C_CLR_RD_REQ register"] +pub struct RD_REQ_R(crate::FieldReader); +impl RD_REQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RD_REQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RD_REQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TX_EMPTY` reader - This bit is set to 1 when the transmit buffer is at or below the threshold value set in the I2C_TX_TL register. It is automatically cleared by hardware when the buffer level goes above the threshold. When the IC_ENABLE bit 0 is 0, the TX FIFO is flushed and held in reset. There the TX FIFO looks like it has no data within it, so this bit is set to 1, provided there is activity in the master or slave state machines. When there is no longer activity, then with ic_en=0, this bit is set to 0."] +pub struct TX_EMPTY_R(crate::FieldReader); +impl TX_EMPTY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TX_EMPTY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TX_EMPTY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TX_OVER` reader - Set during transmit if the transmit buffer is filled to 32 and the processor attempts to issue another I2C command by writing to the IC_DATA_CMD register. When the module is disabled, this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared"] +pub struct TX_OVER_R(crate::FieldReader); +impl TX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RX_FULL` reader - Set when the receive buffer reaches or goes above the RX_TL threshold in the I2C_RX_TL register. It is automatically cleared by hardware when buffer level goes below the threshold. If the module is disabled (I2C_ENABLE\\[0\\]=0), the RX FIFO is flushed and held in reset; therefore the RX FIFO is not full. So this bit is cleared once the I2C_ENABLE bit 0 is programmed with a 0, regardless of the activity that continues."] +pub struct RX_FULL_R(crate::FieldReader); +impl RX_FULL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RX_FULL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RX_FULL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RX_OVER` reader - Set if the receive buffer is completely filled to 32 and an additional byte is received from an external I2C device. The controller acknowledges this, but any data bytes received after the FIFO is full are lost. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] +pub struct RX_OVER_R(crate::FieldReader); +impl RX_OVER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RX_OVER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RX_OVER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RX_UNDER` reader - Set if the processor attempts to read the receive buffer when it is empty by reading from the IC_DATA_CMD register. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] +pub struct RX_UNDER_R(crate::FieldReader); +impl RX_UNDER_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RX_UNDER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RX_UNDER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 11 - Set only when a General Call address is received and it is acknowledged. It stays set until it is cleared either by disabling controller or when the CPU reads bit 0 of the I2C_CLR_GEN_CALL register. I2C Ctrl stores the received data in the Rx buffer."] + #[inline(always)] + pub fn gen_call(&self) -> GEN_CALL_R { + GEN_CALL_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - Indicates whether a START or RESTART condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] + #[inline(always)] + pub fn start_det(&self) -> START_DET_R { + START_DET_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - Indicates whether a STOP condition has occurred on the I2C interface regardless of whether controller is operating in slave or master mode."] + #[inline(always)] + pub fn stop_det(&self) -> STOP_DET_R { + STOP_DET_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - This bit captures I2C Ctrl activity and stays set until it is cleared. There are four ways to clear it: => Disabling the I2C Ctrl => Reading the IC_CLR_ACTIVITY register => Reading the IC_CLR_INTR register => System reset Once this bit is set, it stays set unless one of the four methods is used to clear it. Even if the controller module is idle, this bit remains set until cleared, indicating that there was activity on the bus."] + #[inline(always)] + pub fn activity(&self) -> ACTIVITY_R { + ACTIVITY_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - When the controller is acting as a slave-transmitter, this bit is set to 1 if the master does not acknowledge a transmitted byte. This occurs on the last byte of the transmission, indicating that the transmission is done."] + #[inline(always)] + pub fn rx_done(&self) -> RX_DONE_R { + RX_DONE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - This bit indicates if the controller, as an I2C transmitter, is unable to complete the intended actions on the contents of the transmit FIFO. This situation can occur both as an I2C master or an I2C slave, and is referred to as a \"transmit abort\". When this bit is set to 1, the I2C_TX_ABRT_SOURCE register indicates the reason why the transmit abort takes places. NOTE: The controller flushes/resets/empties the TX FIFO whenever this bit is set. The TX FIFO remains in this flushed state until the register I2C_CLR_TX_ABRT is read. Once this read is performed, the TX FIFO is then ready to accept more data bytes from the APB interface."] + #[inline(always)] + pub fn tx_abrt(&self) -> TX_ABRT_R { + TX_ABRT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - This bit is set to 1 when I2C Ctrl is acting as a slave and another I2C master is attempting to read data from the controller. The controller holds the I2C bus in a wait state (SCL=0) until this interrupt is serviced, which means that the slave has been addressed by a remote master that is asking for data to be transferred. The processor must respond to this interrupt and then write the requested data to the I2C_DATA_CMD register. This bit is set to 0 just after the processor reads the I2C_CLR_RD_REQ register"] + #[inline(always)] + pub fn rd_req(&self) -> RD_REQ_R { + RD_REQ_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - This bit is set to 1 when the transmit buffer is at or below the threshold value set in the I2C_TX_TL register. It is automatically cleared by hardware when the buffer level goes above the threshold. When the IC_ENABLE bit 0 is 0, the TX FIFO is flushed and held in reset. There the TX FIFO looks like it has no data within it, so this bit is set to 1, provided there is activity in the master or slave state machines. When there is no longer activity, then with ic_en=0, this bit is set to 0."] + #[inline(always)] + pub fn tx_empty(&self) -> TX_EMPTY_R { + TX_EMPTY_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Set during transmit if the transmit buffer is filled to 32 and the processor attempts to issue another I2C command by writing to the IC_DATA_CMD register. When the module is disabled, this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared"] + #[inline(always)] + pub fn tx_over(&self) -> TX_OVER_R { + TX_OVER_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Set when the receive buffer reaches or goes above the RX_TL threshold in the I2C_RX_TL register. It is automatically cleared by hardware when buffer level goes below the threshold. If the module is disabled (I2C_ENABLE\\[0\\]=0), the RX FIFO is flushed and held in reset; therefore the RX FIFO is not full. So this bit is cleared once the I2C_ENABLE bit 0 is programmed with a 0, regardless of the activity that continues."] + #[inline(always)] + pub fn rx_full(&self) -> RX_FULL_R { + RX_FULL_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Set if the receive buffer is completely filled to 32 and an additional byte is received from an external I2C device. The controller acknowledges this, but any data bytes received after the FIFO is full are lost. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] + #[inline(always)] + pub fn rx_over(&self) -> RX_OVER_R { + RX_OVER_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Set if the processor attempts to read the receive buffer when it is empty by reading from the IC_DATA_CMD register. If the module is disabled (I2C_ENABLE\\[0\\]=0), this bit keeps its level until the master or slave state machines go into idle, and when ic_en goes to 0, this interrupt is cleared."] + #[inline(always)] + pub fn rx_under(&self) -> RX_UNDER_R { + RX_UNDER_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Raw Interrupt Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_raw_intr_stat_reg](index.html) module"] +pub struct I2C_RAW_INTR_STAT_REG_SPEC; +impl crate::RegisterSpec for I2C_RAW_INTR_STAT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_raw_intr_stat_reg::R](R) reader structure"] +impl crate::Readable for I2C_RAW_INTR_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_raw_intr_stat_reg::W](W) writer structure"] +impl crate::Writable for I2C_RAW_INTR_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_RAW_INTR_STAT_REG to value 0"] +impl crate::Resettable for I2C_RAW_INTR_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_rx_tl_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_rx_tl_reg.rs new file mode 100644 index 0000000..247b3f0 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_rx_tl_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_RX_TL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_RX_TL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RX_TL` reader - Receive FIFO Threshold Level Controls the level of entries (or above) that triggers the RX_FULL interrupt (bit 2 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that hardware does not allow this value to be set to a value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 1 entry, and a value of 31 sets the threshold for 32 entries."] +pub struct RX_TL_R(crate::FieldReader); +impl RX_TL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RX_TL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RX_TL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RX_TL` writer - Receive FIFO Threshold Level Controls the level of entries (or above) that triggers the RX_FULL interrupt (bit 2 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that hardware does not allow this value to be set to a value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 1 entry, and a value of 31 sets the threshold for 32 entries."] +pub struct RX_TL_W<'a> { + w: &'a mut W, +} +impl<'a> RX_TL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u16 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 0:4 - Receive FIFO Threshold Level Controls the level of entries (or above) that triggers the RX_FULL interrupt (bit 2 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that hardware does not allow this value to be set to a value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 1 entry, and a value of 31 sets the threshold for 32 entries."] + #[inline(always)] + pub fn rx_tl(&self) -> RX_TL_R { + RX_TL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 0:4 - Receive FIFO Threshold Level Controls the level of entries (or above) that triggers the RX_FULL interrupt (bit 2 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that hardware does not allow this value to be set to a value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 1 entry, and a value of 31 sets the threshold for 32 entries."] + #[inline(always)] + pub fn rx_tl(&mut self) -> RX_TL_W { + RX_TL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Receive FIFO Threshold Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_rx_tl_reg](index.html) module"] +pub struct I2C_RX_TL_REG_SPEC; +impl crate::RegisterSpec for I2C_RX_TL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_rx_tl_reg::R](R) reader structure"] +impl crate::Readable for I2C_RX_TL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_rx_tl_reg::W](W) writer structure"] +impl crate::Writable for I2C_RX_TL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_RX_TL_REG to value 0"] +impl crate::Resettable for I2C_RX_TL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_rxflr_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_rxflr_reg.rs new file mode 100644 index 0000000..22eb144 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_rxflr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_RXFLR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_RXFLR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RXFLR` reader - Receive FIFO Level. Contains the number of valid data entries in the receive FIFO. Size is constrained by the RXFLR value"] +pub struct RXFLR_R(crate::FieldReader); +impl RXFLR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RXFLR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RXFLR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:5 - Receive FIFO Level. Contains the number of valid data entries in the receive FIFO. Size is constrained by the RXFLR value"] + #[inline(always)] + pub fn rxflr(&self) -> RXFLR_R { + RXFLR_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Receive FIFO Level Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_rxflr_reg](index.html) module"] +pub struct I2C_RXFLR_REG_SPEC; +impl crate::RegisterSpec for I2C_RXFLR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_rxflr_reg::R](R) reader structure"] +impl crate::Readable for I2C_RXFLR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_rxflr_reg::W](W) writer structure"] +impl crate::Writable for I2C_RXFLR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_RXFLR_REG to value 0"] +impl crate::Resettable for I2C_RXFLR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_sar_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_sar_reg.rs new file mode 100644 index 0000000..5001fa3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_sar_reg.rs @@ -0,0 +1,107 @@ +#[doc = "Register `I2C_SAR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_SAR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_SAR` reader - The IC_SAR holds the slave address when the I2C is operating as a slave. For 7-bit addressing, only IC_SAR\\[6:0\\] +is used. This register can be written only when the I2C interface is disabled, which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect."] +pub struct IC_SAR_R(crate::FieldReader); +impl IC_SAR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_SAR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_SAR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_SAR` writer - The IC_SAR holds the slave address when the I2C is operating as a slave. For 7-bit addressing, only IC_SAR\\[6:0\\] +is used. This register can be written only when the I2C interface is disabled, which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect."] +pub struct IC_SAR_W<'a> { + w: &'a mut W, +} +impl<'a> IC_SAR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u16 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 0:9 - The IC_SAR holds the slave address when the I2C is operating as a slave. For 7-bit addressing, only IC_SAR\\[6:0\\] +is used. This register can be written only when the I2C interface is disabled, which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect."] + #[inline(always)] + pub fn ic_sar(&self) -> IC_SAR_R { + IC_SAR_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 0:9 - The IC_SAR holds the slave address when the I2C is operating as a slave. For 7-bit addressing, only IC_SAR\\[6:0\\] +is used. This register can be written only when the I2C interface is disabled, which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect."] + #[inline(always)] + pub fn ic_sar(&mut self) -> IC_SAR_W { + IC_SAR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Slave Address Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_sar_reg](index.html) module"] +pub struct I2C_SAR_REG_SPEC; +impl crate::RegisterSpec for I2C_SAR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_sar_reg::R](R) reader structure"] +impl crate::Readable for I2C_SAR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_sar_reg::W](W) writer structure"] +impl crate::Writable for I2C_SAR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_SAR_REG to value 0x55"] +impl crate::Resettable for I2C_SAR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x55 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_hold_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_hold_reg.rs new file mode 100644 index 0000000..fc9c78e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_hold_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_SDA_HOLD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_SDA_HOLD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_SDA_HOLD` reader - SDA Hold time"] +pub struct IC_SDA_HOLD_R(crate::FieldReader); +impl IC_SDA_HOLD_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_SDA_HOLD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_SDA_HOLD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_SDA_HOLD` writer - SDA Hold time"] +pub struct IC_SDA_HOLD_W<'a> { + w: &'a mut W, +} +impl<'a> IC_SDA_HOLD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - SDA Hold time"] + #[inline(always)] + pub fn ic_sda_hold(&self) -> IC_SDA_HOLD_R { + IC_SDA_HOLD_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - SDA Hold time"] + #[inline(always)] + pub fn ic_sda_hold(&mut self) -> IC_SDA_HOLD_W { + IC_SDA_HOLD_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C SDA Hold Time Length Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_sda_hold_reg](index.html) module"] +pub struct I2C_SDA_HOLD_REG_SPEC; +impl crate::RegisterSpec for I2C_SDA_HOLD_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_sda_hold_reg::R](R) reader structure"] +impl crate::Readable for I2C_SDA_HOLD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_sda_hold_reg::W](W) writer structure"] +impl crate::Writable for I2C_SDA_HOLD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_SDA_HOLD_REG to value 0x01"] +impl crate::Resettable for I2C_SDA_HOLD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_setup_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_setup_reg.rs new file mode 100644 index 0000000..037fc34 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_sda_setup_reg.rs @@ -0,0 +1,107 @@ +#[doc = "Register `I2C_SDA_SETUP_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_SDA_SETUP_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SDA_SETUP` reader - SDA Setup. This register controls the amount of time delay (number of I2C clock periods) between the rising edge of SCL and SDA changing by holding SCL low when I2C block services a read request while operating as a slave-transmitter. The relevant I2C requirement is tSU:DAT (note 4) as detailed in the I2C Bus Specification. This register must be programmed with a value equal to or greater than 2. It is recommended that if the required delay is 1000ns, then for an I2C frequency of 10 MHz, IC_SDA_SETUP should be programmed to a value of 11.Writes to this register succeed only when IC_ENABLE\\[0\\] += 0."] +pub struct SDA_SETUP_R(crate::FieldReader); +impl SDA_SETUP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SDA_SETUP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SDA_SETUP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SDA_SETUP` writer - SDA Setup. This register controls the amount of time delay (number of I2C clock periods) between the rising edge of SCL and SDA changing by holding SCL low when I2C block services a read request while operating as a slave-transmitter. The relevant I2C requirement is tSU:DAT (note 4) as detailed in the I2C Bus Specification. This register must be programmed with a value equal to or greater than 2. It is recommended that if the required delay is 1000ns, then for an I2C frequency of 10 MHz, IC_SDA_SETUP should be programmed to a value of 11.Writes to this register succeed only when IC_ENABLE\\[0\\] += 0."] +pub struct SDA_SETUP_W<'a> { + w: &'a mut W, +} +impl<'a> SDA_SETUP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - SDA Setup. This register controls the amount of time delay (number of I2C clock periods) between the rising edge of SCL and SDA changing by holding SCL low when I2C block services a read request while operating as a slave-transmitter. The relevant I2C requirement is tSU:DAT (note 4) as detailed in the I2C Bus Specification. This register must be programmed with a value equal to or greater than 2. It is recommended that if the required delay is 1000ns, then for an I2C frequency of 10 MHz, IC_SDA_SETUP should be programmed to a value of 11.Writes to this register succeed only when IC_ENABLE\\[0\\] += 0."] + #[inline(always)] + pub fn sda_setup(&self) -> SDA_SETUP_R { + SDA_SETUP_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - SDA Setup. This register controls the amount of time delay (number of I2C clock periods) between the rising edge of SCL and SDA changing by holding SCL low when I2C block services a read request while operating as a slave-transmitter. The relevant I2C requirement is tSU:DAT (note 4) as detailed in the I2C Bus Specification. This register must be programmed with a value equal to or greater than 2. It is recommended that if the required delay is 1000ns, then for an I2C frequency of 10 MHz, IC_SDA_SETUP should be programmed to a value of 11.Writes to this register succeed only when IC_ENABLE\\[0\\] += 0."] + #[inline(always)] + pub fn sda_setup(&mut self) -> SDA_SETUP_W { + SDA_SETUP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C SDA Setup Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_sda_setup_reg](index.html) module"] +pub struct I2C_SDA_SETUP_REG_SPEC; +impl crate::RegisterSpec for I2C_SDA_SETUP_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_sda_setup_reg::R](R) reader structure"] +impl crate::Readable for I2C_SDA_SETUP_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_sda_setup_reg::W](W) writer structure"] +impl crate::Writable for I2C_SDA_SETUP_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_SDA_SETUP_REG to value 0x64"] +impl crate::Resettable for I2C_SDA_SETUP_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x64 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_hcnt_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_hcnt_reg.rs new file mode 100644 index 0000000..719e17e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_hcnt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_SS_SCL_HCNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_SS_SCL_HCNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_SS_SCL_HCNT` reader - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set. NOTE: This register must not be programmed to a value higher than 65525, because the controller uses a 16-bit counter to flag an I2C bus idle condition when this counter reaches a value of IC_SS_SCL_HCNT + 10."] +pub struct IC_SS_SCL_HCNT_R(crate::FieldReader); +impl IC_SS_SCL_HCNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_SS_SCL_HCNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_SS_SCL_HCNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_SS_SCL_HCNT` writer - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set. NOTE: This register must not be programmed to a value higher than 65525, because the controller uses a 16-bit counter to flag an I2C bus idle condition when this counter reaches a value of IC_SS_SCL_HCNT + 10."] +pub struct IC_SS_SCL_HCNT_W<'a> { + w: &'a mut W, +} +impl<'a> IC_SS_SCL_HCNT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set. NOTE: This register must not be programmed to a value higher than 65525, because the controller uses a 16-bit counter to flag an I2C bus idle condition when this counter reaches a value of IC_SS_SCL_HCNT + 10."] + #[inline(always)] + pub fn ic_ss_scl_hcnt(&self) -> IC_SS_SCL_HCNT_R { + IC_SS_SCL_HCNT_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock high-period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the IC_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 6; hardware prevents values less than this being written, and if attempted results in 6 being set. NOTE: This register must not be programmed to a value higher than 65525, because the controller uses a 16-bit counter to flag an I2C bus idle condition when this counter reaches a value of IC_SS_SCL_HCNT + 10."] + #[inline(always)] + pub fn ic_ss_scl_hcnt(&mut self) -> IC_SS_SCL_HCNT_W { + IC_SS_SCL_HCNT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Standard Speed I2C Clock SCL High Count Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_ss_scl_hcnt_reg](index.html) module"] +pub struct I2C_SS_SCL_HCNT_REG_SPEC; +impl crate::RegisterSpec for I2C_SS_SCL_HCNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_ss_scl_hcnt_reg::R](R) reader structure"] +impl crate::Readable for I2C_SS_SCL_HCNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_ss_scl_hcnt_reg::W](W) writer structure"] +impl crate::Writable for I2C_SS_SCL_HCNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_SS_SCL_HCNT_REG to value 0x48"] +impl crate::Resettable for I2C_SS_SCL_HCNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x48 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_lcnt_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_lcnt_reg.rs new file mode 100644 index 0000000..da495c4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_ss_scl_lcnt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_SS_SCL_LCNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_SS_SCL_LCNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IC_SS_SCL_LCNT` reader - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted, results in 8 being set."] +pub struct IC_SS_SCL_LCNT_R(crate::FieldReader); +impl IC_SS_SCL_LCNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_SS_SCL_LCNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_SS_SCL_LCNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_SS_SCL_LCNT` writer - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted, results in 8 being set."] +pub struct IC_SS_SCL_LCNT_W<'a> { + w: &'a mut W, +} +impl<'a> IC_SS_SCL_LCNT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted, results in 8 being set."] + #[inline(always)] + pub fn ic_ss_scl_lcnt(&self) -> IC_SS_SCL_LCNT_R { + IC_SS_SCL_LCNT_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - This register must be set before any I2C bus transaction can take place to ensure proper I/O timing. This register sets the SCL clock low period count for standard speed. This register can be written only when the I2C interface is disabled which corresponds to the I2C_ENABLE register being set to 0. Writes at other times have no effect. The minimum valid value is 8; hardware prevents values less than this being written, and if attempted, results in 8 being set."] + #[inline(always)] + pub fn ic_ss_scl_lcnt(&mut self) -> IC_SS_SCL_LCNT_W { + IC_SS_SCL_LCNT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Standard Speed I2C Clock SCL Low Count Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_ss_scl_lcnt_reg](index.html) module"] +pub struct I2C_SS_SCL_LCNT_REG_SPEC; +impl crate::RegisterSpec for I2C_SS_SCL_LCNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_ss_scl_lcnt_reg::R](R) reader structure"] +impl crate::Readable for I2C_SS_SCL_LCNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_ss_scl_lcnt_reg::W](W) writer structure"] +impl crate::Writable for I2C_SS_SCL_LCNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_SS_SCL_LCNT_REG to value 0x4f"] +impl crate::Resettable for I2C_SS_SCL_LCNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x4f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_status_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_status_reg.rs new file mode 100644 index 0000000..76e8458 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_status_reg.rs @@ -0,0 +1,206 @@ +#[doc = "Register `I2C_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SLV_ACTIVITY` reader - Slave FSM Activity Status. When the Slave Finite State Machine (FSM) is not in the IDLE state, this bit is set. 0: Slave FSM is in IDLE state so the Slave part of the controller is not Active 1: Slave FSM is not in IDLE state so the Slave part of the controller is Active"] +pub struct SLV_ACTIVITY_R(crate::FieldReader); +impl SLV_ACTIVITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SLV_ACTIVITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SLV_ACTIVITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MST_ACTIVITY` reader - Master FSM Activity Status. When the Master Finite State Machine (FSM) is not in the IDLE state, this bit is set. 0: Master FSM is in IDLE state so the Master part of the controller is not Active 1: Master FSM is not in IDLE state so the Master part of the controller is Active"] +pub struct MST_ACTIVITY_R(crate::FieldReader); +impl MST_ACTIVITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MST_ACTIVITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MST_ACTIVITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFF` reader - Receive FIFO Completely Full. When the receive FIFO is completely full, this bit is set. When the receive FIFO contains one or more empty location, this bit is cleared. 0: Receive FIFO is not full 1: Receive FIFO is full"] +pub struct RFF_R(crate::FieldReader); +impl RFF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFNE` reader - Receive FIFO Not Empty. This bit is set when the receive FIFO contains one or more entries; it is cleared when the receive FIFO is empty. 0: Receive FIFO is empty 1: Receive FIFO is not empty"] +pub struct RFNE_R(crate::FieldReader); +impl RFNE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFNE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFNE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TFE` reader - Transmit FIFO Completely Empty. When the transmit FIFO is completely empty, this bit is set. When it contains one or more valid entries, this bit is cleared. This bit field does not request an interrupt. 0: Transmit FIFO is not empty 1: Transmit FIFO is empty"] +pub struct TFE_R(crate::FieldReader); +impl TFE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TFE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TFE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TFNF` reader - Transmit FIFO Not Full. Set when the transmit FIFO contains one or more empty locations, and is cleared when the FIFO is full. 0: Transmit FIFO is full 1: Transmit FIFO is not full"] +pub struct TFNF_R(crate::FieldReader); +impl TFNF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TFNF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TFNF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `I2C_ACTIVITY` reader - I2C Activity Status."] +pub struct I2C_ACTIVITY_R(crate::FieldReader); +impl I2C_ACTIVITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + I2C_ACTIVITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for I2C_ACTIVITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 6 - Slave FSM Activity Status. When the Slave Finite State Machine (FSM) is not in the IDLE state, this bit is set. 0: Slave FSM is in IDLE state so the Slave part of the controller is not Active 1: Slave FSM is not in IDLE state so the Slave part of the controller is Active"] + #[inline(always)] + pub fn slv_activity(&self) -> SLV_ACTIVITY_R { + SLV_ACTIVITY_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Master FSM Activity Status. When the Master Finite State Machine (FSM) is not in the IDLE state, this bit is set. 0: Master FSM is in IDLE state so the Master part of the controller is not Active 1: Master FSM is not in IDLE state so the Master part of the controller is Active"] + #[inline(always)] + pub fn mst_activity(&self) -> MST_ACTIVITY_R { + MST_ACTIVITY_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Receive FIFO Completely Full. When the receive FIFO is completely full, this bit is set. When the receive FIFO contains one or more empty location, this bit is cleared. 0: Receive FIFO is not full 1: Receive FIFO is full"] + #[inline(always)] + pub fn rff(&self) -> RFF_R { + RFF_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Receive FIFO Not Empty. This bit is set when the receive FIFO contains one or more entries; it is cleared when the receive FIFO is empty. 0: Receive FIFO is empty 1: Receive FIFO is not empty"] + #[inline(always)] + pub fn rfne(&self) -> RFNE_R { + RFNE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Transmit FIFO Completely Empty. When the transmit FIFO is completely empty, this bit is set. When it contains one or more valid entries, this bit is cleared. This bit field does not request an interrupt. 0: Transmit FIFO is not empty 1: Transmit FIFO is empty"] + #[inline(always)] + pub fn tfe(&self) -> TFE_R { + TFE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Transmit FIFO Not Full. Set when the transmit FIFO contains one or more empty locations, and is cleared when the FIFO is full. 0: Transmit FIFO is full 1: Transmit FIFO is not full"] + #[inline(always)] + pub fn tfnf(&self) -> TFNF_R { + TFNF_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - I2C Activity Status."] + #[inline(always)] + pub fn i2c_activity(&self) -> I2C_ACTIVITY_R { + I2C_ACTIVITY_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_status_reg](index.html) module"] +pub struct I2C_STATUS_REG_SPEC; +impl crate::RegisterSpec for I2C_STATUS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_status_reg::R](R) reader structure"] +impl crate::Readable for I2C_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_status_reg::W](W) writer structure"] +impl crate::Writable for I2C_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_STATUS_REG to value 0x06"] +impl crate::Resettable for I2C_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x06 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_tar_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_tar_reg.rs new file mode 100644 index 0000000..315f822 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_tar_reg.rs @@ -0,0 +1,197 @@ +#[doc = "Register `I2C_TAR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_TAR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPECIAL` reader - This bit indicates whether software performs a General Call or START BYTE command. 0: ignore bit 10 GC_OR_START and use IC_TAR normally 1: perform special I2C command as specified in GC_OR_START bit"] +pub struct SPECIAL_R(crate::FieldReader); +impl SPECIAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPECIAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPECIAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPECIAL` writer - This bit indicates whether software performs a General Call or START BYTE command. 0: ignore bit 10 GC_OR_START and use IC_TAR normally 1: perform special I2C command as specified in GC_OR_START bit"] +pub struct SPECIAL_W<'a> { + w: &'a mut W, +} +impl<'a> SPECIAL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `GC_OR_START` reader - If bit 11 (SPECIAL) is set to 1, then this bit indicates whether a General Call or START byte command is to be performed by the controller. 0: General Call Address - after issuing a General Call, only writes may be performed. Attempting to issue a read command results in setting bit 6 (TX_ABRT) of the IC_RAW_INTR_STAT register. The controller remains in General Call mode until the SPECIAL bit value (bit 11) is cleared. 1: START BYTE"] +pub struct GC_OR_START_R(crate::FieldReader); +impl GC_OR_START_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + GC_OR_START_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for GC_OR_START_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `GC_OR_START` writer - If bit 11 (SPECIAL) is set to 1, then this bit indicates whether a General Call or START byte command is to be performed by the controller. 0: General Call Address - after issuing a General Call, only writes may be performed. Attempting to issue a read command results in setting bit 6 (TX_ABRT) of the IC_RAW_INTR_STAT register. The controller remains in General Call mode until the SPECIAL bit value (bit 11) is cleared. 1: START BYTE"] +pub struct GC_OR_START_W<'a> { + w: &'a mut W, +} +impl<'a> GC_OR_START_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `IC_TAR` reader - This is the target address for any master transaction. When transmitting a General Call, these bits are ignored. To generate a START BYTE, the CPU needs to write only once into these bits. Note: If the IC_TAR and IC_SAR are the same, loopback exists but the FIFOs are shared between master and slave, so full loopback is not feasible. Only one direction loopback mode is supported (simplex), not duplex. A master cannot transmit to itself; it can transmit to only a slave"] +pub struct IC_TAR_R(crate::FieldReader); +impl IC_TAR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + IC_TAR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IC_TAR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IC_TAR` writer - This is the target address for any master transaction. When transmitting a General Call, these bits are ignored. To generate a START BYTE, the CPU needs to write only once into these bits. Note: If the IC_TAR and IC_SAR are the same, loopback exists but the FIFOs are shared between master and slave, so full loopback is not feasible. Only one direction loopback mode is supported (simplex), not duplex. A master cannot transmit to itself; it can transmit to only a slave"] +pub struct IC_TAR_W<'a> { + w: &'a mut W, +} +impl<'a> IC_TAR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u16 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bit 11 - This bit indicates whether software performs a General Call or START BYTE command. 0: ignore bit 10 GC_OR_START and use IC_TAR normally 1: perform special I2C command as specified in GC_OR_START bit"] + #[inline(always)] + pub fn special(&self) -> SPECIAL_R { + SPECIAL_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - If bit 11 (SPECIAL) is set to 1, then this bit indicates whether a General Call or START byte command is to be performed by the controller. 0: General Call Address - after issuing a General Call, only writes may be performed. Attempting to issue a read command results in setting bit 6 (TX_ABRT) of the IC_RAW_INTR_STAT register. The controller remains in General Call mode until the SPECIAL bit value (bit 11) is cleared. 1: START BYTE"] + #[inline(always)] + pub fn gc_or_start(&self) -> GC_OR_START_R { + GC_OR_START_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bits 0:9 - This is the target address for any master transaction. When transmitting a General Call, these bits are ignored. To generate a START BYTE, the CPU needs to write only once into these bits. Note: If the IC_TAR and IC_SAR are the same, loopback exists but the FIFOs are shared between master and slave, so full loopback is not feasible. Only one direction loopback mode is supported (simplex), not duplex. A master cannot transmit to itself; it can transmit to only a slave"] + #[inline(always)] + pub fn ic_tar(&self) -> IC_TAR_R { + IC_TAR_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bit 11 - This bit indicates whether software performs a General Call or START BYTE command. 0: ignore bit 10 GC_OR_START and use IC_TAR normally 1: perform special I2C command as specified in GC_OR_START bit"] + #[inline(always)] + pub fn special(&mut self) -> SPECIAL_W { + SPECIAL_W { w: self } + } + #[doc = "Bit 10 - If bit 11 (SPECIAL) is set to 1, then this bit indicates whether a General Call or START byte command is to be performed by the controller. 0: General Call Address - after issuing a General Call, only writes may be performed. Attempting to issue a read command results in setting bit 6 (TX_ABRT) of the IC_RAW_INTR_STAT register. The controller remains in General Call mode until the SPECIAL bit value (bit 11) is cleared. 1: START BYTE"] + #[inline(always)] + pub fn gc_or_start(&mut self) -> GC_OR_START_W { + GC_OR_START_W { w: self } + } + #[doc = "Bits 0:9 - This is the target address for any master transaction. When transmitting a General Call, these bits are ignored. To generate a START BYTE, the CPU needs to write only once into these bits. Note: If the IC_TAR and IC_SAR are the same, loopback exists but the FIFOs are shared between master and slave, so full loopback is not feasible. Only one direction loopback mode is supported (simplex), not duplex. A master cannot transmit to itself; it can transmit to only a slave"] + #[inline(always)] + pub fn ic_tar(&mut self) -> IC_TAR_W { + IC_TAR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Target Address Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_tar_reg](index.html) module"] +pub struct I2C_TAR_REG_SPEC; +impl crate::RegisterSpec for I2C_TAR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_tar_reg::R](R) reader structure"] +impl crate::Readable for I2C_TAR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_tar_reg::W](W) writer structure"] +impl crate::Writable for I2C_TAR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_TAR_REG to value 0x55"] +impl crate::Resettable for I2C_TAR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x55 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_abrt_source_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_abrt_source_reg.rs new file mode 100644 index 0000000..5146a1e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_abrt_source_reg.rs @@ -0,0 +1,392 @@ +#[doc = "Register `I2C_TX_ABRT_SOURCE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_TX_ABRT_SOURCE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ABRT_SLVRD_INTX` reader - 1: When the processor side responds to a slave mode request for data to be transmitted to a remote master and user writes a 1 in CMD (bit 8) of 2IC_DATA_CMD register"] +pub struct ABRT_SLVRD_INTX_R(crate::FieldReader); +impl ABRT_SLVRD_INTX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_SLVRD_INTX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_SLVRD_INTX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_SLV_ARBLOST` reader - 1: Slave lost the bus while transmitting data to a remote master. I2C_TX_ABRT_SOURCE\\[12\\] +is set at the same time. Note: Even though the slave never \"owns\" the bus, something could go wrong on the bus. This is a fail safe check. For instance, during a data transmission at the low-to-high transition of SCL, if what is on the data bus is not what is supposed to be transmitted, then the controller no longer own the bus."] +pub struct ABRT_SLV_ARBLOST_R(crate::FieldReader); +impl ABRT_SLV_ARBLOST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_SLV_ARBLOST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_SLV_ARBLOST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_SLVFLUSH_TXFIFO` reader - 1: Slave has received a read command and some data exists in the TX FIFO so the slave issues a TX_ABRT interrupt to flush old data in TX FIFO."] +pub struct ABRT_SLVFLUSH_TXFIFO_R(crate::FieldReader); +impl ABRT_SLVFLUSH_TXFIFO_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_SLVFLUSH_TXFIFO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_SLVFLUSH_TXFIFO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ARB_LOST` reader - 1: Master has lost arbitration, or if I2C_TX_ABRT_SOURCE\\[14\\] +is also set, then the slave transmitter has lost arbitration. Note: I2C can be both master and slave at the same time."] +pub struct ARB_LOST_R(crate::FieldReader); +impl ARB_LOST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ARB_LOST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ARB_LOST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_MASTER_DIS` reader - 1: User tries to initiate a Master operation with the Master mode disabled."] +pub struct ABRT_MASTER_DIS_R(crate::FieldReader); +impl ABRT_MASTER_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_MASTER_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_MASTER_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_10B_RD_NORSTRT` reader - 1: The restart is disabled (IC_RESTART_EN bit (I2C_CON\\[5\\]) = 0) and the master sends a read command in 10-bit addressing mode."] +pub struct ABRT_10B_RD_NORSTRT_R(crate::FieldReader); +impl ABRT_10B_RD_NORSTRT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_10B_RD_NORSTRT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_10B_RD_NORSTRT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_SBYTE_NORSTRT` reader - To clear Bit 9, the source of the ABRT_SBYTE_NORSTRT must be fixed first; restart must be enabled (I2C_CON\\[5\\]=1), the SPECIAL bit must be cleared (I2C_TAR\\[11\\]), or the GC_OR_START bit must be cleared (I2C_TAR\\[10\\]). Once the source of the ABRT_SBYTE_NORSTRT is fixed, then this bit can be cleared in the same manner as other bits in this register. If the source of the ABRT_SBYTE_NORSTRT is not fixed before attempting to clear this bit, bit 9 clears for one cycle and then gets re-asserted. 1: The restart is disabled (IC_RESTART_EN bit (I2C_CON\\[5\\]) = 0) and the user is trying to send a START Byte."] +pub struct ABRT_SBYTE_NORSTRT_R(crate::FieldReader); +impl ABRT_SBYTE_NORSTRT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_SBYTE_NORSTRT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_SBYTE_NORSTRT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_HS_NORSTRT` reader - 1: The restart is disabled (IC_RESTART_EN bit (I2C_CON\\[5\\]) = 0) and the user is trying to use the master to transfer data in High Speed mode"] +pub struct ABRT_HS_NORSTRT_R(crate::FieldReader); +impl ABRT_HS_NORSTRT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_HS_NORSTRT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_HS_NORSTRT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_SBYTE_ACKDET` reader - 1: Master has sent a START Byte and the START Byte was acknowledged (wrong behavior)."] +pub struct ABRT_SBYTE_ACKDET_R(crate::FieldReader); +impl ABRT_SBYTE_ACKDET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_SBYTE_ACKDET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_SBYTE_ACKDET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_HS_ACKDET` reader - 1: Master is in High Speed mode and the High Speed Master code was acknowledged (wrong behavior)."] +pub struct ABRT_HS_ACKDET_R(crate::FieldReader); +impl ABRT_HS_ACKDET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_HS_ACKDET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_HS_ACKDET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_GCALL_READ` reader - 1: the controller in master mode sent a General Call but the user programmed the byte following the General Call to be a read from the bus (IC_DATA_CMD\\[9\\] +is set to 1)."] +pub struct ABRT_GCALL_READ_R(crate::FieldReader); +impl ABRT_GCALL_READ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_GCALL_READ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_GCALL_READ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_GCALL_NOACK` reader - 1: the controller in master mode sent a General Call and no slave on the bus acknowledged the General Call."] +pub struct ABRT_GCALL_NOACK_R(crate::FieldReader); +impl ABRT_GCALL_NOACK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_GCALL_NOACK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_GCALL_NOACK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_TXDATA_NOACK` reader - 1: This is a master-mode only bit. Master has received an acknowledgement for the address, but when it sent data byte(s) following the address, it did not receive an acknowledge from the remote slave(s)."] +pub struct ABRT_TXDATA_NOACK_R(crate::FieldReader); +impl ABRT_TXDATA_NOACK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_TXDATA_NOACK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_TXDATA_NOACK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_10ADDR2_NOACK` reader - 1: Master is in 10-bit address mode and the second address byte of the 10-bit address was not acknowledged by any slave."] +pub struct ABRT_10ADDR2_NOACK_R(crate::FieldReader); +impl ABRT_10ADDR2_NOACK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_10ADDR2_NOACK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_10ADDR2_NOACK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_10ADDR1_NOACK` reader - 1: Master is in 10-bit address mode and the first 10-bit address byte was not acknowledged by any slave."] +pub struct ABRT_10ADDR1_NOACK_R(crate::FieldReader); +impl ABRT_10ADDR1_NOACK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_10ADDR1_NOACK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_10ADDR1_NOACK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ABRT_7B_ADDR_NOACK` reader - 1: Master is in 7-bit addressing mode and the address sent was not acknowledged by any slave."] +pub struct ABRT_7B_ADDR_NOACK_R(crate::FieldReader); +impl ABRT_7B_ADDR_NOACK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ABRT_7B_ADDR_NOACK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ABRT_7B_ADDR_NOACK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 15 - 1: When the processor side responds to a slave mode request for data to be transmitted to a remote master and user writes a 1 in CMD (bit 8) of 2IC_DATA_CMD register"] + #[inline(always)] + pub fn abrt_slvrd_intx(&self) -> ABRT_SLVRD_INTX_R { + ABRT_SLVRD_INTX_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14 - 1: Slave lost the bus while transmitting data to a remote master. I2C_TX_ABRT_SOURCE\\[12\\] +is set at the same time. Note: Even though the slave never \"owns\" the bus, something could go wrong on the bus. This is a fail safe check. For instance, during a data transmission at the low-to-high transition of SCL, if what is on the data bus is not what is supposed to be transmitted, then the controller no longer own the bus."] + #[inline(always)] + pub fn abrt_slv_arblost(&self) -> ABRT_SLV_ARBLOST_R { + ABRT_SLV_ARBLOST_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13 - 1: Slave has received a read command and some data exists in the TX FIFO so the slave issues a TX_ABRT interrupt to flush old data in TX FIFO."] + #[inline(always)] + pub fn abrt_slvflush_txfifo(&self) -> ABRT_SLVFLUSH_TXFIFO_R { + ABRT_SLVFLUSH_TXFIFO_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12 - 1: Master has lost arbitration, or if I2C_TX_ABRT_SOURCE\\[14\\] +is also set, then the slave transmitter has lost arbitration. Note: I2C can be both master and slave at the same time."] + #[inline(always)] + pub fn arb_lost(&self) -> ARB_LOST_R { + ARB_LOST_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11 - 1: User tries to initiate a Master operation with the Master mode disabled."] + #[inline(always)] + pub fn abrt_master_dis(&self) -> ABRT_MASTER_DIS_R { + ABRT_MASTER_DIS_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - 1: The restart is disabled (IC_RESTART_EN bit (I2C_CON\\[5\\]) = 0) and the master sends a read command in 10-bit addressing mode."] + #[inline(always)] + pub fn abrt_10b_rd_norstrt(&self) -> ABRT_10B_RD_NORSTRT_R { + ABRT_10B_RD_NORSTRT_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - To clear Bit 9, the source of the ABRT_SBYTE_NORSTRT must be fixed first; restart must be enabled (I2C_CON\\[5\\]=1), the SPECIAL bit must be cleared (I2C_TAR\\[11\\]), or the GC_OR_START bit must be cleared (I2C_TAR\\[10\\]). Once the source of the ABRT_SBYTE_NORSTRT is fixed, then this bit can be cleared in the same manner as other bits in this register. If the source of the ABRT_SBYTE_NORSTRT is not fixed before attempting to clear this bit, bit 9 clears for one cycle and then gets re-asserted. 1: The restart is disabled (IC_RESTART_EN bit (I2C_CON\\[5\\]) = 0) and the user is trying to send a START Byte."] + #[inline(always)] + pub fn abrt_sbyte_norstrt(&self) -> ABRT_SBYTE_NORSTRT_R { + ABRT_SBYTE_NORSTRT_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - 1: The restart is disabled (IC_RESTART_EN bit (I2C_CON\\[5\\]) = 0) and the user is trying to use the master to transfer data in High Speed mode"] + #[inline(always)] + pub fn abrt_hs_norstrt(&self) -> ABRT_HS_NORSTRT_R { + ABRT_HS_NORSTRT_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - 1: Master has sent a START Byte and the START Byte was acknowledged (wrong behavior)."] + #[inline(always)] + pub fn abrt_sbyte_ackdet(&self) -> ABRT_SBYTE_ACKDET_R { + ABRT_SBYTE_ACKDET_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - 1: Master is in High Speed mode and the High Speed Master code was acknowledged (wrong behavior)."] + #[inline(always)] + pub fn abrt_hs_ackdet(&self) -> ABRT_HS_ACKDET_R { + ABRT_HS_ACKDET_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - 1: the controller in master mode sent a General Call but the user programmed the byte following the General Call to be a read from the bus (IC_DATA_CMD\\[9\\] +is set to 1)."] + #[inline(always)] + pub fn abrt_gcall_read(&self) -> ABRT_GCALL_READ_R { + ABRT_GCALL_READ_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - 1: the controller in master mode sent a General Call and no slave on the bus acknowledged the General Call."] + #[inline(always)] + pub fn abrt_gcall_noack(&self) -> ABRT_GCALL_NOACK_R { + ABRT_GCALL_NOACK_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - 1: This is a master-mode only bit. Master has received an acknowledgement for the address, but when it sent data byte(s) following the address, it did not receive an acknowledge from the remote slave(s)."] + #[inline(always)] + pub fn abrt_txdata_noack(&self) -> ABRT_TXDATA_NOACK_R { + ABRT_TXDATA_NOACK_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - 1: Master is in 10-bit address mode and the second address byte of the 10-bit address was not acknowledged by any slave."] + #[inline(always)] + pub fn abrt_10addr2_noack(&self) -> ABRT_10ADDR2_NOACK_R { + ABRT_10ADDR2_NOACK_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - 1: Master is in 10-bit address mode and the first 10-bit address byte was not acknowledged by any slave."] + #[inline(always)] + pub fn abrt_10addr1_noack(&self) -> ABRT_10ADDR1_NOACK_R { + ABRT_10ADDR1_NOACK_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 1: Master is in 7-bit addressing mode and the address sent was not acknowledged by any slave."] + #[inline(always)] + pub fn abrt_7b_addr_noack(&self) -> ABRT_7B_ADDR_NOACK_R { + ABRT_7B_ADDR_NOACK_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Transmit Abort Source Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_tx_abrt_source_reg](index.html) module"] +pub struct I2C_TX_ABRT_SOURCE_REG_SPEC; +impl crate::RegisterSpec for I2C_TX_ABRT_SOURCE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_tx_abrt_source_reg::R](R) reader structure"] +impl crate::Readable for I2C_TX_ABRT_SOURCE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_tx_abrt_source_reg::W](W) writer structure"] +impl crate::Writable for I2C_TX_ABRT_SOURCE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_TX_ABRT_SOURCE_REG to value 0"] +impl crate::Resettable for I2C_TX_ABRT_SOURCE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_tl_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_tl_reg.rs new file mode 100644 index 0000000..afbbf29 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_tx_tl_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `I2C_TX_TL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_TX_TL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RX_TL` reader - Transmit FIFO Threshold Level Controls the level of entries (or below) that trigger the TX_EMPTY interrupt (bit 4 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that it may not be set to value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 0 entries, and a value of 31 sets the threshold for 32 entries.."] +pub struct RX_TL_R(crate::FieldReader); +impl RX_TL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RX_TL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RX_TL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RX_TL` writer - Transmit FIFO Threshold Level Controls the level of entries (or below) that trigger the TX_EMPTY interrupt (bit 4 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that it may not be set to value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 0 entries, and a value of 31 sets the threshold for 32 entries.."] +pub struct RX_TL_W<'a> { + w: &'a mut W, +} +impl<'a> RX_TL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u16 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 0:4 - Transmit FIFO Threshold Level Controls the level of entries (or below) that trigger the TX_EMPTY interrupt (bit 4 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that it may not be set to value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 0 entries, and a value of 31 sets the threshold for 32 entries.."] + #[inline(always)] + pub fn rx_tl(&self) -> RX_TL_R { + RX_TL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 0:4 - Transmit FIFO Threshold Level Controls the level of entries (or below) that trigger the TX_EMPTY interrupt (bit 4 in I2C_RAW_INTR_STAT register). The valid range is 0-31, with the additional restriction that it may not be set to value larger than the depth of the buffer. If an attempt is made to do that, the actual value set will be the maximum depth of the buffer. A value of 0 sets the threshold for 0 entries, and a value of 31 sets the threshold for 32 entries.."] + #[inline(always)] + pub fn rx_tl(&mut self) -> RX_TL_W { + RX_TL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Transmit FIFO Threshold Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_tx_tl_reg](index.html) module"] +pub struct I2C_TX_TL_REG_SPEC; +impl crate::RegisterSpec for I2C_TX_TL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_tx_tl_reg::R](R) reader structure"] +impl crate::Readable for I2C_TX_TL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_tx_tl_reg::W](W) writer structure"] +impl crate::Writable for I2C_TX_TL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_TX_TL_REG to value 0"] +impl crate::Resettable for I2C_TX_TL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/i2c/i2c_txflr_reg.rs b/bitbox02-bt/vendor/da14531/src/i2c/i2c_txflr_reg.rs new file mode 100644 index 0000000..6472bed --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/i2c/i2c_txflr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `I2C_TXFLR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `I2C_TXFLR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TXFLR` reader - Transmit FIFO Level. Contains the number of valid data entries in the transmit FIFO. Size is constrained by the TXFLR value"] +pub struct TXFLR_R(crate::FieldReader); +impl TXFLR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TXFLR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TXFLR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:5 - Transmit FIFO Level. Contains the number of valid data entries in the transmit FIFO. Size is constrained by the TXFLR value"] + #[inline(always)] + pub fn txflr(&self) -> TXFLR_R { + TXFLR_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "I2C Transmit FIFO Level Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [i2c_txflr_reg](index.html) module"] +pub struct I2C_TXFLR_REG_SPEC; +impl crate::RegisterSpec for I2C_TXFLR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [i2c_txflr_reg::R](R) reader structure"] +impl crate::Readable for I2C_TXFLR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [i2c_txflr_reg::W](W) writer structure"] +impl crate::Writable for I2C_TXFLR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets I2C_TXFLR_REG to value 0"] +impl crate::Resettable for I2C_TXFLR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd.rs b/bitbox02-bt/vendor/da14531/src/kbrd.rs new file mode 100644 index 0000000..f5ad421 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd.rs @@ -0,0 +1,66 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - GPIO interrupt selection for GPIO_IRQ0"] + pub gpio_irq0_in_sel_reg: crate::Reg, + #[doc = "0x02 - GPIO interrupt selection for GPIO_IRQ1"] + pub gpio_irq1_in_sel_reg: crate::Reg, + #[doc = "0x04 - GPIO interrupt selection for GPIO_IRQ2"] + pub gpio_irq2_in_sel_reg: crate::Reg, + #[doc = "0x06 - GPIO interrupt selection for GPIO_IRQ3"] + pub gpio_irq3_in_sel_reg: crate::Reg, + #[doc = "0x08 - GPIO interrupt selection for GPIO_IRQ4"] + pub gpio_irq4_in_sel_reg: crate::Reg, + _reserved5: [u8; 0x02], + #[doc = "0x0c - debounce counter value for GPIO inputs"] + pub gpio_debounce_reg: crate::Reg, + #[doc = "0x0e - GPIO interrupt reset register"] + pub gpio_reset_irq_reg: crate::Reg, + #[doc = "0x10 - high or low level select for GPIO interrupts"] + pub gpio_int_level_ctrl_reg: crate::Reg, + #[doc = "0x12 - GPIO interrupt selection for KBRD_IRQ for P0"] + pub kbrd_irq_in_sel0_reg: crate::Reg, + #[doc = "0x14 - GPIO Kbrd control register"] + pub kbrd_ctrl_reg: crate::Reg, +} +#[doc = "GPIO_DEBOUNCE_REG register accessor: an alias for `Reg`"] +pub type GPIO_DEBOUNCE_REG = crate::Reg; +#[doc = "debounce counter value for GPIO inputs"] +pub mod gpio_debounce_reg; +#[doc = "GPIO_INT_LEVEL_CTRL_REG register accessor: an alias for `Reg`"] +pub type GPIO_INT_LEVEL_CTRL_REG = + crate::Reg; +#[doc = "high or low level select for GPIO interrupts"] +pub mod gpio_int_level_ctrl_reg; +#[doc = "GPIO_IRQ0_IN_SEL_REG register accessor: an alias for `Reg`"] +pub type GPIO_IRQ0_IN_SEL_REG = crate::Reg; +#[doc = "GPIO interrupt selection for GPIO_IRQ0"] +pub mod gpio_irq0_in_sel_reg; +#[doc = "GPIO_IRQ1_IN_SEL_REG register accessor: an alias for `Reg`"] +pub type GPIO_IRQ1_IN_SEL_REG = crate::Reg; +#[doc = "GPIO interrupt selection for GPIO_IRQ1"] +pub mod gpio_irq1_in_sel_reg; +#[doc = "GPIO_IRQ2_IN_SEL_REG register accessor: an alias for `Reg`"] +pub type GPIO_IRQ2_IN_SEL_REG = crate::Reg; +#[doc = "GPIO interrupt selection for GPIO_IRQ2"] +pub mod gpio_irq2_in_sel_reg; +#[doc = "GPIO_IRQ3_IN_SEL_REG register accessor: an alias for `Reg`"] +pub type GPIO_IRQ3_IN_SEL_REG = crate::Reg; +#[doc = "GPIO interrupt selection for GPIO_IRQ3"] +pub mod gpio_irq3_in_sel_reg; +#[doc = "GPIO_IRQ4_IN_SEL_REG register accessor: an alias for `Reg`"] +pub type GPIO_IRQ4_IN_SEL_REG = crate::Reg; +#[doc = "GPIO interrupt selection for GPIO_IRQ4"] +pub mod gpio_irq4_in_sel_reg; +#[doc = "GPIO_RESET_IRQ_REG register accessor: an alias for `Reg`"] +pub type GPIO_RESET_IRQ_REG = crate::Reg; +#[doc = "GPIO interrupt reset register"] +pub mod gpio_reset_irq_reg; +#[doc = "KBRD_CTRL_REG register accessor: an alias for `Reg`"] +pub type KBRD_CTRL_REG = crate::Reg; +#[doc = "GPIO Kbrd control register"] +pub mod kbrd_ctrl_reg; +#[doc = "KBRD_IRQ_IN_SEL0_REG register accessor: an alias for `Reg`"] +pub type KBRD_IRQ_IN_SEL0_REG = crate::Reg; +#[doc = "GPIO interrupt selection for KBRD_IRQ for P0"] +pub mod kbrd_irq_in_sel0_reg; diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_debounce_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_debounce_reg.rs new file mode 100644 index 0000000..1a3a789 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_debounce_reg.rs @@ -0,0 +1,385 @@ +#[doc = "Register `GPIO_DEBOUNCE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_DEBOUNCE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DEB_ENABLE_KBRD` reader - enables the debounce counter for the KBRD interface"] +pub struct DEB_ENABLE_KBRD_R(crate::FieldReader); +impl DEB_ENABLE_KBRD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEB_ENABLE_KBRD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEB_ENABLE_KBRD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEB_ENABLE_KBRD` writer - enables the debounce counter for the KBRD interface"] +pub struct DEB_ENABLE_KBRD_W<'a> { + w: &'a mut W, +} +impl<'a> DEB_ENABLE_KBRD_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `DEB_ENABLE4` reader - enables the debounce counter for GPIO IRQ4"] +pub struct DEB_ENABLE4_R(crate::FieldReader); +impl DEB_ENABLE4_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEB_ENABLE4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEB_ENABLE4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEB_ENABLE4` writer - enables the debounce counter for GPIO IRQ4"] +pub struct DEB_ENABLE4_W<'a> { + w: &'a mut W, +} +impl<'a> DEB_ENABLE4_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `DEB_ENABLE3` reader - enables the debounce counter for GPIO IRQ3"] +pub struct DEB_ENABLE3_R(crate::FieldReader); +impl DEB_ENABLE3_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEB_ENABLE3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEB_ENABLE3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEB_ENABLE3` writer - enables the debounce counter for GPIO IRQ3"] +pub struct DEB_ENABLE3_W<'a> { + w: &'a mut W, +} +impl<'a> DEB_ENABLE3_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `DEB_ENABLE2` reader - enables the debounce counter for GPIO IRQ2"] +pub struct DEB_ENABLE2_R(crate::FieldReader); +impl DEB_ENABLE2_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEB_ENABLE2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEB_ENABLE2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEB_ENABLE2` writer - enables the debounce counter for GPIO IRQ2"] +pub struct DEB_ENABLE2_W<'a> { + w: &'a mut W, +} +impl<'a> DEB_ENABLE2_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `DEB_ENABLE1` reader - enables the debounce counter for GPIO IRQ1"] +pub struct DEB_ENABLE1_R(crate::FieldReader); +impl DEB_ENABLE1_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEB_ENABLE1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEB_ENABLE1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEB_ENABLE1` writer - enables the debounce counter for GPIO IRQ1"] +pub struct DEB_ENABLE1_W<'a> { + w: &'a mut W, +} +impl<'a> DEB_ENABLE1_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `DEB_ENABLE0` reader - enables the debounce counter for GPIO IRQ0"] +pub struct DEB_ENABLE0_R(crate::FieldReader); +impl DEB_ENABLE0_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DEB_ENABLE0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEB_ENABLE0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEB_ENABLE0` writer - enables the debounce counter for GPIO IRQ0"] +pub struct DEB_ENABLE0_W<'a> { + w: &'a mut W, +} +impl<'a> DEB_ENABLE0_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `DEB_VALUE` reader - Keyboard debounce time if enabled. Generate KEYB_INT after specified time. Debounce time: N*1 ms. N =0..63"] +pub struct DEB_VALUE_R(crate::FieldReader); +impl DEB_VALUE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEB_VALUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEB_VALUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEB_VALUE` writer - Keyboard debounce time if enabled. Generate KEYB_INT after specified time. Debounce time: N*1 ms. N =0..63"] +pub struct DEB_VALUE_W<'a> { + w: &'a mut W, +} +impl<'a> DEB_VALUE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u16 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bit 11 - enables the debounce counter for the KBRD interface"] + #[inline(always)] + pub fn deb_enable_kbrd(&self) -> DEB_ENABLE_KBRD_R { + DEB_ENABLE_KBRD_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - enables the debounce counter for GPIO IRQ4"] + #[inline(always)] + pub fn deb_enable4(&self) -> DEB_ENABLE4_R { + DEB_ENABLE4_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - enables the debounce counter for GPIO IRQ3"] + #[inline(always)] + pub fn deb_enable3(&self) -> DEB_ENABLE3_R { + DEB_ENABLE3_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - enables the debounce counter for GPIO IRQ2"] + #[inline(always)] + pub fn deb_enable2(&self) -> DEB_ENABLE2_R { + DEB_ENABLE2_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - enables the debounce counter for GPIO IRQ1"] + #[inline(always)] + pub fn deb_enable1(&self) -> DEB_ENABLE1_R { + DEB_ENABLE1_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - enables the debounce counter for GPIO IRQ0"] + #[inline(always)] + pub fn deb_enable0(&self) -> DEB_ENABLE0_R { + DEB_ENABLE0_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 0:5 - Keyboard debounce time if enabled. Generate KEYB_INT after specified time. Debounce time: N*1 ms. N =0..63"] + #[inline(always)] + pub fn deb_value(&self) -> DEB_VALUE_R { + DEB_VALUE_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bit 11 - enables the debounce counter for the KBRD interface"] + #[inline(always)] + pub fn deb_enable_kbrd(&mut self) -> DEB_ENABLE_KBRD_W { + DEB_ENABLE_KBRD_W { w: self } + } + #[doc = "Bit 10 - enables the debounce counter for GPIO IRQ4"] + #[inline(always)] + pub fn deb_enable4(&mut self) -> DEB_ENABLE4_W { + DEB_ENABLE4_W { w: self } + } + #[doc = "Bit 9 - enables the debounce counter for GPIO IRQ3"] + #[inline(always)] + pub fn deb_enable3(&mut self) -> DEB_ENABLE3_W { + DEB_ENABLE3_W { w: self } + } + #[doc = "Bit 8 - enables the debounce counter for GPIO IRQ2"] + #[inline(always)] + pub fn deb_enable2(&mut self) -> DEB_ENABLE2_W { + DEB_ENABLE2_W { w: self } + } + #[doc = "Bit 7 - enables the debounce counter for GPIO IRQ1"] + #[inline(always)] + pub fn deb_enable1(&mut self) -> DEB_ENABLE1_W { + DEB_ENABLE1_W { w: self } + } + #[doc = "Bit 6 - enables the debounce counter for GPIO IRQ0"] + #[inline(always)] + pub fn deb_enable0(&mut self) -> DEB_ENABLE0_W { + DEB_ENABLE0_W { w: self } + } + #[doc = "Bits 0:5 - Keyboard debounce time if enabled. Generate KEYB_INT after specified time. Debounce time: N*1 ms. N =0..63"] + #[inline(always)] + pub fn deb_value(&mut self) -> DEB_VALUE_W { + DEB_VALUE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "debounce counter value for GPIO inputs\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_debounce_reg](index.html) module"] +pub struct GPIO_DEBOUNCE_REG_SPEC; +impl crate::RegisterSpec for GPIO_DEBOUNCE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_debounce_reg::R](R) reader structure"] +impl crate::Readable for GPIO_DEBOUNCE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_debounce_reg::W](W) writer structure"] +impl crate::Writable for GPIO_DEBOUNCE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_DEBOUNCE_REG to value 0"] +impl crate::Resettable for GPIO_DEBOUNCE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_int_level_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_int_level_ctrl_reg.rs new file mode 100644 index 0000000..36a33c7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_int_level_ctrl_reg.rs @@ -0,0 +1,536 @@ +#[doc = "Register `GPIO_INT_LEVEL_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_INT_LEVEL_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `EDGE_LEVELn4` reader - see EDGE_LEVELn0, but for GPIO IRQ4"] +pub struct EDGE_LEVELN4_R(crate::FieldReader); +impl EDGE_LEVELN4_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EDGE_LEVELN4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EDGE_LEVELN4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EDGE_LEVELn4` writer - see EDGE_LEVELn0, but for GPIO IRQ4"] +pub struct EDGE_LEVELN4_W<'a> { + w: &'a mut W, +} +impl<'a> EDGE_LEVELN4_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `EDGE_LEVELn3` reader - see EDGE_LEVELn0, but for GPIO IRQ3"] +pub struct EDGE_LEVELN3_R(crate::FieldReader); +impl EDGE_LEVELN3_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EDGE_LEVELN3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EDGE_LEVELN3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EDGE_LEVELn3` writer - see EDGE_LEVELn0, but for GPIO IRQ3"] +pub struct EDGE_LEVELN3_W<'a> { + w: &'a mut W, +} +impl<'a> EDGE_LEVELN3_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `EDGE_LEVELn2` reader - see EDGE_LEVELn0, but for GPIO IRQ2"] +pub struct EDGE_LEVELN2_R(crate::FieldReader); +impl EDGE_LEVELN2_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EDGE_LEVELN2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EDGE_LEVELN2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EDGE_LEVELn2` writer - see EDGE_LEVELn0, but for GPIO IRQ2"] +pub struct EDGE_LEVELN2_W<'a> { + w: &'a mut W, +} +impl<'a> EDGE_LEVELN2_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `EDGE_LEVELn1` reader - see EDGE_LEVELn0, but for GPIO IRQ1"] +pub struct EDGE_LEVELN1_R(crate::FieldReader); +impl EDGE_LEVELN1_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EDGE_LEVELN1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EDGE_LEVELN1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EDGE_LEVELn1` writer - see EDGE_LEVELn0, but for GPIO IRQ1"] +pub struct EDGE_LEVELN1_W<'a> { + w: &'a mut W, +} +impl<'a> EDGE_LEVELN1_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `EDGE_LEVELn0` reader - 0: do not wait for key release after interrupt was reset for GPIO IRQ0, so a new interrupt can be initiated immediately 1: wait for key release after interrupt was reset for IRQ0"] +pub struct EDGE_LEVELN0_R(crate::FieldReader); +impl EDGE_LEVELN0_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EDGE_LEVELN0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EDGE_LEVELN0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EDGE_LEVELn0` writer - 0: do not wait for key release after interrupt was reset for GPIO IRQ0, so a new interrupt can be initiated immediately 1: wait for key release after interrupt was reset for IRQ0"] +pub struct EDGE_LEVELN0_W<'a> { + w: &'a mut W, +} +impl<'a> EDGE_LEVELN0_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `INPUT_LEVEL4` reader - see INPUT_LEVEL0, but for GPIO IRQ4"] +pub struct INPUT_LEVEL4_R(crate::FieldReader); +impl INPUT_LEVEL4_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INPUT_LEVEL4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INPUT_LEVEL4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INPUT_LEVEL4` writer - see INPUT_LEVEL0, but for GPIO IRQ4"] +pub struct INPUT_LEVEL4_W<'a> { + w: &'a mut W, +} +impl<'a> INPUT_LEVEL4_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `INPUT_LEVEL3` reader - see INPUT_LEVEL0, but for GPIO IRQ3"] +pub struct INPUT_LEVEL3_R(crate::FieldReader); +impl INPUT_LEVEL3_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INPUT_LEVEL3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INPUT_LEVEL3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INPUT_LEVEL3` writer - see INPUT_LEVEL0, but for GPIO IRQ3"] +pub struct INPUT_LEVEL3_W<'a> { + w: &'a mut W, +} +impl<'a> INPUT_LEVEL3_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `INPUT_LEVEL2` reader - see INPUT_LEVEL0, but for GPIO IRQ2"] +pub struct INPUT_LEVEL2_R(crate::FieldReader); +impl INPUT_LEVEL2_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INPUT_LEVEL2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INPUT_LEVEL2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INPUT_LEVEL2` writer - see INPUT_LEVEL0, but for GPIO IRQ2"] +pub struct INPUT_LEVEL2_W<'a> { + w: &'a mut W, +} +impl<'a> INPUT_LEVEL2_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `INPUT_LEVEL1` reader - see INPUT_LEVEL0, but for GPIO IRQ1"] +pub struct INPUT_LEVEL1_R(crate::FieldReader); +impl INPUT_LEVEL1_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INPUT_LEVEL1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INPUT_LEVEL1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INPUT_LEVEL1` writer - see INPUT_LEVEL0, but for GPIO IRQ1"] +pub struct INPUT_LEVEL1_W<'a> { + w: &'a mut W, +} +impl<'a> INPUT_LEVEL1_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `INPUT_LEVEL0` reader - 0 = selected input will generate GPIO IRQ0 if that input is high. 1 = selected input will generate GPIO IRQ0 if that input is low."] +pub struct INPUT_LEVEL0_R(crate::FieldReader); +impl INPUT_LEVEL0_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + INPUT_LEVEL0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for INPUT_LEVEL0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `INPUT_LEVEL0` writer - 0 = selected input will generate GPIO IRQ0 if that input is high. 1 = selected input will generate GPIO IRQ0 if that input is low."] +pub struct INPUT_LEVEL0_W<'a> { + w: &'a mut W, +} +impl<'a> INPUT_LEVEL0_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 9 - see EDGE_LEVELn0, but for GPIO IRQ4"] + #[inline(always)] + pub fn edge_leveln4(&self) -> EDGE_LEVELN4_R { + EDGE_LEVELN4_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - see EDGE_LEVELn0, but for GPIO IRQ3"] + #[inline(always)] + pub fn edge_leveln3(&self) -> EDGE_LEVELN3_R { + EDGE_LEVELN3_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - see EDGE_LEVELn0, but for GPIO IRQ2"] + #[inline(always)] + pub fn edge_leveln2(&self) -> EDGE_LEVELN2_R { + EDGE_LEVELN2_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - see EDGE_LEVELn0, but for GPIO IRQ1"] + #[inline(always)] + pub fn edge_leveln1(&self) -> EDGE_LEVELN1_R { + EDGE_LEVELN1_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - 0: do not wait for key release after interrupt was reset for GPIO IRQ0, so a new interrupt can be initiated immediately 1: wait for key release after interrupt was reset for IRQ0"] + #[inline(always)] + pub fn edge_leveln0(&self) -> EDGE_LEVELN0_R { + EDGE_LEVELN0_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - see INPUT_LEVEL0, but for GPIO IRQ4"] + #[inline(always)] + pub fn input_level4(&self) -> INPUT_LEVEL4_R { + INPUT_LEVEL4_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - see INPUT_LEVEL0, but for GPIO IRQ3"] + #[inline(always)] + pub fn input_level3(&self) -> INPUT_LEVEL3_R { + INPUT_LEVEL3_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - see INPUT_LEVEL0, but for GPIO IRQ2"] + #[inline(always)] + pub fn input_level2(&self) -> INPUT_LEVEL2_R { + INPUT_LEVEL2_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - see INPUT_LEVEL0, but for GPIO IRQ1"] + #[inline(always)] + pub fn input_level1(&self) -> INPUT_LEVEL1_R { + INPUT_LEVEL1_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 0 = selected input will generate GPIO IRQ0 if that input is high. 1 = selected input will generate GPIO IRQ0 if that input is low."] + #[inline(always)] + pub fn input_level0(&self) -> INPUT_LEVEL0_R { + INPUT_LEVEL0_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 9 - see EDGE_LEVELn0, but for GPIO IRQ4"] + #[inline(always)] + pub fn edge_leveln4(&mut self) -> EDGE_LEVELN4_W { + EDGE_LEVELN4_W { w: self } + } + #[doc = "Bit 8 - see EDGE_LEVELn0, but for GPIO IRQ3"] + #[inline(always)] + pub fn edge_leveln3(&mut self) -> EDGE_LEVELN3_W { + EDGE_LEVELN3_W { w: self } + } + #[doc = "Bit 7 - see EDGE_LEVELn0, but for GPIO IRQ2"] + #[inline(always)] + pub fn edge_leveln2(&mut self) -> EDGE_LEVELN2_W { + EDGE_LEVELN2_W { w: self } + } + #[doc = "Bit 6 - see EDGE_LEVELn0, but for GPIO IRQ1"] + #[inline(always)] + pub fn edge_leveln1(&mut self) -> EDGE_LEVELN1_W { + EDGE_LEVELN1_W { w: self } + } + #[doc = "Bit 5 - 0: do not wait for key release after interrupt was reset for GPIO IRQ0, so a new interrupt can be initiated immediately 1: wait for key release after interrupt was reset for IRQ0"] + #[inline(always)] + pub fn edge_leveln0(&mut self) -> EDGE_LEVELN0_W { + EDGE_LEVELN0_W { w: self } + } + #[doc = "Bit 4 - see INPUT_LEVEL0, but for GPIO IRQ4"] + #[inline(always)] + pub fn input_level4(&mut self) -> INPUT_LEVEL4_W { + INPUT_LEVEL4_W { w: self } + } + #[doc = "Bit 3 - see INPUT_LEVEL0, but for GPIO IRQ3"] + #[inline(always)] + pub fn input_level3(&mut self) -> INPUT_LEVEL3_W { + INPUT_LEVEL3_W { w: self } + } + #[doc = "Bit 2 - see INPUT_LEVEL0, but for GPIO IRQ2"] + #[inline(always)] + pub fn input_level2(&mut self) -> INPUT_LEVEL2_W { + INPUT_LEVEL2_W { w: self } + } + #[doc = "Bit 1 - see INPUT_LEVEL0, but for GPIO IRQ1"] + #[inline(always)] + pub fn input_level1(&mut self) -> INPUT_LEVEL1_W { + INPUT_LEVEL1_W { w: self } + } + #[doc = "Bit 0 - 0 = selected input will generate GPIO IRQ0 if that input is high. 1 = selected input will generate GPIO IRQ0 if that input is low."] + #[inline(always)] + pub fn input_level0(&mut self) -> INPUT_LEVEL0_W { + INPUT_LEVEL0_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "high or low level select for GPIO interrupts\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_int_level_ctrl_reg](index.html) module"] +pub struct GPIO_INT_LEVEL_CTRL_REG_SPEC; +impl crate::RegisterSpec for GPIO_INT_LEVEL_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_int_level_ctrl_reg::R](R) reader structure"] +impl crate::Readable for GPIO_INT_LEVEL_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_int_level_ctrl_reg::W](W) writer structure"] +impl crate::Writable for GPIO_INT_LEVEL_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_INT_LEVEL_CTRL_REG to value 0"] +impl crate::Resettable for GPIO_INT_LEVEL_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq0_in_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq0_in_sel_reg.rs new file mode 100644 index 0000000..057ff4e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq0_in_sel_reg.rs @@ -0,0 +1,151 @@ +#[doc = "Register `GPIO_IRQ0_IN_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_IRQ0_IN_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KBRD_IRQ0_SEL` reader - input selection that can generate a GPIO interrupt 1: P0\\[0\\] +is selected 2: P0\\[1\\] +is selected 3: P0\\[2\\] +is selected 4: P0\\[3\\] +is selected 5: P0\\[4\\] +is selected 6: P0\\[5\\] +is selected 7: P0\\[6\\] +is selected 8: P0\\[7\\] +is selected 9: P0\\[8\\] +is selected 10: P0\\[9\\] +is selected 11: P0\\[10\\] +is selected 12: P0\\[11\\] +is selected all others: no input selected"] +pub struct KBRD_IRQ0_SEL_R(crate::FieldReader); +impl KBRD_IRQ0_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KBRD_IRQ0_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_IRQ0_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_IRQ0_SEL` writer - input selection that can generate a GPIO interrupt 1: P0\\[0\\] +is selected 2: P0\\[1\\] +is selected 3: P0\\[2\\] +is selected 4: P0\\[3\\] +is selected 5: P0\\[4\\] +is selected 6: P0\\[5\\] +is selected 7: P0\\[6\\] +is selected 8: P0\\[7\\] +is selected 9: P0\\[8\\] +is selected 10: P0\\[9\\] +is selected 11: P0\\[10\\] +is selected 12: P0\\[11\\] +is selected all others: no input selected"] +pub struct KBRD_IRQ0_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_IRQ0_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 0:3 - input selection that can generate a GPIO interrupt 1: P0\\[0\\] +is selected 2: P0\\[1\\] +is selected 3: P0\\[2\\] +is selected 4: P0\\[3\\] +is selected 5: P0\\[4\\] +is selected 6: P0\\[5\\] +is selected 7: P0\\[6\\] +is selected 8: P0\\[7\\] +is selected 9: P0\\[8\\] +is selected 10: P0\\[9\\] +is selected 11: P0\\[10\\] +is selected 12: P0\\[11\\] +is selected all others: no input selected"] + #[inline(always)] + pub fn kbrd_irq0_sel(&self) -> KBRD_IRQ0_SEL_R { + KBRD_IRQ0_SEL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 0:3 - input selection that can generate a GPIO interrupt 1: P0\\[0\\] +is selected 2: P0\\[1\\] +is selected 3: P0\\[2\\] +is selected 4: P0\\[3\\] +is selected 5: P0\\[4\\] +is selected 6: P0\\[5\\] +is selected 7: P0\\[6\\] +is selected 8: P0\\[7\\] +is selected 9: P0\\[8\\] +is selected 10: P0\\[9\\] +is selected 11: P0\\[10\\] +is selected 12: P0\\[11\\] +is selected all others: no input selected"] + #[inline(always)] + pub fn kbrd_irq0_sel(&mut self) -> KBRD_IRQ0_SEL_W { + KBRD_IRQ0_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO interrupt selection for GPIO_IRQ0\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_irq0_in_sel_reg](index.html) module"] +pub struct GPIO_IRQ0_IN_SEL_REG_SPEC; +impl crate::RegisterSpec for GPIO_IRQ0_IN_SEL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_irq0_in_sel_reg::R](R) reader structure"] +impl crate::Readable for GPIO_IRQ0_IN_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_irq0_in_sel_reg::W](W) writer structure"] +impl crate::Writable for GPIO_IRQ0_IN_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_IRQ0_IN_SEL_REG to value 0"] +impl crate::Resettable for GPIO_IRQ0_IN_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq1_in_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq1_in_sel_reg.rs new file mode 100644 index 0000000..fb096f4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq1_in_sel_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `GPIO_IRQ1_IN_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_IRQ1_IN_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KBRD_IRQ1_SEL` reader - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ1_SEL_R(crate::FieldReader); +impl KBRD_IRQ1_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KBRD_IRQ1_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_IRQ1_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_IRQ1_SEL` writer - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ1_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_IRQ1_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq1_sel(&self) -> KBRD_IRQ1_SEL_R { + KBRD_IRQ1_SEL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq1_sel(&mut self) -> KBRD_IRQ1_SEL_W { + KBRD_IRQ1_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO interrupt selection for GPIO_IRQ1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_irq1_in_sel_reg](index.html) module"] +pub struct GPIO_IRQ1_IN_SEL_REG_SPEC; +impl crate::RegisterSpec for GPIO_IRQ1_IN_SEL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_irq1_in_sel_reg::R](R) reader structure"] +impl crate::Readable for GPIO_IRQ1_IN_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_irq1_in_sel_reg::W](W) writer structure"] +impl crate::Writable for GPIO_IRQ1_IN_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_IRQ1_IN_SEL_REG to value 0"] +impl crate::Resettable for GPIO_IRQ1_IN_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq2_in_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq2_in_sel_reg.rs new file mode 100644 index 0000000..9904698 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq2_in_sel_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `GPIO_IRQ2_IN_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_IRQ2_IN_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KBRD_IRQ2_SEL` reader - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ2_SEL_R(crate::FieldReader); +impl KBRD_IRQ2_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KBRD_IRQ2_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_IRQ2_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_IRQ2_SEL` writer - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ2_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_IRQ2_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq2_sel(&self) -> KBRD_IRQ2_SEL_R { + KBRD_IRQ2_SEL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq2_sel(&mut self) -> KBRD_IRQ2_SEL_W { + KBRD_IRQ2_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO interrupt selection for GPIO_IRQ2\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_irq2_in_sel_reg](index.html) module"] +pub struct GPIO_IRQ2_IN_SEL_REG_SPEC; +impl crate::RegisterSpec for GPIO_IRQ2_IN_SEL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_irq2_in_sel_reg::R](R) reader structure"] +impl crate::Readable for GPIO_IRQ2_IN_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_irq2_in_sel_reg::W](W) writer structure"] +impl crate::Writable for GPIO_IRQ2_IN_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_IRQ2_IN_SEL_REG to value 0"] +impl crate::Resettable for GPIO_IRQ2_IN_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq3_in_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq3_in_sel_reg.rs new file mode 100644 index 0000000..a6b6a23 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq3_in_sel_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `GPIO_IRQ3_IN_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_IRQ3_IN_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KBRD_IRQ3_SEL` reader - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ3_SEL_R(crate::FieldReader); +impl KBRD_IRQ3_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KBRD_IRQ3_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_IRQ3_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_IRQ3_SEL` writer - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ3_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_IRQ3_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq3_sel(&self) -> KBRD_IRQ3_SEL_R { + KBRD_IRQ3_SEL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq3_sel(&mut self) -> KBRD_IRQ3_SEL_W { + KBRD_IRQ3_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO interrupt selection for GPIO_IRQ3\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_irq3_in_sel_reg](index.html) module"] +pub struct GPIO_IRQ3_IN_SEL_REG_SPEC; +impl crate::RegisterSpec for GPIO_IRQ3_IN_SEL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_irq3_in_sel_reg::R](R) reader structure"] +impl crate::Readable for GPIO_IRQ3_IN_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_irq3_in_sel_reg::W](W) writer structure"] +impl crate::Writable for GPIO_IRQ3_IN_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_IRQ3_IN_SEL_REG to value 0"] +impl crate::Resettable for GPIO_IRQ3_IN_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq4_in_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq4_in_sel_reg.rs new file mode 100644 index 0000000..ec1d04e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_irq4_in_sel_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `GPIO_IRQ4_IN_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_IRQ4_IN_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KBRD_IRQ4_SEL` reader - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ4_SEL_R(crate::FieldReader); +impl KBRD_IRQ4_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KBRD_IRQ4_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_IRQ4_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_IRQ4_SEL` writer - see KBRD_IRQ0_SEL"] +pub struct KBRD_IRQ4_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_IRQ4_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq4_sel(&self) -> KBRD_IRQ4_SEL_R { + KBRD_IRQ4_SEL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 0:3 - see KBRD_IRQ0_SEL"] + #[inline(always)] + pub fn kbrd_irq4_sel(&mut self) -> KBRD_IRQ4_SEL_W { + KBRD_IRQ4_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO interrupt selection for GPIO_IRQ4\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_irq4_in_sel_reg](index.html) module"] +pub struct GPIO_IRQ4_IN_SEL_REG_SPEC; +impl crate::RegisterSpec for GPIO_IRQ4_IN_SEL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_irq4_in_sel_reg::R](R) reader structure"] +impl crate::Readable for GPIO_IRQ4_IN_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_irq4_in_sel_reg::W](W) writer structure"] +impl crate::Writable for GPIO_IRQ4_IN_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_IRQ4_IN_SEL_REG to value 0"] +impl crate::Resettable for GPIO_IRQ4_IN_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/gpio_reset_irq_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_reset_irq_reg.rs new file mode 100644 index 0000000..f811aae --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/gpio_reset_irq_reg.rs @@ -0,0 +1,226 @@ +#[doc = "Register `GPIO_RESET_IRQ_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `GPIO_RESET_IRQ_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_KBRD_IRQ` writer - writing a 1 to this bit will reset the KBRD IRQ. Reading returns 0."] +pub struct RESET_KBRD_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_KBRD_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `RESET_GPIO4_IRQ` writer - writing a 1 to this bit will reset the GPIO4 IRQ. Reading returns 0."] +pub struct RESET_GPIO4_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_GPIO4_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `RESET_GPIO3_IRQ` writer - writing a 1 to this bit will reset the GPIO3 IRQ. Reading returns 0."] +pub struct RESET_GPIO3_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_GPIO3_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `RESET_GPIO2_IRQ` writer - writing a 1 to this bit will reset the GPIO2 IRQ. Reading returns 0."] +pub struct RESET_GPIO2_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_GPIO2_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `RESET_GPIO1_IRQ` writer - writing a 1 to this bit will reset the GPIO1 IRQ. Reading returns 0."] +pub struct RESET_GPIO1_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_GPIO1_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `RESET_GPIO0_IRQ` writer - writing a 1 to this bit will reset the GPIO0 IRQ. Reading returns 0."] +pub struct RESET_GPIO0_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_GPIO0_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl W { + #[doc = "Bit 5 - writing a 1 to this bit will reset the KBRD IRQ. Reading returns 0."] + #[inline(always)] + pub fn reset_kbrd_irq(&mut self) -> RESET_KBRD_IRQ_W { + RESET_KBRD_IRQ_W { w: self } + } + #[doc = "Bit 4 - writing a 1 to this bit will reset the GPIO4 IRQ. Reading returns 0."] + #[inline(always)] + pub fn reset_gpio4_irq(&mut self) -> RESET_GPIO4_IRQ_W { + RESET_GPIO4_IRQ_W { w: self } + } + #[doc = "Bit 3 - writing a 1 to this bit will reset the GPIO3 IRQ. Reading returns 0."] + #[inline(always)] + pub fn reset_gpio3_irq(&mut self) -> RESET_GPIO3_IRQ_W { + RESET_GPIO3_IRQ_W { w: self } + } + #[doc = "Bit 2 - writing a 1 to this bit will reset the GPIO2 IRQ. Reading returns 0."] + #[inline(always)] + pub fn reset_gpio2_irq(&mut self) -> RESET_GPIO2_IRQ_W { + RESET_GPIO2_IRQ_W { w: self } + } + #[doc = "Bit 1 - writing a 1 to this bit will reset the GPIO1 IRQ. Reading returns 0."] + #[inline(always)] + pub fn reset_gpio1_irq(&mut self) -> RESET_GPIO1_IRQ_W { + RESET_GPIO1_IRQ_W { w: self } + } + #[doc = "Bit 0 - writing a 1 to this bit will reset the GPIO0 IRQ. Reading returns 0."] + #[inline(always)] + pub fn reset_gpio0_irq(&mut self) -> RESET_GPIO0_IRQ_W { + RESET_GPIO0_IRQ_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO interrupt reset register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_reset_irq_reg](index.html) module"] +pub struct GPIO_RESET_IRQ_REG_SPEC; +impl crate::RegisterSpec for GPIO_RESET_IRQ_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [gpio_reset_irq_reg::R](R) reader structure"] +impl crate::Readable for GPIO_RESET_IRQ_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [gpio_reset_irq_reg::W](W) writer structure"] +impl crate::Writable for GPIO_RESET_IRQ_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets GPIO_RESET_IRQ_REG to value 0"] +impl crate::Resettable for GPIO_RESET_IRQ_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/kbrd_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/kbrd_ctrl_reg.rs new file mode 100644 index 0000000..c80c26d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/kbrd_ctrl_reg.rs @@ -0,0 +1,197 @@ +#[doc = "Register `KBRD_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `KBRD_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KBRD_REL` reader - 0 = No interrupt on key release 1 = Interrupt also on key release (also debouncing if enabled)"] +pub struct KBRD_REL_R(crate::FieldReader); +impl KBRD_REL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_REL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_REL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_REL` writer - 0 = No interrupt on key release 1 = Interrupt also on key release (also debouncing if enabled)"] +pub struct KBRD_REL_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_REL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `KBRD_LEVEL` reader - 0 = enabled input will generate KBRD IRQ if that input is high. 1 = enabled input will generate KBRD IRQ if that input is low."] +pub struct KBRD_LEVEL_R(crate::FieldReader); +impl KBRD_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_LEVEL` writer - 0 = enabled input will generate KBRD IRQ if that input is high. 1 = enabled input will generate KBRD IRQ if that input is low."] +pub struct KBRD_LEVEL_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_LEVEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `KEY_REPEAT` reader - While key is pressed, automatically generate repeating KEYB_INT after specified time unequal to 0. Repeat time: N*1 ms. N =1..63, N=0 disables the timer."] +pub struct KEY_REPEAT_R(crate::FieldReader); +impl KEY_REPEAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + KEY_REPEAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KEY_REPEAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KEY_REPEAT` writer - While key is pressed, automatically generate repeating KEYB_INT after specified time unequal to 0. Repeat time: N*1 ms. N =1..63, N=0 disables the timer."] +pub struct KEY_REPEAT_W<'a> { + w: &'a mut W, +} +impl<'a> KEY_REPEAT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u16 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bit 7 - 0 = No interrupt on key release 1 = Interrupt also on key release (also debouncing if enabled)"] + #[inline(always)] + pub fn kbrd_rel(&self) -> KBRD_REL_R { + KBRD_REL_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - 0 = enabled input will generate KBRD IRQ if that input is high. 1 = enabled input will generate KBRD IRQ if that input is low."] + #[inline(always)] + pub fn kbrd_level(&self) -> KBRD_LEVEL_R { + KBRD_LEVEL_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 0:5 - While key is pressed, automatically generate repeating KEYB_INT after specified time unequal to 0. Repeat time: N*1 ms. N =1..63, N=0 disables the timer."] + #[inline(always)] + pub fn key_repeat(&self) -> KEY_REPEAT_R { + KEY_REPEAT_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bit 7 - 0 = No interrupt on key release 1 = Interrupt also on key release (also debouncing if enabled)"] + #[inline(always)] + pub fn kbrd_rel(&mut self) -> KBRD_REL_W { + KBRD_REL_W { w: self } + } + #[doc = "Bit 6 - 0 = enabled input will generate KBRD IRQ if that input is high. 1 = enabled input will generate KBRD IRQ if that input is low."] + #[inline(always)] + pub fn kbrd_level(&mut self) -> KBRD_LEVEL_W { + KBRD_LEVEL_W { w: self } + } + #[doc = "Bits 0:5 - While key is pressed, automatically generate repeating KEYB_INT after specified time unequal to 0. Repeat time: N*1 ms. N =1..63, N=0 disables the timer."] + #[inline(always)] + pub fn key_repeat(&mut self) -> KEY_REPEAT_W { + KEY_REPEAT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO Kbrd control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [kbrd_ctrl_reg](index.html) module"] +pub struct KBRD_CTRL_REG_SPEC; +impl crate::RegisterSpec for KBRD_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [kbrd_ctrl_reg::R](R) reader structure"] +impl crate::Readable for KBRD_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [kbrd_ctrl_reg::W](W) writer structure"] +impl crate::Writable for KBRD_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets KBRD_CTRL_REG to value 0"] +impl crate::Resettable for KBRD_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/kbrd/kbrd_irq_in_sel0_reg.rs b/bitbox02-bt/vendor/da14531/src/kbrd/kbrd_irq_in_sel0_reg.rs new file mode 100644 index 0000000..e956fba --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/kbrd/kbrd_irq_in_sel0_reg.rs @@ -0,0 +1,678 @@ +#[doc = "Register `KBRD_IRQ_IN_SEL0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `KBRD_IRQ_IN_SEL0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `KBRD_P11_EN` reader - enable P0\\[11\\] +for the keyboard interrupt"] +pub struct KBRD_P11_EN_R(crate::FieldReader); +impl KBRD_P11_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P11_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P11_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P11_EN` writer - enable P0\\[11\\] +for the keyboard interrupt"] +pub struct KBRD_P11_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P11_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `KBRD_P10_EN` reader - enable P0\\[10\\] +for the keyboard interrupt"] +pub struct KBRD_P10_EN_R(crate::FieldReader); +impl KBRD_P10_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P10_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P10_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P10_EN` writer - enable P0\\[10\\] +for the keyboard interrupt"] +pub struct KBRD_P10_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P10_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `KBRD_P09_EN` reader - enable P0\\[9\\] +for the keyboard interrupt"] +pub struct KBRD_P09_EN_R(crate::FieldReader); +impl KBRD_P09_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P09_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P09_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P09_EN` writer - enable P0\\[9\\] +for the keyboard interrupt"] +pub struct KBRD_P09_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P09_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `KBRD_P08_EN` reader - enable P0\\[8\\] +for the keyboard interrupt"] +pub struct KBRD_P08_EN_R(crate::FieldReader); +impl KBRD_P08_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P08_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P08_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P08_EN` writer - enable P0\\[8\\] +for the keyboard interrupt"] +pub struct KBRD_P08_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P08_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `KBRD_P07_EN` reader - enable P0\\[7\\] +for the keyboard interrupt"] +pub struct KBRD_P07_EN_R(crate::FieldReader); +impl KBRD_P07_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P07_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P07_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P07_EN` writer - enable P0\\[7\\] +for the keyboard interrupt"] +pub struct KBRD_P07_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P07_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `KBRD_P06_EN` reader - enable P0\\[6\\] +for the keyboard interrupt"] +pub struct KBRD_P06_EN_R(crate::FieldReader); +impl KBRD_P06_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P06_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P06_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P06_EN` writer - enable P0\\[6\\] +for the keyboard interrupt"] +pub struct KBRD_P06_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P06_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `KBRD_P05_EN` reader - enable P0\\[5\\] +for the keyboard interrupt"] +pub struct KBRD_P05_EN_R(crate::FieldReader); +impl KBRD_P05_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P05_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P05_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P05_EN` writer - enable P0\\[5\\] +for the keyboard interrupt"] +pub struct KBRD_P05_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P05_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `KBRD_P04_EN` reader - enable P0\\[4\\] +for the keyboard interrupt"] +pub struct KBRD_P04_EN_R(crate::FieldReader); +impl KBRD_P04_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P04_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P04_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P04_EN` writer - enable P0\\[4\\] +for the keyboard interrupt"] +pub struct KBRD_P04_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P04_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `KBRD_P03_EN` reader - enable P0\\[3\\] +for the keyboard interrupt"] +pub struct KBRD_P03_EN_R(crate::FieldReader); +impl KBRD_P03_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P03_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P03_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P03_EN` writer - enable P0\\[3\\] +for the keyboard interrupt"] +pub struct KBRD_P03_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P03_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `KBRD_P02_EN` reader - enable P0\\[2\\] +for the keyboard interrupt"] +pub struct KBRD_P02_EN_R(crate::FieldReader); +impl KBRD_P02_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P02_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P02_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P02_EN` writer - enable P0\\[2\\] +for the keyboard interrupt"] +pub struct KBRD_P02_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P02_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `KBRD_P01_EN` reader - enable P0\\[1\\] +for the keyboard interrupt"] +pub struct KBRD_P01_EN_R(crate::FieldReader); +impl KBRD_P01_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P01_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P01_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P01_EN` writer - enable P0\\[1\\] +for the keyboard interrupt"] +pub struct KBRD_P01_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P01_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `KBRD_P00_EN` reader - enable P0\\[0\\] +for the keyboard interrupt"] +pub struct KBRD_P00_EN_R(crate::FieldReader); +impl KBRD_P00_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + KBRD_P00_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for KBRD_P00_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `KBRD_P00_EN` writer - enable P0\\[0\\] +for the keyboard interrupt"] +pub struct KBRD_P00_EN_W<'a> { + w: &'a mut W, +} +impl<'a> KBRD_P00_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 11 - enable P0\\[11\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p11_en(&self) -> KBRD_P11_EN_R { + KBRD_P11_EN_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - enable P0\\[10\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p10_en(&self) -> KBRD_P10_EN_R { + KBRD_P10_EN_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - enable P0\\[9\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p09_en(&self) -> KBRD_P09_EN_R { + KBRD_P09_EN_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8 - enable P0\\[8\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p08_en(&self) -> KBRD_P08_EN_R { + KBRD_P08_EN_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - enable P0\\[7\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p07_en(&self) -> KBRD_P07_EN_R { + KBRD_P07_EN_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - enable P0\\[6\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p06_en(&self) -> KBRD_P06_EN_R { + KBRD_P06_EN_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - enable P0\\[5\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p05_en(&self) -> KBRD_P05_EN_R { + KBRD_P05_EN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - enable P0\\[4\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p04_en(&self) -> KBRD_P04_EN_R { + KBRD_P04_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - enable P0\\[3\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p03_en(&self) -> KBRD_P03_EN_R { + KBRD_P03_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - enable P0\\[2\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p02_en(&self) -> KBRD_P02_EN_R { + KBRD_P02_EN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - enable P0\\[1\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p01_en(&self) -> KBRD_P01_EN_R { + KBRD_P01_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - enable P0\\[0\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p00_en(&self) -> KBRD_P00_EN_R { + KBRD_P00_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 11 - enable P0\\[11\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p11_en(&mut self) -> KBRD_P11_EN_W { + KBRD_P11_EN_W { w: self } + } + #[doc = "Bit 10 - enable P0\\[10\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p10_en(&mut self) -> KBRD_P10_EN_W { + KBRD_P10_EN_W { w: self } + } + #[doc = "Bit 9 - enable P0\\[9\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p09_en(&mut self) -> KBRD_P09_EN_W { + KBRD_P09_EN_W { w: self } + } + #[doc = "Bit 8 - enable P0\\[8\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p08_en(&mut self) -> KBRD_P08_EN_W { + KBRD_P08_EN_W { w: self } + } + #[doc = "Bit 7 - enable P0\\[7\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p07_en(&mut self) -> KBRD_P07_EN_W { + KBRD_P07_EN_W { w: self } + } + #[doc = "Bit 6 - enable P0\\[6\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p06_en(&mut self) -> KBRD_P06_EN_W { + KBRD_P06_EN_W { w: self } + } + #[doc = "Bit 5 - enable P0\\[5\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p05_en(&mut self) -> KBRD_P05_EN_W { + KBRD_P05_EN_W { w: self } + } + #[doc = "Bit 4 - enable P0\\[4\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p04_en(&mut self) -> KBRD_P04_EN_W { + KBRD_P04_EN_W { w: self } + } + #[doc = "Bit 3 - enable P0\\[3\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p03_en(&mut self) -> KBRD_P03_EN_W { + KBRD_P03_EN_W { w: self } + } + #[doc = "Bit 2 - enable P0\\[2\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p02_en(&mut self) -> KBRD_P02_EN_W { + KBRD_P02_EN_W { w: self } + } + #[doc = "Bit 1 - enable P0\\[1\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p01_en(&mut self) -> KBRD_P01_EN_W { + KBRD_P01_EN_W { w: self } + } + #[doc = "Bit 0 - enable P0\\[0\\] +for the keyboard interrupt"] + #[inline(always)] + pub fn kbrd_p00_en(&mut self) -> KBRD_P00_EN_W { + KBRD_P00_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "GPIO interrupt selection for KBRD_IRQ for P0\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [kbrd_irq_in_sel0_reg](index.html) module"] +pub struct KBRD_IRQ_IN_SEL0_REG_SPEC; +impl crate::RegisterSpec for KBRD_IRQ_IN_SEL0_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [kbrd_irq_in_sel0_reg::R](R) reader structure"] +impl crate::Readable for KBRD_IRQ_IN_SEL0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [kbrd_irq_in_sel0_reg::W](W) writer structure"] +impl crate::Writable for KBRD_IRQ_IN_SEL0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets KBRD_IRQ_IN_SEL0_REG to value 0"] +impl crate::Resettable for KBRD_IRQ_IN_SEL0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/lib.rs b/bitbox02-bt/vendor/da14531/src/lib.rs new file mode 100644 index 0000000..096de54 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/lib.rs @@ -0,0 +1,1038 @@ +#![doc = "Peripheral access API for DA14531 microcontrollers (generated using svd2rust v0.22.1 ( ))\n\nYou can find an overview of the generated API [here].\n\nAPI features to be included in the [next] +svd2rust release can be generated by cloning the svd2rust [repository], checking out the above commit, and running `cargo doc --open`.\n\n[here]: https://docs.rs/svd2rust/0.22.1/svd2rust/#peripheral-api\n[next]: https://github.com/rust-embedded/svd2rust/blob/master/CHANGELOG.md#unreleased\n[repository]: https://github.com/rust-embedded/svd2rust"] +#![deny(const_err)] +#![deny(dead_code)] +#![deny(improper_ctypes)] +#![deny(missing_docs)] +#![deny(no_mangle_generic_items)] +#![deny(non_shorthand_field_patterns)] +#![deny(overflowing_literals)] +#![deny(path_statements)] +#![deny(patterns_in_fns_without_body)] +#![deny(private_in_public)] +#![deny(unconditional_recursion)] +#![deny(unused_allocation)] +#![deny(unused_comparisons)] +#![deny(unused_parens)] +#![deny(while_true)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![no_std] +use core::marker::PhantomData; +use core::ops::Deref; +#[doc = r"Number available in the NVIC for configuring priority"] +pub const NVIC_PRIO_BITS: u8 = 3; +#[cfg(feature = "rt")] +pub use self::Interrupt as interrupt; +pub use cortex_m::peripheral::Peripherals as CorePeripherals; +pub use cortex_m::peripheral::{CBP, CPUID, DCB, DWT, FPB, FPU, ITM, MPU, NVIC, SCB, SYST, TPIU}; +#[cfg(feature = "rt")] +pub use cortex_m_rt::interrupt; +#[allow(unused_imports)] +use generic::*; +#[doc = r"Common register and bit access and modify traits"] +pub mod generic; +#[cfg(feature = "rt")] +extern "C" {} +#[doc(hidden)] +pub union Vector { + _handler: unsafe extern "C" fn(), + _reserved: u32, +} +#[cfg(feature = "rt")] +#[doc(hidden)] +#[link_section = ".vector_table.interrupts"] +#[no_mangle] +pub static __INTERRUPTS: [Vector; 0] = []; +#[doc = r"Enumeration of all the interrupts."] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Interrupt {} +unsafe impl cortex_m::interrupt::InterruptNumber for Interrupt { + #[inline(always)] + fn number(self) -> u16 { + match self {} + } +} +#[doc = "Cortex M0 SysTick registers"] +pub struct SYSTICK { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for SYSTICK {} +impl SYSTICK { + #[doc = r"Pointer to the register block"] + pub const PTR: *const sys_tick::RegisterBlock = 0xe000_e010 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const sys_tick::RegisterBlock { + Self::PTR + } +} +impl Deref for SYSTICK { + type Target = sys_tick::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for SYSTICK { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("SYSTICK").finish() + } +} +#[doc = "Cortex M0 SysTick registers"] +pub mod sys_tick; +#[doc = "adplldig registers"] +pub struct ADPLLDIG { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for ADPLLDIG {} +impl ADPLLDIG { + #[doc = r"Pointer to the register block"] + pub const PTR: *const adplldig::RegisterBlock = 0x4000_3000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const adplldig::RegisterBlock { + Self::PTR + } +} +impl Deref for ADPLLDIG { + type Target = adplldig::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for ADPLLDIG { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("ADPLLDIG").finish() + } +} +#[doc = "adplldig registers"] +pub mod adplldig; +#[doc = "ANAMISC registers"] +pub struct ANAMISC { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for ANAMISC {} +impl ANAMISC { + #[doc = r"Pointer to the register block"] + pub const PTR: *const anamisc::RegisterBlock = 0x5000_1600 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const anamisc::RegisterBlock { + Self::PTR + } +} +impl Deref for ANAMISC { + type Target = anamisc::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for ANAMISC { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("ANAMISC").finish() + } +} +#[doc = "ANAMISC registers"] +pub mod anamisc; +#[doc = "BLE registers"] +pub struct BLE { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for BLE {} +impl BLE { + #[doc = r"Pointer to the register block"] + pub const PTR: *const ble::RegisterBlock = 0x4000_0000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const ble::RegisterBlock { + Self::PTR + } +} +impl Deref for BLE { + type Target = ble::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for BLE { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("BLE").finish() + } +} +#[doc = "BLE registers"] +pub mod ble; +#[doc = "CHIP_VERSION registers"] +pub struct CHIP_VERSION { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for CHIP_VERSION {} +impl CHIP_VERSION { + #[doc = r"Pointer to the register block"] + pub const PTR: *const chip_version::RegisterBlock = 0x5000_3200 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const chip_version::RegisterBlock { + Self::PTR + } +} +impl Deref for CHIP_VERSION { + type Target = chip_version::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for CHIP_VERSION { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("CHIP_VERSION").finish() + } +} +#[doc = "CHIP_VERSION registers"] +pub mod chip_version; +#[doc = "CRG_AON registers"] +pub struct CRG_AON { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for CRG_AON {} +impl CRG_AON { + #[doc = r"Pointer to the register block"] + pub const PTR: *const crg_aon::RegisterBlock = 0x5000_0300 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const crg_aon::RegisterBlock { + Self::PTR + } +} +impl Deref for CRG_AON { + type Target = crg_aon::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for CRG_AON { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("CRG_AON").finish() + } +} +#[doc = "CRG_AON registers"] +pub mod crg_aon; +#[doc = "CRG_TIM registers"] +pub struct CRG_TIM { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for CRG_TIM {} +impl CRG_TIM { + #[doc = r"Pointer to the register block"] + pub const PTR: *const crg_tim::RegisterBlock = 0x5000_4200 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const crg_tim::RegisterBlock { + Self::PTR + } +} +impl Deref for CRG_TIM { + type Target = crg_tim::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for CRG_TIM { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("CRG_TIM").finish() + } +} +#[doc = "CRG_TIM registers"] +pub mod crg_tim; +#[doc = "CRG_TOP registers"] +pub struct CRG_TOP { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for CRG_TOP {} +impl CRG_TOP { + #[doc = r"Pointer to the register block"] + pub const PTR: *const crg_top::RegisterBlock = 0x5000_0000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const crg_top::RegisterBlock { + Self::PTR + } +} +impl Deref for CRG_TOP { + type Target = crg_top::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for CRG_TOP { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("CRG_TOP").finish() + } +} +#[doc = "CRG_TOP registers"] +pub mod crg_top; +#[doc = "GPADC registers"] +pub struct GPADC { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for GPADC {} +impl GPADC { + #[doc = r"Pointer to the register block"] + pub const PTR: *const gpadc::RegisterBlock = 0x5000_1500 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const gpadc::RegisterBlock { + Self::PTR + } +} +impl Deref for GPADC { + type Target = gpadc::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for GPADC { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("GPADC").finish() + } +} +#[doc = "GPADC registers"] +pub mod gpadc; +#[doc = "GPIO registers"] +pub struct GPIO { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for GPIO {} +impl GPIO { + #[doc = r"Pointer to the register block"] + pub const PTR: *const gpio::RegisterBlock = 0x5000_3000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const gpio::RegisterBlock { + Self::PTR + } +} +impl Deref for GPIO { + type Target = gpio::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for GPIO { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("GPIO").finish() + } +} +#[doc = "GPIO registers"] +pub mod gpio; +#[doc = "GPREG registers"] +pub struct GPREG { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for GPREG {} +impl GPREG { + #[doc = r"Pointer to the register block"] + pub const PTR: *const gpreg::RegisterBlock = 0x5000_3300 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const gpreg::RegisterBlock { + Self::PTR + } +} +impl Deref for GPREG { + type Target = gpreg::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for GPREG { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("GPREG").finish() + } +} +#[doc = "GPREG registers"] +pub mod gpreg; +#[doc = "I2C registers"] +pub struct I2C { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for I2C {} +impl I2C { + #[doc = r"Pointer to the register block"] + pub const PTR: *const i2c::RegisterBlock = 0x5000_1300 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const i2c::RegisterBlock { + Self::PTR + } +} +impl Deref for I2C { + type Target = i2c::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for I2C { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("I2C").finish() + } +} +#[doc = "I2C registers"] +pub mod i2c; +#[doc = "KBRD registers"] +pub struct KBRD { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for KBRD {} +impl KBRD { + #[doc = r"Pointer to the register block"] + pub const PTR: *const kbrd::RegisterBlock = 0x5000_1400 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const kbrd::RegisterBlock { + Self::PTR + } +} +impl Deref for KBRD { + type Target = kbrd::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for KBRD { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("KBRD").finish() + } +} +#[doc = "KBRD registers"] +pub mod kbrd; +#[doc = "MBIST_SRAM12 registers"] +pub struct MBIST_SRAM12 { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for MBIST_SRAM12 {} +impl MBIST_SRAM12 { + #[doc = r"Pointer to the register block"] + pub const PTR: *const mbist_sram12::RegisterBlock = 0x5000_3700 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const mbist_sram12::RegisterBlock { + Self::PTR + } +} +impl Deref for MBIST_SRAM12 { + type Target = mbist_sram12::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for MBIST_SRAM12 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("MBIST_SRAM12").finish() + } +} +#[doc = "MBIST_SRAM12 registers"] +pub mod mbist_sram12; +#[doc = "MBIST_SRAM3 registers"] +pub struct MBIST_SRAM3 { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for MBIST_SRAM3 {} +impl MBIST_SRAM3 { + #[doc = r"Pointer to the register block"] + pub const PTR: *const mbist_sram3::RegisterBlock = 0x5000_3800 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const mbist_sram3::RegisterBlock { + Self::PTR + } +} +impl Deref for MBIST_SRAM3 { + type Target = mbist_sram3::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for MBIST_SRAM3 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("MBIST_SRAM3").finish() + } +} +#[doc = "MBIST_SRAM3 registers"] +pub mod mbist_sram3; +#[doc = "OTPC registers"] +pub struct OTPC { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for OTPC {} +impl OTPC { + #[doc = r"Pointer to the register block"] + pub const PTR: *const otpc::RegisterBlock = 0x07f4_0000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const otpc::RegisterBlock { + Self::PTR + } +} +impl Deref for OTPC { + type Target = otpc::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for OTPC { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("OTPC").finish() + } +} +#[doc = "OTPC registers"] +pub mod otpc; +#[doc = "PATCH registers"] +pub struct PATCH { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for PATCH {} +impl PATCH { + #[doc = r"Pointer to the register block"] + pub const PTR: *const patch::RegisterBlock = 0x4008_0000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const patch::RegisterBlock { + Self::PTR + } +} +impl Deref for PATCH { + type Target = patch::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for PATCH { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("PATCH").finish() + } +} +#[doc = "PATCH registers"] +pub mod patch; +#[doc = "QUADEC registers"] +pub struct QUADEC { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for QUADEC {} +impl QUADEC { + #[doc = r"Pointer to the register block"] + pub const PTR: *const quadec::RegisterBlock = 0x5000_0200 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const quadec::RegisterBlock { + Self::PTR + } +} +impl Deref for QUADEC { + type Target = quadec::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for QUADEC { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("QUADEC").finish() + } +} +#[doc = "QUADEC registers"] +pub mod quadec; +#[doc = "RFCU registers"] +pub struct RFCU { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for RFCU {} +impl RFCU { + #[doc = r"Pointer to the register block"] + pub const PTR: *const rfcu::RegisterBlock = 0x4000_1000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const rfcu::RegisterBlock { + Self::PTR + } +} +impl Deref for RFCU { + type Target = rfcu::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for RFCU { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("RFCU").finish() + } +} +#[doc = "RFCU registers"] +pub mod rfcu; +#[doc = "RFCU_POWER registers"] +pub struct RFCU_POWER { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for RFCU_POWER {} +impl RFCU_POWER { + #[doc = r"Pointer to the register block"] + pub const PTR: *const rfcu_power::RegisterBlock = 0x4000_1200 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const rfcu_power::RegisterBlock { + Self::PTR + } +} +impl Deref for RFCU_POWER { + type Target = rfcu_power::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for RFCU_POWER { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("RFCU_POWER").finish() + } +} +#[doc = "RFCU_POWER registers"] +pub mod rfcu_power; +#[doc = "RFMON registers"] +pub struct RFMON { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for RFMON {} +impl RFMON { + #[doc = r"Pointer to the register block"] + pub const PTR: *const rfmon::RegisterBlock = 0x5000_3500 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const rfmon::RegisterBlock { + Self::PTR + } +} +impl Deref for RFMON { + type Target = rfmon::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for RFMON { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("RFMON").finish() + } +} +#[doc = "RFMON registers"] +pub mod rfmon; +#[doc = "RTC registers"] +pub struct RTC { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for RTC {} +impl RTC { + #[doc = r"Pointer to the register block"] + pub const PTR: *const rtc::RegisterBlock = 0x5000_4100 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const rtc::RegisterBlock { + Self::PTR + } +} +impl Deref for RTC { + type Target = rtc::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for RTC { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("RTC").finish() + } +} +#[doc = "RTC registers"] +pub mod rtc; +#[doc = "SPI registers"] +pub struct SPI { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for SPI {} +impl SPI { + #[doc = r"Pointer to the register block"] + pub const PTR: *const spi::RegisterBlock = 0x5000_1200 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const spi::RegisterBlock { + Self::PTR + } +} +impl Deref for SPI { + type Target = spi::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for SPI { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("SPI").finish() + } +} +#[doc = "SPI registers"] +pub mod spi; +#[doc = "SYS_WDOG registers"] +pub struct SYS_WDOG { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for SYS_WDOG {} +impl SYS_WDOG { + #[doc = r"Pointer to the register block"] + pub const PTR: *const sys_wdog::RegisterBlock = 0x5000_3100 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const sys_wdog::RegisterBlock { + Self::PTR + } +} +impl Deref for SYS_WDOG { + type Target = sys_wdog::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for SYS_WDOG { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("SYS_WDOG").finish() + } +} +#[doc = "SYS_WDOG registers"] +pub mod sys_wdog; +#[doc = "TIMER0 registers"] +pub struct TIMER0 { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for TIMER0 {} +impl TIMER0 { + #[doc = r"Pointer to the register block"] + pub const PTR: *const timer0::RegisterBlock = 0x5000_3400 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const timer0::RegisterBlock { + Self::PTR + } +} +impl Deref for TIMER0 { + type Target = timer0::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for TIMER0 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("TIMER0").finish() + } +} +#[doc = "TIMER0 registers"] +pub mod timer0; +#[doc = "TIMER1 registers"] +pub struct TIMER1 { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for TIMER1 {} +impl TIMER1 { + #[doc = r"Pointer to the register block"] + pub const PTR: *const timer1::RegisterBlock = 0x5000_4000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const timer1::RegisterBlock { + Self::PTR + } +} +impl Deref for TIMER1 { + type Target = timer1::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for TIMER1 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("TIMER1").finish() + } +} +#[doc = "TIMER1 registers"] +pub mod timer1; +#[doc = "UART registers"] +pub struct UART { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for UART {} +impl UART { + #[doc = r"Pointer to the register block"] + pub const PTR: *const uart::RegisterBlock = 0x5000_1000 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const uart::RegisterBlock { + Self::PTR + } +} +impl Deref for UART { + type Target = uart::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for UART { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("UART").finish() + } +} +#[doc = "UART registers"] +pub mod uart; +#[doc = "UART2 registers"] +pub struct UART2 { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for UART2 {} +impl UART2 { + #[doc = r"Pointer to the register block"] + pub const PTR: *const uart2::RegisterBlock = 0x5000_1100 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const uart2::RegisterBlock { + Self::PTR + } +} +impl Deref for UART2 { + type Target = uart2::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for UART2 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("UART2").finish() + } +} +#[doc = "UART2 registers"] +pub mod uart2; +#[doc = "WKUP registers"] +pub struct WKUP { + _marker: PhantomData<*const ()>, +} +unsafe impl Send for WKUP {} +impl WKUP { + #[doc = r"Pointer to the register block"] + pub const PTR: *const wkup::RegisterBlock = 0x5000_0100 as *const _; + #[doc = r"Return the pointer to the register block"] + #[inline(always)] + pub const fn ptr() -> *const wkup::RegisterBlock { + Self::PTR + } +} +impl Deref for WKUP { + type Target = wkup::RegisterBlock; + #[inline(always)] + fn deref(&self) -> &Self::Target { + unsafe { &*Self::PTR } + } +} +impl core::fmt::Debug for WKUP { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("WKUP").finish() + } +} +#[doc = "WKUP registers"] +pub mod wkup; +#[no_mangle] +static mut DEVICE_PERIPHERALS: bool = false; +#[doc = r"All the peripherals"] +#[allow(non_snake_case)] +pub struct Peripherals { + #[doc = "SYSTICK"] + pub SYSTICK: SYSTICK, + #[doc = "ADPLLDIG"] + pub ADPLLDIG: ADPLLDIG, + #[doc = "ANAMISC"] + pub ANAMISC: ANAMISC, + #[doc = "BLE"] + pub BLE: BLE, + #[doc = "CHIP_VERSION"] + pub CHIP_VERSION: CHIP_VERSION, + #[doc = "CRG_AON"] + pub CRG_AON: CRG_AON, + #[doc = "CRG_TIM"] + pub CRG_TIM: CRG_TIM, + #[doc = "CRG_TOP"] + pub CRG_TOP: CRG_TOP, + #[doc = "GPADC"] + pub GPADC: GPADC, + #[doc = "GPIO"] + pub GPIO: GPIO, + #[doc = "GPREG"] + pub GPREG: GPREG, + #[doc = "I2C"] + pub I2C: I2C, + #[doc = "KBRD"] + pub KBRD: KBRD, + #[doc = "MBIST_SRAM12"] + pub MBIST_SRAM12: MBIST_SRAM12, + #[doc = "MBIST_SRAM3"] + pub MBIST_SRAM3: MBIST_SRAM3, + #[doc = "OTPC"] + pub OTPC: OTPC, + #[doc = "PATCH"] + pub PATCH: PATCH, + #[doc = "QUADEC"] + pub QUADEC: QUADEC, + #[doc = "RFCU"] + pub RFCU: RFCU, + #[doc = "RFCU_POWER"] + pub RFCU_POWER: RFCU_POWER, + #[doc = "RFMON"] + pub RFMON: RFMON, + #[doc = "RTC"] + pub RTC: RTC, + #[doc = "SPI"] + pub SPI: SPI, + #[doc = "SYS_WDOG"] + pub SYS_WDOG: SYS_WDOG, + #[doc = "TIMER0"] + pub TIMER0: TIMER0, + #[doc = "TIMER1"] + pub TIMER1: TIMER1, + #[doc = "UART"] + pub UART: UART, + #[doc = "UART2"] + pub UART2: UART2, + #[doc = "WKUP"] + pub WKUP: WKUP, +} +impl Peripherals { + #[doc = r"Returns all the peripherals *once*"] + #[inline] + pub fn take() -> Option { + cortex_m::interrupt::free(|_| { + if unsafe { DEVICE_PERIPHERALS } { + None + } else { + Some(unsafe { Peripherals::steal() }) + } + }) + } + #[doc = r"Unchecked version of `Peripherals::take`"] + #[inline] + pub unsafe fn steal() -> Self { + DEVICE_PERIPHERALS = true; + Peripherals { + SYSTICK: SYSTICK { + _marker: PhantomData, + }, + ADPLLDIG: ADPLLDIG { + _marker: PhantomData, + }, + ANAMISC: ANAMISC { + _marker: PhantomData, + }, + BLE: BLE { + _marker: PhantomData, + }, + CHIP_VERSION: CHIP_VERSION { + _marker: PhantomData, + }, + CRG_AON: CRG_AON { + _marker: PhantomData, + }, + CRG_TIM: CRG_TIM { + _marker: PhantomData, + }, + CRG_TOP: CRG_TOP { + _marker: PhantomData, + }, + GPADC: GPADC { + _marker: PhantomData, + }, + GPIO: GPIO { + _marker: PhantomData, + }, + GPREG: GPREG { + _marker: PhantomData, + }, + I2C: I2C { + _marker: PhantomData, + }, + KBRD: KBRD { + _marker: PhantomData, + }, + MBIST_SRAM12: MBIST_SRAM12 { + _marker: PhantomData, + }, + MBIST_SRAM3: MBIST_SRAM3 { + _marker: PhantomData, + }, + OTPC: OTPC { + _marker: PhantomData, + }, + PATCH: PATCH { + _marker: PhantomData, + }, + QUADEC: QUADEC { + _marker: PhantomData, + }, + RFCU: RFCU { + _marker: PhantomData, + }, + RFCU_POWER: RFCU_POWER { + _marker: PhantomData, + }, + RFMON: RFMON { + _marker: PhantomData, + }, + RTC: RTC { + _marker: PhantomData, + }, + SPI: SPI { + _marker: PhantomData, + }, + SYS_WDOG: SYS_WDOG { + _marker: PhantomData, + }, + TIMER0: TIMER0 { + _marker: PhantomData, + }, + TIMER1: TIMER1 { + _marker: PhantomData, + }, + UART: UART { + _marker: PhantomData, + }, + UART2: UART2 { + _marker: PhantomData, + }, + WKUP: WKUP { + _marker: PhantomData, + }, + } + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram12.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram12.rs new file mode 100644 index 0000000..30779e2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram12.rs @@ -0,0 +1,30 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - "] + pub mbist_sram12_addr_reg: crate::Reg, + #[doc = "0x02 - "] + pub mbist_sram12_state_reg: crate::Reg, + #[doc = "0x04 - "] + pub mbist_sram12_rd_msb_reg: crate::Reg, + #[doc = "0x06 - "] + pub mbist_sram12_rd_lsb_reg: crate::Reg, +} +#[doc = "MBIST_SRAM12_ADDR_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM12_ADDR_REG = crate::Reg; +#[doc = ""] +pub mod mbist_sram12_addr_reg; +#[doc = "MBIST_SRAM12_RD_LSB_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM12_RD_LSB_REG = + crate::Reg; +#[doc = ""] +pub mod mbist_sram12_rd_lsb_reg; +#[doc = "MBIST_SRAM12_RD_MSB_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM12_RD_MSB_REG = + crate::Reg; +#[doc = ""] +pub mod mbist_sram12_rd_msb_reg; +#[doc = "MBIST_SRAM12_STATE_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM12_STATE_REG = crate::Reg; +#[doc = ""] +pub mod mbist_sram12_state_reg; diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_addr_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_addr_reg.rs new file mode 100644 index 0000000..c6929cb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_addr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM12_ADDR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM12_ADDR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_ADDR` reader - Returns the current address register in case of a mismatch."] +pub struct MBIST_ADDR_R(crate::FieldReader); +impl MBIST_ADDR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_ADDR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_ADDR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the current address register in case of a mismatch."] + #[inline(always)] + pub fn mbist_addr(&self) -> MBIST_ADDR_R { + MBIST_ADDR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram12_addr_reg](index.html) module"] +pub struct MBIST_SRAM12_ADDR_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM12_ADDR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram12_addr_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM12_ADDR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram12_addr_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM12_ADDR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM12_ADDR_REG to value 0"] +impl crate::Resettable for MBIST_SRAM12_ADDR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_lsb_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_lsb_reg.rs new file mode 100644 index 0000000..a15141f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_lsb_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM12_RD_LSB_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM12_RD_LSB_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_LSB_DATA` reader - Returns the actual LSB read data in case of a mismatch."] +pub struct MBIST_LSB_DATA_R(crate::FieldReader); +impl MBIST_LSB_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_LSB_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_LSB_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the actual LSB read data in case of a mismatch."] + #[inline(always)] + pub fn mbist_lsb_data(&self) -> MBIST_LSB_DATA_R { + MBIST_LSB_DATA_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram12_rd_lsb_reg](index.html) module"] +pub struct MBIST_SRAM12_RD_LSB_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM12_RD_LSB_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram12_rd_lsb_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM12_RD_LSB_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram12_rd_lsb_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM12_RD_LSB_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM12_RD_LSB_REG to value 0"] +impl crate::Resettable for MBIST_SRAM12_RD_LSB_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_msb_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_msb_reg.rs new file mode 100644 index 0000000..49416f6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_rd_msb_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM12_RD_MSB_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM12_RD_MSB_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_MSB_DATA` reader - Returns the actual MSB read data in case of a mismatch."] +pub struct MBIST_MSB_DATA_R(crate::FieldReader); +impl MBIST_MSB_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_MSB_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_MSB_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the actual MSB read data in case of a mismatch."] + #[inline(always)] + pub fn mbist_msb_data(&self) -> MBIST_MSB_DATA_R { + MBIST_MSB_DATA_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram12_rd_msb_reg](index.html) module"] +pub struct MBIST_SRAM12_RD_MSB_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM12_RD_MSB_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram12_rd_msb_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM12_RD_MSB_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram12_rd_msb_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM12_RD_MSB_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM12_RD_MSB_REG to value 0"] +impl crate::Resettable for MBIST_SRAM12_RD_MSB_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_state_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_state_reg.rs new file mode 100644 index 0000000..446dabb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram12/mbist_sram12_state_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM12_STATE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM12_STATE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_STATE` reader - Returns the current state in case of a mismatch."] +pub struct MBIST_STATE_R(crate::FieldReader); +impl MBIST_STATE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_STATE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_STATE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the current state in case of a mismatch."] + #[inline(always)] + pub fn mbist_state(&self) -> MBIST_STATE_R { + MBIST_STATE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram12_state_reg](index.html) module"] +pub struct MBIST_SRAM12_STATE_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM12_STATE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram12_state_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM12_STATE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram12_state_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM12_STATE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM12_STATE_REG to value 0"] +impl crate::Resettable for MBIST_SRAM12_STATE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram3.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram3.rs new file mode 100644 index 0000000..f641cb0 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram3.rs @@ -0,0 +1,28 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - "] + pub mbist_sram3_addr_reg: crate::Reg, + #[doc = "0x02 - "] + pub mbist_sram3_state_reg: crate::Reg, + #[doc = "0x04 - "] + pub mbist_sram3_rd_msb_reg: crate::Reg, + #[doc = "0x06 - "] + pub mbist_sram3_rd_lsb_reg: crate::Reg, +} +#[doc = "MBIST_SRAM3_ADDR_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM3_ADDR_REG = crate::Reg; +#[doc = ""] +pub mod mbist_sram3_addr_reg; +#[doc = "MBIST_SRAM3_RD_LSB_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM3_RD_LSB_REG = crate::Reg; +#[doc = ""] +pub mod mbist_sram3_rd_lsb_reg; +#[doc = "MBIST_SRAM3_RD_MSB_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM3_RD_MSB_REG = crate::Reg; +#[doc = ""] +pub mod mbist_sram3_rd_msb_reg; +#[doc = "MBIST_SRAM3_STATE_REG register accessor: an alias for `Reg`"] +pub type MBIST_SRAM3_STATE_REG = crate::Reg; +#[doc = ""] +pub mod mbist_sram3_state_reg; diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_addr_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_addr_reg.rs new file mode 100644 index 0000000..9ca9836 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_addr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM3_ADDR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM3_ADDR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_ADDR` reader - Returns the current address register in case of a mismatch."] +pub struct MBIST_ADDR_R(crate::FieldReader); +impl MBIST_ADDR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_ADDR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_ADDR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the current address register in case of a mismatch."] + #[inline(always)] + pub fn mbist_addr(&self) -> MBIST_ADDR_R { + MBIST_ADDR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram3_addr_reg](index.html) module"] +pub struct MBIST_SRAM3_ADDR_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM3_ADDR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram3_addr_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM3_ADDR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram3_addr_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM3_ADDR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM3_ADDR_REG to value 0"] +impl crate::Resettable for MBIST_SRAM3_ADDR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_lsb_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_lsb_reg.rs new file mode 100644 index 0000000..5f476e4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_lsb_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM3_RD_LSB_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM3_RD_LSB_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_LSB_DATA` reader - Returns the actual LSB read data in case of a mismatch."] +pub struct MBIST_LSB_DATA_R(crate::FieldReader); +impl MBIST_LSB_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_LSB_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_LSB_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the actual LSB read data in case of a mismatch."] + #[inline(always)] + pub fn mbist_lsb_data(&self) -> MBIST_LSB_DATA_R { + MBIST_LSB_DATA_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram3_rd_lsb_reg](index.html) module"] +pub struct MBIST_SRAM3_RD_LSB_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM3_RD_LSB_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram3_rd_lsb_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM3_RD_LSB_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram3_rd_lsb_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM3_RD_LSB_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM3_RD_LSB_REG to value 0"] +impl crate::Resettable for MBIST_SRAM3_RD_LSB_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_msb_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_msb_reg.rs new file mode 100644 index 0000000..6643a1f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_rd_msb_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM3_RD_MSB_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM3_RD_MSB_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_MSB_DATA` reader - Returns the actual MSB read data in case of a mismatch."] +pub struct MBIST_MSB_DATA_R(crate::FieldReader); +impl MBIST_MSB_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_MSB_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_MSB_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the actual MSB read data in case of a mismatch."] + #[inline(always)] + pub fn mbist_msb_data(&self) -> MBIST_MSB_DATA_R { + MBIST_MSB_DATA_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram3_rd_msb_reg](index.html) module"] +pub struct MBIST_SRAM3_RD_MSB_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM3_RD_MSB_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram3_rd_msb_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM3_RD_MSB_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram3_rd_msb_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM3_RD_MSB_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM3_RD_MSB_REG to value 0"] +impl crate::Resettable for MBIST_SRAM3_RD_MSB_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_state_reg.rs b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_state_reg.rs new file mode 100644 index 0000000..b9fbd84 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/mbist_sram3/mbist_sram3_state_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `MBIST_SRAM3_STATE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `MBIST_SRAM3_STATE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MBIST_STATE` reader - Returns the current state in case of a mismatch."] +pub struct MBIST_STATE_R(crate::FieldReader); +impl MBIST_STATE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MBIST_STATE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MBIST_STATE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Returns the current state in case of a mismatch."] + #[inline(always)] + pub fn mbist_state(&self) -> MBIST_STATE_R { + MBIST_STATE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mbist_sram3_state_reg](index.html) module"] +pub struct MBIST_SRAM3_STATE_REG_SPEC; +impl crate::RegisterSpec for MBIST_SRAM3_STATE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [mbist_sram3_state_reg::R](R) reader structure"] +impl crate::Readable for MBIST_SRAM3_STATE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [mbist_sram3_state_reg::W](W) writer structure"] +impl crate::Writable for MBIST_SRAM3_STATE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets MBIST_SRAM3_STATE_REG to value 0"] +impl crate::Resettable for MBIST_SRAM3_STATE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc.rs b/bitbox02-bt/vendor/da14531/src/otpc.rs new file mode 100644 index 0000000..b46aec7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc.rs @@ -0,0 +1,58 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Mode register"] + pub otpc_mode_reg: crate::Reg, + #[doc = "0x04 - Status register"] + pub otpc_stat_reg: crate::Reg, + #[doc = "0x08 - The address of the word that will be programmed, when the PROG mode is used."] + pub otpc_paddr_reg: crate::Reg, + #[doc = "0x0c - The 32-bit word that will be programmed, when the PROG mode is used."] + pub otpc_pword_reg: crate::Reg, + #[doc = "0x10 - Various timing parameters of the OTP cell."] + pub otpc_tim1_reg: crate::Reg, + #[doc = "0x14 - Various timing parameters of the OTP cell."] + pub otpc_tim2_reg: crate::Reg, + #[doc = "0x18 - AHB master start address"] + pub otpc_ahbadr_reg: crate::Reg, + #[doc = "0x1c - OTP cell start address"] + pub otpc_celadr_reg: crate::Reg, + #[doc = "0x20 - Number of words"] + pub otpc_nwords_reg: crate::Reg, +} +#[doc = "OTPC_AHBADR_REG register accessor: an alias for `Reg`"] +pub type OTPC_AHBADR_REG = crate::Reg; +#[doc = "AHB master start address"] +pub mod otpc_ahbadr_reg; +#[doc = "OTPC_CELADR_REG register accessor: an alias for `Reg`"] +pub type OTPC_CELADR_REG = crate::Reg; +#[doc = "OTP cell start address"] +pub mod otpc_celadr_reg; +#[doc = "OTPC_MODE_REG register accessor: an alias for `Reg`"] +pub type OTPC_MODE_REG = crate::Reg; +#[doc = "Mode register"] +pub mod otpc_mode_reg; +#[doc = "OTPC_NWORDS_REG register accessor: an alias for `Reg`"] +pub type OTPC_NWORDS_REG = crate::Reg; +#[doc = "Number of words"] +pub mod otpc_nwords_reg; +#[doc = "OTPC_PADDR_REG register accessor: an alias for `Reg`"] +pub type OTPC_PADDR_REG = crate::Reg; +#[doc = "The address of the word that will be programmed, when the PROG mode is used."] +pub mod otpc_paddr_reg; +#[doc = "OTPC_PWORD_REG register accessor: an alias for `Reg`"] +pub type OTPC_PWORD_REG = crate::Reg; +#[doc = "The 32-bit word that will be programmed, when the PROG mode is used."] +pub mod otpc_pword_reg; +#[doc = "OTPC_STAT_REG register accessor: an alias for `Reg`"] +pub type OTPC_STAT_REG = crate::Reg; +#[doc = "Status register"] +pub mod otpc_stat_reg; +#[doc = "OTPC_TIM1_REG register accessor: an alias for `Reg`"] +pub type OTPC_TIM1_REG = crate::Reg; +#[doc = "Various timing parameters of the OTP cell."] +pub mod otpc_tim1_reg; +#[doc = "OTPC_TIM2_REG register accessor: an alias for `Reg`"] +pub type OTPC_TIM2_REG = crate::Reg; +#[doc = "Various timing parameters of the OTP cell."] +pub mod otpc_tim2_reg; diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_ahbadr_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_ahbadr_reg.rs new file mode 100644 index 0000000..58eee1c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_ahbadr_reg.rs @@ -0,0 +1,107 @@ +#[doc = "Register `OTPC_AHBADR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_AHBADR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_AHBADR` reader - It is the AHB address used by the AHB master interface of the controller (the bits \\[15:2\\]). The bits \\[1:0\\] +of the address are considered always as equal to zero. The value of the register remains unchanged, by the internal logic of the controller."] +pub struct OTPC_AHBADR_R(crate::FieldReader); +impl OTPC_AHBADR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + OTPC_AHBADR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_AHBADR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_AHBADR` writer - It is the AHB address used by the AHB master interface of the controller (the bits \\[15:2\\]). The bits \\[1:0\\] +of the address are considered always as equal to zero. The value of the register remains unchanged, by the internal logic of the controller."] +pub struct OTPC_AHBADR_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_AHBADR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3fff << 2)) | ((value as u32 & 0x3fff) << 2); + self.w + } +} +impl R { + #[doc = "Bits 2:15 - It is the AHB address used by the AHB master interface of the controller (the bits \\[15:2\\]). The bits \\[1:0\\] +of the address are considered always as equal to zero. The value of the register remains unchanged, by the internal logic of the controller."] + #[inline(always)] + pub fn otpc_ahbadr(&self) -> OTPC_AHBADR_R { + OTPC_AHBADR_R::new(((self.bits >> 2) & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 2:15 - It is the AHB address used by the AHB master interface of the controller (the bits \\[15:2\\]). The bits \\[1:0\\] +of the address are considered always as equal to zero. The value of the register remains unchanged, by the internal logic of the controller."] + #[inline(always)] + pub fn otpc_ahbadr(&mut self) -> OTPC_AHBADR_W { + OTPC_AHBADR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "AHB master start address\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_ahbadr_reg](index.html) module"] +pub struct OTPC_AHBADR_REG_SPEC; +impl crate::RegisterSpec for OTPC_AHBADR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_ahbadr_reg::R](R) reader structure"] +impl crate::Readable for OTPC_AHBADR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_ahbadr_reg::W](W) writer structure"] +impl crate::Writable for OTPC_AHBADR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_AHBADR_REG to value 0"] +impl crate::Resettable for OTPC_AHBADR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_celadr_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_celadr_reg.rs new file mode 100644 index 0000000..f43598f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_celadr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `OTPC_CELADR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_CELADR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_CELADR` reader - Defines a word address inside the OTP cell that will be used during the AREAD mode and the OTP mirroring."] +pub struct OTPC_CELADR_R(crate::FieldReader); +impl OTPC_CELADR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + OTPC_CELADR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_CELADR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_CELADR` writer - Defines a word address inside the OTP cell that will be used during the AREAD mode and the OTP mirroring."] +pub struct OTPC_CELADR_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_CELADR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1fff) | (value as u32 & 0x1fff); + self.w + } +} +impl R { + #[doc = "Bits 0:12 - Defines a word address inside the OTP cell that will be used during the AREAD mode and the OTP mirroring."] + #[inline(always)] + pub fn otpc_celadr(&self) -> OTPC_CELADR_R { + OTPC_CELADR_R::new((self.bits & 0x1fff) as u16) + } +} +impl W { + #[doc = "Bits 0:12 - Defines a word address inside the OTP cell that will be used during the AREAD mode and the OTP mirroring."] + #[inline(always)] + pub fn otpc_celadr(&mut self) -> OTPC_CELADR_W { + OTPC_CELADR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "OTP cell start address\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_celadr_reg](index.html) module"] +pub struct OTPC_CELADR_REG_SPEC; +impl crate::RegisterSpec for OTPC_CELADR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_celadr_reg::R](R) reader structure"] +impl crate::Readable for OTPC_CELADR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_celadr_reg::W](W) writer structure"] +impl crate::Writable for OTPC_CELADR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_CELADR_REG to value 0"] +impl crate::Resettable for OTPC_CELADR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_mode_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_mode_reg.rs new file mode 100644 index 0000000..ebf1924 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_mode_reg.rs @@ -0,0 +1,246 @@ +#[doc = "Register `OTPC_MODE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_MODE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_MODE_PRG_SEL` reader - Defines the part of the OTP cell that is programmed by the controller during the PROG mode, for each program request that is applied. 0x0 : Both normal and redundancy arrays are programmed. This is the normal way of programming. 0x1 : Only the normal array is programmed. 0x2 : Only the redundancy array is programmed. 0x3 : Reserved The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The setting will take effect when will be enabled again the PROG mode."] +pub struct OTPC_MODE_PRG_SEL_R(crate::FieldReader); +impl OTPC_MODE_PRG_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_MODE_PRG_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_MODE_PRG_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_MODE_PRG_SEL` writer - Defines the part of the OTP cell that is programmed by the controller during the PROG mode, for each program request that is applied. 0x0 : Both normal and redundancy arrays are programmed. This is the normal way of programming. 0x1 : Only the normal array is programmed. 0x2 : Only the redundancy array is programmed. 0x3 : Reserved The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The setting will take effect when will be enabled again the PROG mode."] +pub struct OTPC_MODE_PRG_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_MODE_PRG_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 6)) | ((value as u32 & 3) << 6); + self.w + } +} +#[doc = "Field `OTPC_MODE_HT_MARG_EN` reader - Defines the temperature condition under which is performed a margin read. It affects only the initial margin read (RINI mode) and the programming verification margin read (PVFY). 0 : Regular temperature condition (less than 85°C) 1 : High temperature condition (85°C or more) The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next PVFY or RINI mode that will be enabled. The READ mode is not affected by the setting of this configuration bit."] +pub struct OTPC_MODE_HT_MARG_EN_R(crate::FieldReader); +impl OTPC_MODE_HT_MARG_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTPC_MODE_HT_MARG_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_MODE_HT_MARG_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_MODE_HT_MARG_EN` writer - Defines the temperature condition under which is performed a margin read. It affects only the initial margin read (RINI mode) and the programming verification margin read (PVFY). 0 : Regular temperature condition (less than 85°C) 1 : High temperature condition (85°C or more) The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next PVFY or RINI mode that will be enabled. The READ mode is not affected by the setting of this configuration bit."] +pub struct OTPC_MODE_HT_MARG_EN_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_MODE_HT_MARG_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `OTPC_MODE_USE_TST_ROW` reader - Selects the memory area of the OTP cell that will be used. 0 - Uses the main memory area of the OTP cell 1 - Uses the test row of the OTP cell The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next programming or reading mode that will be enabled."] +pub struct OTPC_MODE_USE_TST_ROW_R(crate::FieldReader); +impl OTPC_MODE_USE_TST_ROW_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTPC_MODE_USE_TST_ROW_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_MODE_USE_TST_ROW_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_MODE_USE_TST_ROW` writer - Selects the memory area of the OTP cell that will be used. 0 - Uses the main memory area of the OTP cell 1 - Uses the test row of the OTP cell The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next programming or reading mode that will be enabled."] +pub struct OTPC_MODE_USE_TST_ROW_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_MODE_USE_TST_ROW_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `OTPC_MODE_MODE` reader - Defines the mode of operation of the OTPC controller. The encoding of the modes is as follows: 0x0: DSTBY. The OTP memory is in deep standby mode (power supply ON and internal LDO OFF). 0x1: STBY. The OTP memory is powered (power supply ON and internal LDO ON, but is not selected). 0x2: READ. The OTP memory is in the normal read mode. 0x3: PROG. The OTP memory is in programming mode. 0x4: PVFY. The OTP memory is in programming verification mode (margin read after programming). 0x5: RINI. The OTP memory is in initial read mode (initial margin read). 0x6: AREAD. Copying of data from the OTP memory to a system RAM by using the internal DMA. See also the registers OTPC_AHBADR_REG, OTPC_CELADR_REG and OTPC_NWORDS_REG. Whenever the OTPC_MODE_REG\\[MODE\\] +is changing, the status bit OTPC_STAT_REG\\[OTPC_STAT_MRDY\\] +gets the value zero. The new mode will be ready for use when the OTPC_STAT_MRDY become again 1. During the mode transition the OTPC_MODE_REG\\[MODE\\] +become read only. Do not try to use or change any function of the controller until the OTPC_STAT_MRDY bit to become equal to 1. The data transferring that is performed by using the AREAD mode is completed when OTPC_STAT_MRDY becomes again 1. The mode change automatically to DSTBY with the completion of the transfer."] +pub struct OTPC_MODE_MODE_R(crate::FieldReader); +impl OTPC_MODE_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_MODE_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_MODE_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_MODE_MODE` writer - Defines the mode of operation of the OTPC controller. The encoding of the modes is as follows: 0x0: DSTBY. The OTP memory is in deep standby mode (power supply ON and internal LDO OFF). 0x1: STBY. The OTP memory is powered (power supply ON and internal LDO ON, but is not selected). 0x2: READ. The OTP memory is in the normal read mode. 0x3: PROG. The OTP memory is in programming mode. 0x4: PVFY. The OTP memory is in programming verification mode (margin read after programming). 0x5: RINI. The OTP memory is in initial read mode (initial margin read). 0x6: AREAD. Copying of data from the OTP memory to a system RAM by using the internal DMA. See also the registers OTPC_AHBADR_REG, OTPC_CELADR_REG and OTPC_NWORDS_REG. Whenever the OTPC_MODE_REG\\[MODE\\] +is changing, the status bit OTPC_STAT_REG\\[OTPC_STAT_MRDY\\] +gets the value zero. The new mode will be ready for use when the OTPC_STAT_MRDY become again 1. During the mode transition the OTPC_MODE_REG\\[MODE\\] +become read only. Do not try to use or change any function of the controller until the OTPC_STAT_MRDY bit to become equal to 1. The data transferring that is performed by using the AREAD mode is completed when OTPC_STAT_MRDY becomes again 1. The mode change automatically to DSTBY with the completion of the transfer."] +pub struct OTPC_MODE_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_MODE_MODE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bits 6:7 - Defines the part of the OTP cell that is programmed by the controller during the PROG mode, for each program request that is applied. 0x0 : Both normal and redundancy arrays are programmed. This is the normal way of programming. 0x1 : Only the normal array is programmed. 0x2 : Only the redundancy array is programmed. 0x3 : Reserved The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The setting will take effect when will be enabled again the PROG mode."] + #[inline(always)] + pub fn otpc_mode_prg_sel(&self) -> OTPC_MODE_PRG_SEL_R { + OTPC_MODE_PRG_SEL_R::new(((self.bits >> 6) & 3) as u8) + } + #[doc = "Bit 5 - Defines the temperature condition under which is performed a margin read. It affects only the initial margin read (RINI mode) and the programming verification margin read (PVFY). 0 : Regular temperature condition (less than 85°C) 1 : High temperature condition (85°C or more) The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next PVFY or RINI mode that will be enabled. The READ mode is not affected by the setting of this configuration bit."] + #[inline(always)] + pub fn otpc_mode_ht_marg_en(&self) -> OTPC_MODE_HT_MARG_EN_R { + OTPC_MODE_HT_MARG_EN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Selects the memory area of the OTP cell that will be used. 0 - Uses the main memory area of the OTP cell 1 - Uses the test row of the OTP cell The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next programming or reading mode that will be enabled."] + #[inline(always)] + pub fn otpc_mode_use_tst_row(&self) -> OTPC_MODE_USE_TST_ROW_R { + OTPC_MODE_USE_TST_ROW_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 0:2 - Defines the mode of operation of the OTPC controller. The encoding of the modes is as follows: 0x0: DSTBY. The OTP memory is in deep standby mode (power supply ON and internal LDO OFF). 0x1: STBY. The OTP memory is powered (power supply ON and internal LDO ON, but is not selected). 0x2: READ. The OTP memory is in the normal read mode. 0x3: PROG. The OTP memory is in programming mode. 0x4: PVFY. The OTP memory is in programming verification mode (margin read after programming). 0x5: RINI. The OTP memory is in initial read mode (initial margin read). 0x6: AREAD. Copying of data from the OTP memory to a system RAM by using the internal DMA. See also the registers OTPC_AHBADR_REG, OTPC_CELADR_REG and OTPC_NWORDS_REG. Whenever the OTPC_MODE_REG\\[MODE\\] +is changing, the status bit OTPC_STAT_REG\\[OTPC_STAT_MRDY\\] +gets the value zero. The new mode will be ready for use when the OTPC_STAT_MRDY become again 1. During the mode transition the OTPC_MODE_REG\\[MODE\\] +become read only. Do not try to use or change any function of the controller until the OTPC_STAT_MRDY bit to become equal to 1. The data transferring that is performed by using the AREAD mode is completed when OTPC_STAT_MRDY becomes again 1. The mode change automatically to DSTBY with the completion of the transfer."] + #[inline(always)] + pub fn otpc_mode_mode(&self) -> OTPC_MODE_MODE_R { + OTPC_MODE_MODE_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 6:7 - Defines the part of the OTP cell that is programmed by the controller during the PROG mode, for each program request that is applied. 0x0 : Both normal and redundancy arrays are programmed. This is the normal way of programming. 0x1 : Only the normal array is programmed. 0x2 : Only the redundancy array is programmed. 0x3 : Reserved The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The setting will take effect when will be enabled again the PROG mode."] + #[inline(always)] + pub fn otpc_mode_prg_sel(&mut self) -> OTPC_MODE_PRG_SEL_W { + OTPC_MODE_PRG_SEL_W { w: self } + } + #[doc = "Bit 5 - Defines the temperature condition under which is performed a margin read. It affects only the initial margin read (RINI mode) and the programming verification margin read (PVFY). 0 : Regular temperature condition (less than 85°C) 1 : High temperature condition (85°C or more) The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next PVFY or RINI mode that will be enabled. The READ mode is not affected by the setting of this configuration bit."] + #[inline(always)] + pub fn otpc_mode_ht_marg_en(&mut self) -> OTPC_MODE_HT_MARG_EN_W { + OTPC_MODE_HT_MARG_EN_W { w: self } + } + #[doc = "Bit 4 - Selects the memory area of the OTP cell that will be used. 0 - Uses the main memory area of the OTP cell 1 - Uses the test row of the OTP cell The value of this configuration field can be modified only when the controller is in an inactive mode (DSTBY or STBY). The selection will take effect at the next programming or reading mode that will be enabled."] + #[inline(always)] + pub fn otpc_mode_use_tst_row(&mut self) -> OTPC_MODE_USE_TST_ROW_W { + OTPC_MODE_USE_TST_ROW_W { w: self } + } + #[doc = "Bits 0:2 - Defines the mode of operation of the OTPC controller. The encoding of the modes is as follows: 0x0: DSTBY. The OTP memory is in deep standby mode (power supply ON and internal LDO OFF). 0x1: STBY. The OTP memory is powered (power supply ON and internal LDO ON, but is not selected). 0x2: READ. The OTP memory is in the normal read mode. 0x3: PROG. The OTP memory is in programming mode. 0x4: PVFY. The OTP memory is in programming verification mode (margin read after programming). 0x5: RINI. The OTP memory is in initial read mode (initial margin read). 0x6: AREAD. Copying of data from the OTP memory to a system RAM by using the internal DMA. See also the registers OTPC_AHBADR_REG, OTPC_CELADR_REG and OTPC_NWORDS_REG. Whenever the OTPC_MODE_REG\\[MODE\\] +is changing, the status bit OTPC_STAT_REG\\[OTPC_STAT_MRDY\\] +gets the value zero. The new mode will be ready for use when the OTPC_STAT_MRDY become again 1. During the mode transition the OTPC_MODE_REG\\[MODE\\] +become read only. Do not try to use or change any function of the controller until the OTPC_STAT_MRDY bit to become equal to 1. The data transferring that is performed by using the AREAD mode is completed when OTPC_STAT_MRDY becomes again 1. The mode change automatically to DSTBY with the completion of the transfer."] + #[inline(always)] + pub fn otpc_mode_mode(&mut self) -> OTPC_MODE_MODE_W { + OTPC_MODE_MODE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Mode register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_mode_reg](index.html) module"] +pub struct OTPC_MODE_REG_SPEC; +impl crate::RegisterSpec for OTPC_MODE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_mode_reg::R](R) reader structure"] +impl crate::Readable for OTPC_MODE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_mode_reg::W](W) writer structure"] +impl crate::Writable for OTPC_MODE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_MODE_REG to value 0"] +impl crate::Resettable for OTPC_MODE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_nwords_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_nwords_reg.rs new file mode 100644 index 0000000..cf0694e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_nwords_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `OTPC_NWORDS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_NWORDS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_NWORDS` reader - The number of words (minus one) that will be copied by the AREAD mode. During mirroring, this register reflects the amount of data that will be copied."] +pub struct OTPC_NWORDS_R(crate::FieldReader); +impl OTPC_NWORDS_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + OTPC_NWORDS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_NWORDS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_NWORDS` writer - The number of words (minus one) that will be copied by the AREAD mode. During mirroring, this register reflects the amount of data that will be copied."] +pub struct OTPC_NWORDS_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_NWORDS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1fff) | (value as u32 & 0x1fff); + self.w + } +} +impl R { + #[doc = "Bits 0:12 - The number of words (minus one) that will be copied by the AREAD mode. During mirroring, this register reflects the amount of data that will be copied."] + #[inline(always)] + pub fn otpc_nwords(&self) -> OTPC_NWORDS_R { + OTPC_NWORDS_R::new((self.bits & 0x1fff) as u16) + } +} +impl W { + #[doc = "Bits 0:12 - The number of words (minus one) that will be copied by the AREAD mode. During mirroring, this register reflects the amount of data that will be copied."] + #[inline(always)] + pub fn otpc_nwords(&mut self) -> OTPC_NWORDS_W { + OTPC_NWORDS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Number of words\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_nwords_reg](index.html) module"] +pub struct OTPC_NWORDS_REG_SPEC; +impl crate::RegisterSpec for OTPC_NWORDS_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_nwords_reg::R](R) reader structure"] +impl crate::Readable for OTPC_NWORDS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_nwords_reg::W](W) writer structure"] +impl crate::Writable for OTPC_NWORDS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_NWORDS_REG to value 0"] +impl crate::Resettable for OTPC_NWORDS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_paddr_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_paddr_reg.rs new file mode 100644 index 0000000..902c9be --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_paddr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `OTPC_PADDR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_PADDR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_PADDR` reader - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTPC_PADDR_REG refers to a word address. The OTPC_PADDR_REG has to be writen after the OTP_PWORD_REG and only if the OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0). A writting to the OTPC_PADDR_REG triggers the controller to start the programming procedure (only if the PROG mode is active)."] +pub struct OTPC_PADDR_R(crate::FieldReader); +impl OTPC_PADDR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + OTPC_PADDR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_PADDR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_PADDR` writer - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTPC_PADDR_REG refers to a word address. The OTPC_PADDR_REG has to be writen after the OTP_PWORD_REG and only if the OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0). A writting to the OTPC_PADDR_REG triggers the controller to start the programming procedure (only if the PROG mode is active)."] +pub struct OTPC_PADDR_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_PADDR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1fff) | (value as u32 & 0x1fff); + self.w + } +} +impl R { + #[doc = "Bits 0:12 - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTPC_PADDR_REG refers to a word address. The OTPC_PADDR_REG has to be writen after the OTP_PWORD_REG and only if the OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0). A writting to the OTPC_PADDR_REG triggers the controller to start the programming procedure (only if the PROG mode is active)."] + #[inline(always)] + pub fn otpc_paddr(&self) -> OTPC_PADDR_R { + OTPC_PADDR_R::new((self.bits & 0x1fff) as u16) + } +} +impl W { + #[doc = "Bits 0:12 - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTPC_PADDR_REG refers to a word address. The OTPC_PADDR_REG has to be writen after the OTP_PWORD_REG and only if the OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0). A writting to the OTPC_PADDR_REG triggers the controller to start the programming procedure (only if the PROG mode is active)."] + #[inline(always)] + pub fn otpc_paddr(&mut self) -> OTPC_PADDR_W { + OTPC_PADDR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "The address of the word that will be programmed, when the PROG mode is used.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_paddr_reg](index.html) module"] +pub struct OTPC_PADDR_REG_SPEC; +impl crate::RegisterSpec for OTPC_PADDR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_paddr_reg::R](R) reader structure"] +impl crate::Readable for OTPC_PADDR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_paddr_reg::W](W) writer structure"] +impl crate::Writable for OTPC_PADDR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_PADDR_REG to value 0"] +impl crate::Resettable for OTPC_PADDR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_pword_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_pword_reg.rs new file mode 100644 index 0000000..e3eee44 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_pword_reg.rs @@ -0,0 +1,107 @@ +#[doc = "Register `OTPC_PWORD_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_PWORD_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_PWORD` reader - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP memory, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTP_PWORD_REG must be written before the OTPC_PADDR_REG and only if OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\] += 1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0)."] +pub struct OTPC_PWORD_R(crate::FieldReader); +impl OTPC_PWORD_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + OTPC_PWORD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_PWORD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_PWORD` writer - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP memory, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTP_PWORD_REG must be written before the OTPC_PADDR_REG and only if OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\] += 1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0)."] +pub struct OTPC_PWORD_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_PWORD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31 - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP memory, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTP_PWORD_REG must be written before the OTPC_PADDR_REG and only if OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\] += 1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0)."] + #[inline(always)] + pub fn otpc_pword(&self) -> OTPC_PWORD_R { + OTPC_PWORD_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31 - The OTPC_PADDR_REG and the OTPC_PWORD_REG consist the PBUF buffer that keeps the information that will be programmed in the OTP memory, by using the PROG mode. The PBUF holds the address (OTPC_PADDR_REG) and the data (OTPC_PWORD_REG) of each of the programming requests that are applied in the OTP memory. The OTP_PWORD_REG must be written before the OTPC_PADDR_REG and only if OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\] += 1. The register is read only for as long the PBUF is not empty (OTPC_STAT_REG\\[OTPC_STAT_PBUF_EMPTY\\]=0)."] + #[inline(always)] + pub fn otpc_pword(&mut self) -> OTPC_PWORD_W { + OTPC_PWORD_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "The 32-bit word that will be programmed, when the PROG mode is used.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_pword_reg](index.html) module"] +pub struct OTPC_PWORD_REG_SPEC; +impl crate::RegisterSpec for OTPC_PWORD_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_pword_reg::R](R) reader structure"] +impl crate::Readable for OTPC_PWORD_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_pword_reg::W](W) writer structure"] +impl crate::Writable for OTPC_PWORD_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_PWORD_REG to value 0"] +impl crate::Resettable for OTPC_PWORD_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_stat_reg.rs new file mode 100644 index 0000000..dffa4e3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_stat_reg.rs @@ -0,0 +1,128 @@ +#[doc = "Register `OTPC_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_STAT_MRDY` reader - Indicates the progress of the transition from a mode of operation to a new mode of operation. 0 : There is a transition in progress in a new mode of operation . Wait until the transition to be completed. 1 : The transition to the new mode of operation has been completed. The function that has been enabled by the new mode can be used. A new mode can be applied. This status bit gets the value zero every time where the OTPC_MODE_REG\\[MODE\\] +is changing. Do not try to use or change any function of the controller until this status bit to become equal to 1."] +pub struct OTPC_STAT_MRDY_R(crate::FieldReader); +impl OTPC_STAT_MRDY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTPC_STAT_MRDY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_STAT_MRDY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_STAT_PBUF_EMPTY` reader - Indicates the status of the programming buffer (PBUF). 0 : The PBUF contains the address and the data of a programming request. The OTPC_PADDR_REG and the OTPC_PWORD_REG should not be written as long as this status bit is zero. 1 : The PBUF is empty and a new programming request can be registered in the PBUF by using the OTPC_PADDR_REG and the OTPC_PWORD_REG registers. This status bit gets the value zero every time where a programming is triggered by the OTPC_PADDR_REG (only if the PROG mode is active)."] +pub struct OTPC_STAT_PBUF_EMPTY_R(crate::FieldReader); +impl OTPC_STAT_PBUF_EMPTY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTPC_STAT_PBUF_EMPTY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_STAT_PBUF_EMPTY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_STAT_PRDY` reader - Indicates the state of the programming process. 0: The controller is busy. A programming is in progress. 1: The logic which performs programming is idle."] +pub struct OTPC_STAT_PRDY_R(crate::FieldReader); +impl OTPC_STAT_PRDY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTPC_STAT_PRDY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_STAT_PRDY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 2 - Indicates the progress of the transition from a mode of operation to a new mode of operation. 0 : There is a transition in progress in a new mode of operation . Wait until the transition to be completed. 1 : The transition to the new mode of operation has been completed. The function that has been enabled by the new mode can be used. A new mode can be applied. This status bit gets the value zero every time where the OTPC_MODE_REG\\[MODE\\] +is changing. Do not try to use or change any function of the controller until this status bit to become equal to 1."] + #[inline(always)] + pub fn otpc_stat_mrdy(&self) -> OTPC_STAT_MRDY_R { + OTPC_STAT_MRDY_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Indicates the status of the programming buffer (PBUF). 0 : The PBUF contains the address and the data of a programming request. The OTPC_PADDR_REG and the OTPC_PWORD_REG should not be written as long as this status bit is zero. 1 : The PBUF is empty and a new programming request can be registered in the PBUF by using the OTPC_PADDR_REG and the OTPC_PWORD_REG registers. This status bit gets the value zero every time where a programming is triggered by the OTPC_PADDR_REG (only if the PROG mode is active)."] + #[inline(always)] + pub fn otpc_stat_pbuf_empty(&self) -> OTPC_STAT_PBUF_EMPTY_R { + OTPC_STAT_PBUF_EMPTY_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Indicates the state of the programming process. 0: The controller is busy. A programming is in progress. 1: The logic which performs programming is idle."] + #[inline(always)] + pub fn otpc_stat_prdy(&self) -> OTPC_STAT_PRDY_R { + OTPC_STAT_PRDY_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_stat_reg](index.html) module"] +pub struct OTPC_STAT_REG_SPEC; +impl crate::RegisterSpec for OTPC_STAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_stat_reg::R](R) reader structure"] +impl crate::Readable for OTPC_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_stat_reg::W](W) writer structure"] +impl crate::Writable for OTPC_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_STAT_REG to value 0x07"] +impl crate::Resettable for OTPC_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_tim1_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_tim1_reg.rs new file mode 100644 index 0000000..2da7a6c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_tim1_reg.rs @@ -0,0 +1,288 @@ +#[doc = "Register `OTPC_TIM1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_TIM1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_TIM1_US_T_CSP` reader - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for programming. It must be : - at least 10us - no more than 100us"] +pub struct OTPC_TIM1_US_T_CSP_R(crate::FieldReader); +impl OTPC_TIM1_US_T_CSP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM1_US_T_CSP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM1_US_T_CSP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM1_US_T_CSP` writer - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for programming. It must be : - at least 10us - no more than 100us"] +pub struct OTPC_TIM1_US_T_CSP_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM1_US_T_CSP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 24)) | ((value as u32 & 0x7f) << 24); + self.w + } +} +#[doc = "Field `OTPC_TIM1_US_T_CS` reader - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for any kind of read. It must be at least 10us."] +pub struct OTPC_TIM1_US_T_CS_R(crate::FieldReader); +impl OTPC_TIM1_US_T_CS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM1_US_T_CS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM1_US_T_CS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM1_US_T_CS` writer - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for any kind of read. It must be at least 10us."] +pub struct OTPC_TIM1_US_T_CS_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM1_US_T_CS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 20)) | ((value as u32 & 0x0f) << 20); + self.w + } +} +#[doc = "Field `OTPC_TIM1_US_T_PL` reader - The number of microseconds (minus one) that are required until to be enabled the LDO of the OTP. It must be at least 10us."] +pub struct OTPC_TIM1_US_T_PL_R(crate::FieldReader); +impl OTPC_TIM1_US_T_PL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM1_US_T_PL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM1_US_T_PL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM1_US_T_PL` writer - The number of microseconds (minus one) that are required until to be enabled the LDO of the OTP. It must be at least 10us."] +pub struct OTPC_TIM1_US_T_PL_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM1_US_T_PL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); + self.w + } +} +#[doc = "Field `OTPC_TIM1_CC_T_RD` reader - The number of hclk_c clock periods (minus one) that give a time interval at least higher than 60ns. This timing parameter refers to the access time of the OTP memory."] +pub struct OTPC_TIM1_CC_T_RD_R(crate::FieldReader); +impl OTPC_TIM1_CC_T_RD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM1_CC_T_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM1_CC_T_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM1_CC_T_RD` writer - The number of hclk_c clock periods (minus one) that give a time interval at least higher than 60ns. This timing parameter refers to the access time of the OTP memory."] +pub struct OTPC_TIM1_CC_T_RD_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM1_CC_T_RD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 12)) | ((value as u32 & 7) << 12); + self.w + } +} +#[doc = "Field `OTPC_TIM1_CC_T_20NS` reader - The number of hclk_c clock periods (minus one) that give a time interval that is at least higher than 20 ns."] +pub struct OTPC_TIM1_CC_T_20NS_R(crate::FieldReader); +impl OTPC_TIM1_CC_T_20NS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM1_CC_T_20NS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM1_CC_T_20NS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM1_CC_T_20NS` writer - The number of hclk_c clock periods (minus one) that give a time interval that is at least higher than 20 ns."] +pub struct OTPC_TIM1_CC_T_20NS_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM1_CC_T_20NS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u32 & 3) << 8); + self.w + } +} +#[doc = "Field `OTPC_TIM1_CC_T_1US` reader - The number of hclk_c clock periods (minus one) that give a time interval equal to 1us. This setting affects all the timing parameters that refer to microseconds, due to that defines the correspondence of a microsecond to a number of hclk_c clock cycles."] +pub struct OTPC_TIM1_CC_T_1US_R(crate::FieldReader); +impl OTPC_TIM1_CC_T_1US_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM1_CC_T_1US_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM1_CC_T_1US_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM1_CC_T_1US` writer - The number of hclk_c clock periods (minus one) that give a time interval equal to 1us. This setting affects all the timing parameters that refer to microseconds, due to that defines the correspondence of a microsecond to a number of hclk_c clock cycles."] +pub struct OTPC_TIM1_CC_T_1US_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM1_CC_T_1US_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x7f) | (value as u32 & 0x7f); + self.w + } +} +impl R { + #[doc = "Bits 24:30 - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for programming. It must be : - at least 10us - no more than 100us"] + #[inline(always)] + pub fn otpc_tim1_us_t_csp(&self) -> OTPC_TIM1_US_T_CSP_R { + OTPC_TIM1_US_T_CSP_R::new(((self.bits >> 24) & 0x7f) as u8) + } + #[doc = "Bits 20:23 - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for any kind of read. It must be at least 10us."] + #[inline(always)] + pub fn otpc_tim1_us_t_cs(&self) -> OTPC_TIM1_US_T_CS_R { + OTPC_TIM1_US_T_CS_R::new(((self.bits >> 20) & 0x0f) as u8) + } + #[doc = "Bits 16:19 - The number of microseconds (minus one) that are required until to be enabled the LDO of the OTP. It must be at least 10us."] + #[inline(always)] + pub fn otpc_tim1_us_t_pl(&self) -> OTPC_TIM1_US_T_PL_R { + OTPC_TIM1_US_T_PL_R::new(((self.bits >> 16) & 0x0f) as u8) + } + #[doc = "Bits 12:14 - The number of hclk_c clock periods (minus one) that give a time interval at least higher than 60ns. This timing parameter refers to the access time of the OTP memory."] + #[inline(always)] + pub fn otpc_tim1_cc_t_rd(&self) -> OTPC_TIM1_CC_T_RD_R { + OTPC_TIM1_CC_T_RD_R::new(((self.bits >> 12) & 7) as u8) + } + #[doc = "Bits 8:9 - The number of hclk_c clock periods (minus one) that give a time interval that is at least higher than 20 ns."] + #[inline(always)] + pub fn otpc_tim1_cc_t_20ns(&self) -> OTPC_TIM1_CC_T_20NS_R { + OTPC_TIM1_CC_T_20NS_R::new(((self.bits >> 8) & 3) as u8) + } + #[doc = "Bits 0:6 - The number of hclk_c clock periods (minus one) that give a time interval equal to 1us. This setting affects all the timing parameters that refer to microseconds, due to that defines the correspondence of a microsecond to a number of hclk_c clock cycles."] + #[inline(always)] + pub fn otpc_tim1_cc_t_1us(&self) -> OTPC_TIM1_CC_T_1US_R { + OTPC_TIM1_CC_T_1US_R::new((self.bits & 0x7f) as u8) + } +} +impl W { + #[doc = "Bits 24:30 - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for programming. It must be : - at least 10us - no more than 100us"] + #[inline(always)] + pub fn otpc_tim1_us_t_csp(&mut self) -> OTPC_TIM1_US_T_CSP_W { + OTPC_TIM1_US_T_CSP_W { w: self } + } + #[doc = "Bits 20:23 - The number of microseconds (minus one) that are required after the selection of the OTP memory, until to be ready for any kind of read. It must be at least 10us."] + #[inline(always)] + pub fn otpc_tim1_us_t_cs(&mut self) -> OTPC_TIM1_US_T_CS_W { + OTPC_TIM1_US_T_CS_W { w: self } + } + #[doc = "Bits 16:19 - The number of microseconds (minus one) that are required until to be enabled the LDO of the OTP. It must be at least 10us."] + #[inline(always)] + pub fn otpc_tim1_us_t_pl(&mut self) -> OTPC_TIM1_US_T_PL_W { + OTPC_TIM1_US_T_PL_W { w: self } + } + #[doc = "Bits 12:14 - The number of hclk_c clock periods (minus one) that give a time interval at least higher than 60ns. This timing parameter refers to the access time of the OTP memory."] + #[inline(always)] + pub fn otpc_tim1_cc_t_rd(&mut self) -> OTPC_TIM1_CC_T_RD_W { + OTPC_TIM1_CC_T_RD_W { w: self } + } + #[doc = "Bits 8:9 - The number of hclk_c clock periods (minus one) that give a time interval that is at least higher than 20 ns."] + #[inline(always)] + pub fn otpc_tim1_cc_t_20ns(&mut self) -> OTPC_TIM1_CC_T_20NS_W { + OTPC_TIM1_CC_T_20NS_W { w: self } + } + #[doc = "Bits 0:6 - The number of hclk_c clock periods (minus one) that give a time interval equal to 1us. This setting affects all the timing parameters that refer to microseconds, due to that defines the correspondence of a microsecond to a number of hclk_c clock cycles."] + #[inline(always)] + pub fn otpc_tim1_cc_t_1us(&mut self) -> OTPC_TIM1_CC_T_1US_W { + OTPC_TIM1_CC_T_1US_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Various timing parameters of the OTP cell.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_tim1_reg](index.html) module"] +pub struct OTPC_TIM1_REG_SPEC; +impl crate::RegisterSpec for OTPC_TIM1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_tim1_reg::R](R) reader structure"] +impl crate::Readable for OTPC_TIM1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_tim1_reg::W](W) writer structure"] +impl crate::Writable for OTPC_TIM1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_TIM1_REG to value 0x0999_000f"] +impl crate::Resettable for OTPC_TIM1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0999_000f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/otpc/otpc_tim2_reg.rs b/bitbox02-bt/vendor/da14531/src/otpc/otpc_tim2_reg.rs new file mode 100644 index 0000000..509d88b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/otpc/otpc_tim2_reg.rs @@ -0,0 +1,372 @@ +#[doc = "Register `OTPC_TIM2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `OTPC_TIM2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `OTPC_TIM2_US_ADD_CC_EN` reader - Adds an additional hclk_c clock cycle at all the time intervals that count in microseconds. 0 : The extra hclk_c clock cycle is not applied 1 : The extra hclk_c clock cycle is applied"] +pub struct OTPC_TIM2_US_ADD_CC_EN_R(crate::FieldReader); +impl OTPC_TIM2_US_ADD_CC_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OTPC_TIM2_US_ADD_CC_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_ADD_CC_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_ADD_CC_EN` writer - Adds an additional hclk_c clock cycle at all the time intervals that count in microseconds. 0 : The extra hclk_c clock cycle is not applied 1 : The extra hclk_c clock cycle is applied"] +pub struct OTPC_TIM2_US_ADD_CC_EN_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_ADD_CC_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `OTPC_TIM2_US_T_SAS` reader - The number of microseconds (minus one) that are required after the exit from the deep sleep standby mode and before to become ready to enter in an active mode (reading or programming). It must be at least 2us."] +pub struct OTPC_TIM2_US_T_SAS_R(crate::FieldReader); +impl OTPC_TIM2_US_T_SAS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM2_US_T_SAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_T_SAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_T_SAS` writer - The number of microseconds (minus one) that are required after the exit from the deep sleep standby mode and before to become ready to enter in an active mode (reading or programming). It must be at least 2us."] +pub struct OTPC_TIM2_US_T_SAS_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_T_SAS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 29)) | ((value as u32 & 3) << 29); + self.w + } +} +#[doc = "Field `OTPC_TIM2_US_T_PPH` reader - The number of microseconds (minus one) that are required after the last programming pulse and before to be disabled the programming mode in the OTP memory. It must be: - at least 5us - no more than 20us"] +pub struct OTPC_TIM2_US_T_PPH_R(crate::FieldReader); +impl OTPC_TIM2_US_T_PPH_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM2_US_T_PPH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_T_PPH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_T_PPH` writer - The number of microseconds (minus one) that are required after the last programming pulse and before to be disabled the programming mode in the OTP memory. It must be: - at least 5us - no more than 20us"] +pub struct OTPC_TIM2_US_T_PPH_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_T_PPH_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 24)) | ((value as u32 & 0x1f) << 24); + self.w + } +} +#[doc = "Field `OTPC_TIM2_US_T_VDS` reader - The number of microseconds (minus one) that are required after the enabling of the power supply of the OTP memory and before to become ready for the enabling of the internal LDO. It must be at least 1us."] +pub struct OTPC_TIM2_US_T_VDS_R(crate::FieldReader); +impl OTPC_TIM2_US_T_VDS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM2_US_T_VDS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_T_VDS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_T_VDS` writer - The number of microseconds (minus one) that are required after the enabling of the power supply of the OTP memory and before to become ready for the enabling of the internal LDO. It must be at least 1us."] +pub struct OTPC_TIM2_US_T_VDS_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_T_VDS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 21)) | ((value as u32 & 7) << 21); + self.w + } +} +#[doc = "Field `OTPC_TIM2_US_T_PPS` reader - The number of microseconds (minus one) that are required after the enabling of the programming in the OTP memory and before to be applied the first programming pulse. It must be : - at least 5us - no more than 20us"] +pub struct OTPC_TIM2_US_T_PPS_R(crate::FieldReader); +impl OTPC_TIM2_US_T_PPS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM2_US_T_PPS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_T_PPS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_T_PPS` writer - The number of microseconds (minus one) that are required after the enabling of the programming in the OTP memory and before to be applied the first programming pulse. It must be : - at least 5us - no more than 20us"] +pub struct OTPC_TIM2_US_T_PPS_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_T_PPS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 16)) | ((value as u32 & 0x1f) << 16); + self.w + } +} +#[doc = "Field `OTPC_TIM2_US_T_PPR` reader - The number of microseconds (minus one) for recovery after a programming sequence. It must be : - at least 5us - no more than 100us"] +pub struct OTPC_TIM2_US_T_PPR_R(crate::FieldReader); +impl OTPC_TIM2_US_T_PPR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM2_US_T_PPR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_T_PPR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_T_PPR` writer - The number of microseconds (minus one) for recovery after a programming sequence. It must be : - at least 5us - no more than 100us"] +pub struct OTPC_TIM2_US_T_PPR_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_T_PPR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 8)) | ((value as u32 & 0x7f) << 8); + self.w + } +} +#[doc = "Field `OTPC_TIM2_US_T_PWI` reader - The number of microseconds (minus one) between two consecutive programming pulses. It must be : - at least 1us - no more than 5us"] +pub struct OTPC_TIM2_US_T_PWI_R(crate::FieldReader); +impl OTPC_TIM2_US_T_PWI_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM2_US_T_PWI_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_T_PWI_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_T_PWI` writer - The number of microseconds (minus one) between two consecutive programming pulses. It must be : - at least 1us - no more than 5us"] +pub struct OTPC_TIM2_US_T_PWI_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_T_PWI_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 5)) | ((value as u32 & 7) << 5); + self.w + } +} +#[doc = "Field `OTPC_TIM2_US_T_PW` reader - The number of microseconds (minus one) that lasts the programming of each bit. It must be : - at least 10us - no more than 20us"] +pub struct OTPC_TIM2_US_T_PW_R(crate::FieldReader); +impl OTPC_TIM2_US_T_PW_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + OTPC_TIM2_US_T_PW_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OTPC_TIM2_US_T_PW_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OTPC_TIM2_US_T_PW` writer - The number of microseconds (minus one) that lasts the programming of each bit. It must be : - at least 10us - no more than 20us"] +pub struct OTPC_TIM2_US_T_PW_W<'a> { + w: &'a mut W, +} +impl<'a> OTPC_TIM2_US_T_PW_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bit 31 - Adds an additional hclk_c clock cycle at all the time intervals that count in microseconds. 0 : The extra hclk_c clock cycle is not applied 1 : The extra hclk_c clock cycle is applied"] + #[inline(always)] + pub fn otpc_tim2_us_add_cc_en(&self) -> OTPC_TIM2_US_ADD_CC_EN_R { + OTPC_TIM2_US_ADD_CC_EN_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bits 29:30 - The number of microseconds (minus one) that are required after the exit from the deep sleep standby mode and before to become ready to enter in an active mode (reading or programming). It must be at least 2us."] + #[inline(always)] + pub fn otpc_tim2_us_t_sas(&self) -> OTPC_TIM2_US_T_SAS_R { + OTPC_TIM2_US_T_SAS_R::new(((self.bits >> 29) & 3) as u8) + } + #[doc = "Bits 24:28 - The number of microseconds (minus one) that are required after the last programming pulse and before to be disabled the programming mode in the OTP memory. It must be: - at least 5us - no more than 20us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pph(&self) -> OTPC_TIM2_US_T_PPH_R { + OTPC_TIM2_US_T_PPH_R::new(((self.bits >> 24) & 0x1f) as u8) + } + #[doc = "Bits 21:23 - The number of microseconds (minus one) that are required after the enabling of the power supply of the OTP memory and before to become ready for the enabling of the internal LDO. It must be at least 1us."] + #[inline(always)] + pub fn otpc_tim2_us_t_vds(&self) -> OTPC_TIM2_US_T_VDS_R { + OTPC_TIM2_US_T_VDS_R::new(((self.bits >> 21) & 7) as u8) + } + #[doc = "Bits 16:20 - The number of microseconds (minus one) that are required after the enabling of the programming in the OTP memory and before to be applied the first programming pulse. It must be : - at least 5us - no more than 20us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pps(&self) -> OTPC_TIM2_US_T_PPS_R { + OTPC_TIM2_US_T_PPS_R::new(((self.bits >> 16) & 0x1f) as u8) + } + #[doc = "Bits 8:14 - The number of microseconds (minus one) for recovery after a programming sequence. It must be : - at least 5us - no more than 100us"] + #[inline(always)] + pub fn otpc_tim2_us_t_ppr(&self) -> OTPC_TIM2_US_T_PPR_R { + OTPC_TIM2_US_T_PPR_R::new(((self.bits >> 8) & 0x7f) as u8) + } + #[doc = "Bits 5:7 - The number of microseconds (minus one) between two consecutive programming pulses. It must be : - at least 1us - no more than 5us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pwi(&self) -> OTPC_TIM2_US_T_PWI_R { + OTPC_TIM2_US_T_PWI_R::new(((self.bits >> 5) & 7) as u8) + } + #[doc = "Bits 0:4 - The number of microseconds (minus one) that lasts the programming of each bit. It must be : - at least 10us - no more than 20us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pw(&self) -> OTPC_TIM2_US_T_PW_R { + OTPC_TIM2_US_T_PW_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bit 31 - Adds an additional hclk_c clock cycle at all the time intervals that count in microseconds. 0 : The extra hclk_c clock cycle is not applied 1 : The extra hclk_c clock cycle is applied"] + #[inline(always)] + pub fn otpc_tim2_us_add_cc_en(&mut self) -> OTPC_TIM2_US_ADD_CC_EN_W { + OTPC_TIM2_US_ADD_CC_EN_W { w: self } + } + #[doc = "Bits 29:30 - The number of microseconds (minus one) that are required after the exit from the deep sleep standby mode and before to become ready to enter in an active mode (reading or programming). It must be at least 2us."] + #[inline(always)] + pub fn otpc_tim2_us_t_sas(&mut self) -> OTPC_TIM2_US_T_SAS_W { + OTPC_TIM2_US_T_SAS_W { w: self } + } + #[doc = "Bits 24:28 - The number of microseconds (minus one) that are required after the last programming pulse and before to be disabled the programming mode in the OTP memory. It must be: - at least 5us - no more than 20us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pph(&mut self) -> OTPC_TIM2_US_T_PPH_W { + OTPC_TIM2_US_T_PPH_W { w: self } + } + #[doc = "Bits 21:23 - The number of microseconds (minus one) that are required after the enabling of the power supply of the OTP memory and before to become ready for the enabling of the internal LDO. It must be at least 1us."] + #[inline(always)] + pub fn otpc_tim2_us_t_vds(&mut self) -> OTPC_TIM2_US_T_VDS_W { + OTPC_TIM2_US_T_VDS_W { w: self } + } + #[doc = "Bits 16:20 - The number of microseconds (minus one) that are required after the enabling of the programming in the OTP memory and before to be applied the first programming pulse. It must be : - at least 5us - no more than 20us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pps(&mut self) -> OTPC_TIM2_US_T_PPS_W { + OTPC_TIM2_US_T_PPS_W { w: self } + } + #[doc = "Bits 8:14 - The number of microseconds (minus one) for recovery after a programming sequence. It must be : - at least 5us - no more than 100us"] + #[inline(always)] + pub fn otpc_tim2_us_t_ppr(&mut self) -> OTPC_TIM2_US_T_PPR_W { + OTPC_TIM2_US_T_PPR_W { w: self } + } + #[doc = "Bits 5:7 - The number of microseconds (minus one) between two consecutive programming pulses. It must be : - at least 1us - no more than 5us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pwi(&mut self) -> OTPC_TIM2_US_T_PWI_W { + OTPC_TIM2_US_T_PWI_W { w: self } + } + #[doc = "Bits 0:4 - The number of microseconds (minus one) that lasts the programming of each bit. It must be : - at least 10us - no more than 20us"] + #[inline(always)] + pub fn otpc_tim2_us_t_pw(&mut self) -> OTPC_TIM2_US_T_PW_W { + OTPC_TIM2_US_T_PW_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Various timing parameters of the OTP cell.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otpc_tim2_reg](index.html) module"] +pub struct OTPC_TIM2_REG_SPEC; +impl crate::RegisterSpec for OTPC_TIM2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [otpc_tim2_reg::R](R) reader structure"] +impl crate::Readable for OTPC_TIM2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [otpc_tim2_reg::W](W) writer structure"] +impl crate::Writable for OTPC_TIM2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets OTPC_TIM2_REG to value 0x7fff_ffff"] +impl crate::Resettable for OTPC_TIM2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7fff_ffff + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch.rs b/bitbox02-bt/vendor/da14531/src/patch.rs new file mode 100644 index 0000000..946a951 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch.rs @@ -0,0 +1,175 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - "] + pub patch_valid_reg: crate::Reg, + _reserved1: [u8; 0x1c], + #[doc = "0x20 - "] + pub patch_addr0_reg: crate::Reg, + _reserved2: [u8; 0x04], + #[doc = "0x28 - "] + pub patch_addr1_reg: crate::Reg, + _reserved3: [u8; 0x04], + #[doc = "0x30 - "] + pub patch_addr2_reg: crate::Reg, + _reserved4: [u8; 0x04], + #[doc = "0x38 - "] + pub patch_addr3_reg: crate::Reg, + _reserved5: [u8; 0x04], + #[doc = "0x40 - "] + pub patch_addr4_reg: crate::Reg, + _reserved6: [u8; 0x04], + #[doc = "0x48 - "] + pub patch_addr5_reg: crate::Reg, + _reserved7: [u8; 0x04], + #[doc = "0x50 - "] + pub patch_addr6_reg: crate::Reg, + _reserved8: [u8; 0x04], + #[doc = "0x58 - "] + pub patch_addr7_reg: crate::Reg, + _reserved9: [u8; 0x04], + #[doc = "0x60 - "] + pub patch_addr8_reg: crate::Reg, + _reserved10: [u8; 0x04], + #[doc = "0x68 - "] + pub patch_addr9_reg: crate::Reg, + _reserved11: [u8; 0x04], + #[doc = "0x70 - "] + pub patch_addr10_reg: crate::Reg, + _reserved12: [u8; 0x04], + #[doc = "0x78 - "] + pub patch_addr11_reg: crate::Reg, + _reserved13: [u8; 0x04], + #[doc = "0x80 - "] + pub patch_addr12_reg: crate::Reg, + _reserved14: [u8; 0x04], + #[doc = "0x88 - "] + pub patch_addr13_reg: crate::Reg, + _reserved15: [u8; 0x04], + #[doc = "0x90 - "] + pub patch_addr14_reg: crate::Reg, + _reserved16: [u8; 0x04], + #[doc = "0x98 - "] + pub patch_addr15_reg: crate::Reg, + _reserved17: [u8; 0x04], + #[doc = "0xa0 - "] + pub patch_addr16_reg: crate::Reg, + _reserved18: [u8; 0x04], + #[doc = "0xa8 - "] + pub patch_addr17_reg: crate::Reg, + _reserved19: [u8; 0x04], + #[doc = "0xb0 - "] + pub patch_addr18_reg: crate::Reg, + _reserved20: [u8; 0x04], + #[doc = "0xb8 - "] + pub patch_addr19_reg: crate::Reg, + _reserved21: [u8; 0x04], + #[doc = "0xc0 - "] + pub patch_addr20_reg: crate::Reg, + #[doc = "0xc4 - "] + pub patch_data20_reg: crate::Reg, + #[doc = "0xc8 - "] + pub patch_addr21_reg: crate::Reg, + #[doc = "0xcc - "] + pub patch_data21_reg: crate::Reg, +} +#[doc = "PATCH_ADDR0_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR0_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr0_reg; +#[doc = "PATCH_ADDR10_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR10_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr10_reg; +#[doc = "PATCH_ADDR11_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR11_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr11_reg; +#[doc = "PATCH_ADDR12_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR12_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr12_reg; +#[doc = "PATCH_ADDR13_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR13_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr13_reg; +#[doc = "PATCH_ADDR14_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR14_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr14_reg; +#[doc = "PATCH_ADDR15_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR15_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr15_reg; +#[doc = "PATCH_ADDR16_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR16_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr16_reg; +#[doc = "PATCH_ADDR17_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR17_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr17_reg; +#[doc = "PATCH_ADDR18_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR18_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr18_reg; +#[doc = "PATCH_ADDR19_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR19_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr19_reg; +#[doc = "PATCH_ADDR1_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR1_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr1_reg; +#[doc = "PATCH_ADDR20_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR20_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr20_reg; +#[doc = "PATCH_ADDR21_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR21_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr21_reg; +#[doc = "PATCH_ADDR2_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR2_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr2_reg; +#[doc = "PATCH_ADDR3_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR3_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr3_reg; +#[doc = "PATCH_ADDR4_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR4_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr4_reg; +#[doc = "PATCH_ADDR5_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR5_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr5_reg; +#[doc = "PATCH_ADDR6_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR6_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr6_reg; +#[doc = "PATCH_ADDR7_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR7_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr7_reg; +#[doc = "PATCH_ADDR8_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR8_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr8_reg; +#[doc = "PATCH_ADDR9_REG register accessor: an alias for `Reg`"] +pub type PATCH_ADDR9_REG = crate::Reg; +#[doc = ""] +pub mod patch_addr9_reg; +#[doc = "PATCH_DATA20_REG register accessor: an alias for `Reg`"] +pub type PATCH_DATA20_REG = crate::Reg; +#[doc = ""] +pub mod patch_data20_reg; +#[doc = "PATCH_DATA21_REG register accessor: an alias for `Reg`"] +pub type PATCH_DATA21_REG = crate::Reg; +#[doc = ""] +pub mod patch_data21_reg; +#[doc = "PATCH_VALID_REG register accessor: an alias for `Reg`"] +pub type PATCH_VALID_REG = crate::Reg; +#[doc = ""] +pub mod patch_valid_reg; diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr0_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr0_reg.rs new file mode 100644 index 0000000..e553679 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr0_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr0_reg](index.html) module"] +pub struct PATCH_ADDR0_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR0_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr0_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr0_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR0_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr10_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr10_reg.rs new file mode 100644 index 0000000..09306f7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr10_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR10_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR10_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr10_reg](index.html) module"] +pub struct PATCH_ADDR10_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR10_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr10_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR10_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr10_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR10_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR10_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR10_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr11_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr11_reg.rs new file mode 100644 index 0000000..98ca258 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr11_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR11_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR11_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr11_reg](index.html) module"] +pub struct PATCH_ADDR11_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR11_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr11_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR11_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr11_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR11_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR11_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR11_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr12_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr12_reg.rs new file mode 100644 index 0000000..73445fa --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr12_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR12_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR12_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr12_reg](index.html) module"] +pub struct PATCH_ADDR12_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR12_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr12_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR12_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr12_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR12_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR12_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR12_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr13_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr13_reg.rs new file mode 100644 index 0000000..04fa810 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr13_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR13_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR13_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr13_reg](index.html) module"] +pub struct PATCH_ADDR13_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR13_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr13_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR13_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr13_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR13_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR13_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR13_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr14_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr14_reg.rs new file mode 100644 index 0000000..b70401e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr14_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR14_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR14_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr14_reg](index.html) module"] +pub struct PATCH_ADDR14_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR14_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr14_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR14_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr14_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR14_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR14_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR14_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr15_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr15_reg.rs new file mode 100644 index 0000000..1b0bbd5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr15_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR15_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR15_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr15_reg](index.html) module"] +pub struct PATCH_ADDR15_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR15_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr15_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR15_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr15_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR15_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR15_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR15_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr16_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr16_reg.rs new file mode 100644 index 0000000..6431cfe --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr16_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR16_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR16_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr16_reg](index.html) module"] +pub struct PATCH_ADDR16_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR16_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr16_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR16_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr16_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR16_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR16_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR16_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr17_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr17_reg.rs new file mode 100644 index 0000000..b6c10e7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr17_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR17_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR17_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr17_reg](index.html) module"] +pub struct PATCH_ADDR17_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR17_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr17_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR17_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr17_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR17_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR17_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR17_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr18_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr18_reg.rs new file mode 100644 index 0000000..b1e8551 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr18_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR18_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR18_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr18_reg](index.html) module"] +pub struct PATCH_ADDR18_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR18_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr18_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR18_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr18_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR18_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR18_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR18_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr19_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr19_reg.rs new file mode 100644 index 0000000..6b64467 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr19_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR19_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR19_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr19_reg](index.html) module"] +pub struct PATCH_ADDR19_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR19_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr19_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR19_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr19_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR19_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR19_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR19_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr1_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr1_reg.rs new file mode 100644 index 0000000..192c40d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr1_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr1_reg](index.html) module"] +pub struct PATCH_ADDR1_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr1_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr1_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR1_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr20_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr20_reg.rs new file mode 100644 index 0000000..6eb4dc2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr20_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR20_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR20_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_D` reader - "] +pub struct PATCH_ADDR_D_R(crate::FieldReader); +impl PATCH_ADDR_D_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + PATCH_ADDR_D_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_D_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_D` writer - "] +pub struct PATCH_ADDR_D_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_D_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xffff << 2)) | ((value as u32 & 0xffff) << 2); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 2:17"] + #[inline(always)] + pub fn patch_addr_d(&self) -> PATCH_ADDR_D_R { + PATCH_ADDR_D_R::new(((self.bits >> 2) & 0xffff) as u16) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 2:17"] + #[inline(always)] + pub fn patch_addr_d(&mut self) -> PATCH_ADDR_D_W { + PATCH_ADDR_D_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr20_reg](index.html) module"] +pub struct PATCH_ADDR20_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR20_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr20_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR20_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr20_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR20_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR20_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR20_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr21_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr21_reg.rs new file mode 100644 index 0000000..8672aef --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr21_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR21_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR21_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_D` reader - "] +pub struct PATCH_ADDR_D_R(crate::FieldReader); +impl PATCH_ADDR_D_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + PATCH_ADDR_D_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_D_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_D` writer - "] +pub struct PATCH_ADDR_D_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_D_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xffff << 2)) | ((value as u32 & 0xffff) << 2); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 2:17"] + #[inline(always)] + pub fn patch_addr_d(&self) -> PATCH_ADDR_D_R { + PATCH_ADDR_D_R::new(((self.bits >> 2) & 0xffff) as u16) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 2:17"] + #[inline(always)] + pub fn patch_addr_d(&mut self) -> PATCH_ADDR_D_W { + PATCH_ADDR_D_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr21_reg](index.html) module"] +pub struct PATCH_ADDR21_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR21_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr21_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR21_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr21_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR21_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR21_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR21_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr2_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr2_reg.rs new file mode 100644 index 0000000..0fc0d34 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr2_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr2_reg](index.html) module"] +pub struct PATCH_ADDR2_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr2_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr2_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR2_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr3_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr3_reg.rs new file mode 100644 index 0000000..ee87a47 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr3_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr3_reg](index.html) module"] +pub struct PATCH_ADDR3_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr3_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr3_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR3_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr4_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr4_reg.rs new file mode 100644 index 0000000..a3f4600 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr4_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR4_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR4_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr4_reg](index.html) module"] +pub struct PATCH_ADDR4_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR4_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr4_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR4_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr4_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR4_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR4_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR4_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr5_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr5_reg.rs new file mode 100644 index 0000000..e9d3161 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr5_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR5_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR5_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr5_reg](index.html) module"] +pub struct PATCH_ADDR5_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR5_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr5_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR5_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr5_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR5_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR5_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR5_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr6_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr6_reg.rs new file mode 100644 index 0000000..e611e3b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr6_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR6_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR6_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr6_reg](index.html) module"] +pub struct PATCH_ADDR6_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR6_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr6_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR6_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr6_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR6_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR6_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR6_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr7_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr7_reg.rs new file mode 100644 index 0000000..a4f75e5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr7_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR7_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR7_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr7_reg](index.html) module"] +pub struct PATCH_ADDR7_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR7_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr7_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR7_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr7_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR7_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR7_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR7_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr8_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr8_reg.rs new file mode 100644 index 0000000..56e4351 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr8_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR8_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR8_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr8_reg](index.html) module"] +pub struct PATCH_ADDR8_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR8_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr8_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR8_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr8_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR8_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR8_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR8_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_addr9_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_addr9_reg.rs new file mode 100644 index 0000000..83c6f4a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_addr9_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `PATCH_ADDR9_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_ADDR9_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_ADDR_19` reader - "] +pub struct PATCH_ADDR_19_R(crate::FieldReader); +impl PATCH_ADDR_19_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PATCH_ADDR_19_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_19_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_19` writer - "] +pub struct PATCH_ADDR_19_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_19_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `PATCH_ADDR_C` reader - "] +pub struct PATCH_ADDR_C_R(crate::FieldReader); +impl PATCH_ADDR_C_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_ADDR_C_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_ADDR_C_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_ADDR_C` writer - "] +pub struct PATCH_ADDR_C_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_ADDR_C_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0001_ffff << 1)) | ((value as u32 & 0x0001_ffff) << 1); + self.w + } +} +impl R { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&self) -> PATCH_ADDR_19_R { + PATCH_ADDR_19_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&self) -> PATCH_ADDR_C_R { + PATCH_ADDR_C_R::new(((self.bits >> 1) & 0x0001_ffff) as u32) + } +} +impl W { + #[doc = "Bit 19"] + #[inline(always)] + pub fn patch_addr_19(&mut self) -> PATCH_ADDR_19_W { + PATCH_ADDR_19_W { w: self } + } + #[doc = "Bits 1:17"] + #[inline(always)] + pub fn patch_addr_c(&mut self) -> PATCH_ADDR_C_W { + PATCH_ADDR_C_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_addr9_reg](index.html) module"] +pub struct PATCH_ADDR9_REG_SPEC; +impl crate::RegisterSpec for PATCH_ADDR9_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_addr9_reg::R](R) reader structure"] +impl crate::Readable for PATCH_ADDR9_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_addr9_reg::W](W) writer structure"] +impl crate::Writable for PATCH_ADDR9_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_ADDR9_REG to value 0x07f0_0000"] +impl crate::Resettable for PATCH_ADDR9_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x07f0_0000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_data20_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_data20_reg.rs new file mode 100644 index 0000000..36047a5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_data20_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PATCH_DATA20_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_DATA20_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_DATA` reader - "] +pub struct PATCH_DATA_R(crate::FieldReader); +impl PATCH_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_DATA` writer - "] +pub struct PATCH_DATA_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_DATA_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31"] + #[inline(always)] + pub fn patch_data(&self) -> PATCH_DATA_R { + PATCH_DATA_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31"] + #[inline(always)] + pub fn patch_data(&mut self) -> PATCH_DATA_W { + PATCH_DATA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_data20_reg](index.html) module"] +pub struct PATCH_DATA20_REG_SPEC; +impl crate::RegisterSpec for PATCH_DATA20_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_data20_reg::R](R) reader structure"] +impl crate::Readable for PATCH_DATA20_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_data20_reg::W](W) writer structure"] +impl crate::Writable for PATCH_DATA20_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_DATA20_REG to value 0"] +impl crate::Resettable for PATCH_DATA20_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_data21_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_data21_reg.rs new file mode 100644 index 0000000..83b5677 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_data21_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PATCH_DATA21_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_DATA21_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_DATA` reader - "] +pub struct PATCH_DATA_R(crate::FieldReader); +impl PATCH_DATA_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_DATA_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_DATA_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_DATA` writer - "] +pub struct PATCH_DATA_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_DATA_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:31"] + #[inline(always)] + pub fn patch_data(&self) -> PATCH_DATA_R { + PATCH_DATA_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:31"] + #[inline(always)] + pub fn patch_data(&mut self) -> PATCH_DATA_W { + PATCH_DATA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_data21_reg](index.html) module"] +pub struct PATCH_DATA21_REG_SPEC; +impl crate::RegisterSpec for PATCH_DATA21_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_data21_reg::R](R) reader structure"] +impl crate::Readable for PATCH_DATA21_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_data21_reg::W](W) writer structure"] +impl crate::Writable for PATCH_DATA21_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_DATA21_REG to value 0"] +impl crate::Resettable for PATCH_DATA21_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/patch/patch_valid_reg.rs b/bitbox02-bt/vendor/da14531/src/patch/patch_valid_reg.rs new file mode 100644 index 0000000..310a7a2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/patch/patch_valid_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PATCH_VALID_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PATCH_VALID_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PATCH_VALID` reader - "] +pub struct PATCH_VALID_R(crate::FieldReader); +impl PATCH_VALID_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + PATCH_VALID_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PATCH_VALID_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PATCH_VALID` writer - "] +pub struct PATCH_VALID_W<'a> { + w: &'a mut W, +} +impl<'a> PATCH_VALID_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !0x003f_ffff) | (value as u32 & 0x003f_ffff); + self.w + } +} +impl R { + #[doc = "Bits 0:21"] + #[inline(always)] + pub fn patch_valid(&self) -> PATCH_VALID_R { + PATCH_VALID_R::new((self.bits & 0x003f_ffff) as u32) + } +} +impl W { + #[doc = "Bits 0:21"] + #[inline(always)] + pub fn patch_valid(&mut self) -> PATCH_VALID_W { + PATCH_VALID_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [patch_valid_reg](index.html) module"] +pub struct PATCH_VALID_REG_SPEC; +impl crate::RegisterSpec for PATCH_VALID_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [patch_valid_reg::R](R) reader structure"] +impl crate::Readable for PATCH_VALID_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [patch_valid_reg::W](W) writer structure"] +impl crate::Writable for PATCH_VALID_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PATCH_VALID_REG to value 0"] +impl crate::Resettable for PATCH_VALID_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/quadec.rs b/bitbox02-bt/vendor/da14531/src/quadec.rs new file mode 100644 index 0000000..ad06d10 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec.rs @@ -0,0 +1,46 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Quad Decoder control register"] + pub qdec_ctrl_reg: crate::Reg, + #[doc = "0x02 - Counter value of the X Axis"] + pub qdec_xcnt_reg: crate::Reg, + #[doc = "0x04 - Counter value of the Y Axis"] + pub qdec_ycnt_reg: crate::Reg, + #[doc = "0x06 - Clock divider register"] + pub qdec_clockdiv_reg: crate::Reg, + #[doc = "0x08 - Quad Decoder port selection register"] + pub qdec_ctrl2_reg: crate::Reg, + #[doc = "0x0a - Counter value of the Z Axis"] + pub qdec_zcnt_reg: crate::Reg, + #[doc = "0x0c - Event counter register"] + pub qdec_event_cnt_reg: crate::Reg, +} +#[doc = "QDEC_CLOCKDIV_REG register accessor: an alias for `Reg`"] +pub type QDEC_CLOCKDIV_REG = crate::Reg; +#[doc = "Clock divider register"] +pub mod qdec_clockdiv_reg; +#[doc = "QDEC_CTRL2_REG register accessor: an alias for `Reg`"] +pub type QDEC_CTRL2_REG = crate::Reg; +#[doc = "Quad Decoder port selection register"] +pub mod qdec_ctrl2_reg; +#[doc = "QDEC_CTRL_REG register accessor: an alias for `Reg`"] +pub type QDEC_CTRL_REG = crate::Reg; +#[doc = "Quad Decoder control register"] +pub mod qdec_ctrl_reg; +#[doc = "QDEC_EVENT_CNT_REG register accessor: an alias for `Reg`"] +pub type QDEC_EVENT_CNT_REG = crate::Reg; +#[doc = "Event counter register"] +pub mod qdec_event_cnt_reg; +#[doc = "QDEC_XCNT_REG register accessor: an alias for `Reg`"] +pub type QDEC_XCNT_REG = crate::Reg; +#[doc = "Counter value of the X Axis"] +pub mod qdec_xcnt_reg; +#[doc = "QDEC_YCNT_REG register accessor: an alias for `Reg`"] +pub type QDEC_YCNT_REG = crate::Reg; +#[doc = "Counter value of the Y Axis"] +pub mod qdec_ycnt_reg; +#[doc = "QDEC_ZCNT_REG register accessor: an alias for `Reg`"] +pub type QDEC_ZCNT_REG = crate::Reg; +#[doc = "Counter value of the Z Axis"] +pub mod qdec_zcnt_reg; diff --git a/bitbox02-bt/vendor/da14531/src/quadec/qdec_clockdiv_reg.rs b/bitbox02-bt/vendor/da14531/src/quadec/qdec_clockdiv_reg.rs new file mode 100644 index 0000000..94eac81 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec/qdec_clockdiv_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `QDEC_CLOCKDIV_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `QDEC_CLOCKDIV_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QDEC_PRESCALER_EN` reader - 0 = no prescaler enabled 1 = in sleep and active mode, quadrature clock is divided by 2"] +pub struct QDEC_PRESCALER_EN_R(crate::FieldReader); +impl QDEC_PRESCALER_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QDEC_PRESCALER_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_PRESCALER_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_PRESCALER_EN` writer - 0 = no prescaler enabled 1 = in sleep and active mode, quadrature clock is divided by 2"] +pub struct QDEC_PRESCALER_EN_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_PRESCALER_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `QDEC_CLOCKDIV` reader - Contains the number of the input clock cycles minus one, that are required to generate one logic clock cycle. Clock divider is bypassed when system runs at LP_CLK"] +pub struct QDEC_CLOCKDIV_R(crate::FieldReader); +impl QDEC_CLOCKDIV_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + QDEC_CLOCKDIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_CLOCKDIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_CLOCKDIV` writer - Contains the number of the input clock cycles minus one, that are required to generate one logic clock cycle. Clock divider is bypassed when system runs at LP_CLK"] +pub struct QDEC_CLOCKDIV_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_CLOCKDIV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u16 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bit 10 - 0 = no prescaler enabled 1 = in sleep and active mode, quadrature clock is divided by 2"] + #[inline(always)] + pub fn qdec_prescaler_en(&self) -> QDEC_PRESCALER_EN_R { + QDEC_PRESCALER_EN_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bits 0:9 - Contains the number of the input clock cycles minus one, that are required to generate one logic clock cycle. Clock divider is bypassed when system runs at LP_CLK"] + #[inline(always)] + pub fn qdec_clockdiv(&self) -> QDEC_CLOCKDIV_R { + QDEC_CLOCKDIV_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bit 10 - 0 = no prescaler enabled 1 = in sleep and active mode, quadrature clock is divided by 2"] + #[inline(always)] + pub fn qdec_prescaler_en(&mut self) -> QDEC_PRESCALER_EN_W { + QDEC_PRESCALER_EN_W { w: self } + } + #[doc = "Bits 0:9 - Contains the number of the input clock cycles minus one, that are required to generate one logic clock cycle. Clock divider is bypassed when system runs at LP_CLK"] + #[inline(always)] + pub fn qdec_clockdiv(&mut self) -> QDEC_CLOCKDIV_W { + QDEC_CLOCKDIV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clock divider register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qdec_clockdiv_reg](index.html) module"] +pub struct QDEC_CLOCKDIV_REG_SPEC; +impl crate::RegisterSpec for QDEC_CLOCKDIV_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [qdec_clockdiv_reg::R](R) reader structure"] +impl crate::Readable for QDEC_CLOCKDIV_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [qdec_clockdiv_reg::W](W) writer structure"] +impl crate::Writable for QDEC_CLOCKDIV_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets QDEC_CLOCKDIV_REG to value 0x03e7"] +impl crate::Resettable for QDEC_CLOCKDIV_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x03e7 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl2_reg.rs new file mode 100644 index 0000000..5ad82a3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl2_reg.rs @@ -0,0 +1,462 @@ +#[doc = "Register `QDEC_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `QDEC_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QDEC_CHZ_EVENT_MODE` reader - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] +pub struct QDEC_CHZ_EVENT_MODE_R(crate::FieldReader); +impl QDEC_CHZ_EVENT_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QDEC_CHZ_EVENT_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_CHZ_EVENT_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_CHZ_EVENT_MODE` writer - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] +pub struct QDEC_CHZ_EVENT_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_CHZ_EVENT_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u16 & 1) << 11); + self.w + } +} +#[doc = "Field `QDEC_CHY_EVENT_MODE` reader - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] +pub struct QDEC_CHY_EVENT_MODE_R(crate::FieldReader); +impl QDEC_CHY_EVENT_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QDEC_CHY_EVENT_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_CHY_EVENT_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_CHY_EVENT_MODE` writer - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] +pub struct QDEC_CHY_EVENT_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_CHY_EVENT_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u16 & 1) << 10); + self.w + } +} +#[doc = "Field `QDEC_CHX_EVENT_MODE` reader - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] +pub struct QDEC_CHX_EVENT_MODE_R(crate::FieldReader); +impl QDEC_CHX_EVENT_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QDEC_CHX_EVENT_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_CHX_EVENT_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_CHX_EVENT_MODE` writer - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] +pub struct QDEC_CHX_EVENT_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_CHX_EVENT_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u16 & 1) << 9); + self.w + } +} +#[doc = "Field `QDEC_CHZ_PORT_SEL` reader - Defines which GPIOs are mapped on Channel Z 0: none 1: P0\\[2\\] +-> CHZ_A, P0\\[5\\] +-> CHZ_B 2: P0\\[1\\] +-> CHZ_A, P0\\[4\\] +-> CHZ_B 3: P0\\[3\\] +-> CHZ_A, P0\\[10\\] +-> CHZ_B 4: P0\\[6\\] +-> CHZ_A, P0\\[7\\] +-> CHZ_B 5: P0\\[8\\] +-> CHZ_A, P0\\[9\\] +-> CHZ_B 6: P0\\[0\\] +-> CHZ_A, P0\\[11\\] +-> CHZ_B 7: none"] +pub struct QDEC_CHZ_PORT_SEL_R(crate::FieldReader); +impl QDEC_CHZ_PORT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QDEC_CHZ_PORT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_CHZ_PORT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_CHZ_PORT_SEL` writer - Defines which GPIOs are mapped on Channel Z 0: none 1: P0\\[2\\] +-> CHZ_A, P0\\[5\\] +-> CHZ_B 2: P0\\[1\\] +-> CHZ_A, P0\\[4\\] +-> CHZ_B 3: P0\\[3\\] +-> CHZ_A, P0\\[10\\] +-> CHZ_B 4: P0\\[6\\] +-> CHZ_A, P0\\[7\\] +-> CHZ_B 5: P0\\[8\\] +-> CHZ_A, P0\\[9\\] +-> CHZ_B 6: P0\\[0\\] +-> CHZ_A, P0\\[11\\] +-> CHZ_B 7: none"] +pub struct QDEC_CHZ_PORT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_CHZ_PORT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 6)) | ((value as u16 & 7) << 6); + self.w + } +} +#[doc = "Field `QDEC_CHY_PORT_SEL` reader - Defines which GPIOs are mapped on Channel Y 0: none 1: P0\\[2\\] +-> CHY_A, P0\\[5\\] +-> CHY_B 2: P0\\[1\\] +-> CHY_A, P0\\[4\\] +-> CHY_B 3: P0\\[3\\] +-> CHY_A, P0\\[10\\] +-> CHY_B 4: P0\\[6\\] +-> CHY_A, P0\\[7\\] +-> CHY_B 5: P0\\[8\\] +-> CHY_A, P0\\[9\\] +-> CHY_B 6: P0\\[0\\] +-> CHY_A, P0\\[11\\] +-> CHY_B 7: none"] +pub struct QDEC_CHY_PORT_SEL_R(crate::FieldReader); +impl QDEC_CHY_PORT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QDEC_CHY_PORT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_CHY_PORT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_CHY_PORT_SEL` writer - Defines which GPIOs are mapped on Channel Y 0: none 1: P0\\[2\\] +-> CHY_A, P0\\[5\\] +-> CHY_B 2: P0\\[1\\] +-> CHY_A, P0\\[4\\] +-> CHY_B 3: P0\\[3\\] +-> CHY_A, P0\\[10\\] +-> CHY_B 4: P0\\[6\\] +-> CHY_A, P0\\[7\\] +-> CHY_B 5: P0\\[8\\] +-> CHY_A, P0\\[9\\] +-> CHY_B 6: P0\\[0\\] +-> CHY_A, P0\\[11\\] +-> CHY_B 7: none"] +pub struct QDEC_CHY_PORT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_CHY_PORT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 3)) | ((value as u16 & 7) << 3); + self.w + } +} +#[doc = "Field `QDEC_CHX_PORT_SEL` reader - Defines which GPIOs are mapped on Channel X 0: none 1: P0\\[2\\] +-> CHX_A, P0\\[5\\] +-> CHX_B 2: P0\\[1\\] +-> CHX_A, P0\\[4\\] +-> CHX_B 3: P0\\[3\\] +-> CHX_A, P0\\[10\\] +-> CHX_B 4: P0\\[6\\] +-> CHX_A, P0\\[7\\] +-> CHX_B 5: P0\\[8\\] +-> CHX_A, P0\\[9\\] +-> CHX_B 6: P0\\[0\\] +-> CHX_A, P0\\[11\\] +-> CHX_B 7: none"] +pub struct QDEC_CHX_PORT_SEL_R(crate::FieldReader); +impl QDEC_CHX_PORT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QDEC_CHX_PORT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_CHX_PORT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_CHX_PORT_SEL` writer - Defines which GPIOs are mapped on Channel X 0: none 1: P0\\[2\\] +-> CHX_A, P0\\[5\\] +-> CHX_B 2: P0\\[1\\] +-> CHX_A, P0\\[4\\] +-> CHX_B 3: P0\\[3\\] +-> CHX_A, P0\\[10\\] +-> CHX_B 4: P0\\[6\\] +-> CHX_A, P0\\[7\\] +-> CHX_B 5: P0\\[8\\] +-> CHX_A, P0\\[9\\] +-> CHX_B 6: P0\\[0\\] +-> CHX_A, P0\\[11\\] +-> CHX_B 7: none"] +pub struct QDEC_CHX_PORT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_CHX_PORT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u16 & 7); + self.w + } +} +impl R { + #[doc = "Bit 11 - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] + #[inline(always)] + pub fn qdec_chz_event_mode(&self) -> QDEC_CHZ_EVENT_MODE_R { + QDEC_CHZ_EVENT_MODE_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10 - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] + #[inline(always)] + pub fn qdec_chy_event_mode(&self) -> QDEC_CHY_EVENT_MODE_R { + QDEC_CHY_EVENT_MODE_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9 - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] + #[inline(always)] + pub fn qdec_chx_event_mode(&self) -> QDEC_CHX_EVENT_MODE_R { + QDEC_CHX_EVENT_MODE_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bits 6:8 - Defines which GPIOs are mapped on Channel Z 0: none 1: P0\\[2\\] +-> CHZ_A, P0\\[5\\] +-> CHZ_B 2: P0\\[1\\] +-> CHZ_A, P0\\[4\\] +-> CHZ_B 3: P0\\[3\\] +-> CHZ_A, P0\\[10\\] +-> CHZ_B 4: P0\\[6\\] +-> CHZ_A, P0\\[7\\] +-> CHZ_B 5: P0\\[8\\] +-> CHZ_A, P0\\[9\\] +-> CHZ_B 6: P0\\[0\\] +-> CHZ_A, P0\\[11\\] +-> CHZ_B 7: none"] + #[inline(always)] + pub fn qdec_chz_port_sel(&self) -> QDEC_CHZ_PORT_SEL_R { + QDEC_CHZ_PORT_SEL_R::new(((self.bits >> 6) & 7) as u8) + } + #[doc = "Bits 3:5 - Defines which GPIOs are mapped on Channel Y 0: none 1: P0\\[2\\] +-> CHY_A, P0\\[5\\] +-> CHY_B 2: P0\\[1\\] +-> CHY_A, P0\\[4\\] +-> CHY_B 3: P0\\[3\\] +-> CHY_A, P0\\[10\\] +-> CHY_B 4: P0\\[6\\] +-> CHY_A, P0\\[7\\] +-> CHY_B 5: P0\\[8\\] +-> CHY_A, P0\\[9\\] +-> CHY_B 6: P0\\[0\\] +-> CHY_A, P0\\[11\\] +-> CHY_B 7: none"] + #[inline(always)] + pub fn qdec_chy_port_sel(&self) -> QDEC_CHY_PORT_SEL_R { + QDEC_CHY_PORT_SEL_R::new(((self.bits >> 3) & 7) as u8) + } + #[doc = "Bits 0:2 - Defines which GPIOs are mapped on Channel X 0: none 1: P0\\[2\\] +-> CHX_A, P0\\[5\\] +-> CHX_B 2: P0\\[1\\] +-> CHX_A, P0\\[4\\] +-> CHX_B 3: P0\\[3\\] +-> CHX_A, P0\\[10\\] +-> CHX_B 4: P0\\[6\\] +-> CHX_A, P0\\[7\\] +-> CHX_B 5: P0\\[8\\] +-> CHX_A, P0\\[9\\] +-> CHX_B 6: P0\\[0\\] +-> CHX_A, P0\\[11\\] +-> CHX_B 7: none"] + #[inline(always)] + pub fn qdec_chx_port_sel(&self) -> QDEC_CHX_PORT_SEL_R { + QDEC_CHX_PORT_SEL_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bit 11 - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] + #[inline(always)] + pub fn qdec_chz_event_mode(&mut self) -> QDEC_CHZ_EVENT_MODE_W { + QDEC_CHZ_EVENT_MODE_W { w: self } + } + #[doc = "Bit 10 - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] + #[inline(always)] + pub fn qdec_chy_event_mode(&mut self) -> QDEC_CHY_EVENT_MODE_W { + QDEC_CHY_EVENT_MODE_W { w: self } + } + #[doc = "Bit 9 - 0 = Normal quadrature counting 1 = Counts rising and falling edge of both ports (if both ports change at the same time, counter increases by 1)"] + #[inline(always)] + pub fn qdec_chx_event_mode(&mut self) -> QDEC_CHX_EVENT_MODE_W { + QDEC_CHX_EVENT_MODE_W { w: self } + } + #[doc = "Bits 6:8 - Defines which GPIOs are mapped on Channel Z 0: none 1: P0\\[2\\] +-> CHZ_A, P0\\[5\\] +-> CHZ_B 2: P0\\[1\\] +-> CHZ_A, P0\\[4\\] +-> CHZ_B 3: P0\\[3\\] +-> CHZ_A, P0\\[10\\] +-> CHZ_B 4: P0\\[6\\] +-> CHZ_A, P0\\[7\\] +-> CHZ_B 5: P0\\[8\\] +-> CHZ_A, P0\\[9\\] +-> CHZ_B 6: P0\\[0\\] +-> CHZ_A, P0\\[11\\] +-> CHZ_B 7: none"] + #[inline(always)] + pub fn qdec_chz_port_sel(&mut self) -> QDEC_CHZ_PORT_SEL_W { + QDEC_CHZ_PORT_SEL_W { w: self } + } + #[doc = "Bits 3:5 - Defines which GPIOs are mapped on Channel Y 0: none 1: P0\\[2\\] +-> CHY_A, P0\\[5\\] +-> CHY_B 2: P0\\[1\\] +-> CHY_A, P0\\[4\\] +-> CHY_B 3: P0\\[3\\] +-> CHY_A, P0\\[10\\] +-> CHY_B 4: P0\\[6\\] +-> CHY_A, P0\\[7\\] +-> CHY_B 5: P0\\[8\\] +-> CHY_A, P0\\[9\\] +-> CHY_B 6: P0\\[0\\] +-> CHY_A, P0\\[11\\] +-> CHY_B 7: none"] + #[inline(always)] + pub fn qdec_chy_port_sel(&mut self) -> QDEC_CHY_PORT_SEL_W { + QDEC_CHY_PORT_SEL_W { w: self } + } + #[doc = "Bits 0:2 - Defines which GPIOs are mapped on Channel X 0: none 1: P0\\[2\\] +-> CHX_A, P0\\[5\\] +-> CHX_B 2: P0\\[1\\] +-> CHX_A, P0\\[4\\] +-> CHX_B 3: P0\\[3\\] +-> CHX_A, P0\\[10\\] +-> CHX_B 4: P0\\[6\\] +-> CHX_A, P0\\[7\\] +-> CHX_B 5: P0\\[8\\] +-> CHX_A, P0\\[9\\] +-> CHX_B 6: P0\\[0\\] +-> CHX_A, P0\\[11\\] +-> CHX_B 7: none"] + #[inline(always)] + pub fn qdec_chx_port_sel(&mut self) -> QDEC_CHX_PORT_SEL_W { + QDEC_CHX_PORT_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Quad Decoder port selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qdec_ctrl2_reg](index.html) module"] +pub struct QDEC_CTRL2_REG_SPEC; +impl crate::RegisterSpec for QDEC_CTRL2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [qdec_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for QDEC_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [qdec_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for QDEC_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets QDEC_CTRL2_REG to value 0x0ed1"] +impl crate::Resettable for QDEC_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0ed1 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl_reg.rs new file mode 100644 index 0000000..0c2bf0a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec/qdec_ctrl_reg.rs @@ -0,0 +1,244 @@ +#[doc = "Register `QDEC_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `QDEC_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QDEC_IRQ_THRES` reader - Defines the number of events on either counter (X or Y or Z) that need to be reached before an interrupt is generated. Events are equal to QDEC_IRQ_THRES+1."] +pub struct QDEC_IRQ_THRES_R(crate::FieldReader); +impl QDEC_IRQ_THRES_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QDEC_IRQ_THRES_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_IRQ_THRES_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_IRQ_THRES` writer - Defines the number of events on either counter (X or Y or Z) that need to be reached before an interrupt is generated. Events are equal to QDEC_IRQ_THRES+1."] +pub struct QDEC_IRQ_THRES_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_IRQ_THRES_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 3)) | ((value as u16 & 0xff) << 3); + self.w + } +} +#[doc = "Field `QDEC_IRQ_STATUS` reader - 1 = Interrupt is occured. 0 = No interrupt pending Write 1 will clear the pending interrupt"] +pub struct QDEC_IRQ_STATUS_R(crate::FieldReader); +impl QDEC_IRQ_STATUS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QDEC_IRQ_STATUS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_IRQ_STATUS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_IRQ_STATUS` writer - 1 = Interrupt is occured. 0 = No interrupt pending Write 1 will clear the pending interrupt"] +pub struct QDEC_IRQ_STATUS_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_IRQ_STATUS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `QDEC_EVENT_CNT_CLR` reader - Writing 1 QDEC_EVENT_CNT_REG is cleared"] +pub struct QDEC_EVENT_CNT_CLR_R(crate::FieldReader); +impl QDEC_EVENT_CNT_CLR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QDEC_EVENT_CNT_CLR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_EVENT_CNT_CLR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_EVENT_CNT_CLR` writer - Writing 1 QDEC_EVENT_CNT_REG is cleared"] +pub struct QDEC_EVENT_CNT_CLR_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_EVENT_CNT_CLR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `QDEC_IRQ_ENABLE` reader - 0 = interrupt is masked 1 = interrupt is enabled"] +pub struct QDEC_IRQ_ENABLE_R(crate::FieldReader); +impl QDEC_IRQ_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + QDEC_IRQ_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_IRQ_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `QDEC_IRQ_ENABLE` writer - 0 = interrupt is masked 1 = interrupt is enabled"] +pub struct QDEC_IRQ_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> QDEC_IRQ_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 3:10 - Defines the number of events on either counter (X or Y or Z) that need to be reached before an interrupt is generated. Events are equal to QDEC_IRQ_THRES+1."] + #[inline(always)] + pub fn qdec_irq_thres(&self) -> QDEC_IRQ_THRES_R { + QDEC_IRQ_THRES_R::new(((self.bits >> 3) & 0xff) as u8) + } + #[doc = "Bit 2 - 1 = Interrupt is occured. 0 = No interrupt pending Write 1 will clear the pending interrupt"] + #[inline(always)] + pub fn qdec_irq_status(&self) -> QDEC_IRQ_STATUS_R { + QDEC_IRQ_STATUS_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Writing 1 QDEC_EVENT_CNT_REG is cleared"] + #[inline(always)] + pub fn qdec_event_cnt_clr(&self) -> QDEC_EVENT_CNT_CLR_R { + QDEC_EVENT_CNT_CLR_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 0 = interrupt is masked 1 = interrupt is enabled"] + #[inline(always)] + pub fn qdec_irq_enable(&self) -> QDEC_IRQ_ENABLE_R { + QDEC_IRQ_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 3:10 - Defines the number of events on either counter (X or Y or Z) that need to be reached before an interrupt is generated. Events are equal to QDEC_IRQ_THRES+1."] + #[inline(always)] + pub fn qdec_irq_thres(&mut self) -> QDEC_IRQ_THRES_W { + QDEC_IRQ_THRES_W { w: self } + } + #[doc = "Bit 2 - 1 = Interrupt is occured. 0 = No interrupt pending Write 1 will clear the pending interrupt"] + #[inline(always)] + pub fn qdec_irq_status(&mut self) -> QDEC_IRQ_STATUS_W { + QDEC_IRQ_STATUS_W { w: self } + } + #[doc = "Bit 1 - Writing 1 QDEC_EVENT_CNT_REG is cleared"] + #[inline(always)] + pub fn qdec_event_cnt_clr(&mut self) -> QDEC_EVENT_CNT_CLR_W { + QDEC_EVENT_CNT_CLR_W { w: self } + } + #[doc = "Bit 0 - 0 = interrupt is masked 1 = interrupt is enabled"] + #[inline(always)] + pub fn qdec_irq_enable(&mut self) -> QDEC_IRQ_ENABLE_W { + QDEC_IRQ_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Quad Decoder control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qdec_ctrl_reg](index.html) module"] +pub struct QDEC_CTRL_REG_SPEC; +impl crate::RegisterSpec for QDEC_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [qdec_ctrl_reg::R](R) reader structure"] +impl crate::Readable for QDEC_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [qdec_ctrl_reg::W](W) writer structure"] +impl crate::Writable for QDEC_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets QDEC_CTRL_REG to value 0x11"] +impl crate::Resettable for QDEC_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x11 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/quadec/qdec_event_cnt_reg.rs b/bitbox02-bt/vendor/da14531/src/quadec/qdec_event_cnt_reg.rs new file mode 100644 index 0000000..25ef0fa --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec/qdec_event_cnt_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `QDEC_EVENT_CNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `QDEC_EVENT_CNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QDEC_EVENT_CNT` reader - Gives the number of events at all channels."] +pub struct QDEC_EVENT_CNT_R(crate::FieldReader); +impl QDEC_EVENT_CNT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + QDEC_EVENT_CNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_EVENT_CNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:7 - Gives the number of events at all channels."] + #[inline(always)] + pub fn qdec_event_cnt(&self) -> QDEC_EVENT_CNT_R { + QDEC_EVENT_CNT_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Event counter register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qdec_event_cnt_reg](index.html) module"] +pub struct QDEC_EVENT_CNT_REG_SPEC; +impl crate::RegisterSpec for QDEC_EVENT_CNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [qdec_event_cnt_reg::R](R) reader structure"] +impl crate::Readable for QDEC_EVENT_CNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [qdec_event_cnt_reg::W](W) writer structure"] +impl crate::Writable for QDEC_EVENT_CNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets QDEC_EVENT_CNT_REG to value 0"] +impl crate::Resettable for QDEC_EVENT_CNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/quadec/qdec_xcnt_reg.rs b/bitbox02-bt/vendor/da14531/src/quadec/qdec_xcnt_reg.rs new file mode 100644 index 0000000..602e207 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec/qdec_xcnt_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `QDEC_XCNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `QDEC_XCNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QDEC_X_CNT` reader - Contains a signed value of the events. Zero when channel is disabled"] +pub struct QDEC_X_CNT_R(crate::FieldReader); +impl QDEC_X_CNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + QDEC_X_CNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_X_CNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Contains a signed value of the events. Zero when channel is disabled"] + #[inline(always)] + pub fn qdec_x_cnt(&self) -> QDEC_X_CNT_R { + QDEC_X_CNT_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Counter value of the X Axis\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qdec_xcnt_reg](index.html) module"] +pub struct QDEC_XCNT_REG_SPEC; +impl crate::RegisterSpec for QDEC_XCNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [qdec_xcnt_reg::R](R) reader structure"] +impl crate::Readable for QDEC_XCNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [qdec_xcnt_reg::W](W) writer structure"] +impl crate::Writable for QDEC_XCNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets QDEC_XCNT_REG to value 0"] +impl crate::Resettable for QDEC_XCNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/quadec/qdec_ycnt_reg.rs b/bitbox02-bt/vendor/da14531/src/quadec/qdec_ycnt_reg.rs new file mode 100644 index 0000000..f409aa8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec/qdec_ycnt_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `QDEC_YCNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `QDEC_YCNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QDEC_Y_CNT` reader - Contains a signed value of the events. Zero when channel is disabled"] +pub struct QDEC_Y_CNT_R(crate::FieldReader); +impl QDEC_Y_CNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + QDEC_Y_CNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_Y_CNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Contains a signed value of the events. Zero when channel is disabled"] + #[inline(always)] + pub fn qdec_y_cnt(&self) -> QDEC_Y_CNT_R { + QDEC_Y_CNT_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Counter value of the Y Axis\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qdec_ycnt_reg](index.html) module"] +pub struct QDEC_YCNT_REG_SPEC; +impl crate::RegisterSpec for QDEC_YCNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [qdec_ycnt_reg::R](R) reader structure"] +impl crate::Readable for QDEC_YCNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [qdec_ycnt_reg::W](W) writer structure"] +impl crate::Writable for QDEC_YCNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets QDEC_YCNT_REG to value 0"] +impl crate::Resettable for QDEC_YCNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/quadec/qdec_zcnt_reg.rs b/bitbox02-bt/vendor/da14531/src/quadec/qdec_zcnt_reg.rs new file mode 100644 index 0000000..376e1a6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/quadec/qdec_zcnt_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `QDEC_ZCNT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `QDEC_ZCNT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `QDEC_Z_CNT` reader - Contains a signed value of the events. Zero when channel is disabled"] +pub struct QDEC_Z_CNT_R(crate::FieldReader); +impl QDEC_Z_CNT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + QDEC_Z_CNT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for QDEC_Z_CNT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Contains a signed value of the events. Zero when channel is disabled"] + #[inline(always)] + pub fn qdec_z_cnt(&self) -> QDEC_Z_CNT_R { + QDEC_Z_CNT_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Counter value of the Z Axis\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qdec_zcnt_reg](index.html) module"] +pub struct QDEC_ZCNT_REG_SPEC; +impl crate::RegisterSpec for QDEC_ZCNT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [qdec_zcnt_reg::R](R) reader structure"] +impl crate::Readable for QDEC_ZCNT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [qdec_zcnt_reg::W](W) writer structure"] +impl crate::Writable for QDEC_ZCNT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets QDEC_ZCNT_REG to value 0"] +impl crate::Resettable for QDEC_ZCNT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu.rs b/bitbox02-bt/vendor/da14531/src/rfcu.rs new file mode 100644 index 0000000..8c6a6cc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu.rs @@ -0,0 +1,193 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - "] + pub rf_attr_reg: crate::Reg, + #[doc = "0x04 - "] + pub rf_radio_init_reg: crate::Reg, + #[doc = "0x08 - "] + pub rf_ldo_status_reg: crate::Reg, + #[doc = "0x0c - "] + pub rf_adplldig_ctrl_reg: crate::Reg, + #[doc = "0x10 - "] + pub rf_agc_ext_lut_reg: crate::Reg, + #[doc = "0x14 - "] + pub rf_calstate_reg: crate::Reg, + #[doc = "0x18 - "] + pub rf_scan_feedback_reg: crate::Reg, + _reserved7: [u8; 0x04], + #[doc = "0x20 - "] + pub rf_cal_ctrl_reg: crate::Reg, + #[doc = "0x24 - "] + pub rf_irq_ctrl_reg: crate::Reg, + #[doc = "0x28 - "] + pub rf_adci_dc_offset_reg: crate::Reg, + #[doc = "0x2c - "] + pub rf_adcq_dc_offset_reg: crate::Reg, + #[doc = "0x30 - "] + pub rf_spare_reg: crate::Reg, + _reserved12: [u8; 0x08], + #[doc = "0x3c - "] + pub rf_iff_ctrl_reg: crate::Reg, + #[doc = "0x40 - "] + pub rf_adc_ctrl1_reg: crate::Reg, + #[doc = "0x44 - "] + pub rf_adc_ctrl2_reg: crate::Reg, + #[doc = "0x48 - "] + pub rf_adc_ctrl3_reg: crate::Reg, + #[doc = "0x4c - "] + pub rf_pa_ctrl_reg: crate::Reg, + _reserved17: [u8; 0x08], + #[doc = "0x58 - "] + pub rf_ldo_vref_sel_reg: crate::Reg, + _reserved18: [u8; 0x08], + #[doc = "0x64 - "] + pub rf_mixer_ctrl1_reg: crate::Reg, + #[doc = "0x68 - "] + pub rf_mixer_ctrl2_reg: crate::Reg, + _reserved20: [u8; 0x08], + #[doc = "0x74 - "] + pub rf_io_ctrl_reg: crate::Reg, + #[doc = "0x78 - "] + pub rf_lna_ctrl1_reg: crate::Reg, + #[doc = "0x7c - "] + pub rf_lna_ctrl2_reg: crate::Reg, + #[doc = "0x80 - "] + pub rf_lna_ctrl3_reg: crate::Reg, + _reserved24: [u8; 0x1c], + #[doc = "0xa0 - "] + pub rf_adplldig_rfmon_ctrl_reg: + crate::Reg, + _reserved25: [u8; 0x04], + #[doc = "0xa8 - "] + pub rf_rfcu_ctrl_reg: crate::Reg, + #[doc = "0xac - "] + pub rf_overrule_reg: crate::Reg, + #[doc = "0xb0 - "] + pub rf_diagirq_ctrl_reg: crate::Reg, + #[doc = "0xb4 - "] + pub rf_diagirq_stat_reg: crate::Reg, + #[doc = "0xb8 - "] + pub rf_ldo_ctrl_reg: crate::Reg, +} +#[doc = "RF_ADCI_DC_OFFSET_REG register accessor: an alias for `Reg`"] +pub type RF_ADCI_DC_OFFSET_REG = crate::Reg; +#[doc = ""] +pub mod rf_adci_dc_offset_reg; +#[doc = "RF_ADCQ_DC_OFFSET_REG register accessor: an alias for `Reg`"] +pub type RF_ADCQ_DC_OFFSET_REG = crate::Reg; +#[doc = ""] +pub mod rf_adcq_dc_offset_reg; +#[doc = "RF_ADC_CTRL1_REG register accessor: an alias for `Reg`"] +pub type RF_ADC_CTRL1_REG = crate::Reg; +#[doc = ""] +pub mod rf_adc_ctrl1_reg; +#[doc = "RF_ADC_CTRL2_REG register accessor: an alias for `Reg`"] +pub type RF_ADC_CTRL2_REG = crate::Reg; +#[doc = ""] +pub mod rf_adc_ctrl2_reg; +#[doc = "RF_ADC_CTRL3_REG register accessor: an alias for `Reg`"] +pub type RF_ADC_CTRL3_REG = crate::Reg; +#[doc = ""] +pub mod rf_adc_ctrl3_reg; +#[doc = "RF_ADPLLDIG_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_ADPLLDIG_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_adplldig_ctrl_reg; +#[doc = "RF_ADPLLDIG_RFMON_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_ADPLLDIG_RFMON_CTRL_REG = + crate::Reg; +#[doc = ""] +pub mod rf_adplldig_rfmon_ctrl_reg; +#[doc = "RF_AGC_EXT_LUT_REG register accessor: an alias for `Reg`"] +pub type RF_AGC_EXT_LUT_REG = crate::Reg; +#[doc = ""] +pub mod rf_agc_ext_lut_reg; +#[doc = "RF_ATTR_REG register accessor: an alias for `Reg`"] +pub type RF_ATTR_REG = crate::Reg; +#[doc = ""] +pub mod rf_attr_reg; +#[doc = "RF_CALSTATE_REG register accessor: an alias for `Reg`"] +pub type RF_CALSTATE_REG = crate::Reg; +#[doc = ""] +pub mod rf_calstate_reg; +#[doc = "RF_CAL_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_CAL_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_cal_ctrl_reg; +#[doc = "RF_DIAGIRQ_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_DIAGIRQ_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_diagirq_ctrl_reg; +#[doc = "RF_DIAGIRQ_STAT_REG register accessor: an alias for `Reg`"] +pub type RF_DIAGIRQ_STAT_REG = crate::Reg; +#[doc = ""] +pub mod rf_diagirq_stat_reg; +#[doc = "RF_IFF_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_IFF_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_iff_ctrl_reg; +#[doc = "RF_IO_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_IO_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_io_ctrl_reg; +#[doc = "RF_IRQ_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_IRQ_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_irq_ctrl_reg; +#[doc = "RF_LDO_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_LDO_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_ldo_ctrl_reg; +#[doc = "RF_LDO_STATUS_REG register accessor: an alias for `Reg`"] +pub type RF_LDO_STATUS_REG = crate::Reg; +#[doc = ""] +pub mod rf_ldo_status_reg; +#[doc = "RF_LDO_VREF_SEL_REG register accessor: an alias for `Reg`"] +pub type RF_LDO_VREF_SEL_REG = crate::Reg; +#[doc = ""] +pub mod rf_ldo_vref_sel_reg; +#[doc = "RF_LNA_CTRL1_REG register accessor: an alias for `Reg`"] +pub type RF_LNA_CTRL1_REG = crate::Reg; +#[doc = ""] +pub mod rf_lna_ctrl1_reg; +#[doc = "RF_LNA_CTRL2_REG register accessor: an alias for `Reg`"] +pub type RF_LNA_CTRL2_REG = crate::Reg; +#[doc = ""] +pub mod rf_lna_ctrl2_reg; +#[doc = "RF_LNA_CTRL3_REG register accessor: an alias for `Reg`"] +pub type RF_LNA_CTRL3_REG = crate::Reg; +#[doc = ""] +pub mod rf_lna_ctrl3_reg; +#[doc = "RF_MIXER_CTRL1_REG register accessor: an alias for `Reg`"] +pub type RF_MIXER_CTRL1_REG = crate::Reg; +#[doc = ""] +pub mod rf_mixer_ctrl1_reg; +#[doc = "RF_MIXER_CTRL2_REG register accessor: an alias for `Reg`"] +pub type RF_MIXER_CTRL2_REG = crate::Reg; +#[doc = ""] +pub mod rf_mixer_ctrl2_reg; +#[doc = "RF_OVERRULE_REG register accessor: an alias for `Reg`"] +pub type RF_OVERRULE_REG = crate::Reg; +#[doc = ""] +pub mod rf_overrule_reg; +#[doc = "RF_PA_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_PA_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_pa_ctrl_reg; +#[doc = "RF_RADIO_INIT_REG register accessor: an alias for `Reg`"] +pub type RF_RADIO_INIT_REG = crate::Reg; +#[doc = ""] +pub mod rf_radio_init_reg; +#[doc = "RF_RFCU_CTRL_REG register accessor: an alias for `Reg`"] +pub type RF_RFCU_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rf_rfcu_ctrl_reg; +#[doc = "RF_SCAN_FEEDBACK_REG register accessor: an alias for `Reg`"] +pub type RF_SCAN_FEEDBACK_REG = crate::Reg; +#[doc = ""] +pub mod rf_scan_feedback_reg; +#[doc = "RF_SPARE_REG register accessor: an alias for `Reg`"] +pub type RF_SPARE_REG = crate::Reg; +#[doc = ""] +pub mod rf_spare_reg; diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl1_reg.rs new file mode 100644 index 0000000..fd2703f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl1_reg.rs @@ -0,0 +1,207 @@ +#[doc = "Register `RF_ADC_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ADC_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADC_SIGN` reader - "] +pub struct ADC_SIGN_R(crate::FieldReader); +impl ADC_SIGN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADC_SIGN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_SIGN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_SIGN` writer - "] +pub struct ADC_SIGN_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_SIGN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u32 & 1) << 14); + self.w + } +} +#[doc = "Field `ADC_MUTE` reader - "] +pub struct ADC_MUTE_R(crate::FieldReader); +impl ADC_MUTE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADC_MUTE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_MUTE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_MUTE` writer - "] +pub struct ADC_MUTE_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_MUTE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u32 & 1) << 13); + self.w + } +} +#[doc = "Field `ADC_DC_OFFSET_SEL` reader - "] +pub struct ADC_DC_OFFSET_SEL_R(crate::FieldReader); +impl ADC_DC_OFFSET_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADC_DC_OFFSET_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_DC_OFFSET_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_DC_OFFSET_SEL` writer - "] +pub struct ADC_DC_OFFSET_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_DC_OFFSET_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 14"] + #[inline(always)] + pub fn adc_sign(&self) -> ADC_SIGN_R { + ADC_SIGN_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn adc_mute(&self) -> ADC_MUTE_R { + ADC_MUTE_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn adc_dc_offset_sel(&self) -> ADC_DC_OFFSET_SEL_R { + ADC_DC_OFFSET_SEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 14"] + #[inline(always)] + pub fn adc_sign(&mut self) -> ADC_SIGN_W { + ADC_SIGN_W { w: self } + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn adc_mute(&mut self) -> ADC_MUTE_W { + ADC_MUTE_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn adc_dc_offset_sel(&mut self) -> ADC_DC_OFFSET_SEL_W { + ADC_DC_OFFSET_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_adc_ctrl1_reg](index.html) module"] +pub struct RF_ADC_CTRL1_REG_SPEC; +impl crate::RegisterSpec for RF_ADC_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_adc_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for RF_ADC_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_adc_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for RF_ADC_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ADC_CTRL1_REG to value 0"] +impl crate::Resettable for RF_ADC_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl2_reg.rs new file mode 100644 index 0000000..aff1912 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl2_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ADC_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ADC_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADC_OFFN_I_WR` reader - "] +pub struct ADC_OFFN_I_WR_R(crate::FieldReader); +impl ADC_OFFN_I_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFN_I_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFN_I_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_OFFN_I_WR` writer - "] +pub struct ADC_OFFN_I_WR_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_OFFN_I_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 9)) | ((value as u32 & 0x01ff) << 9); + self.w + } +} +#[doc = "Field `ADC_OFFP_I_WR` reader - "] +pub struct ADC_OFFP_I_WR_R(crate::FieldReader); +impl ADC_OFFP_I_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFP_I_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFP_I_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_OFFP_I_WR` writer - "] +pub struct ADC_OFFP_I_WR_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_OFFP_I_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x01ff) | (value as u32 & 0x01ff); + self.w + } +} +impl R { + #[doc = "Bits 9:17"] + #[inline(always)] + pub fn adc_offn_i_wr(&self) -> ADC_OFFN_I_WR_R { + ADC_OFFN_I_WR_R::new(((self.bits >> 9) & 0x01ff) as u16) + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn adc_offp_i_wr(&self) -> ADC_OFFP_I_WR_R { + ADC_OFFP_I_WR_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Bits 9:17"] + #[inline(always)] + pub fn adc_offn_i_wr(&mut self) -> ADC_OFFN_I_WR_W { + ADC_OFFN_I_WR_W { w: self } + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn adc_offp_i_wr(&mut self) -> ADC_OFFP_I_WR_W { + ADC_OFFP_I_WR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_adc_ctrl2_reg](index.html) module"] +pub struct RF_ADC_CTRL2_REG_SPEC; +impl crate::RegisterSpec for RF_ADC_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_adc_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for RF_ADC_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_adc_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for RF_ADC_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ADC_CTRL2_REG to value 0"] +impl crate::Resettable for RF_ADC_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl3_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl3_reg.rs new file mode 100644 index 0000000..2016c8b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adc_ctrl3_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ADC_CTRL3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ADC_CTRL3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADC_OFFN_Q_WR` reader - "] +pub struct ADC_OFFN_Q_WR_R(crate::FieldReader); +impl ADC_OFFN_Q_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFN_Q_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFN_Q_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_OFFN_Q_WR` writer - "] +pub struct ADC_OFFN_Q_WR_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_OFFN_Q_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 9)) | ((value as u32 & 0x01ff) << 9); + self.w + } +} +#[doc = "Field `ADC_OFFP_Q_WR` reader - "] +pub struct ADC_OFFP_Q_WR_R(crate::FieldReader); +impl ADC_OFFP_Q_WR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFP_Q_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFP_Q_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_OFFP_Q_WR` writer - "] +pub struct ADC_OFFP_Q_WR_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_OFFP_Q_WR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x01ff) | (value as u32 & 0x01ff); + self.w + } +} +impl R { + #[doc = "Bits 9:17"] + #[inline(always)] + pub fn adc_offn_q_wr(&self) -> ADC_OFFN_Q_WR_R { + ADC_OFFN_Q_WR_R::new(((self.bits >> 9) & 0x01ff) as u16) + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn adc_offp_q_wr(&self) -> ADC_OFFP_Q_WR_R { + ADC_OFFP_Q_WR_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Bits 9:17"] + #[inline(always)] + pub fn adc_offn_q_wr(&mut self) -> ADC_OFFN_Q_WR_W { + ADC_OFFN_Q_WR_W { w: self } + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn adc_offp_q_wr(&mut self) -> ADC_OFFP_Q_WR_W { + ADC_OFFP_Q_WR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_adc_ctrl3_reg](index.html) module"] +pub struct RF_ADC_CTRL3_REG_SPEC; +impl crate::RegisterSpec for RF_ADC_CTRL3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_adc_ctrl3_reg::R](R) reader structure"] +impl crate::Readable for RF_ADC_CTRL3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_adc_ctrl3_reg::W](W) writer structure"] +impl crate::Writable for RF_ADC_CTRL3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ADC_CTRL3_REG to value 0"] +impl crate::Resettable for RF_ADC_CTRL3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_adci_dc_offset_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adci_dc_offset_reg.rs new file mode 100644 index 0000000..faf7b25 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adci_dc_offset_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `RF_ADCI_DC_OFFSET_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ADCI_DC_OFFSET_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADC_OFFN_I_RD` reader - "] +pub struct ADC_OFFN_I_RD_R(crate::FieldReader); +impl ADC_OFFN_I_RD_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFN_I_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFN_I_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_OFFP_I_RD` reader - "] +pub struct ADC_OFFP_I_RD_R(crate::FieldReader); +impl ADC_OFFP_I_RD_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFP_I_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFP_I_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 9:17"] + #[inline(always)] + pub fn adc_offn_i_rd(&self) -> ADC_OFFN_I_RD_R { + ADC_OFFN_I_RD_R::new(((self.bits >> 9) & 0x01ff) as u16) + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn adc_offp_i_rd(&self) -> ADC_OFFP_I_RD_R { + ADC_OFFP_I_RD_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_adci_dc_offset_reg](index.html) module"] +pub struct RF_ADCI_DC_OFFSET_REG_SPEC; +impl crate::RegisterSpec for RF_ADCI_DC_OFFSET_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_adci_dc_offset_reg::R](R) reader structure"] +impl crate::Readable for RF_ADCI_DC_OFFSET_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_adci_dc_offset_reg::W](W) writer structure"] +impl crate::Writable for RF_ADCI_DC_OFFSET_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ADCI_DC_OFFSET_REG to value 0x0002_0100"] +impl crate::Resettable for RF_ADCI_DC_OFFSET_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0002_0100 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_adcq_dc_offset_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adcq_dc_offset_reg.rs new file mode 100644 index 0000000..b12c066 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adcq_dc_offset_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `RF_ADCQ_DC_OFFSET_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ADCQ_DC_OFFSET_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADC_OFFN_Q_RD` reader - "] +pub struct ADC_OFFN_Q_RD_R(crate::FieldReader); +impl ADC_OFFN_Q_RD_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFN_Q_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFN_Q_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_OFFP_Q_RD` reader - "] +pub struct ADC_OFFP_Q_RD_R(crate::FieldReader); +impl ADC_OFFP_Q_RD_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + ADC_OFFP_Q_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_OFFP_Q_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 9:17"] + #[inline(always)] + pub fn adc_offn_q_rd(&self) -> ADC_OFFN_Q_RD_R { + ADC_OFFN_Q_RD_R::new(((self.bits >> 9) & 0x01ff) as u16) + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn adc_offp_q_rd(&self) -> ADC_OFFP_Q_RD_R { + ADC_OFFP_Q_RD_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_adcq_dc_offset_reg](index.html) module"] +pub struct RF_ADCQ_DC_OFFSET_REG_SPEC; +impl crate::RegisterSpec for RF_ADCQ_DC_OFFSET_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_adcq_dc_offset_reg::R](R) reader structure"] +impl crate::Readable for RF_ADCQ_DC_OFFSET_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_adcq_dc_offset_reg::W](W) writer structure"] +impl crate::Writable for RF_ADCQ_DC_OFFSET_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ADCQ_DC_OFFSET_REG to value 0x0002_0100"] +impl crate::Resettable for RF_ADCQ_DC_OFFSET_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0002_0100 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_ctrl_reg.rs new file mode 100644 index 0000000..1e0c166 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_ctrl_reg.rs @@ -0,0 +1,197 @@ +#[doc = "Register `RF_ADPLLDIG_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ADPLLDIG_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PWR_SW_TIM_CTRL` reader - "] +pub struct PWR_SW_TIM_CTRL_R(crate::FieldReader); +impl PWR_SW_TIM_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PWR_SW_TIM_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PWR_SW_TIM_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PWR_SW_TIM_CTRL` writer - "] +pub struct PWR_SW_TIM_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> PWR_SW_TIM_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u32 & 7) << 4); + self.w + } +} +#[doc = "Field `OPENLOOP_RDY_WR` reader - "] +pub struct OPENLOOP_RDY_WR_R(crate::FieldReader); +impl OPENLOOP_RDY_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OPENLOOP_RDY_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OPENLOOP_RDY_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OPENLOOP_RDY_WR` writer - "] +pub struct OPENLOOP_RDY_WR_W<'a> { + w: &'a mut W, +} +impl<'a> OPENLOOP_RDY_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `OPENLOOP_RDY_SEL` reader - "] +pub struct OPENLOOP_RDY_SEL_R(crate::FieldReader); +impl OPENLOOP_RDY_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + OPENLOOP_RDY_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for OPENLOOP_RDY_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `OPENLOOP_RDY_SEL` writer - "] +pub struct OPENLOOP_RDY_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> OPENLOOP_RDY_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn pwr_sw_tim_ctrl(&self) -> PWR_SW_TIM_CTRL_R { + PWR_SW_TIM_CTRL_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn openloop_rdy_wr(&self) -> OPENLOOP_RDY_WR_R { + OPENLOOP_RDY_WR_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn openloop_rdy_sel(&self) -> OPENLOOP_RDY_SEL_R { + OPENLOOP_RDY_SEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn pwr_sw_tim_ctrl(&mut self) -> PWR_SW_TIM_CTRL_W { + PWR_SW_TIM_CTRL_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn openloop_rdy_wr(&mut self) -> OPENLOOP_RDY_WR_W { + OPENLOOP_RDY_WR_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn openloop_rdy_sel(&mut self) -> OPENLOOP_RDY_SEL_W { + OPENLOOP_RDY_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_adplldig_ctrl_reg](index.html) module"] +pub struct RF_ADPLLDIG_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_ADPLLDIG_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_adplldig_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_ADPLLDIG_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_adplldig_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_ADPLLDIG_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ADPLLDIG_CTRL_REG to value 0x10"] +impl crate::Resettable for RF_ADPLLDIG_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x10 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_rfmon_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_rfmon_ctrl_reg.rs new file mode 100644 index 0000000..5c5fbe7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_adplldig_rfmon_ctrl_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `RF_ADPLLDIG_RFMON_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ADPLLDIG_RFMON_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLLDIG_RFMON_SPARE` reader - "] +pub struct ADPLLDIG_RFMON_SPARE_R(crate::FieldReader); +impl ADPLLDIG_RFMON_SPARE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_RFMON_SPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_RFMON_SPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_RFMON_SPARE` writer - "] +pub struct ADPLLDIG_RFMON_SPARE_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_RFMON_SPARE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u32 & 0x0f) << 4); + self.w + } +} +#[doc = "Field `ADPLLDIG_RFMON_MUX_SEL` reader - "] +pub struct ADPLLDIG_RFMON_MUX_SEL_R(crate::FieldReader); +impl ADPLLDIG_RFMON_MUX_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_RFMON_MUX_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_RFMON_MUX_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_RFMON_MUX_SEL` writer - "] +pub struct ADPLLDIG_RFMON_MUX_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_RFMON_MUX_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 1)) | ((value as u32 & 7) << 1); + self.w + } +} +#[doc = "Field `ADPLLDIG_SYNC_CLK_INV` reader - "] +pub struct ADPLLDIG_SYNC_CLK_INV_R(crate::FieldReader); +impl ADPLLDIG_SYNC_CLK_INV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_SYNC_CLK_INV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_SYNC_CLK_INV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_SYNC_CLK_INV` writer - "] +pub struct ADPLLDIG_SYNC_CLK_INV_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_SYNC_CLK_INV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bits 4:7"] + #[inline(always)] + pub fn adplldig_rfmon_spare(&self) -> ADPLLDIG_RFMON_SPARE_R { + ADPLLDIG_RFMON_SPARE_R::new(((self.bits >> 4) & 0x0f) as u8) + } + #[doc = "Bits 1:3"] + #[inline(always)] + pub fn adplldig_rfmon_mux_sel(&self) -> ADPLLDIG_RFMON_MUX_SEL_R { + ADPLLDIG_RFMON_MUX_SEL_R::new(((self.bits >> 1) & 7) as u8) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn adplldig_sync_clk_inv(&self) -> ADPLLDIG_SYNC_CLK_INV_R { + ADPLLDIG_SYNC_CLK_INV_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 4:7"] + #[inline(always)] + pub fn adplldig_rfmon_spare(&mut self) -> ADPLLDIG_RFMON_SPARE_W { + ADPLLDIG_RFMON_SPARE_W { w: self } + } + #[doc = "Bits 1:3"] + #[inline(always)] + pub fn adplldig_rfmon_mux_sel(&mut self) -> ADPLLDIG_RFMON_MUX_SEL_W { + ADPLLDIG_RFMON_MUX_SEL_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn adplldig_sync_clk_inv(&mut self) -> ADPLLDIG_SYNC_CLK_INV_W { + ADPLLDIG_SYNC_CLK_INV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_adplldig_rfmon_ctrl_reg](index.html) module"] +pub struct RF_ADPLLDIG_RFMON_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_ADPLLDIG_RFMON_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_adplldig_rfmon_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_ADPLLDIG_RFMON_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_adplldig_rfmon_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_ADPLLDIG_RFMON_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ADPLLDIG_RFMON_CTRL_REG to value 0x01"] +impl crate::Resettable for RF_ADPLLDIG_RFMON_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_agc_ext_lut_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_agc_ext_lut_reg.rs new file mode 100644 index 0000000..986648d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_agc_ext_lut_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `RF_AGC_EXT_LUT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_AGC_EXT_LUT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `AGC_EXT_LUT` reader - "] +pub struct AGC_EXT_LUT_R(crate::FieldReader); +impl AGC_EXT_LUT_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + AGC_EXT_LUT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for AGC_EXT_LUT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `AGC_EXT_LUT` writer - "] +pub struct AGC_EXT_LUT_W<'a> { + w: &'a mut W, +} +impl<'a> AGC_EXT_LUT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff); + self.w + } +} +impl R { + #[doc = "Bits 0:9"] + #[inline(always)] + pub fn agc_ext_lut(&self) -> AGC_EXT_LUT_R { + AGC_EXT_LUT_R::new((self.bits & 0x03ff) as u16) + } +} +impl W { + #[doc = "Bits 0:9"] + #[inline(always)] + pub fn agc_ext_lut(&mut self) -> AGC_EXT_LUT_W { + AGC_EXT_LUT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_agc_ext_lut_reg](index.html) module"] +pub struct RF_AGC_EXT_LUT_REG_SPEC; +impl crate::RegisterSpec for RF_AGC_EXT_LUT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_agc_ext_lut_reg::R](R) reader structure"] +impl crate::Readable for RF_AGC_EXT_LUT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_agc_ext_lut_reg::W](W) writer structure"] +impl crate::Writable for RF_AGC_EXT_LUT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_AGC_EXT_LUT_REG to value 0"] +impl crate::Resettable for RF_AGC_EXT_LUT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_attr_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_attr_reg.rs new file mode 100644 index 0000000..ba0480d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_attr_reg.rs @@ -0,0 +1,234 @@ +#[doc = "Register `RF_ATTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ATTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PA_POWER_SETTING` reader - "] +pub struct PA_POWER_SETTING_R(crate::FieldReader); +impl PA_POWER_SETTING_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_POWER_SETTING_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_POWER_SETTING_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_POWER_SETTING` writer - "] +pub struct PA_POWER_SETTING_W<'a> { + w: &'a mut W, +} +impl<'a> PA_POWER_SETTING_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 24)) | ((value as u32 & 0x0f) << 24); + self.w + } +} +#[doc = "Field `TIA_BIAS` reader - "] +pub struct TIA_BIAS_R(crate::FieldReader); +impl TIA_BIAS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIA_BIAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIA_BIAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIA_BIAS` writer - "] +pub struct TIA_BIAS_W<'a> { + w: &'a mut W, +} +impl<'a> TIA_BIAS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u32 & 1) << 12); + self.w + } +} +#[doc = "Field `RF_BIAS` reader - "] +pub struct RF_BIAS_R(crate::FieldReader); +impl RF_BIAS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_BIAS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_BIAS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_BIAS` writer - "] +pub struct RF_BIAS_W<'a> { + w: &'a mut W, +} +impl<'a> RF_BIAS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `IFF_POLARITY` reader - "] +pub struct IFF_POLARITY_R(crate::FieldReader); +impl IFF_POLARITY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + IFF_POLARITY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_POLARITY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_POLARITY` writer - "] +pub struct IFF_POLARITY_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_POLARITY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +impl R { + #[doc = "Bits 24:27"] + #[inline(always)] + pub fn pa_power_setting(&self) -> PA_POWER_SETTING_R { + PA_POWER_SETTING_R::new(((self.bits >> 24) & 0x0f) as u8) + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn tia_bias(&self) -> TIA_BIAS_R { + TIA_BIAS_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn rf_bias(&self) -> RF_BIAS_R { + RF_BIAS_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn iff_polarity(&self) -> IFF_POLARITY_R { + IFF_POLARITY_R::new(((self.bits >> 3) & 1) != 0) + } +} +impl W { + #[doc = "Bits 24:27"] + #[inline(always)] + pub fn pa_power_setting(&mut self) -> PA_POWER_SETTING_W { + PA_POWER_SETTING_W { w: self } + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn tia_bias(&mut self) -> TIA_BIAS_W { + TIA_BIAS_W { w: self } + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn rf_bias(&mut self) -> RF_BIAS_W { + RF_BIAS_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn iff_polarity(&mut self) -> IFF_POLARITY_W { + IFF_POLARITY_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_attr_reg](index.html) module"] +pub struct RF_ATTR_REG_SPEC; +impl crate::RegisterSpec for RF_ATTR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_attr_reg::R](R) reader structure"] +impl crate::Readable for RF_ATTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_attr_reg::W](W) writer structure"] +impl crate::Writable for RF_ATTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ATTR_REG to value 0x0c00_0820"] +impl crate::Resettable for RF_ATTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0c00_0820 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_cal_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_cal_ctrl_reg.rs new file mode 100644 index 0000000..37f4a3a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_cal_ctrl_reg.rs @@ -0,0 +1,207 @@ +#[doc = "Register `RF_CAL_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CAL_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DC_OFFSET_CAL_DIS` reader - "] +pub struct DC_OFFSET_CAL_DIS_R(crate::FieldReader); +impl DC_OFFSET_CAL_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DC_OFFSET_CAL_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DC_OFFSET_CAL_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DC_OFFSET_CAL_DIS` writer - "] +pub struct DC_OFFSET_CAL_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> DC_OFFSET_CAL_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `RF_CAL_CTRL_SPARE` reader - "] +pub struct RF_CAL_CTRL_SPARE_R(crate::FieldReader); +impl RF_CAL_CTRL_SPARE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_CAL_CTRL_SPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_CAL_CTRL_SPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_CAL_CTRL_SPARE` writer - "] +pub struct RF_CAL_CTRL_SPARE_W<'a> { + w: &'a mut W, +} +impl<'a> RF_CAL_CTRL_SPARE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `EO_CAL` reader - "] +pub struct EO_CAL_R(crate::FieldReader); +impl EO_CAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EO_CAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EO_CAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SO_CAL` writer - "] +pub struct SO_CAL_W<'a> { + w: &'a mut W, +} +impl<'a> SO_CAL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 4"] + #[inline(always)] + pub fn dc_offset_cal_dis(&self) -> DC_OFFSET_CAL_DIS_R { + DC_OFFSET_CAL_DIS_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_cal_ctrl_spare(&self) -> RF_CAL_CTRL_SPARE_R { + RF_CAL_CTRL_SPARE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn eo_cal(&self) -> EO_CAL_R { + EO_CAL_R::new(((self.bits >> 1) & 1) != 0) + } +} +impl W { + #[doc = "Bit 4"] + #[inline(always)] + pub fn dc_offset_cal_dis(&mut self) -> DC_OFFSET_CAL_DIS_W { + DC_OFFSET_CAL_DIS_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_cal_ctrl_spare(&mut self) -> RF_CAL_CTRL_SPARE_W { + RF_CAL_CTRL_SPARE_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn so_cal(&mut self) -> SO_CAL_W { + SO_CAL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cal_ctrl_reg](index.html) module"] +pub struct RF_CAL_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_CAL_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cal_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_CAL_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cal_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_CAL_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CAL_CTRL_REG to value 0"] +impl crate::Resettable for RF_CAL_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_calstate_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_calstate_reg.rs new file mode 100644 index 0000000..469b93c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_calstate_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `RF_CALSTATE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CALSTATE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CALSTATE` reader - "] +pub struct CALSTATE_R(crate::FieldReader); +impl CALSTATE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CALSTATE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CALSTATE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn calstate(&self) -> CALSTATE_R { + CALSTATE_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_calstate_reg](index.html) module"] +pub struct RF_CALSTATE_REG_SPEC; +impl crate::RegisterSpec for RF_CALSTATE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_calstate_reg::R](R) reader structure"] +impl crate::Readable for RF_CALSTATE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_calstate_reg::W](W) writer structure"] +impl crate::Writable for RF_CALSTATE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CALSTATE_REG to value 0"] +impl crate::Resettable for RF_CALSTATE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_ctrl_reg.rs new file mode 100644 index 0000000..d75e860 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_ctrl_reg.rs @@ -0,0 +1,738 @@ +#[doc = "Register `RF_DIAGIRQ_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_DIAGIRQ_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DIAG_BUS3_EDGE_SEL` reader - "] +pub struct DIAG_BUS3_EDGE_SEL_R(crate::FieldReader); +impl DIAG_BUS3_EDGE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS3_EDGE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS3_EDGE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS3_EDGE_SEL` writer - "] +pub struct DIAG_BUS3_EDGE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS3_EDGE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 30)) | ((value as u32 & 1) << 30); + self.w + } +} +#[doc = "Field `DIAG_BUS3_BIT_SEL` reader - "] +pub struct DIAG_BUS3_BIT_SEL_R(crate::FieldReader); +impl DIAG_BUS3_BIT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS3_BIT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS3_BIT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS3_BIT_SEL` writer - "] +pub struct DIAG_BUS3_BIT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS3_BIT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 27)) | ((value as u32 & 7) << 27); + self.w + } +} +#[doc = "Field `DIAG_BUS3_SEL` reader - "] +pub struct DIAG_BUS3_SEL_R(crate::FieldReader); +impl DIAG_BUS3_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS3_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS3_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS3_SEL` writer - "] +pub struct DIAG_BUS3_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS3_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 25)) | ((value as u32 & 3) << 25); + self.w + } +} +#[doc = "Field `DIAG_BUS3_IRQ_MASK` reader - "] +pub struct DIAG_BUS3_IRQ_MASK_R(crate::FieldReader); +impl DIAG_BUS3_IRQ_MASK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS3_IRQ_MASK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS3_IRQ_MASK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS3_IRQ_MASK` writer - "] +pub struct DIAG_BUS3_IRQ_MASK_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS3_IRQ_MASK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 24)) | ((value as u32 & 1) << 24); + self.w + } +} +#[doc = "Field `DIAG_BUS2_EDGE_SEL` reader - "] +pub struct DIAG_BUS2_EDGE_SEL_R(crate::FieldReader); +impl DIAG_BUS2_EDGE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS2_EDGE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS2_EDGE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS2_EDGE_SEL` writer - "] +pub struct DIAG_BUS2_EDGE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS2_EDGE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 22)) | ((value as u32 & 1) << 22); + self.w + } +} +#[doc = "Field `DIAG_BUS2_BIT_SEL` reader - "] +pub struct DIAG_BUS2_BIT_SEL_R(crate::FieldReader); +impl DIAG_BUS2_BIT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS2_BIT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS2_BIT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS2_BIT_SEL` writer - "] +pub struct DIAG_BUS2_BIT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS2_BIT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 19)) | ((value as u32 & 7) << 19); + self.w + } +} +#[doc = "Field `DIAG_BUS2_SEL` reader - "] +pub struct DIAG_BUS2_SEL_R(crate::FieldReader); +impl DIAG_BUS2_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS2_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS2_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS2_SEL` writer - "] +pub struct DIAG_BUS2_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS2_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 17)) | ((value as u32 & 3) << 17); + self.w + } +} +#[doc = "Field `DIAG_BUS2_IRQ_MASK` reader - "] +pub struct DIAG_BUS2_IRQ_MASK_R(crate::FieldReader); +impl DIAG_BUS2_IRQ_MASK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS2_IRQ_MASK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS2_IRQ_MASK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS2_IRQ_MASK` writer - "] +pub struct DIAG_BUS2_IRQ_MASK_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS2_IRQ_MASK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `DIAG_BUS1_EDGE_SEL` reader - "] +pub struct DIAG_BUS1_EDGE_SEL_R(crate::FieldReader); +impl DIAG_BUS1_EDGE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS1_EDGE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS1_EDGE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS1_EDGE_SEL` writer - "] +pub struct DIAG_BUS1_EDGE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS1_EDGE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u32 & 1) << 14); + self.w + } +} +#[doc = "Field `DIAG_BUS1_BIT_SEL` reader - "] +pub struct DIAG_BUS1_BIT_SEL_R(crate::FieldReader); +impl DIAG_BUS1_BIT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS1_BIT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS1_BIT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS1_BIT_SEL` writer - "] +pub struct DIAG_BUS1_BIT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS1_BIT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 11)) | ((value as u32 & 7) << 11); + self.w + } +} +#[doc = "Field `DIAG_BUS1_SEL` reader - "] +pub struct DIAG_BUS1_SEL_R(crate::FieldReader); +impl DIAG_BUS1_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS1_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS1_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS1_SEL` writer - "] +pub struct DIAG_BUS1_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS1_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 9)) | ((value as u32 & 3) << 9); + self.w + } +} +#[doc = "Field `DIAG_BUS1_IRQ_MASK` reader - "] +pub struct DIAG_BUS1_IRQ_MASK_R(crate::FieldReader); +impl DIAG_BUS1_IRQ_MASK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS1_IRQ_MASK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS1_IRQ_MASK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS1_IRQ_MASK` writer - "] +pub struct DIAG_BUS1_IRQ_MASK_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS1_IRQ_MASK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `DIAG_BUS0_EDGE_SEL` reader - "] +pub struct DIAG_BUS0_EDGE_SEL_R(crate::FieldReader); +impl DIAG_BUS0_EDGE_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS0_EDGE_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS0_EDGE_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS0_EDGE_SEL` writer - "] +pub struct DIAG_BUS0_EDGE_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS0_EDGE_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `DIAG_BUS0_BIT_SEL` reader - "] +pub struct DIAG_BUS0_BIT_SEL_R(crate::FieldReader); +impl DIAG_BUS0_BIT_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS0_BIT_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS0_BIT_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS0_BIT_SEL` writer - "] +pub struct DIAG_BUS0_BIT_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS0_BIT_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 3)) | ((value as u32 & 7) << 3); + self.w + } +} +#[doc = "Field `DIAG_BUS0_SEL` reader - "] +pub struct DIAG_BUS0_SEL_R(crate::FieldReader); +impl DIAG_BUS0_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAG_BUS0_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS0_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS0_SEL` writer - "] +pub struct DIAG_BUS0_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS0_SEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 1)) | ((value as u32 & 3) << 1); + self.w + } +} +#[doc = "Field `DIAG_BUS0_IRQ_MASK` reader - "] +pub struct DIAG_BUS0_IRQ_MASK_R(crate::FieldReader); +impl DIAG_BUS0_IRQ_MASK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + DIAG_BUS0_IRQ_MASK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAG_BUS0_IRQ_MASK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DIAG_BUS0_IRQ_MASK` writer - "] +pub struct DIAG_BUS0_IRQ_MASK_W<'a> { + w: &'a mut W, +} +impl<'a> DIAG_BUS0_IRQ_MASK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 30"] + #[inline(always)] + pub fn diag_bus3_edge_sel(&self) -> DIAG_BUS3_EDGE_SEL_R { + DIAG_BUS3_EDGE_SEL_R::new(((self.bits >> 30) & 1) != 0) + } + #[doc = "Bits 27:29"] + #[inline(always)] + pub fn diag_bus3_bit_sel(&self) -> DIAG_BUS3_BIT_SEL_R { + DIAG_BUS3_BIT_SEL_R::new(((self.bits >> 27) & 7) as u8) + } + #[doc = "Bits 25:26"] + #[inline(always)] + pub fn diag_bus3_sel(&self) -> DIAG_BUS3_SEL_R { + DIAG_BUS3_SEL_R::new(((self.bits >> 25) & 3) as u8) + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn diag_bus3_irq_mask(&self) -> DIAG_BUS3_IRQ_MASK_R { + DIAG_BUS3_IRQ_MASK_R::new(((self.bits >> 24) & 1) != 0) + } + #[doc = "Bit 22"] + #[inline(always)] + pub fn diag_bus2_edge_sel(&self) -> DIAG_BUS2_EDGE_SEL_R { + DIAG_BUS2_EDGE_SEL_R::new(((self.bits >> 22) & 1) != 0) + } + #[doc = "Bits 19:21"] + #[inline(always)] + pub fn diag_bus2_bit_sel(&self) -> DIAG_BUS2_BIT_SEL_R { + DIAG_BUS2_BIT_SEL_R::new(((self.bits >> 19) & 7) as u8) + } + #[doc = "Bits 17:18"] + #[inline(always)] + pub fn diag_bus2_sel(&self) -> DIAG_BUS2_SEL_R { + DIAG_BUS2_SEL_R::new(((self.bits >> 17) & 3) as u8) + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn diag_bus2_irq_mask(&self) -> DIAG_BUS2_IRQ_MASK_R { + DIAG_BUS2_IRQ_MASK_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bit 14"] + #[inline(always)] + pub fn diag_bus1_edge_sel(&self) -> DIAG_BUS1_EDGE_SEL_R { + DIAG_BUS1_EDGE_SEL_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bits 11:13"] + #[inline(always)] + pub fn diag_bus1_bit_sel(&self) -> DIAG_BUS1_BIT_SEL_R { + DIAG_BUS1_BIT_SEL_R::new(((self.bits >> 11) & 7) as u8) + } + #[doc = "Bits 9:10"] + #[inline(always)] + pub fn diag_bus1_sel(&self) -> DIAG_BUS1_SEL_R { + DIAG_BUS1_SEL_R::new(((self.bits >> 9) & 3) as u8) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn diag_bus1_irq_mask(&self) -> DIAG_BUS1_IRQ_MASK_R { + DIAG_BUS1_IRQ_MASK_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn diag_bus0_edge_sel(&self) -> DIAG_BUS0_EDGE_SEL_R { + DIAG_BUS0_EDGE_SEL_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn diag_bus0_bit_sel(&self) -> DIAG_BUS0_BIT_SEL_R { + DIAG_BUS0_BIT_SEL_R::new(((self.bits >> 3) & 7) as u8) + } + #[doc = "Bits 1:2"] + #[inline(always)] + pub fn diag_bus0_sel(&self) -> DIAG_BUS0_SEL_R { + DIAG_BUS0_SEL_R::new(((self.bits >> 1) & 3) as u8) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn diag_bus0_irq_mask(&self) -> DIAG_BUS0_IRQ_MASK_R { + DIAG_BUS0_IRQ_MASK_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 30"] + #[inline(always)] + pub fn diag_bus3_edge_sel(&mut self) -> DIAG_BUS3_EDGE_SEL_W { + DIAG_BUS3_EDGE_SEL_W { w: self } + } + #[doc = "Bits 27:29"] + #[inline(always)] + pub fn diag_bus3_bit_sel(&mut self) -> DIAG_BUS3_BIT_SEL_W { + DIAG_BUS3_BIT_SEL_W { w: self } + } + #[doc = "Bits 25:26"] + #[inline(always)] + pub fn diag_bus3_sel(&mut self) -> DIAG_BUS3_SEL_W { + DIAG_BUS3_SEL_W { w: self } + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn diag_bus3_irq_mask(&mut self) -> DIAG_BUS3_IRQ_MASK_W { + DIAG_BUS3_IRQ_MASK_W { w: self } + } + #[doc = "Bit 22"] + #[inline(always)] + pub fn diag_bus2_edge_sel(&mut self) -> DIAG_BUS2_EDGE_SEL_W { + DIAG_BUS2_EDGE_SEL_W { w: self } + } + #[doc = "Bits 19:21"] + #[inline(always)] + pub fn diag_bus2_bit_sel(&mut self) -> DIAG_BUS2_BIT_SEL_W { + DIAG_BUS2_BIT_SEL_W { w: self } + } + #[doc = "Bits 17:18"] + #[inline(always)] + pub fn diag_bus2_sel(&mut self) -> DIAG_BUS2_SEL_W { + DIAG_BUS2_SEL_W { w: self } + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn diag_bus2_irq_mask(&mut self) -> DIAG_BUS2_IRQ_MASK_W { + DIAG_BUS2_IRQ_MASK_W { w: self } + } + #[doc = "Bit 14"] + #[inline(always)] + pub fn diag_bus1_edge_sel(&mut self) -> DIAG_BUS1_EDGE_SEL_W { + DIAG_BUS1_EDGE_SEL_W { w: self } + } + #[doc = "Bits 11:13"] + #[inline(always)] + pub fn diag_bus1_bit_sel(&mut self) -> DIAG_BUS1_BIT_SEL_W { + DIAG_BUS1_BIT_SEL_W { w: self } + } + #[doc = "Bits 9:10"] + #[inline(always)] + pub fn diag_bus1_sel(&mut self) -> DIAG_BUS1_SEL_W { + DIAG_BUS1_SEL_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn diag_bus1_irq_mask(&mut self) -> DIAG_BUS1_IRQ_MASK_W { + DIAG_BUS1_IRQ_MASK_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn diag_bus0_edge_sel(&mut self) -> DIAG_BUS0_EDGE_SEL_W { + DIAG_BUS0_EDGE_SEL_W { w: self } + } + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn diag_bus0_bit_sel(&mut self) -> DIAG_BUS0_BIT_SEL_W { + DIAG_BUS0_BIT_SEL_W { w: self } + } + #[doc = "Bits 1:2"] + #[inline(always)] + pub fn diag_bus0_sel(&mut self) -> DIAG_BUS0_SEL_W { + DIAG_BUS0_SEL_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn diag_bus0_irq_mask(&mut self) -> DIAG_BUS0_IRQ_MASK_W { + DIAG_BUS0_IRQ_MASK_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_diagirq_ctrl_reg](index.html) module"] +pub struct RF_DIAGIRQ_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_DIAGIRQ_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_diagirq_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_DIAGIRQ_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_diagirq_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_DIAGIRQ_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_DIAGIRQ_CTRL_REG to value 0"] +impl crate::Resettable for RF_DIAGIRQ_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_stat_reg.rs new file mode 100644 index 0000000..6364f37 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_diagirq_stat_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `RF_DIAGIRQ_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_DIAGIRQ_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DIAGIRQ_STAT` reader - "] +pub struct DIAGIRQ_STAT_R(crate::FieldReader); +impl DIAGIRQ_STAT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DIAGIRQ_STAT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DIAGIRQ_STAT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn diagirq_stat(&self) -> DIAGIRQ_STAT_R { + DIAGIRQ_STAT_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_diagirq_stat_reg](index.html) module"] +pub struct RF_DIAGIRQ_STAT_REG_SPEC; +impl crate::RegisterSpec for RF_DIAGIRQ_STAT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_diagirq_stat_reg::R](R) reader structure"] +impl crate::Readable for RF_DIAGIRQ_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_diagirq_stat_reg::W](W) writer structure"] +impl crate::Writable for RF_DIAGIRQ_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_DIAGIRQ_STAT_REG to value 0"] +impl crate::Resettable for RF_DIAGIRQ_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_iff_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_iff_ctrl_reg.rs new file mode 100644 index 0000000..e14afa2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_iff_ctrl_reg.rs @@ -0,0 +1,318 @@ +#[doc = "Register `RF_IFF_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_IFF_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IFF_DCOC_DAC_REFCUR_CTRL` reader - "] +pub struct IFF_DCOC_DAC_REFCUR_CTRL_R(crate::FieldReader); +impl IFF_DCOC_DAC_REFCUR_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFF_DCOC_DAC_REFCUR_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_DCOC_DAC_REFCUR_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_DCOC_DAC_REFCUR_CTRL` writer - "] +pub struct IFF_DCOC_DAC_REFCUR_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_DCOC_DAC_REFCUR_CTRL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 13)) | ((value as u32 & 3) << 13); + self.w + } +} +#[doc = "Field `IFF_COMPLEX_DIS` reader - "] +pub struct IFF_COMPLEX_DIS_R(crate::FieldReader); +impl IFF_COMPLEX_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + IFF_COMPLEX_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_COMPLEX_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_COMPLEX_DIS` writer - "] +pub struct IFF_COMPLEX_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_COMPLEX_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u32 & 1) << 12); + self.w + } +} +#[doc = "Field `RF_IFF_CTRL_SPARE` reader - "] +pub struct RF_IFF_CTRL_SPARE_R(crate::FieldReader); +impl RF_IFF_CTRL_SPARE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_IFF_CTRL_SPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_IFF_CTRL_SPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_IFF_CTRL_SPARE` writer - "] +pub struct RF_IFF_CTRL_SPARE_W<'a> { + w: &'a mut W, +} +impl<'a> RF_IFF_CTRL_SPARE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 6)) | ((value as u32 & 0x3f) << 6); + self.w + } +} +#[doc = "Field `IFF_DCOC_DAC_DIS` reader - "] +pub struct IFF_DCOC_DAC_DIS_R(crate::FieldReader); +impl IFF_DCOC_DAC_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + IFF_DCOC_DAC_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_DCOC_DAC_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_DCOC_DAC_DIS` writer - "] +pub struct IFF_DCOC_DAC_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_DCOC_DAC_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `IF_MUTE` reader - "] +pub struct IF_MUTE_R(crate::FieldReader); +impl IF_MUTE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + IF_MUTE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IF_MUTE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IF_MUTE` writer - "] +pub struct IF_MUTE_W<'a> { + w: &'a mut W, +} +impl<'a> IF_MUTE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `IF_CAL_TRIM` reader - "] +pub struct IF_CAL_TRIM_R(crate::FieldReader); +impl IF_CAL_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IF_CAL_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IF_CAL_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IF_CAL_TRIM` writer - "] +pub struct IF_CAL_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> IF_CAL_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u32 & 3); + self.w + } +} +impl R { + #[doc = "Bits 13:14"] + #[inline(always)] + pub fn iff_dcoc_dac_refcur_ctrl(&self) -> IFF_DCOC_DAC_REFCUR_CTRL_R { + IFF_DCOC_DAC_REFCUR_CTRL_R::new(((self.bits >> 13) & 3) as u8) + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn iff_complex_dis(&self) -> IFF_COMPLEX_DIS_R { + IFF_COMPLEX_DIS_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bits 6:11"] + #[inline(always)] + pub fn rf_iff_ctrl_spare(&self) -> RF_IFF_CTRL_SPARE_R { + RF_IFF_CTRL_SPARE_R::new(((self.bits >> 6) & 0x3f) as u8) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn iff_dcoc_dac_dis(&self) -> IFF_DCOC_DAC_DIS_R { + IFF_DCOC_DAC_DIS_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn if_mute(&self) -> IF_MUTE_R { + IF_MUTE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn if_cal_trim(&self) -> IF_CAL_TRIM_R { + IF_CAL_TRIM_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 13:14"] + #[inline(always)] + pub fn iff_dcoc_dac_refcur_ctrl(&mut self) -> IFF_DCOC_DAC_REFCUR_CTRL_W { + IFF_DCOC_DAC_REFCUR_CTRL_W { w: self } + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn iff_complex_dis(&mut self) -> IFF_COMPLEX_DIS_W { + IFF_COMPLEX_DIS_W { w: self } + } + #[doc = "Bits 6:11"] + #[inline(always)] + pub fn rf_iff_ctrl_spare(&mut self) -> RF_IFF_CTRL_SPARE_W { + RF_IFF_CTRL_SPARE_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn iff_dcoc_dac_dis(&mut self) -> IFF_DCOC_DAC_DIS_W { + IFF_DCOC_DAC_DIS_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn if_mute(&mut self) -> IF_MUTE_W { + IF_MUTE_W { w: self } + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn if_cal_trim(&mut self) -> IF_CAL_TRIM_W { + IF_CAL_TRIM_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_iff_ctrl_reg](index.html) module"] +pub struct RF_IFF_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_IFF_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_iff_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_IFF_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_iff_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_IFF_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_IFF_CTRL_REG to value 0x01"] +impl crate::Resettable for RF_IFF_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_io_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_io_ctrl_reg.rs new file mode 100644 index 0000000..20c9b00 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_io_ctrl_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_IO_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_IO_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFIO_TUNE_CAP_TRIM_TX` reader - "] +pub struct RFIO_TUNE_CAP_TRIM_TX_R(crate::FieldReader); +impl RFIO_TUNE_CAP_TRIM_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_TUNE_CAP_TRIM_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_TUNE_CAP_TRIM_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_TUNE_CAP_TRIM_TX` writer - "] +pub struct RFIO_TUNE_CAP_TRIM_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_TUNE_CAP_TRIM_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `RFIO_TUNE_CAP_TRIM_RX` reader - "] +pub struct RFIO_TUNE_CAP_TRIM_RX_R(crate::FieldReader); +impl RFIO_TUNE_CAP_TRIM_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_TUNE_CAP_TRIM_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_TUNE_CAP_TRIM_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_TUNE_CAP_TRIM_RX` writer - "] +pub struct RFIO_TUNE_CAP_TRIM_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_TUNE_CAP_TRIM_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn rfio_tune_cap_trim_tx(&self) -> RFIO_TUNE_CAP_TRIM_TX_R { + RFIO_TUNE_CAP_TRIM_TX_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rfio_tune_cap_trim_rx(&self) -> RFIO_TUNE_CAP_TRIM_RX_R { + RFIO_TUNE_CAP_TRIM_RX_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn rfio_tune_cap_trim_tx(&mut self) -> RFIO_TUNE_CAP_TRIM_TX_W { + RFIO_TUNE_CAP_TRIM_TX_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn rfio_tune_cap_trim_rx(&mut self) -> RFIO_TUNE_CAP_TRIM_RX_W { + RFIO_TUNE_CAP_TRIM_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_io_ctrl_reg](index.html) module"] +pub struct RF_IO_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_IO_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_io_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_IO_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_io_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_IO_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_IO_CTRL_REG to value 0x0100"] +impl crate::Resettable for RF_IO_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0100 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_irq_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_irq_ctrl_reg.rs new file mode 100644 index 0000000..1102ddb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_irq_ctrl_reg.rs @@ -0,0 +1,91 @@ +#[doc = "Register `RF_IRQ_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_IRQ_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `EO_CAL_CLEAR` writer - "] +pub struct EO_CAL_CLEAR_W<'a> { + w: &'a mut W, +} +impl<'a> EO_CAL_CLEAR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl W { + #[doc = "Bit 0"] + #[inline(always)] + pub fn eo_cal_clear(&mut self) -> EO_CAL_CLEAR_W { + EO_CAL_CLEAR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_irq_ctrl_reg](index.html) module"] +pub struct RF_IRQ_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_IRQ_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_irq_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_IRQ_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_irq_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_IRQ_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_IRQ_CTRL_REG to value 0x01"] +impl crate::Resettable for RF_IRQ_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_ctrl_reg.rs new file mode 100644 index 0000000..84b27ce --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_ctrl_reg.rs @@ -0,0 +1,637 @@ +#[doc = "Register `RF_LDO_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_LDO_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LDO_DCO_HOLD_OVR_EN` reader - "] +pub struct LDO_DCO_HOLD_OVR_EN_R(crate::FieldReader); +impl LDO_DCO_HOLD_OVR_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DCO_HOLD_OVR_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DCO_HOLD_OVR_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DCO_HOLD_OVR_EN` writer - "] +pub struct LDO_DCO_HOLD_OVR_EN_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DCO_HOLD_OVR_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 29)) | ((value as u32 & 1) << 29); + self.w + } +} +#[doc = "Field `LDO_DCO_HOLD_OVR_VAL` reader - "] +pub struct LDO_DCO_HOLD_OVR_VAL_R(crate::FieldReader); +impl LDO_DCO_HOLD_OVR_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DCO_HOLD_OVR_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DCO_HOLD_OVR_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DCO_HOLD_OVR_VAL` writer - "] +pub struct LDO_DCO_HOLD_OVR_VAL_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DCO_HOLD_OVR_VAL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 28)) | ((value as u32 & 1) << 28); + self.w + } +} +#[doc = "Field `LDO_DTC_HOLD_OVR_EN` reader - "] +pub struct LDO_DTC_HOLD_OVR_EN_R(crate::FieldReader); +impl LDO_DTC_HOLD_OVR_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DTC_HOLD_OVR_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DTC_HOLD_OVR_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DTC_HOLD_OVR_EN` writer - "] +pub struct LDO_DTC_HOLD_OVR_EN_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DTC_HOLD_OVR_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 27)) | ((value as u32 & 1) << 27); + self.w + } +} +#[doc = "Field `LDO_DTC_HOLD_OVR_VAL` reader - "] +pub struct LDO_DTC_HOLD_OVR_VAL_R(crate::FieldReader); +impl LDO_DTC_HOLD_OVR_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DTC_HOLD_OVR_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DTC_HOLD_OVR_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DTC_HOLD_OVR_VAL` writer - "] +pub struct LDO_DTC_HOLD_OVR_VAL_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DTC_HOLD_OVR_VAL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 26)) | ((value as u32 & 1) << 26); + self.w + } +} +#[doc = "Field `LDO_RADIO_HOLD_OVR_EN` reader - "] +pub struct LDO_RADIO_HOLD_OVR_EN_R(crate::FieldReader); +impl LDO_RADIO_HOLD_OVR_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_RADIO_HOLD_OVR_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_RADIO_HOLD_OVR_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_RADIO_HOLD_OVR_EN` writer - "] +pub struct LDO_RADIO_HOLD_OVR_EN_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_RADIO_HOLD_OVR_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 25)) | ((value as u32 & 1) << 25); + self.w + } +} +#[doc = "Field `LDO_RADIO_HOLD_OVR_VAL` reader - "] +pub struct LDO_RADIO_HOLD_OVR_VAL_R(crate::FieldReader); +impl LDO_RADIO_HOLD_OVR_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_RADIO_HOLD_OVR_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_RADIO_HOLD_OVR_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_RADIO_HOLD_OVR_VAL` writer - "] +pub struct LDO_RADIO_HOLD_OVR_VAL_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_RADIO_HOLD_OVR_VAL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 24)) | ((value as u32 & 1) << 24); + self.w + } +} +#[doc = "Field `LDO_VREF_SMPL_TIME` reader - "] +pub struct LDO_VREF_SMPL_TIME_R(crate::FieldReader); +impl LDO_VREF_SMPL_TIME_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_VREF_SMPL_TIME_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_VREF_SMPL_TIME_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_VREF_SMPL_TIME` writer - "] +pub struct LDO_VREF_SMPL_TIME_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_VREF_SMPL_TIME_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 16)) | ((value as u32 & 0x1f) << 16); + self.w + } +} +#[doc = "Field `LDO_DCO_CONT_ENABLE` reader - "] +pub struct LDO_DCO_CONT_ENABLE_R(crate::FieldReader); +impl LDO_DCO_CONT_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DCO_CONT_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DCO_CONT_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DCO_CONT_ENABLE` writer - "] +pub struct LDO_DCO_CONT_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DCO_CONT_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u32 & 1) << 11); + self.w + } +} +#[doc = "Field `LDO_DCO_LEVEL` reader - "] +pub struct LDO_DCO_LEVEL_R(crate::FieldReader); +impl LDO_DCO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_DCO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DCO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DCO_LEVEL` writer - "] +pub struct LDO_DCO_LEVEL_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DCO_LEVEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 8)) | ((value as u32 & 7) << 8); + self.w + } +} +#[doc = "Field `LDO_DTC_CONT_ENABLE` reader - "] +pub struct LDO_DTC_CONT_ENABLE_R(crate::FieldReader); +impl LDO_DTC_CONT_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DTC_CONT_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DTC_CONT_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DTC_CONT_ENABLE` writer - "] +pub struct LDO_DTC_CONT_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DTC_CONT_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `LDO_DTC_LEVEL` reader - "] +pub struct LDO_DTC_LEVEL_R(crate::FieldReader); +impl LDO_DTC_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_DTC_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DTC_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_DTC_LEVEL` writer - "] +pub struct LDO_DTC_LEVEL_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_DTC_LEVEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u32 & 7) << 4); + self.w + } +} +#[doc = "Field `LDO_RADIO_CONT_ENABLE` reader - "] +pub struct LDO_RADIO_CONT_ENABLE_R(crate::FieldReader); +impl LDO_RADIO_CONT_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_RADIO_CONT_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_RADIO_CONT_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_RADIO_CONT_ENABLE` writer - "] +pub struct LDO_RADIO_CONT_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_RADIO_CONT_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `LDO_RADIO_LEVEL` reader - "] +pub struct LDO_RADIO_LEVEL_R(crate::FieldReader); +impl LDO_RADIO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_RADIO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_RADIO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_RADIO_LEVEL` writer - "] +pub struct LDO_RADIO_LEVEL_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_RADIO_LEVEL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bit 29"] + #[inline(always)] + pub fn ldo_dco_hold_ovr_en(&self) -> LDO_DCO_HOLD_OVR_EN_R { + LDO_DCO_HOLD_OVR_EN_R::new(((self.bits >> 29) & 1) != 0) + } + #[doc = "Bit 28"] + #[inline(always)] + pub fn ldo_dco_hold_ovr_val(&self) -> LDO_DCO_HOLD_OVR_VAL_R { + LDO_DCO_HOLD_OVR_VAL_R::new(((self.bits >> 28) & 1) != 0) + } + #[doc = "Bit 27"] + #[inline(always)] + pub fn ldo_dtc_hold_ovr_en(&self) -> LDO_DTC_HOLD_OVR_EN_R { + LDO_DTC_HOLD_OVR_EN_R::new(((self.bits >> 27) & 1) != 0) + } + #[doc = "Bit 26"] + #[inline(always)] + pub fn ldo_dtc_hold_ovr_val(&self) -> LDO_DTC_HOLD_OVR_VAL_R { + LDO_DTC_HOLD_OVR_VAL_R::new(((self.bits >> 26) & 1) != 0) + } + #[doc = "Bit 25"] + #[inline(always)] + pub fn ldo_radio_hold_ovr_en(&self) -> LDO_RADIO_HOLD_OVR_EN_R { + LDO_RADIO_HOLD_OVR_EN_R::new(((self.bits >> 25) & 1) != 0) + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn ldo_radio_hold_ovr_val(&self) -> LDO_RADIO_HOLD_OVR_VAL_R { + LDO_RADIO_HOLD_OVR_VAL_R::new(((self.bits >> 24) & 1) != 0) + } + #[doc = "Bits 16:20"] + #[inline(always)] + pub fn ldo_vref_smpl_time(&self) -> LDO_VREF_SMPL_TIME_R { + LDO_VREF_SMPL_TIME_R::new(((self.bits >> 16) & 0x1f) as u8) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn ldo_dco_cont_enable(&self) -> LDO_DCO_CONT_ENABLE_R { + LDO_DCO_CONT_ENABLE_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bits 8:10"] + #[inline(always)] + pub fn ldo_dco_level(&self) -> LDO_DCO_LEVEL_R { + LDO_DCO_LEVEL_R::new(((self.bits >> 8) & 7) as u8) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn ldo_dtc_cont_enable(&self) -> LDO_DTC_CONT_ENABLE_R { + LDO_DTC_CONT_ENABLE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn ldo_dtc_level(&self) -> LDO_DTC_LEVEL_R { + LDO_DTC_LEVEL_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn ldo_radio_cont_enable(&self) -> LDO_RADIO_CONT_ENABLE_R { + LDO_RADIO_CONT_ENABLE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn ldo_radio_level(&self) -> LDO_RADIO_LEVEL_R { + LDO_RADIO_LEVEL_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bit 29"] + #[inline(always)] + pub fn ldo_dco_hold_ovr_en(&mut self) -> LDO_DCO_HOLD_OVR_EN_W { + LDO_DCO_HOLD_OVR_EN_W { w: self } + } + #[doc = "Bit 28"] + #[inline(always)] + pub fn ldo_dco_hold_ovr_val(&mut self) -> LDO_DCO_HOLD_OVR_VAL_W { + LDO_DCO_HOLD_OVR_VAL_W { w: self } + } + #[doc = "Bit 27"] + #[inline(always)] + pub fn ldo_dtc_hold_ovr_en(&mut self) -> LDO_DTC_HOLD_OVR_EN_W { + LDO_DTC_HOLD_OVR_EN_W { w: self } + } + #[doc = "Bit 26"] + #[inline(always)] + pub fn ldo_dtc_hold_ovr_val(&mut self) -> LDO_DTC_HOLD_OVR_VAL_W { + LDO_DTC_HOLD_OVR_VAL_W { w: self } + } + #[doc = "Bit 25"] + #[inline(always)] + pub fn ldo_radio_hold_ovr_en(&mut self) -> LDO_RADIO_HOLD_OVR_EN_W { + LDO_RADIO_HOLD_OVR_EN_W { w: self } + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn ldo_radio_hold_ovr_val(&mut self) -> LDO_RADIO_HOLD_OVR_VAL_W { + LDO_RADIO_HOLD_OVR_VAL_W { w: self } + } + #[doc = "Bits 16:20"] + #[inline(always)] + pub fn ldo_vref_smpl_time(&mut self) -> LDO_VREF_SMPL_TIME_W { + LDO_VREF_SMPL_TIME_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn ldo_dco_cont_enable(&mut self) -> LDO_DCO_CONT_ENABLE_W { + LDO_DCO_CONT_ENABLE_W { w: self } + } + #[doc = "Bits 8:10"] + #[inline(always)] + pub fn ldo_dco_level(&mut self) -> LDO_DCO_LEVEL_W { + LDO_DCO_LEVEL_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn ldo_dtc_cont_enable(&mut self) -> LDO_DTC_CONT_ENABLE_W { + LDO_DTC_CONT_ENABLE_W { w: self } + } + #[doc = "Bits 4:6"] + #[inline(always)] + pub fn ldo_dtc_level(&mut self) -> LDO_DTC_LEVEL_W { + LDO_DTC_LEVEL_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn ldo_radio_cont_enable(&mut self) -> LDO_RADIO_CONT_ENABLE_W { + LDO_RADIO_CONT_ENABLE_W { w: self } + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn ldo_radio_level(&mut self) -> LDO_RADIO_LEVEL_W { + LDO_RADIO_LEVEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_ldo_ctrl_reg](index.html) module"] +pub struct RF_LDO_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_LDO_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_ldo_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_LDO_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_ldo_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_LDO_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_LDO_CTRL_REG to value 0x0019_0333"] +impl crate::Resettable for RF_LDO_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0019_0333 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_status_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_status_reg.rs new file mode 100644 index 0000000..d42f4bd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_status_reg.rs @@ -0,0 +1,246 @@ +#[doc = "Register `RF_LDO_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_LDO_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ldo_dtc_vref_hold_rd` reader - "] +pub struct LDO_DTC_VREF_HOLD_RD_R(crate::FieldReader); +impl LDO_DTC_VREF_HOLD_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DTC_VREF_HOLD_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DTC_VREF_HOLD_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ldo_dco_vref_hold_rd` reader - "] +pub struct LDO_DCO_VREF_HOLD_RD_R(crate::FieldReader); +impl LDO_DCO_VREF_HOLD_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DCO_VREF_HOLD_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DCO_VREF_HOLD_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ldo_radio_vref_hold_rd` reader - "] +pub struct LDO_RADIO_VREF_HOLD_RD_R(crate::FieldReader); +impl LDO_RADIO_VREF_HOLD_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_RADIO_VREF_HOLD_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_RADIO_VREF_HOLD_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ldo_dtc_en_rd` reader - "] +pub struct LDO_DTC_EN_RD_R(crate::FieldReader); +impl LDO_DTC_EN_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DTC_EN_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DTC_EN_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ldo_dco_en_rd` reader - "] +pub struct LDO_DCO_EN_RD_R(crate::FieldReader); +impl LDO_DCO_EN_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + LDO_DCO_EN_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_DCO_EN_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_ZERO_EN_RD` reader - "] +pub struct ADPLLDIG_LDO_ZERO_EN_RD_R(crate::FieldReader); +impl ADPLLDIG_LDO_ZERO_EN_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_LDO_ZERO_EN_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_ZERO_EN_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_EN_RD` reader - "] +pub struct ADPLLDIG_LDO_EN_RD_R(crate::FieldReader); +impl ADPLLDIG_LDO_EN_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_LDO_EN_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_EN_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_LDO_ZERO_EN_RD` reader - "] +pub struct RADIO_LDO_ZERO_EN_RD_R(crate::FieldReader); +impl RADIO_LDO_ZERO_EN_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_LDO_ZERO_EN_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_LDO_ZERO_EN_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_LDO_EN_RD` reader - "] +pub struct RADIO_LDO_EN_RD_R(crate::FieldReader); +impl RADIO_LDO_EN_RD_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_LDO_EN_RD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_LDO_EN_RD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 8"] + #[inline(always)] + pub fn ldo_dtc_vref_hold_rd(&self) -> LDO_DTC_VREF_HOLD_RD_R { + LDO_DTC_VREF_HOLD_RD_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn ldo_dco_vref_hold_rd(&self) -> LDO_DCO_VREF_HOLD_RD_R { + LDO_DCO_VREF_HOLD_RD_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn ldo_radio_vref_hold_rd(&self) -> LDO_RADIO_VREF_HOLD_RD_R { + LDO_RADIO_VREF_HOLD_RD_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn ldo_dtc_en_rd(&self) -> LDO_DTC_EN_RD_R { + LDO_DTC_EN_RD_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn ldo_dco_en_rd(&self) -> LDO_DCO_EN_RD_R { + LDO_DCO_EN_RD_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn adplldig_ldo_zero_en_rd(&self) -> ADPLLDIG_LDO_ZERO_EN_RD_R { + ADPLLDIG_LDO_ZERO_EN_RD_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn adplldig_ldo_en_rd(&self) -> ADPLLDIG_LDO_EN_RD_R { + ADPLLDIG_LDO_EN_RD_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn radio_ldo_zero_en_rd(&self) -> RADIO_LDO_ZERO_EN_RD_R { + RADIO_LDO_ZERO_EN_RD_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn radio_ldo_en_rd(&self) -> RADIO_LDO_EN_RD_R { + RADIO_LDO_EN_RD_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_ldo_status_reg](index.html) module"] +pub struct RF_LDO_STATUS_REG_SPEC; +impl crate::RegisterSpec for RF_LDO_STATUS_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_ldo_status_reg::R](R) reader structure"] +impl crate::Readable for RF_LDO_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_ldo_status_reg::W](W) writer structure"] +impl crate::Writable for RF_LDO_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_LDO_STATUS_REG to value 0"] +impl crate::Resettable for RF_LDO_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_vref_sel_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_vref_sel_reg.rs new file mode 100644 index 0000000..33551f9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_ldo_vref_sel_reg.rs @@ -0,0 +1,207 @@ +#[doc = "Register `RF_LDO_VREF_SEL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_LDO_VREF_SEL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RF_LDO_DCO_VREF_SEL` reader - "] +pub struct RF_LDO_DCO_VREF_SEL_R(crate::FieldReader); +impl RF_LDO_DCO_VREF_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_LDO_DCO_VREF_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_LDO_DCO_VREF_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_LDO_DCO_VREF_SEL` writer - "] +pub struct RF_LDO_DCO_VREF_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_LDO_DCO_VREF_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RF_LDO_DTC_VREF_SEL` reader - "] +pub struct RF_LDO_DTC_VREF_SEL_R(crate::FieldReader); +impl RF_LDO_DTC_VREF_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_LDO_DTC_VREF_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_LDO_DTC_VREF_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_LDO_DTC_VREF_SEL` writer - "] +pub struct RF_LDO_DTC_VREF_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_LDO_DTC_VREF_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RF_LDO_RADIO_VREF_SEL` reader - "] +pub struct RF_LDO_RADIO_VREF_SEL_R(crate::FieldReader); +impl RF_LDO_RADIO_VREF_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_LDO_RADIO_VREF_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_LDO_RADIO_VREF_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_LDO_RADIO_VREF_SEL` writer - "] +pub struct RF_LDO_RADIO_VREF_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_LDO_RADIO_VREF_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_ldo_dco_vref_sel(&self) -> RF_LDO_DCO_VREF_SEL_R { + RF_LDO_DCO_VREF_SEL_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rf_ldo_dtc_vref_sel(&self) -> RF_LDO_DTC_VREF_SEL_R { + RF_LDO_DTC_VREF_SEL_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_ldo_radio_vref_sel(&self) -> RF_LDO_RADIO_VREF_SEL_R { + RF_LDO_RADIO_VREF_SEL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_ldo_dco_vref_sel(&mut self) -> RF_LDO_DCO_VREF_SEL_W { + RF_LDO_DCO_VREF_SEL_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rf_ldo_dtc_vref_sel(&mut self) -> RF_LDO_DTC_VREF_SEL_W { + RF_LDO_DTC_VREF_SEL_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_ldo_radio_vref_sel(&mut self) -> RF_LDO_RADIO_VREF_SEL_W { + RF_LDO_RADIO_VREF_SEL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_ldo_vref_sel_reg](index.html) module"] +pub struct RF_LDO_VREF_SEL_REG_SPEC; +impl crate::RegisterSpec for RF_LDO_VREF_SEL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_ldo_vref_sel_reg::R](R) reader structure"] +impl crate::Readable for RF_LDO_VREF_SEL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_ldo_vref_sel_reg::W](W) writer structure"] +impl crate::Writable for RF_LDO_VREF_SEL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_LDO_VREF_SEL_REG to value 0"] +impl crate::Resettable for RF_LDO_VREF_SEL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl1_reg.rs new file mode 100644 index 0000000..750061e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl1_reg.rs @@ -0,0 +1,251 @@ +#[doc = "Register `RF_LNA_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_LNA_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LNA_TRIM_GAIN4_HP` reader - "] +pub struct LNA_TRIM_GAIN4_HP_R(crate::FieldReader); +impl LNA_TRIM_GAIN4_HP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN4_HP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN4_HP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN4_HP` writer - "] +pub struct LNA_TRIM_GAIN4_HP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN4_HP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 20)) | ((value as u32 & 0x1f) << 20); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN3_HP` reader - "] +pub struct LNA_TRIM_GAIN3_HP_R(crate::FieldReader); +impl LNA_TRIM_GAIN3_HP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN3_HP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN3_HP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN3_HP` writer - "] +pub struct LNA_TRIM_GAIN3_HP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN3_HP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 15)) | ((value as u32 & 0x1f) << 15); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN2_HP` reader - "] +pub struct LNA_TRIM_GAIN2_HP_R(crate::FieldReader); +impl LNA_TRIM_GAIN2_HP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN2_HP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN2_HP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN2_HP` writer - "] +pub struct LNA_TRIM_GAIN2_HP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN2_HP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 10)) | ((value as u32 & 0x1f) << 10); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN1_HP` reader - "] +pub struct LNA_TRIM_GAIN1_HP_R(crate::FieldReader); +impl LNA_TRIM_GAIN1_HP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN1_HP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN1_HP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN1_HP` writer - "] +pub struct LNA_TRIM_GAIN1_HP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN1_HP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN0_HP` reader - "] +pub struct LNA_TRIM_GAIN0_HP_R(crate::FieldReader); +impl LNA_TRIM_GAIN0_HP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN0_HP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN0_HP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN0_HP` writer - "] +pub struct LNA_TRIM_GAIN0_HP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN0_HP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 20:24"] + #[inline(always)] + pub fn lna_trim_gain4_hp(&self) -> LNA_TRIM_GAIN4_HP_R { + LNA_TRIM_GAIN4_HP_R::new(((self.bits >> 20) & 0x1f) as u8) + } + #[doc = "Bits 15:19"] + #[inline(always)] + pub fn lna_trim_gain3_hp(&self) -> LNA_TRIM_GAIN3_HP_R { + LNA_TRIM_GAIN3_HP_R::new(((self.bits >> 15) & 0x1f) as u8) + } + #[doc = "Bits 10:14"] + #[inline(always)] + pub fn lna_trim_gain2_hp(&self) -> LNA_TRIM_GAIN2_HP_R { + LNA_TRIM_GAIN2_HP_R::new(((self.bits >> 10) & 0x1f) as u8) + } + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_trim_gain1_hp(&self) -> LNA_TRIM_GAIN1_HP_R { + LNA_TRIM_GAIN1_HP_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_trim_gain0_hp(&self) -> LNA_TRIM_GAIN0_HP_R { + LNA_TRIM_GAIN0_HP_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 20:24"] + #[inline(always)] + pub fn lna_trim_gain4_hp(&mut self) -> LNA_TRIM_GAIN4_HP_W { + LNA_TRIM_GAIN4_HP_W { w: self } + } + #[doc = "Bits 15:19"] + #[inline(always)] + pub fn lna_trim_gain3_hp(&mut self) -> LNA_TRIM_GAIN3_HP_W { + LNA_TRIM_GAIN3_HP_W { w: self } + } + #[doc = "Bits 10:14"] + #[inline(always)] + pub fn lna_trim_gain2_hp(&mut self) -> LNA_TRIM_GAIN2_HP_W { + LNA_TRIM_GAIN2_HP_W { w: self } + } + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_trim_gain1_hp(&mut self) -> LNA_TRIM_GAIN1_HP_W { + LNA_TRIM_GAIN1_HP_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_trim_gain0_hp(&mut self) -> LNA_TRIM_GAIN0_HP_W { + LNA_TRIM_GAIN0_HP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_lna_ctrl1_reg](index.html) module"] +pub struct RF_LNA_CTRL1_REG_SPEC; +impl crate::RegisterSpec for RF_LNA_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_lna_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for RF_LNA_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_lna_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for RF_LNA_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_LNA_CTRL1_REG to value 0x0108_4210"] +impl crate::Resettable for RF_LNA_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0108_4210 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl2_reg.rs new file mode 100644 index 0000000..a66b1b5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl2_reg.rs @@ -0,0 +1,251 @@ +#[doc = "Register `RF_LNA_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_LNA_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LNA_TRIM_GAIN4_LP` reader - "] +pub struct LNA_TRIM_GAIN4_LP_R(crate::FieldReader); +impl LNA_TRIM_GAIN4_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN4_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN4_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN4_LP` writer - "] +pub struct LNA_TRIM_GAIN4_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN4_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 20)) | ((value as u32 & 0x1f) << 20); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN3_LP` reader - "] +pub struct LNA_TRIM_GAIN3_LP_R(crate::FieldReader); +impl LNA_TRIM_GAIN3_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN3_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN3_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN3_LP` writer - "] +pub struct LNA_TRIM_GAIN3_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN3_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 15)) | ((value as u32 & 0x1f) << 15); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN2_LP` reader - "] +pub struct LNA_TRIM_GAIN2_LP_R(crate::FieldReader); +impl LNA_TRIM_GAIN2_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN2_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN2_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN2_LP` writer - "] +pub struct LNA_TRIM_GAIN2_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN2_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 10)) | ((value as u32 & 0x1f) << 10); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN1_LP` reader - "] +pub struct LNA_TRIM_GAIN1_LP_R(crate::FieldReader); +impl LNA_TRIM_GAIN1_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN1_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN1_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN1_LP` writer - "] +pub struct LNA_TRIM_GAIN1_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN1_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `LNA_TRIM_GAIN0_LP` reader - "] +pub struct LNA_TRIM_GAIN0_LP_R(crate::FieldReader); +impl LNA_TRIM_GAIN0_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_GAIN0_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_GAIN0_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_GAIN0_LP` writer - "] +pub struct LNA_TRIM_GAIN0_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_GAIN0_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 20:24"] + #[inline(always)] + pub fn lna_trim_gain4_lp(&self) -> LNA_TRIM_GAIN4_LP_R { + LNA_TRIM_GAIN4_LP_R::new(((self.bits >> 20) & 0x1f) as u8) + } + #[doc = "Bits 15:19"] + #[inline(always)] + pub fn lna_trim_gain3_lp(&self) -> LNA_TRIM_GAIN3_LP_R { + LNA_TRIM_GAIN3_LP_R::new(((self.bits >> 15) & 0x1f) as u8) + } + #[doc = "Bits 10:14"] + #[inline(always)] + pub fn lna_trim_gain2_lp(&self) -> LNA_TRIM_GAIN2_LP_R { + LNA_TRIM_GAIN2_LP_R::new(((self.bits >> 10) & 0x1f) as u8) + } + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_trim_gain1_lp(&self) -> LNA_TRIM_GAIN1_LP_R { + LNA_TRIM_GAIN1_LP_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_trim_gain0_lp(&self) -> LNA_TRIM_GAIN0_LP_R { + LNA_TRIM_GAIN0_LP_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 20:24"] + #[inline(always)] + pub fn lna_trim_gain4_lp(&mut self) -> LNA_TRIM_GAIN4_LP_W { + LNA_TRIM_GAIN4_LP_W { w: self } + } + #[doc = "Bits 15:19"] + #[inline(always)] + pub fn lna_trim_gain3_lp(&mut self) -> LNA_TRIM_GAIN3_LP_W { + LNA_TRIM_GAIN3_LP_W { w: self } + } + #[doc = "Bits 10:14"] + #[inline(always)] + pub fn lna_trim_gain2_lp(&mut self) -> LNA_TRIM_GAIN2_LP_W { + LNA_TRIM_GAIN2_LP_W { w: self } + } + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_trim_gain1_lp(&mut self) -> LNA_TRIM_GAIN1_LP_W { + LNA_TRIM_GAIN1_LP_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_trim_gain0_lp(&mut self) -> LNA_TRIM_GAIN0_LP_W { + LNA_TRIM_GAIN0_LP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_lna_ctrl2_reg](index.html) module"] +pub struct RF_LNA_CTRL2_REG_SPEC; +impl crate::RegisterSpec for RF_LNA_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_lna_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for RF_LNA_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_lna_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for RF_LNA_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_LNA_CTRL2_REG to value 0x00d6_b5ad"] +impl crate::Resettable for RF_LNA_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x00d6_b5ad + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl3_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl3_reg.rs new file mode 100644 index 0000000..6dd346f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_lna_ctrl3_reg.rs @@ -0,0 +1,325 @@ +#[doc = "Register `RF_LNA_CTRL3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_LNA_CTRL3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LNA_SPARE` reader - "] +pub struct LNA_SPARE_R(crate::FieldReader); +impl LNA_SPARE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_SPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_SPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_SPARE` writer - "] +pub struct LNA_SPARE_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_SPARE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 24)) | ((value as u32 & 3) << 24); + self.w + } +} +#[doc = "Field `LNA_MODE_GAIN4_LP` reader - "] +pub struct LNA_MODE_GAIN4_LP_R(crate::FieldReader); +impl LNA_MODE_GAIN4_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_MODE_GAIN4_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_MODE_GAIN4_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_MODE_GAIN4_LP` writer - "] +pub struct LNA_MODE_GAIN4_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_MODE_GAIN4_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 20)) | ((value as u32 & 3) << 20); + self.w + } +} +#[doc = "Field `LNA_MODE_GAIN3_LP` reader - "] +pub struct LNA_MODE_GAIN3_LP_R(crate::FieldReader); +impl LNA_MODE_GAIN3_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_MODE_GAIN3_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_MODE_GAIN3_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_MODE_GAIN3_LP` writer - "] +pub struct LNA_MODE_GAIN3_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_MODE_GAIN3_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 16)) | ((value as u32 & 3) << 16); + self.w + } +} +#[doc = "Field `LNA_MODE_GAIN2_LP` reader - "] +pub struct LNA_MODE_GAIN2_LP_R(crate::FieldReader); +impl LNA_MODE_GAIN2_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_MODE_GAIN2_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_MODE_GAIN2_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_MODE_GAIN2_LP` writer - "] +pub struct LNA_MODE_GAIN2_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_MODE_GAIN2_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 12)) | ((value as u32 & 3) << 12); + self.w + } +} +#[doc = "Field `LNA_MODE_GAIN1_LP` reader - "] +pub struct LNA_MODE_GAIN1_LP_R(crate::FieldReader); +impl LNA_MODE_GAIN1_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_MODE_GAIN1_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_MODE_GAIN1_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_MODE_GAIN1_LP` writer - "] +pub struct LNA_MODE_GAIN1_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_MODE_GAIN1_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u32 & 3) << 8); + self.w + } +} +#[doc = "Field `LNA_MODE_GAIN0_LP` reader - "] +pub struct LNA_MODE_GAIN0_LP_R(crate::FieldReader); +impl LNA_MODE_GAIN0_LP_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_MODE_GAIN0_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_MODE_GAIN0_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_MODE_GAIN0_LP` writer - "] +pub struct LNA_MODE_GAIN0_LP_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_MODE_GAIN0_LP_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u32 & 3) << 4); + self.w + } +} +#[doc = "Field `LNA_TRIM_CASC` reader - "] +pub struct LNA_TRIM_CASC_R(crate::FieldReader); +impl LNA_TRIM_CASC_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_TRIM_CASC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_TRIM_CASC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_TRIM_CASC` writer - "] +pub struct LNA_TRIM_CASC_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_TRIM_CASC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bits 24:25"] + #[inline(always)] + pub fn lna_spare(&self) -> LNA_SPARE_R { + LNA_SPARE_R::new(((self.bits >> 24) & 3) as u8) + } + #[doc = "Bits 20:21"] + #[inline(always)] + pub fn lna_mode_gain4_lp(&self) -> LNA_MODE_GAIN4_LP_R { + LNA_MODE_GAIN4_LP_R::new(((self.bits >> 20) & 3) as u8) + } + #[doc = "Bits 16:17"] + #[inline(always)] + pub fn lna_mode_gain3_lp(&self) -> LNA_MODE_GAIN3_LP_R { + LNA_MODE_GAIN3_LP_R::new(((self.bits >> 16) & 3) as u8) + } + #[doc = "Bits 12:13"] + #[inline(always)] + pub fn lna_mode_gain2_lp(&self) -> LNA_MODE_GAIN2_LP_R { + LNA_MODE_GAIN2_LP_R::new(((self.bits >> 12) & 3) as u8) + } + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn lna_mode_gain1_lp(&self) -> LNA_MODE_GAIN1_LP_R { + LNA_MODE_GAIN1_LP_R::new(((self.bits >> 8) & 3) as u8) + } + #[doc = "Bits 4:5"] + #[inline(always)] + pub fn lna_mode_gain0_lp(&self) -> LNA_MODE_GAIN0_LP_R { + LNA_MODE_GAIN0_LP_R::new(((self.bits >> 4) & 3) as u8) + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn lna_trim_casc(&self) -> LNA_TRIM_CASC_R { + LNA_TRIM_CASC_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 24:25"] + #[inline(always)] + pub fn lna_spare(&mut self) -> LNA_SPARE_W { + LNA_SPARE_W { w: self } + } + #[doc = "Bits 20:21"] + #[inline(always)] + pub fn lna_mode_gain4_lp(&mut self) -> LNA_MODE_GAIN4_LP_W { + LNA_MODE_GAIN4_LP_W { w: self } + } + #[doc = "Bits 16:17"] + #[inline(always)] + pub fn lna_mode_gain3_lp(&mut self) -> LNA_MODE_GAIN3_LP_W { + LNA_MODE_GAIN3_LP_W { w: self } + } + #[doc = "Bits 12:13"] + #[inline(always)] + pub fn lna_mode_gain2_lp(&mut self) -> LNA_MODE_GAIN2_LP_W { + LNA_MODE_GAIN2_LP_W { w: self } + } + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn lna_mode_gain1_lp(&mut self) -> LNA_MODE_GAIN1_LP_W { + LNA_MODE_GAIN1_LP_W { w: self } + } + #[doc = "Bits 4:5"] + #[inline(always)] + pub fn lna_mode_gain0_lp(&mut self) -> LNA_MODE_GAIN0_LP_W { + LNA_MODE_GAIN0_LP_W { w: self } + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn lna_trim_casc(&mut self) -> LNA_TRIM_CASC_W { + LNA_TRIM_CASC_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_lna_ctrl3_reg](index.html) module"] +pub struct RF_LNA_CTRL3_REG_SPEC; +impl crate::RegisterSpec for RF_LNA_CTRL3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_lna_ctrl3_reg::R](R) reader structure"] +impl crate::Readable for RF_LNA_CTRL3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_lna_ctrl3_reg::W](W) writer structure"] +impl crate::Writable for RF_LNA_CTRL3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_LNA_CTRL3_REG to value 0x0011_1114"] +impl crate::Resettable for RF_LNA_CTRL3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0011_1114 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl1_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl1_reg.rs new file mode 100644 index 0000000..0c62950 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl1_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_MIXER_CTRL1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_MIXER_CTRL1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MIXER_IP2_DAC_Q_TRIM` reader - "] +pub struct MIXER_IP2_DAC_Q_TRIM_R(crate::FieldReader); +impl MIXER_IP2_DAC_Q_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + MIXER_IP2_DAC_Q_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIXER_IP2_DAC_Q_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIXER_IP2_DAC_Q_TRIM` writer - "] +pub struct MIXER_IP2_DAC_Q_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> MIXER_IP2_DAC_Q_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x01ff << 16)) | ((value as u32 & 0x01ff) << 16); + self.w + } +} +#[doc = "Field `MIXER_IP2_DAC_I_TRIM` reader - "] +pub struct MIXER_IP2_DAC_I_TRIM_R(crate::FieldReader); +impl MIXER_IP2_DAC_I_TRIM_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + MIXER_IP2_DAC_I_TRIM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIXER_IP2_DAC_I_TRIM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIXER_IP2_DAC_I_TRIM` writer - "] +pub struct MIXER_IP2_DAC_I_TRIM_W<'a> { + w: &'a mut W, +} +impl<'a> MIXER_IP2_DAC_I_TRIM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x01ff) | (value as u32 & 0x01ff); + self.w + } +} +impl R { + #[doc = "Bits 16:24"] + #[inline(always)] + pub fn mixer_ip2_dac_q_trim(&self) -> MIXER_IP2_DAC_Q_TRIM_R { + MIXER_IP2_DAC_Q_TRIM_R::new(((self.bits >> 16) & 0x01ff) as u16) + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn mixer_ip2_dac_i_trim(&self) -> MIXER_IP2_DAC_I_TRIM_R { + MIXER_IP2_DAC_I_TRIM_R::new((self.bits & 0x01ff) as u16) + } +} +impl W { + #[doc = "Bits 16:24"] + #[inline(always)] + pub fn mixer_ip2_dac_q_trim(&mut self) -> MIXER_IP2_DAC_Q_TRIM_W { + MIXER_IP2_DAC_Q_TRIM_W { w: self } + } + #[doc = "Bits 0:8"] + #[inline(always)] + pub fn mixer_ip2_dac_i_trim(&mut self) -> MIXER_IP2_DAC_I_TRIM_W { + MIXER_IP2_DAC_I_TRIM_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_mixer_ctrl1_reg](index.html) module"] +pub struct RF_MIXER_CTRL1_REG_SPEC; +impl crate::RegisterSpec for RF_MIXER_CTRL1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_mixer_ctrl1_reg::R](R) reader structure"] +impl crate::Readable for RF_MIXER_CTRL1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_mixer_ctrl1_reg::W](W) writer structure"] +impl crate::Writable for RF_MIXER_CTRL1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_MIXER_CTRL1_REG to value 0x010f_010f"] +impl crate::Resettable for RF_MIXER_CTRL1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x010f_010f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl2_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl2_reg.rs new file mode 100644 index 0000000..fc279ea --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_mixer_ctrl2_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `RF_MIXER_CTRL2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_MIXER_CTRL2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MIX_CAL_SELECT` reader - "] +pub struct MIX_CAL_SELECT_R(crate::FieldReader); +impl MIX_CAL_SELECT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + MIX_CAL_SELECT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_CAL_SELECT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_CAL_SELECT` writer - "] +pub struct MIX_CAL_SELECT_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_CAL_SELECT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `MIX_CAL_CAP_WR_2M` reader - "] +pub struct MIX_CAL_CAP_WR_2M_R(crate::FieldReader); +impl MIX_CAL_CAP_WR_2M_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_CAL_CAP_WR_2M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_CAL_CAP_WR_2M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_CAL_CAP_WR_2M` writer - "] +pub struct MIX_CAL_CAP_WR_2M_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_CAL_CAP_WR_2M_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `MIX_CAL_CAP_WR_1M` reader - "] +pub struct MIX_CAL_CAP_WR_1M_R(crate::FieldReader); +impl MIX_CAL_CAP_WR_1M_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_CAL_CAP_WR_1M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_CAL_CAP_WR_1M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_CAL_CAP_WR_1M` writer - "] +pub struct MIX_CAL_CAP_WR_1M_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_CAL_CAP_WR_1M_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 16"] + #[inline(always)] + pub fn mix_cal_select(&self) -> MIX_CAL_SELECT_R { + MIX_CAL_SELECT_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn mix_cal_cap_wr_2m(&self) -> MIX_CAL_CAP_WR_2M_R { + MIX_CAL_CAP_WR_2M_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn mix_cal_cap_wr_1m(&self) -> MIX_CAL_CAP_WR_1M_R { + MIX_CAL_CAP_WR_1M_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bit 16"] + #[inline(always)] + pub fn mix_cal_select(&mut self) -> MIX_CAL_SELECT_W { + MIX_CAL_SELECT_W { w: self } + } + #[doc = "Bits 8:11"] + #[inline(always)] + pub fn mix_cal_cap_wr_2m(&mut self) -> MIX_CAL_CAP_WR_2M_W { + MIX_CAL_CAP_WR_2M_W { w: self } + } + #[doc = "Bits 0:3"] + #[inline(always)] + pub fn mix_cal_cap_wr_1m(&mut self) -> MIX_CAL_CAP_WR_1M_W { + MIX_CAL_CAP_WR_1M_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_mixer_ctrl2_reg](index.html) module"] +pub struct RF_MIXER_CTRL2_REG_SPEC; +impl crate::RegisterSpec for RF_MIXER_CTRL2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_mixer_ctrl2_reg::R](R) reader structure"] +impl crate::Readable for RF_MIXER_CTRL2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_mixer_ctrl2_reg::W](W) writer structure"] +impl crate::Writable for RF_MIXER_CTRL2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_MIXER_CTRL2_REG to value 0"] +impl crate::Resettable for RF_MIXER_CTRL2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_overrule_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_overrule_reg.rs new file mode 100644 index 0000000..2f3a737 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_overrule_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_OVERRULE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_OVERRULE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RX_EN_OVR` reader - "] +pub struct RX_EN_OVR_R(crate::FieldReader); +impl RX_EN_OVR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RX_EN_OVR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RX_EN_OVR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RX_EN_OVR` writer - "] +pub struct RX_EN_OVR_W<'a> { + w: &'a mut W, +} +impl<'a> RX_EN_OVR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 2)) | ((value as u32 & 3) << 2); + self.w + } +} +#[doc = "Field `TX_EN_OVR` reader - "] +pub struct TX_EN_OVR_R(crate::FieldReader); +impl TX_EN_OVR_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TX_EN_OVR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TX_EN_OVR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TX_EN_OVR` writer - "] +pub struct TX_EN_OVR_W<'a> { + w: &'a mut W, +} +impl<'a> TX_EN_OVR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u32 & 3); + self.w + } +} +impl R { + #[doc = "Bits 2:3"] + #[inline(always)] + pub fn rx_en_ovr(&self) -> RX_EN_OVR_R { + RX_EN_OVR_R::new(((self.bits >> 2) & 3) as u8) + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn tx_en_ovr(&self) -> TX_EN_OVR_R { + TX_EN_OVR_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 2:3"] + #[inline(always)] + pub fn rx_en_ovr(&mut self) -> RX_EN_OVR_W { + RX_EN_OVR_W { w: self } + } + #[doc = "Bits 0:1"] + #[inline(always)] + pub fn tx_en_ovr(&mut self) -> TX_EN_OVR_W { + TX_EN_OVR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_overrule_reg](index.html) module"] +pub struct RF_OVERRULE_REG_SPEC; +impl crate::RegisterSpec for RF_OVERRULE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_overrule_reg::R](R) reader structure"] +impl crate::Readable for RF_OVERRULE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_overrule_reg::W](W) writer structure"] +impl crate::Writable for RF_OVERRULE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_OVERRULE_REG to value 0"] +impl crate::Resettable for RF_OVERRULE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_pa_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_pa_ctrl_reg.rs new file mode 100644 index 0000000..2b5c7a3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_pa_ctrl_reg.rs @@ -0,0 +1,177 @@ +#[doc = "Register `RF_PA_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_PA_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PA_RAMP_STEP_SPEED` reader - "] +pub struct PA_RAMP_STEP_SPEED_R(crate::FieldReader); +impl PA_RAMP_STEP_SPEED_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_RAMP_STEP_SPEED_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_RAMP_STEP_SPEED_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_RAMP_STEP_SPEED` writer - "] +pub struct PA_RAMP_STEP_SPEED_W<'a> { + w: &'a mut W, +} +impl<'a> PA_RAMP_STEP_SPEED_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u32 & 3) << 8); + self.w + } +} +#[doc = "Field `TRIM_DUTY_NEG` reader - "] +pub struct TRIM_DUTY_NEG_R(crate::FieldReader); +impl TRIM_DUTY_NEG_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TRIM_DUTY_NEG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TRIM_DUTY_NEG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TRIM_DUTY_NEG` writer - "] +pub struct TRIM_DUTY_NEG_W<'a> { + w: &'a mut W, +} +impl<'a> TRIM_DUTY_NEG_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 3)) | ((value as u32 & 7) << 3); + self.w + } +} +#[doc = "Field `TRIM_DUTY_POS` reader - "] +pub struct TRIM_DUTY_POS_R(crate::FieldReader); +impl TRIM_DUTY_POS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TRIM_DUTY_POS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TRIM_DUTY_POS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TRIM_DUTY_POS` writer - "] +pub struct TRIM_DUTY_POS_W<'a> { + w: &'a mut W, +} +impl<'a> TRIM_DUTY_POS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn pa_ramp_step_speed(&self) -> PA_RAMP_STEP_SPEED_R { + PA_RAMP_STEP_SPEED_R::new(((self.bits >> 8) & 3) as u8) + } + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn trim_duty_neg(&self) -> TRIM_DUTY_NEG_R { + TRIM_DUTY_NEG_R::new(((self.bits >> 3) & 7) as u8) + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn trim_duty_pos(&self) -> TRIM_DUTY_POS_R { + TRIM_DUTY_POS_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 8:9"] + #[inline(always)] + pub fn pa_ramp_step_speed(&mut self) -> PA_RAMP_STEP_SPEED_W { + PA_RAMP_STEP_SPEED_W { w: self } + } + #[doc = "Bits 3:5"] + #[inline(always)] + pub fn trim_duty_neg(&mut self) -> TRIM_DUTY_NEG_W { + TRIM_DUTY_NEG_W { w: self } + } + #[doc = "Bits 0:2"] + #[inline(always)] + pub fn trim_duty_pos(&mut self) -> TRIM_DUTY_POS_W { + TRIM_DUTY_POS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_pa_ctrl_reg](index.html) module"] +pub struct RF_PA_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_PA_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_pa_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_PA_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_pa_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_PA_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_PA_CTRL_REG to value 0x0300"] +impl crate::Resettable for RF_PA_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0300 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_radio_init_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_radio_init_reg.rs new file mode 100644 index 0000000..4e6056e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_radio_init_reg.rs @@ -0,0 +1,583 @@ +#[doc = "Register `RF_RADIO_INIT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_RADIO_INIT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RADIO_INIT_AUTOCLEAR` reader - "] +pub struct RADIO_INIT_AUTOCLEAR_R(crate::FieldReader); +impl RADIO_INIT_AUTOCLEAR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_INIT_AUTOCLEAR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_INIT_AUTOCLEAR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_INIT_AUTOCLEAR` writer - "] +pub struct RADIO_INIT_AUTOCLEAR_W<'a> { + w: &'a mut W, +} +impl<'a> RADIO_INIT_AUTOCLEAR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 24)) | ((value as u32 & 1) << 24); + self.w + } +} +#[doc = "Field `ADPLLDIG_HCLK_DIS` reader - "] +pub struct ADPLLDIG_HCLK_DIS_R(crate::FieldReader); +impl ADPLLDIG_HCLK_DIS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_HCLK_DIS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_HCLK_DIS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_HCLK_DIS` writer - "] +pub struct ADPLLDIG_HCLK_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_HCLK_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 17)) | ((value as u32 & 1) << 17); + self.w + } +} +#[doc = "Field `RADIO_REGS_RDY` reader - "] +pub struct RADIO_REGS_RDY_R(crate::FieldReader); +impl RADIO_REGS_RDY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_REGS_RDY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_REGS_RDY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_REGS_RDY` writer - "] +pub struct RADIO_REGS_RDY_W<'a> { + w: &'a mut W, +} +impl<'a> RADIO_REGS_RDY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `ADPLLDIG_HCLK_EN` reader - "] +pub struct ADPLLDIG_HCLK_EN_R(crate::FieldReader); +impl ADPLLDIG_HCLK_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_HCLK_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_HCLK_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_HCLK_EN` writer - "] +pub struct ADPLLDIG_HCLK_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_HCLK_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `ADPLLDIG_HRESET_N` reader - "] +pub struct ADPLLDIG_HRESET_N_R(crate::FieldReader); +impl ADPLLDIG_HRESET_N_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_HRESET_N_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_HRESET_N_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_HRESET_N` writer - "] +pub struct ADPLLDIG_HRESET_N_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_HRESET_N_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `ADPLLDIG_LDO_EN_WR` reader - "] +pub struct ADPLLDIG_LDO_EN_WR_R(crate::FieldReader); +impl ADPLLDIG_LDO_EN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_LDO_EN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_EN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_EN_WR` writer - "] +pub struct ADPLLDIG_LDO_EN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_LDO_EN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `ADPLLDIG_LDO_EN_SEL` reader - "] +pub struct ADPLLDIG_LDO_EN_SEL_R(crate::FieldReader); +impl ADPLLDIG_LDO_EN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_LDO_EN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_EN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_EN_SEL` writer - "] +pub struct ADPLLDIG_LDO_EN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_LDO_EN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `ADPLLDIG_PWR_SW1_EN` reader - "] +pub struct ADPLLDIG_PWR_SW1_EN_R(crate::FieldReader); +impl ADPLLDIG_PWR_SW1_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ADPLLDIG_PWR_SW1_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_PWR_SW1_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_PWR_SW1_EN` writer - "] +pub struct ADPLLDIG_PWR_SW1_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_PWR_SW1_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `RADIO_LDO_EN_WR` reader - "] +pub struct RADIO_LDO_EN_WR_R(crate::FieldReader); +impl RADIO_LDO_EN_WR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_LDO_EN_WR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_LDO_EN_WR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_LDO_EN_WR` writer - "] +pub struct RADIO_LDO_EN_WR_W<'a> { + w: &'a mut W, +} +impl<'a> RADIO_LDO_EN_WR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RADIO_LDO_EN_SEL` reader - "] +pub struct RADIO_LDO_EN_SEL_R(crate::FieldReader); +impl RADIO_LDO_EN_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_LDO_EN_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_LDO_EN_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_LDO_EN_SEL` writer - "] +pub struct RADIO_LDO_EN_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> RADIO_LDO_EN_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RADIO_LDO_EN` reader - "] +pub struct RADIO_LDO_EN_R(crate::FieldReader); +impl RADIO_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RADIO_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RADIO_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RADIO_LDO_EN` writer - "] +pub struct RADIO_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RADIO_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 24"] + #[inline(always)] + pub fn radio_init_autoclear(&self) -> RADIO_INIT_AUTOCLEAR_R { + RADIO_INIT_AUTOCLEAR_R::new(((self.bits >> 24) & 1) != 0) + } + #[doc = "Bit 17"] + #[inline(always)] + pub fn adplldig_hclk_dis(&self) -> ADPLLDIG_HCLK_DIS_R { + ADPLLDIG_HCLK_DIS_R::new(((self.bits >> 17) & 1) != 0) + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn radio_regs_rdy(&self) -> RADIO_REGS_RDY_R { + RADIO_REGS_RDY_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn adplldig_hclk_en(&self) -> ADPLLDIG_HCLK_EN_R { + ADPLLDIG_HCLK_EN_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn adplldig_hreset_n(&self) -> ADPLLDIG_HRESET_N_R { + ADPLLDIG_HRESET_N_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn adplldig_ldo_en_wr(&self) -> ADPLLDIG_LDO_EN_WR_R { + ADPLLDIG_LDO_EN_WR_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn adplldig_ldo_en_sel(&self) -> ADPLLDIG_LDO_EN_SEL_R { + ADPLLDIG_LDO_EN_SEL_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn adplldig_pwr_sw1_en(&self) -> ADPLLDIG_PWR_SW1_EN_R { + ADPLLDIG_PWR_SW1_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn radio_ldo_en_wr(&self) -> RADIO_LDO_EN_WR_R { + RADIO_LDO_EN_WR_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn radio_ldo_en_sel(&self) -> RADIO_LDO_EN_SEL_R { + RADIO_LDO_EN_SEL_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn radio_ldo_en(&self) -> RADIO_LDO_EN_R { + RADIO_LDO_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 24"] + #[inline(always)] + pub fn radio_init_autoclear(&mut self) -> RADIO_INIT_AUTOCLEAR_W { + RADIO_INIT_AUTOCLEAR_W { w: self } + } + #[doc = "Bit 17"] + #[inline(always)] + pub fn adplldig_hclk_dis(&mut self) -> ADPLLDIG_HCLK_DIS_W { + ADPLLDIG_HCLK_DIS_W { w: self } + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn radio_regs_rdy(&mut self) -> RADIO_REGS_RDY_W { + RADIO_REGS_RDY_W { w: self } + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn adplldig_hclk_en(&mut self) -> ADPLLDIG_HCLK_EN_W { + ADPLLDIG_HCLK_EN_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn adplldig_hreset_n(&mut self) -> ADPLLDIG_HRESET_N_W { + ADPLLDIG_HRESET_N_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn adplldig_ldo_en_wr(&mut self) -> ADPLLDIG_LDO_EN_WR_W { + ADPLLDIG_LDO_EN_WR_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn adplldig_ldo_en_sel(&mut self) -> ADPLLDIG_LDO_EN_SEL_W { + ADPLLDIG_LDO_EN_SEL_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn adplldig_pwr_sw1_en(&mut self) -> ADPLLDIG_PWR_SW1_EN_W { + ADPLLDIG_PWR_SW1_EN_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn radio_ldo_en_wr(&mut self) -> RADIO_LDO_EN_WR_W { + RADIO_LDO_EN_WR_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn radio_ldo_en_sel(&mut self) -> RADIO_LDO_EN_SEL_W { + RADIO_LDO_EN_SEL_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn radio_ldo_en(&mut self) -> RADIO_LDO_EN_W { + RADIO_LDO_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_radio_init_reg](index.html) module"] +pub struct RF_RADIO_INIT_REG_SPEC; +impl crate::RegisterSpec for RF_RADIO_INIT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_radio_init_reg::R](R) reader structure"] +impl crate::Readable for RF_RADIO_INIT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_radio_init_reg::W](W) writer structure"] +impl crate::Writable for RF_RADIO_INIT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_RADIO_INIT_REG to value 0"] +impl crate::Resettable for RF_RADIO_INIT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_rfcu_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_rfcu_ctrl_reg.rs new file mode 100644 index 0000000..5f40901 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_rfcu_ctrl_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `RF_RFCU_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_RFCU_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RF_RFCU_CLK_DIV` reader - "] +pub struct RF_RFCU_CLK_DIV_R(crate::FieldReader); +impl RF_RFCU_CLK_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_RFCU_CLK_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_RFCU_CLK_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_RFCU_CLK_DIV` writer - "] +pub struct RF_RFCU_CLK_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> RF_RFCU_CLK_DIV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_rfcu_clk_div(&self) -> RF_RFCU_CLK_DIV_R { + RF_RFCU_CLK_DIV_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_rfcu_clk_div(&mut self) -> RF_RFCU_CLK_DIV_W { + RF_RFCU_CLK_DIV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_rfcu_ctrl_reg](index.html) module"] +pub struct RF_RFCU_CTRL_REG_SPEC; +impl crate::RegisterSpec for RF_RFCU_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_rfcu_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RF_RFCU_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_rfcu_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RF_RFCU_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_RFCU_CTRL_REG to value 0x01"] +impl crate::Resettable for RF_RFCU_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_scan_feedback_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_scan_feedback_reg.rs new file mode 100644 index 0000000..dd45d51 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_scan_feedback_reg.rs @@ -0,0 +1,64 @@ +#[doc = "Register `RF_SCAN_FEEDBACK_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_SCAN_FEEDBACK_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_scan_feedback_reg](index.html) module"] +pub struct RF_SCAN_FEEDBACK_REG_SPEC; +impl crate::RegisterSpec for RF_SCAN_FEEDBACK_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_scan_feedback_reg::R](R) reader structure"] +impl crate::Readable for RF_SCAN_FEEDBACK_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_scan_feedback_reg::W](W) writer structure"] +impl crate::Writable for RF_SCAN_FEEDBACK_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_SCAN_FEEDBACK_REG to value 0"] +impl crate::Resettable for RF_SCAN_FEEDBACK_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu/rf_spare_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu/rf_spare_reg.rs new file mode 100644 index 0000000..104ad4e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu/rf_spare_reg.rs @@ -0,0 +1,207 @@ +#[doc = "Register `RF_SPARE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_SPARE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RF_SPARE_IN_EN` reader - "] +pub struct RF_SPARE_IN_EN_R(crate::FieldReader); +impl RF_SPARE_IN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_SPARE_IN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_SPARE_IN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_SPARE_IN_EN` writer - "] +pub struct RF_SPARE_IN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RF_SPARE_IN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 28)) | ((value as u32 & 1) << 28); + self.w + } +} +#[doc = "Field `RF_SPARE_IN` reader - "] +pub struct RF_SPARE_IN_R(crate::FieldReader); +impl RF_SPARE_IN_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_SPARE_IN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_SPARE_IN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_SPARE_BITS_HV` reader - "] +pub struct RF_SPARE_BITS_HV_R(crate::FieldReader); +impl RF_SPARE_BITS_HV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RF_SPARE_BITS_HV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_SPARE_BITS_HV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_SPARE_BITS_HV` writer - "] +pub struct RF_SPARE_BITS_HV_W<'a> { + w: &'a mut W, +} +impl<'a> RF_SPARE_BITS_HV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 16)) | ((value as u32 & 0xff) << 16); + self.w + } +} +#[doc = "Field `RF_SPARE_BITS` reader - "] +pub struct RF_SPARE_BITS_R(crate::FieldReader); +impl RF_SPARE_BITS_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RF_SPARE_BITS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_SPARE_BITS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_SPARE_BITS` writer - "] +pub struct RF_SPARE_BITS_W<'a> { + w: &'a mut W, +} +impl<'a> RF_SPARE_BITS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); + self.w + } +} +impl R { + #[doc = "Bit 28"] + #[inline(always)] + pub fn rf_spare_in_en(&self) -> RF_SPARE_IN_EN_R { + RF_SPARE_IN_EN_R::new(((self.bits >> 28) & 1) != 0) + } + #[doc = "Bits 24:27"] + #[inline(always)] + pub fn rf_spare_in(&self) -> RF_SPARE_IN_R { + RF_SPARE_IN_R::new(((self.bits >> 24) & 0x0f) as u8) + } + #[doc = "Bits 16:23"] + #[inline(always)] + pub fn rf_spare_bits_hv(&self) -> RF_SPARE_BITS_HV_R { + RF_SPARE_BITS_HV_R::new(((self.bits >> 16) & 0xff) as u8) + } + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn rf_spare_bits(&self) -> RF_SPARE_BITS_R { + RF_SPARE_BITS_R::new((self.bits & 0xffff) as u16) + } +} +impl W { + #[doc = "Bit 28"] + #[inline(always)] + pub fn rf_spare_in_en(&mut self) -> RF_SPARE_IN_EN_W { + RF_SPARE_IN_EN_W { w: self } + } + #[doc = "Bits 16:23"] + #[inline(always)] + pub fn rf_spare_bits_hv(&mut self) -> RF_SPARE_BITS_HV_W { + RF_SPARE_BITS_HV_W { w: self } + } + #[doc = "Bits 0:15"] + #[inline(always)] + pub fn rf_spare_bits(&mut self) -> RF_SPARE_BITS_W { + RF_SPARE_BITS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_spare_reg](index.html) module"] +pub struct RF_SPARE_REG_SPEC; +impl crate::RegisterSpec for RF_SPARE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_spare_reg::R](R) reader structure"] +impl crate::Readable for RF_SPARE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_spare_reg::W](W) writer structure"] +impl crate::Writable for RF_SPARE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_SPARE_REG to value 0"] +impl crate::Resettable for RF_SPARE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power.rs new file mode 100644 index 0000000..cb0270f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power.rs @@ -0,0 +1,498 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - "] + pub rf_enable_config0_reg: crate::Reg, + #[doc = "0x04 - "] + pub rf_enable_config1_reg: crate::Reg, + #[doc = "0x08 - "] + pub rf_enable_config2_reg: crate::Reg, + #[doc = "0x0c - "] + pub rf_enable_config3_reg: crate::Reg, + #[doc = "0x10 - "] + pub rf_enable_config4_reg: crate::Reg, + #[doc = "0x14 - "] + pub rf_enable_config5_reg: crate::Reg, + #[doc = "0x18 - "] + pub rf_enable_config6_reg: crate::Reg, + #[doc = "0x1c - "] + pub rf_enable_config7_reg: crate::Reg, + #[doc = "0x20 - "] + pub rf_enable_config8_reg: crate::Reg, + #[doc = "0x24 - "] + pub rf_enable_config9_reg: crate::Reg, + #[doc = "0x28 - "] + pub rf_enable_config10_reg: crate::Reg, + #[doc = "0x2c - "] + pub rf_enable_config11_reg: crate::Reg, + #[doc = "0x30 - "] + pub rf_enable_config12_reg: crate::Reg, + #[doc = "0x34 - "] + pub rf_enable_config13_reg: crate::Reg, + #[doc = "0x38 - "] + pub rf_enable_config14_reg: crate::Reg, + #[doc = "0x3c - "] + pub rf_enable_config15_reg: crate::Reg, + #[doc = "0x40 - "] + pub rf_enable_config16_reg: crate::Reg, + #[doc = "0x44 - "] + pub rf_enable_config17_reg: crate::Reg, + #[doc = "0x48 - "] + pub rf_enable_config18_reg: crate::Reg, + #[doc = "0x4c - "] + pub rf_enable_config19_reg: crate::Reg, + #[doc = "0x50 - "] + pub rf_enable_config20_reg: crate::Reg, + #[doc = "0x54 - "] + pub rf_enable_config21_reg: crate::Reg, + #[doc = "0x58 - "] + pub rf_enable_config22_reg: crate::Reg, + #[doc = "0x5c - "] + pub rf_enable_config23_reg: crate::Reg, + #[doc = "0x60 - "] + pub rf_enable_config24_reg: crate::Reg, + #[doc = "0x64 - "] + pub rf_enable_config25_reg: crate::Reg, + #[doc = "0x68 - "] + pub rf_enable_config26_reg: crate::Reg, + #[doc = "0x6c - "] + pub rf_enable_config27_reg: crate::Reg, + #[doc = "0x70 - "] + pub rf_enable_config28_reg: crate::Reg, + #[doc = "0x74 - "] + pub rf_enable_config29_reg: crate::Reg, + #[doc = "0x78 - "] + pub rf_enable_config30_reg: crate::Reg, + #[doc = "0x7c - "] + pub rf_enable_config31_reg: crate::Reg, + #[doc = "0x80 - "] + pub rf_enable_config32_reg: crate::Reg, + #[doc = "0x84 - "] + pub rf_enable_config33_reg: crate::Reg, + #[doc = "0x88 - "] + pub rf_enable_config34_reg: crate::Reg, + #[doc = "0x8c - "] + pub rf_enable_config35_reg: crate::Reg, + #[doc = "0x90 - "] + pub rf_enable_config36_reg: crate::Reg, + #[doc = "0x94 - "] + pub rf_enable_config37_reg: crate::Reg, + #[doc = "0x98 - "] + pub rf_enable_config38_reg: crate::Reg, + #[doc = "0x9c - "] + pub rf_enable_config39_reg: crate::Reg, + #[doc = "0xa0 - "] + pub rf_enable_config40_reg: crate::Reg, + #[doc = "0xa4 - "] + pub rf_enable_config41_reg: crate::Reg, + #[doc = "0xa8 - "] + pub rf_enable_config42_reg: crate::Reg, + #[doc = "0xac - "] + pub rf_enable_config43_reg: crate::Reg, + #[doc = "0xb0 - "] + pub rf_enable_config44_reg: crate::Reg, + #[doc = "0xb4 - "] + pub rf_enable_config45_reg: crate::Reg, + #[doc = "0xb8 - "] + pub rf_enable_config46_reg: crate::Reg, + _reserved47: [u8; 0x44], + #[doc = "0x100 - "] + pub rf_cntrl_timer_1_reg: crate::Reg, + #[doc = "0x104 - "] + pub rf_cntrl_timer_2_reg: crate::Reg, + #[doc = "0x108 - "] + pub rf_cntrl_timer_3_reg: crate::Reg, + #[doc = "0x10c - "] + pub rf_cntrl_timer_4_reg: crate::Reg, + #[doc = "0x110 - "] + pub rf_cntrl_timer_5_reg: crate::Reg, + #[doc = "0x114 - "] + pub rf_cntrl_timer_6_reg: crate::Reg, + #[doc = "0x118 - "] + pub rf_cntrl_timer_7_reg: crate::Reg, + #[doc = "0x11c - "] + pub rf_cntrl_timer_8_reg: crate::Reg, + #[doc = "0x120 - "] + pub rf_cntrl_timer_9_reg: crate::Reg, + #[doc = "0x124 - "] + pub rf_cntrl_timer_10_reg: crate::Reg, + #[doc = "0x128 - "] + pub rf_cntrl_timer_11_reg: crate::Reg, + #[doc = "0x12c - "] + pub rf_cntrl_timer_12_reg: crate::Reg, + #[doc = "0x130 - "] + pub rf_cntrl_timer_13_reg: crate::Reg, + #[doc = "0x134 - "] + pub rf_cntrl_timer_14_reg: crate::Reg, + #[doc = "0x138 - "] + pub rf_cntrl_timer_15_reg: crate::Reg, + #[doc = "0x13c - "] + pub rf_cntrl_timer_16_reg: crate::Reg, + #[doc = "0x140 - "] + pub rf_cntrl_timer_17_reg: crate::Reg, + #[doc = "0x144 - "] + pub rf_cntrl_timer_18_reg: crate::Reg, + #[doc = "0x148 - "] + pub rf_cntrl_timer_19_reg: crate::Reg, + #[doc = "0x14c - "] + pub rf_cntrl_timer_20_reg: crate::Reg, + #[doc = "0x150 - "] + pub rf_cntrl_timer_21_reg: crate::Reg, + #[doc = "0x154 - "] + pub rf_cntrl_timer_22_reg: crate::Reg, + #[doc = "0x158 - "] + pub rf_cntrl_timer_23_reg: crate::Reg, + #[doc = "0x15c - "] + pub rf_cntrl_timer_24_reg: crate::Reg, + #[doc = "0x160 - "] + pub rf_cntrl_timer_25_reg: crate::Reg, + #[doc = "0x164 - "] + pub rf_cntrl_timer_26_reg: crate::Reg, + #[doc = "0x168 - "] + pub rf_cntrl_timer_27_reg: crate::Reg, + #[doc = "0x16c - "] + pub rf_cntrl_timer_28_reg: crate::Reg, + #[doc = "0x170 - "] + pub rf_cntrl_timer_29_reg: crate::Reg, + #[doc = "0x174 - "] + pub rf_cntrl_timer_30_reg: crate::Reg, + #[doc = "0x178 - "] + pub rf_cntrl_timer_31_reg: crate::Reg, + _reserved78: [u8; 0x04], + #[doc = "0x180 - "] + pub rf_always_en1_reg: crate::Reg, + #[doc = "0x184 - "] + pub rf_always_en2_reg: crate::Reg, + #[doc = "0x188 - "] + pub rf_port_en_reg: crate::Reg, + #[doc = "0x18c - "] + pub rf_port_pol_reg: crate::Reg, +} +#[doc = "RF_ALWAYS_EN1_REG register accessor: an alias for `Reg`"] +pub type RF_ALWAYS_EN1_REG = crate::Reg; +#[doc = ""] +pub mod rf_always_en1_reg; +#[doc = "RF_ALWAYS_EN2_REG register accessor: an alias for `Reg`"] +pub type RF_ALWAYS_EN2_REG = crate::Reg; +#[doc = ""] +pub mod rf_always_en2_reg; +#[doc = "RF_CNTRL_TIMER_10_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_10_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_10_reg; +#[doc = "RF_CNTRL_TIMER_11_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_11_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_11_reg; +#[doc = "RF_CNTRL_TIMER_12_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_12_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_12_reg; +#[doc = "RF_CNTRL_TIMER_13_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_13_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_13_reg; +#[doc = "RF_CNTRL_TIMER_14_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_14_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_14_reg; +#[doc = "RF_CNTRL_TIMER_15_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_15_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_15_reg; +#[doc = "RF_CNTRL_TIMER_16_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_16_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_16_reg; +#[doc = "RF_CNTRL_TIMER_17_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_17_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_17_reg; +#[doc = "RF_CNTRL_TIMER_18_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_18_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_18_reg; +#[doc = "RF_CNTRL_TIMER_19_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_19_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_19_reg; +#[doc = "RF_CNTRL_TIMER_1_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_1_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_1_reg; +#[doc = "RF_CNTRL_TIMER_20_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_20_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_20_reg; +#[doc = "RF_CNTRL_TIMER_21_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_21_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_21_reg; +#[doc = "RF_CNTRL_TIMER_22_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_22_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_22_reg; +#[doc = "RF_CNTRL_TIMER_23_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_23_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_23_reg; +#[doc = "RF_CNTRL_TIMER_24_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_24_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_24_reg; +#[doc = "RF_CNTRL_TIMER_25_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_25_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_25_reg; +#[doc = "RF_CNTRL_TIMER_26_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_26_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_26_reg; +#[doc = "RF_CNTRL_TIMER_27_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_27_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_27_reg; +#[doc = "RF_CNTRL_TIMER_28_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_28_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_28_reg; +#[doc = "RF_CNTRL_TIMER_29_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_29_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_29_reg; +#[doc = "RF_CNTRL_TIMER_2_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_2_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_2_reg; +#[doc = "RF_CNTRL_TIMER_30_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_30_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_30_reg; +#[doc = "RF_CNTRL_TIMER_31_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_31_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_31_reg; +#[doc = "RF_CNTRL_TIMER_3_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_3_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_3_reg; +#[doc = "RF_CNTRL_TIMER_4_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_4_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_4_reg; +#[doc = "RF_CNTRL_TIMER_5_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_5_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_5_reg; +#[doc = "RF_CNTRL_TIMER_6_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_6_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_6_reg; +#[doc = "RF_CNTRL_TIMER_7_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_7_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_7_reg; +#[doc = "RF_CNTRL_TIMER_8_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_8_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_8_reg; +#[doc = "RF_CNTRL_TIMER_9_REG register accessor: an alias for `Reg`"] +pub type RF_CNTRL_TIMER_9_REG = crate::Reg; +#[doc = ""] +pub mod rf_cntrl_timer_9_reg; +#[doc = "RF_ENABLE_CONFIG0_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG0_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config0_reg; +#[doc = "RF_ENABLE_CONFIG10_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG10_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config10_reg; +#[doc = "RF_ENABLE_CONFIG11_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG11_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config11_reg; +#[doc = "RF_ENABLE_CONFIG12_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG12_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config12_reg; +#[doc = "RF_ENABLE_CONFIG13_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG13_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config13_reg; +#[doc = "RF_ENABLE_CONFIG14_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG14_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config14_reg; +#[doc = "RF_ENABLE_CONFIG15_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG15_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config15_reg; +#[doc = "RF_ENABLE_CONFIG16_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG16_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config16_reg; +#[doc = "RF_ENABLE_CONFIG17_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG17_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config17_reg; +#[doc = "RF_ENABLE_CONFIG18_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG18_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config18_reg; +#[doc = "RF_ENABLE_CONFIG19_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG19_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config19_reg; +#[doc = "RF_ENABLE_CONFIG1_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG1_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config1_reg; +#[doc = "RF_ENABLE_CONFIG20_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG20_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config20_reg; +#[doc = "RF_ENABLE_CONFIG21_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG21_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config21_reg; +#[doc = "RF_ENABLE_CONFIG22_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG22_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config22_reg; +#[doc = "RF_ENABLE_CONFIG23_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG23_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config23_reg; +#[doc = "RF_ENABLE_CONFIG24_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG24_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config24_reg; +#[doc = "RF_ENABLE_CONFIG25_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG25_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config25_reg; +#[doc = "RF_ENABLE_CONFIG26_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG26_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config26_reg; +#[doc = "RF_ENABLE_CONFIG27_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG27_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config27_reg; +#[doc = "RF_ENABLE_CONFIG28_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG28_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config28_reg; +#[doc = "RF_ENABLE_CONFIG29_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG29_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config29_reg; +#[doc = "RF_ENABLE_CONFIG2_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG2_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config2_reg; +#[doc = "RF_ENABLE_CONFIG30_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG30_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config30_reg; +#[doc = "RF_ENABLE_CONFIG31_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG31_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config31_reg; +#[doc = "RF_ENABLE_CONFIG32_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG32_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config32_reg; +#[doc = "RF_ENABLE_CONFIG33_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG33_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config33_reg; +#[doc = "RF_ENABLE_CONFIG34_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG34_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config34_reg; +#[doc = "RF_ENABLE_CONFIG35_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG35_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config35_reg; +#[doc = "RF_ENABLE_CONFIG36_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG36_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config36_reg; +#[doc = "RF_ENABLE_CONFIG37_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG37_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config37_reg; +#[doc = "RF_ENABLE_CONFIG38_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG38_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config38_reg; +#[doc = "RF_ENABLE_CONFIG39_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG39_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config39_reg; +#[doc = "RF_ENABLE_CONFIG3_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG3_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config3_reg; +#[doc = "RF_ENABLE_CONFIG40_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG40_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config40_reg; +#[doc = "RF_ENABLE_CONFIG41_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG41_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config41_reg; +#[doc = "RF_ENABLE_CONFIG42_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG42_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config42_reg; +#[doc = "RF_ENABLE_CONFIG43_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG43_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config43_reg; +#[doc = "RF_ENABLE_CONFIG44_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG44_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config44_reg; +#[doc = "RF_ENABLE_CONFIG45_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG45_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config45_reg; +#[doc = "RF_ENABLE_CONFIG46_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG46_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config46_reg; +#[doc = "RF_ENABLE_CONFIG4_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG4_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config4_reg; +#[doc = "RF_ENABLE_CONFIG5_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG5_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config5_reg; +#[doc = "RF_ENABLE_CONFIG6_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG6_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config6_reg; +#[doc = "RF_ENABLE_CONFIG7_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG7_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config7_reg; +#[doc = "RF_ENABLE_CONFIG8_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG8_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config8_reg; +#[doc = "RF_ENABLE_CONFIG9_REG register accessor: an alias for `Reg`"] +pub type RF_ENABLE_CONFIG9_REG = crate::Reg; +#[doc = ""] +pub mod rf_enable_config9_reg; +#[doc = "RF_PORT_EN_REG register accessor: an alias for `Reg`"] +pub type RF_PORT_EN_REG = crate::Reg; +#[doc = ""] +pub mod rf_port_en_reg; +#[doc = "RF_PORT_POL_REG register accessor: an alias for `Reg`"] +pub type RF_PORT_POL_REG = crate::Reg; +#[doc = ""] +pub mod rf_port_pol_reg; diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en1_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en1_reg.rs new file mode 100644 index 0000000..91049d8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en1_reg.rs @@ -0,0 +1,1570 @@ +#[doc = "Register `RF_ALWAYS_EN1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ALWAYS_EN1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_EN` reader - "] +pub struct ALW_EN_ADPLLDIG_EN_R(crate::FieldReader); +impl ALW_EN_ADPLLDIG_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLLDIG_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLLDIG_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_EN` writer - "] +pub struct ALW_EN_ADPLLDIG_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLLDIG_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_RST` reader - "] +pub struct ALW_EN_ADPLLDIG_RST_R(crate::FieldReader); +impl ALW_EN_ADPLLDIG_RST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLLDIG_RST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLLDIG_RST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_RST` writer - "] +pub struct ALW_EN_ADPLLDIG_RST_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLLDIG_RST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 30)) | ((value as u32 & 1) << 30); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_CLK_EN` reader - "] +pub struct ALW_EN_ADPLL_CLK_EN_R(crate::FieldReader); +impl ALW_EN_ADPLL_CLK_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_CLK_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_CLK_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_CLK_EN` writer - "] +pub struct ALW_EN_ADPLL_CLK_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_CLK_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 29)) | ((value as u32 & 1) << 29); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_DCO_EN` reader - "] +pub struct ALW_EN_ADPLL_DCO_EN_R(crate::FieldReader); +impl ALW_EN_ADPLL_DCO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_DCO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_DCO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_DCO_EN` writer - "] +pub struct ALW_EN_ADPLL_DCO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_DCO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 28)) | ((value as u32 & 1) << 28); + self.w + } +} +#[doc = "Field `ALW_EN_ADC_EN` reader - "] +pub struct ALW_EN_ADC_EN_R(crate::FieldReader); +impl ALW_EN_ADC_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADC_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADC_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADC_EN` writer - "] +pub struct ALW_EN_ADC_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADC_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 27)) | ((value as u32 & 1) << 27); + self.w + } +} +#[doc = "Field `ALW_EN_ADC_CLK_EN` reader - "] +pub struct ALW_EN_ADC_CLK_EN_R(crate::FieldReader); +impl ALW_EN_ADC_CLK_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADC_CLK_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADC_CLK_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADC_CLK_EN` writer - "] +pub struct ALW_EN_ADC_CLK_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADC_CLK_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 26)) | ((value as u32 & 1) << 26); + self.w + } +} +#[doc = "Field `ALW_EN_IFF_BIAS_SH_OPEN` reader - "] +pub struct ALW_EN_IFF_BIAS_SH_OPEN_R(crate::FieldReader); +impl ALW_EN_IFF_BIAS_SH_OPEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_IFF_BIAS_SH_OPEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_IFF_BIAS_SH_OPEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_IFF_BIAS_SH_OPEN` writer - "] +pub struct ALW_EN_IFF_BIAS_SH_OPEN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_IFF_BIAS_SH_OPEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 25)) | ((value as u32 & 1) << 25); + self.w + } +} +#[doc = "Field `ALW_EN_IFF_EN` reader - "] +pub struct ALW_EN_IFF_EN_R(crate::FieldReader); +impl ALW_EN_IFF_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_IFF_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_IFF_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_IFF_EN` writer - "] +pub struct ALW_EN_IFF_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_IFF_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 24)) | ((value as u32 & 1) << 24); + self.w + } +} +#[doc = "Field `ALW_EN_MIX_BIAS_SH_OPEN` reader - "] +pub struct ALW_EN_MIX_BIAS_SH_OPEN_R(crate::FieldReader); +impl ALW_EN_MIX_BIAS_SH_OPEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_MIX_BIAS_SH_OPEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_MIX_BIAS_SH_OPEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_MIX_BIAS_SH_OPEN` writer - "] +pub struct ALW_EN_MIX_BIAS_SH_OPEN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_MIX_BIAS_SH_OPEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 23)) | ((value as u32 & 1) << 23); + self.w + } +} +#[doc = "Field `ALW_EN_MIX_EN` reader - "] +pub struct ALW_EN_MIX_EN_R(crate::FieldReader); +impl ALW_EN_MIX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_MIX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_MIX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_MIX_EN` writer - "] +pub struct ALW_EN_MIX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_MIX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 22)) | ((value as u32 & 1) << 22); + self.w + } +} +#[doc = "Field `ALW_EN_LNA_CGM_EN` reader - "] +pub struct ALW_EN_LNA_CGM_EN_R(crate::FieldReader); +impl ALW_EN_LNA_CGM_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_LNA_CGM_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_LNA_CGM_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_LNA_CGM_EN` writer - "] +pub struct ALW_EN_LNA_CGM_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_LNA_CGM_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 21)) | ((value as u32 & 1) << 21); + self.w + } +} +#[doc = "Field `ALW_EN_LNA_CORE_EN` reader - "] +pub struct ALW_EN_LNA_CORE_EN_R(crate::FieldReader); +impl ALW_EN_LNA_CORE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_LNA_CORE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_LNA_CORE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_LNA_CORE_EN` writer - "] +pub struct ALW_EN_LNA_CORE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_LNA_CORE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 20)) | ((value as u32 & 1) << 20); + self.w + } +} +#[doc = "Field `ALW_EN_PA_EN` reader - "] +pub struct ALW_EN_PA_EN_R(crate::FieldReader); +impl ALW_EN_PA_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_PA_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_PA_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_PA_EN` writer - "] +pub struct ALW_EN_PA_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_PA_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `ALW_EN_PA_RAMP_EN` reader - "] +pub struct ALW_EN_PA_RAMP_EN_R(crate::FieldReader); +impl ALW_EN_PA_RAMP_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_PA_RAMP_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_PA_RAMP_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_PA_RAMP_EN` writer - "] +pub struct ALW_EN_PA_RAMP_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_PA_RAMP_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 18)) | ((value as u32 & 1) << 18); + self.w + } +} +#[doc = "Field `ALW_EN_RFIO_BIAS_SH_OPEN` reader - "] +pub struct ALW_EN_RFIO_BIAS_SH_OPEN_R(crate::FieldReader); +impl ALW_EN_RFIO_BIAS_SH_OPEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_RFIO_BIAS_SH_OPEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_RFIO_BIAS_SH_OPEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_RFIO_BIAS_SH_OPEN` writer - "] +pub struct ALW_EN_RFIO_BIAS_SH_OPEN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_RFIO_BIAS_SH_OPEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 17)) | ((value as u32 & 1) << 17); + self.w + } +} +#[doc = "Field `ALW_EN_RFIO_BIAS_EN` reader - "] +pub struct ALW_EN_RFIO_BIAS_EN_R(crate::FieldReader); +impl ALW_EN_RFIO_BIAS_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_RFIO_BIAS_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_RFIO_BIAS_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_RFIO_BIAS_EN` writer - "] +pub struct ALW_EN_RFIO_BIAS_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_RFIO_BIAS_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `ALW_EN_RFIO_TX_HARM_EN` reader - "] +pub struct ALW_EN_RFIO_TX_HARM_EN_R(crate::FieldReader); +impl ALW_EN_RFIO_TX_HARM_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_RFIO_TX_HARM_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_RFIO_TX_HARM_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_RFIO_TX_HARM_EN` writer - "] +pub struct ALW_EN_RFIO_TX_HARM_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_RFIO_TX_HARM_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `ALW_EN_RFIO_TX_EN` reader - "] +pub struct ALW_EN_RFIO_TX_EN_R(crate::FieldReader); +impl ALW_EN_RFIO_TX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_RFIO_TX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_RFIO_TX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_RFIO_TX_EN` writer - "] +pub struct ALW_EN_RFIO_TX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_RFIO_TX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u32 & 1) << 14); + self.w + } +} +#[doc = "Field `ALW_EN_RFIO_RX_EN` reader - "] +pub struct ALW_EN_RFIO_RX_EN_R(crate::FieldReader); +impl ALW_EN_RFIO_RX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_RFIO_RX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_RFIO_RX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_RFIO_RX_EN` writer - "] +pub struct ALW_EN_RFIO_RX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_RFIO_RX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u32 & 1) << 13); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_LDO_LP` reader - "] +pub struct ALW_EN_ADPLLDIG_LDO_LP_R(crate::FieldReader); +impl ALW_EN_ADPLLDIG_LDO_LP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLLDIG_LDO_LP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLLDIG_LDO_LP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_LDO_LP` writer - "] +pub struct ALW_EN_ADPLLDIG_LDO_LP_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLLDIG_LDO_LP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u32 & 1) << 12); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_LDO_ACTIVERDY` reader - "] +pub struct ALW_EN_ADPLLDIG_LDO_ACTIVERDY_R(crate::FieldReader); +impl ALW_EN_ADPLLDIG_LDO_ACTIVERDY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLLDIG_LDO_ACTIVERDY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLLDIG_LDO_ACTIVERDY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_LDO_ACTIVERDY` writer - "] +pub struct ALW_EN_ADPLLDIG_LDO_ACTIVERDY_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLLDIG_LDO_ACTIVERDY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u32 & 1) << 11); + self.w + } +} +#[doc = "Field `ALW_EN_LNA_LDO_ZERO` reader - "] +pub struct ALW_EN_LNA_LDO_ZERO_R(crate::FieldReader); +impl ALW_EN_LNA_LDO_ZERO_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_LNA_LDO_ZERO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_LNA_LDO_ZERO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_LNA_LDO_ZERO` writer - "] +pub struct ALW_EN_LNA_LDO_ZERO_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_LNA_LDO_ZERO_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u32 & 1) << 10); + self.w + } +} +#[doc = "Field `ALW_EN_LDO_ZERO_EN` reader - "] +pub struct ALW_EN_LDO_ZERO_EN_R(crate::FieldReader); +impl ALW_EN_LDO_ZERO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_LDO_ZERO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_LDO_ZERO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_LDO_ZERO_EN` writer - "] +pub struct ALW_EN_LDO_ZERO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_LDO_ZERO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_DCO_LDO_EN` reader - "] +pub struct ALW_EN_ADPLL_DCO_LDO_EN_R(crate::FieldReader); +impl ALW_EN_ADPLL_DCO_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_DCO_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_DCO_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_DCO_LDO_EN` writer - "] +pub struct ALW_EN_ADPLL_DCO_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_DCO_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_DTC_LDO_EN` reader - "] +pub struct ALW_EN_ADPLL_DTC_LDO_EN_R(crate::FieldReader); +impl ALW_EN_ADPLL_DTC_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_DTC_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_DTC_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_DTC_LDO_EN` writer - "] +pub struct ALW_EN_ADPLL_DTC_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_DTC_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_TDC_LDO_EN` reader - "] +pub struct ALW_EN_ADPLL_TDC_LDO_EN_R(crate::FieldReader); +impl ALW_EN_ADPLL_TDC_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_TDC_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_TDC_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_TDC_LDO_EN` writer - "] +pub struct ALW_EN_ADPLL_TDC_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_TDC_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `ALW_EN_IFFADC_LDO_EN` reader - "] +pub struct ALW_EN_IFFADC_LDO_EN_R(crate::FieldReader); +impl ALW_EN_IFFADC_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_IFFADC_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_IFFADC_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_IFFADC_LDO_EN` writer - "] +pub struct ALW_EN_IFFADC_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_IFFADC_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `ALW_EN_IFF_LDO_EN` reader - "] +pub struct ALW_EN_IFF_LDO_EN_R(crate::FieldReader); +impl ALW_EN_IFF_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_IFF_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_IFF_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_IFF_LDO_EN` writer - "] +pub struct ALW_EN_IFF_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_IFF_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `ALW_EN_MIX_LDO_EN` reader - "] +pub struct ALW_EN_MIX_LDO_EN_R(crate::FieldReader); +impl ALW_EN_MIX_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_MIX_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_MIX_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_MIX_LDO_EN` writer - "] +pub struct ALW_EN_MIX_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_MIX_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `ALW_EN_LNA_LDO_EN` reader - "] +pub struct ALW_EN_LNA_LDO_EN_R(crate::FieldReader); +impl ALW_EN_LNA_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_LNA_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_LNA_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_LNA_LDO_EN` writer - "] +pub struct ALW_EN_LNA_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_LNA_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `ALW_EN_PA_LDO_EN` reader - "] +pub struct ALW_EN_PA_LDO_EN_R(crate::FieldReader); +impl ALW_EN_PA_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_PA_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_PA_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_PA_LDO_EN` writer - "] +pub struct ALW_EN_PA_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_PA_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `ALW_EN_RFIO_LDO_EN` reader - "] +pub struct ALW_EN_RFIO_LDO_EN_R(crate::FieldReader); +impl ALW_EN_RFIO_LDO_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_RFIO_LDO_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_RFIO_LDO_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_RFIO_LDO_EN` writer - "] +pub struct ALW_EN_RFIO_LDO_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_RFIO_LDO_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 31"] + #[inline(always)] + pub fn alw_en_adplldig_en(&self) -> ALW_EN_ADPLLDIG_EN_R { + ALW_EN_ADPLLDIG_EN_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bit 30"] + #[inline(always)] + pub fn alw_en_adplldig_rst(&self) -> ALW_EN_ADPLLDIG_RST_R { + ALW_EN_ADPLLDIG_RST_R::new(((self.bits >> 30) & 1) != 0) + } + #[doc = "Bit 29"] + #[inline(always)] + pub fn alw_en_adpll_clk_en(&self) -> ALW_EN_ADPLL_CLK_EN_R { + ALW_EN_ADPLL_CLK_EN_R::new(((self.bits >> 29) & 1) != 0) + } + #[doc = "Bit 28"] + #[inline(always)] + pub fn alw_en_adpll_dco_en(&self) -> ALW_EN_ADPLL_DCO_EN_R { + ALW_EN_ADPLL_DCO_EN_R::new(((self.bits >> 28) & 1) != 0) + } + #[doc = "Bit 27"] + #[inline(always)] + pub fn alw_en_adc_en(&self) -> ALW_EN_ADC_EN_R { + ALW_EN_ADC_EN_R::new(((self.bits >> 27) & 1) != 0) + } + #[doc = "Bit 26"] + #[inline(always)] + pub fn alw_en_adc_clk_en(&self) -> ALW_EN_ADC_CLK_EN_R { + ALW_EN_ADC_CLK_EN_R::new(((self.bits >> 26) & 1) != 0) + } + #[doc = "Bit 25"] + #[inline(always)] + pub fn alw_en_iff_bias_sh_open(&self) -> ALW_EN_IFF_BIAS_SH_OPEN_R { + ALW_EN_IFF_BIAS_SH_OPEN_R::new(((self.bits >> 25) & 1) != 0) + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn alw_en_iff_en(&self) -> ALW_EN_IFF_EN_R { + ALW_EN_IFF_EN_R::new(((self.bits >> 24) & 1) != 0) + } + #[doc = "Bit 23"] + #[inline(always)] + pub fn alw_en_mix_bias_sh_open(&self) -> ALW_EN_MIX_BIAS_SH_OPEN_R { + ALW_EN_MIX_BIAS_SH_OPEN_R::new(((self.bits >> 23) & 1) != 0) + } + #[doc = "Bit 22"] + #[inline(always)] + pub fn alw_en_mix_en(&self) -> ALW_EN_MIX_EN_R { + ALW_EN_MIX_EN_R::new(((self.bits >> 22) & 1) != 0) + } + #[doc = "Bit 21"] + #[inline(always)] + pub fn alw_en_lna_cgm_en(&self) -> ALW_EN_LNA_CGM_EN_R { + ALW_EN_LNA_CGM_EN_R::new(((self.bits >> 21) & 1) != 0) + } + #[doc = "Bit 20"] + #[inline(always)] + pub fn alw_en_lna_core_en(&self) -> ALW_EN_LNA_CORE_EN_R { + ALW_EN_LNA_CORE_EN_R::new(((self.bits >> 20) & 1) != 0) + } + #[doc = "Bit 19"] + #[inline(always)] + pub fn alw_en_pa_en(&self) -> ALW_EN_PA_EN_R { + ALW_EN_PA_EN_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bit 18"] + #[inline(always)] + pub fn alw_en_pa_ramp_en(&self) -> ALW_EN_PA_RAMP_EN_R { + ALW_EN_PA_RAMP_EN_R::new(((self.bits >> 18) & 1) != 0) + } + #[doc = "Bit 17"] + #[inline(always)] + pub fn alw_en_rfio_bias_sh_open(&self) -> ALW_EN_RFIO_BIAS_SH_OPEN_R { + ALW_EN_RFIO_BIAS_SH_OPEN_R::new(((self.bits >> 17) & 1) != 0) + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn alw_en_rfio_bias_en(&self) -> ALW_EN_RFIO_BIAS_EN_R { + ALW_EN_RFIO_BIAS_EN_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn alw_en_rfio_tx_harm_en(&self) -> ALW_EN_RFIO_TX_HARM_EN_R { + ALW_EN_RFIO_TX_HARM_EN_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14"] + #[inline(always)] + pub fn alw_en_rfio_tx_en(&self) -> ALW_EN_RFIO_TX_EN_R { + ALW_EN_RFIO_TX_EN_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn alw_en_rfio_rx_en(&self) -> ALW_EN_RFIO_RX_EN_R { + ALW_EN_RFIO_RX_EN_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn alw_en_adplldig_ldo_lp(&self) -> ALW_EN_ADPLLDIG_LDO_LP_R { + ALW_EN_ADPLLDIG_LDO_LP_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn alw_en_adplldig_ldo_activerdy(&self) -> ALW_EN_ADPLLDIG_LDO_ACTIVERDY_R { + ALW_EN_ADPLLDIG_LDO_ACTIVERDY_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn alw_en_lna_ldo_zero(&self) -> ALW_EN_LNA_LDO_ZERO_R { + ALW_EN_LNA_LDO_ZERO_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn alw_en_ldo_zero_en(&self) -> ALW_EN_LDO_ZERO_EN_R { + ALW_EN_LDO_ZERO_EN_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn alw_en_adpll_dco_ldo_en(&self) -> ALW_EN_ADPLL_DCO_LDO_EN_R { + ALW_EN_ADPLL_DCO_LDO_EN_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn alw_en_adpll_dtc_ldo_en(&self) -> ALW_EN_ADPLL_DTC_LDO_EN_R { + ALW_EN_ADPLL_DTC_LDO_EN_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn alw_en_adpll_tdc_ldo_en(&self) -> ALW_EN_ADPLL_TDC_LDO_EN_R { + ALW_EN_ADPLL_TDC_LDO_EN_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn alw_en_iffadc_ldo_en(&self) -> ALW_EN_IFFADC_LDO_EN_R { + ALW_EN_IFFADC_LDO_EN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn alw_en_iff_ldo_en(&self) -> ALW_EN_IFF_LDO_EN_R { + ALW_EN_IFF_LDO_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn alw_en_mix_ldo_en(&self) -> ALW_EN_MIX_LDO_EN_R { + ALW_EN_MIX_LDO_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn alw_en_lna_ldo_en(&self) -> ALW_EN_LNA_LDO_EN_R { + ALW_EN_LNA_LDO_EN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn alw_en_pa_ldo_en(&self) -> ALW_EN_PA_LDO_EN_R { + ALW_EN_PA_LDO_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn alw_en_rfio_ldo_en(&self) -> ALW_EN_RFIO_LDO_EN_R { + ALW_EN_RFIO_LDO_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 31"] + #[inline(always)] + pub fn alw_en_adplldig_en(&mut self) -> ALW_EN_ADPLLDIG_EN_W { + ALW_EN_ADPLLDIG_EN_W { w: self } + } + #[doc = "Bit 30"] + #[inline(always)] + pub fn alw_en_adplldig_rst(&mut self) -> ALW_EN_ADPLLDIG_RST_W { + ALW_EN_ADPLLDIG_RST_W { w: self } + } + #[doc = "Bit 29"] + #[inline(always)] + pub fn alw_en_adpll_clk_en(&mut self) -> ALW_EN_ADPLL_CLK_EN_W { + ALW_EN_ADPLL_CLK_EN_W { w: self } + } + #[doc = "Bit 28"] + #[inline(always)] + pub fn alw_en_adpll_dco_en(&mut self) -> ALW_EN_ADPLL_DCO_EN_W { + ALW_EN_ADPLL_DCO_EN_W { w: self } + } + #[doc = "Bit 27"] + #[inline(always)] + pub fn alw_en_adc_en(&mut self) -> ALW_EN_ADC_EN_W { + ALW_EN_ADC_EN_W { w: self } + } + #[doc = "Bit 26"] + #[inline(always)] + pub fn alw_en_adc_clk_en(&mut self) -> ALW_EN_ADC_CLK_EN_W { + ALW_EN_ADC_CLK_EN_W { w: self } + } + #[doc = "Bit 25"] + #[inline(always)] + pub fn alw_en_iff_bias_sh_open(&mut self) -> ALW_EN_IFF_BIAS_SH_OPEN_W { + ALW_EN_IFF_BIAS_SH_OPEN_W { w: self } + } + #[doc = "Bit 24"] + #[inline(always)] + pub fn alw_en_iff_en(&mut self) -> ALW_EN_IFF_EN_W { + ALW_EN_IFF_EN_W { w: self } + } + #[doc = "Bit 23"] + #[inline(always)] + pub fn alw_en_mix_bias_sh_open(&mut self) -> ALW_EN_MIX_BIAS_SH_OPEN_W { + ALW_EN_MIX_BIAS_SH_OPEN_W { w: self } + } + #[doc = "Bit 22"] + #[inline(always)] + pub fn alw_en_mix_en(&mut self) -> ALW_EN_MIX_EN_W { + ALW_EN_MIX_EN_W { w: self } + } + #[doc = "Bit 21"] + #[inline(always)] + pub fn alw_en_lna_cgm_en(&mut self) -> ALW_EN_LNA_CGM_EN_W { + ALW_EN_LNA_CGM_EN_W { w: self } + } + #[doc = "Bit 20"] + #[inline(always)] + pub fn alw_en_lna_core_en(&mut self) -> ALW_EN_LNA_CORE_EN_W { + ALW_EN_LNA_CORE_EN_W { w: self } + } + #[doc = "Bit 19"] + #[inline(always)] + pub fn alw_en_pa_en(&mut self) -> ALW_EN_PA_EN_W { + ALW_EN_PA_EN_W { w: self } + } + #[doc = "Bit 18"] + #[inline(always)] + pub fn alw_en_pa_ramp_en(&mut self) -> ALW_EN_PA_RAMP_EN_W { + ALW_EN_PA_RAMP_EN_W { w: self } + } + #[doc = "Bit 17"] + #[inline(always)] + pub fn alw_en_rfio_bias_sh_open(&mut self) -> ALW_EN_RFIO_BIAS_SH_OPEN_W { + ALW_EN_RFIO_BIAS_SH_OPEN_W { w: self } + } + #[doc = "Bit 16"] + #[inline(always)] + pub fn alw_en_rfio_bias_en(&mut self) -> ALW_EN_RFIO_BIAS_EN_W { + ALW_EN_RFIO_BIAS_EN_W { w: self } + } + #[doc = "Bit 15"] + #[inline(always)] + pub fn alw_en_rfio_tx_harm_en(&mut self) -> ALW_EN_RFIO_TX_HARM_EN_W { + ALW_EN_RFIO_TX_HARM_EN_W { w: self } + } + #[doc = "Bit 14"] + #[inline(always)] + pub fn alw_en_rfio_tx_en(&mut self) -> ALW_EN_RFIO_TX_EN_W { + ALW_EN_RFIO_TX_EN_W { w: self } + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn alw_en_rfio_rx_en(&mut self) -> ALW_EN_RFIO_RX_EN_W { + ALW_EN_RFIO_RX_EN_W { w: self } + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn alw_en_adplldig_ldo_lp(&mut self) -> ALW_EN_ADPLLDIG_LDO_LP_W { + ALW_EN_ADPLLDIG_LDO_LP_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn alw_en_adplldig_ldo_activerdy(&mut self) -> ALW_EN_ADPLLDIG_LDO_ACTIVERDY_W { + ALW_EN_ADPLLDIG_LDO_ACTIVERDY_W { w: self } + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn alw_en_lna_ldo_zero(&mut self) -> ALW_EN_LNA_LDO_ZERO_W { + ALW_EN_LNA_LDO_ZERO_W { w: self } + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn alw_en_ldo_zero_en(&mut self) -> ALW_EN_LDO_ZERO_EN_W { + ALW_EN_LDO_ZERO_EN_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn alw_en_adpll_dco_ldo_en(&mut self) -> ALW_EN_ADPLL_DCO_LDO_EN_W { + ALW_EN_ADPLL_DCO_LDO_EN_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn alw_en_adpll_dtc_ldo_en(&mut self) -> ALW_EN_ADPLL_DTC_LDO_EN_W { + ALW_EN_ADPLL_DTC_LDO_EN_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn alw_en_adpll_tdc_ldo_en(&mut self) -> ALW_EN_ADPLL_TDC_LDO_EN_W { + ALW_EN_ADPLL_TDC_LDO_EN_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn alw_en_iffadc_ldo_en(&mut self) -> ALW_EN_IFFADC_LDO_EN_W { + ALW_EN_IFFADC_LDO_EN_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn alw_en_iff_ldo_en(&mut self) -> ALW_EN_IFF_LDO_EN_W { + ALW_EN_IFF_LDO_EN_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn alw_en_mix_ldo_en(&mut self) -> ALW_EN_MIX_LDO_EN_W { + ALW_EN_MIX_LDO_EN_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn alw_en_lna_ldo_en(&mut self) -> ALW_EN_LNA_LDO_EN_W { + ALW_EN_LNA_LDO_EN_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn alw_en_pa_ldo_en(&mut self) -> ALW_EN_PA_LDO_EN_W { + ALW_EN_PA_LDO_EN_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn alw_en_rfio_ldo_en(&mut self) -> ALW_EN_RFIO_LDO_EN_W { + ALW_EN_RFIO_LDO_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_always_en1_reg](index.html) module"] +pub struct RF_ALWAYS_EN1_REG_SPEC; +impl crate::RegisterSpec for RF_ALWAYS_EN1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_always_en1_reg::R](R) reader structure"] +impl crate::Readable for RF_ALWAYS_EN1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_always_en1_reg::W](W) writer structure"] +impl crate::Writable for RF_ALWAYS_EN1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ALWAYS_EN1_REG to value 0"] +impl crate::Resettable for RF_ALWAYS_EN1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en2_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en2_reg.rs new file mode 100644 index 0000000..93ce624 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_always_en2_reg.rs @@ -0,0 +1,771 @@ +#[doc = "Register `RF_ALWAYS_EN2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ALWAYS_EN2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ALW_EN_SPARE5` reader - "] +pub struct ALW_EN_SPARE5_R(crate::FieldReader); +impl ALW_EN_SPARE5_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_SPARE5_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_SPARE5_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_SPARE5` writer - "] +pub struct ALW_EN_SPARE5_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_SPARE5_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u32 & 1) << 14); + self.w + } +} +#[doc = "Field `ALW_EN_SPARE4` reader - "] +pub struct ALW_EN_SPARE4_R(crate::FieldReader); +impl ALW_EN_SPARE4_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_SPARE4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_SPARE4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_SPARE4` writer - "] +pub struct ALW_EN_SPARE4_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_SPARE4_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u32 & 1) << 13); + self.w + } +} +#[doc = "Field `ALW_EN_SPARE3` reader - "] +pub struct ALW_EN_SPARE3_R(crate::FieldReader); +impl ALW_EN_SPARE3_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_SPARE3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_SPARE3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_SPARE3` writer - "] +pub struct ALW_EN_SPARE3_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_SPARE3_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u32 & 1) << 12); + self.w + } +} +#[doc = "Field `ALW_EN_SPARE2` reader - "] +pub struct ALW_EN_SPARE2_R(crate::FieldReader); +impl ALW_EN_SPARE2_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_SPARE2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_SPARE2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_SPARE2` writer - "] +pub struct ALW_EN_SPARE2_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_SPARE2_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u32 & 1) << 11); + self.w + } +} +#[doc = "Field `ALW_EN_SPARE1` reader - "] +pub struct ALW_EN_SPARE1_R(crate::FieldReader); +impl ALW_EN_SPARE1_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_SPARE1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_SPARE1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_SPARE1` writer - "] +pub struct ALW_EN_SPARE1_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_SPARE1_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 10)) | ((value as u32 & 1) << 10); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_RDY_FOR_DIV` reader - "] +pub struct ALW_EN_ADPLL_RDY_FOR_DIV_R(crate::FieldReader); +impl ALW_EN_ADPLL_RDY_FOR_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_RDY_FOR_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_RDY_FOR_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_RDY_FOR_DIV` writer - "] +pub struct ALW_EN_ADPLL_RDY_FOR_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_RDY_FOR_DIV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `ALW_EN_PHY_RDY4BS` reader - "] +pub struct ALW_EN_PHY_RDY4BS_R(crate::FieldReader); +impl ALW_EN_PHY_RDY4BS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_PHY_RDY4BS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_PHY_RDY4BS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_PHY_RDY4BS` writer - "] +pub struct ALW_EN_PHY_RDY4BS_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_PHY_RDY4BS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `ALW_EN_DEM_SIGDETECT_EN` reader - "] +pub struct ALW_EN_DEM_SIGDETECT_EN_R(crate::FieldReader); +impl ALW_EN_DEM_SIGDETECT_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_DEM_SIGDETECT_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_DEM_SIGDETECT_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_DEM_SIGDETECT_EN` writer - "] +pub struct ALW_EN_DEM_SIGDETECT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_DEM_SIGDETECT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `ALW_EN_DEM_AGC_UNFREEZE_EN` reader - "] +pub struct ALW_EN_DEM_AGC_UNFREEZE_EN_R(crate::FieldReader); +impl ALW_EN_DEM_AGC_UNFREEZE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_DEM_AGC_UNFREEZE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_DEM_AGC_UNFREEZE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_DEM_AGC_UNFREEZE_EN` writer - "] +pub struct ALW_EN_DEM_AGC_UNFREEZE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_DEM_AGC_UNFREEZE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `ALW_EN_DEM_DC_PARCAL_EN` reader - "] +pub struct ALW_EN_DEM_DC_PARCAL_EN_R(crate::FieldReader); +impl ALW_EN_DEM_DC_PARCAL_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_DEM_DC_PARCAL_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_DEM_DC_PARCAL_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_DEM_DC_PARCAL_EN` writer - "] +pub struct ALW_EN_DEM_DC_PARCAL_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_DEM_DC_PARCAL_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `ALW_EN_DEM_EN` reader - "] +pub struct ALW_EN_DEM_EN_R(crate::FieldReader); +impl ALW_EN_DEM_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_DEM_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_DEM_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_DEM_EN` writer - "] +pub struct ALW_EN_DEM_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_DEM_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `ALW_EN_CAL_EN` reader - "] +pub struct ALW_EN_CAL_EN_R(crate::FieldReader); +impl ALW_EN_CAL_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_CAL_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_CAL_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_CAL_EN` writer - "] +pub struct ALW_EN_CAL_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_CAL_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_LOBUF_PA_EN` reader - "] +pub struct ALW_EN_ADPLL_LOBUF_PA_EN_R(crate::FieldReader); +impl ALW_EN_ADPLL_LOBUF_PA_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_LOBUF_PA_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_LOBUF_PA_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_LOBUF_PA_EN` writer - "] +pub struct ALW_EN_ADPLL_LOBUF_PA_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_LOBUF_PA_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLL_PAIN_EN` reader - "] +pub struct ALW_EN_ADPLL_PAIN_EN_R(crate::FieldReader); +impl ALW_EN_ADPLL_PAIN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLL_PAIN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLL_PAIN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLL_PAIN_EN` writer - "] +pub struct ALW_EN_ADPLL_PAIN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLL_PAIN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_RX_EN` reader - "] +pub struct ALW_EN_ADPLLDIG_RX_EN_R(crate::FieldReader); +impl ALW_EN_ADPLLDIG_RX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ALW_EN_ADPLLDIG_RX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ALW_EN_ADPLLDIG_RX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ALW_EN_ADPLLDIG_RX_EN` writer - "] +pub struct ALW_EN_ADPLLDIG_RX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> ALW_EN_ADPLLDIG_RX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 14"] + #[inline(always)] + pub fn alw_en_spare5(&self) -> ALW_EN_SPARE5_R { + ALW_EN_SPARE5_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn alw_en_spare4(&self) -> ALW_EN_SPARE4_R { + ALW_EN_SPARE4_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn alw_en_spare3(&self) -> ALW_EN_SPARE3_R { + ALW_EN_SPARE3_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn alw_en_spare2(&self) -> ALW_EN_SPARE2_R { + ALW_EN_SPARE2_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn alw_en_spare1(&self) -> ALW_EN_SPARE1_R { + ALW_EN_SPARE1_R::new(((self.bits >> 10) & 1) != 0) + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn alw_en_adpll_rdy_for_div(&self) -> ALW_EN_ADPLL_RDY_FOR_DIV_R { + ALW_EN_ADPLL_RDY_FOR_DIV_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn alw_en_phy_rdy4bs(&self) -> ALW_EN_PHY_RDY4BS_R { + ALW_EN_PHY_RDY4BS_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn alw_en_dem_sigdetect_en(&self) -> ALW_EN_DEM_SIGDETECT_EN_R { + ALW_EN_DEM_SIGDETECT_EN_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn alw_en_dem_agc_unfreeze_en(&self) -> ALW_EN_DEM_AGC_UNFREEZE_EN_R { + ALW_EN_DEM_AGC_UNFREEZE_EN_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn alw_en_dem_dc_parcal_en(&self) -> ALW_EN_DEM_DC_PARCAL_EN_R { + ALW_EN_DEM_DC_PARCAL_EN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn alw_en_dem_en(&self) -> ALW_EN_DEM_EN_R { + ALW_EN_DEM_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn alw_en_cal_en(&self) -> ALW_EN_CAL_EN_R { + ALW_EN_CAL_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn alw_en_adpll_lobuf_pa_en(&self) -> ALW_EN_ADPLL_LOBUF_PA_EN_R { + ALW_EN_ADPLL_LOBUF_PA_EN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn alw_en_adpll_pain_en(&self) -> ALW_EN_ADPLL_PAIN_EN_R { + ALW_EN_ADPLL_PAIN_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn alw_en_adplldig_rx_en(&self) -> ALW_EN_ADPLLDIG_RX_EN_R { + ALW_EN_ADPLLDIG_RX_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 14"] + #[inline(always)] + pub fn alw_en_spare5(&mut self) -> ALW_EN_SPARE5_W { + ALW_EN_SPARE5_W { w: self } + } + #[doc = "Bit 13"] + #[inline(always)] + pub fn alw_en_spare4(&mut self) -> ALW_EN_SPARE4_W { + ALW_EN_SPARE4_W { w: self } + } + #[doc = "Bit 12"] + #[inline(always)] + pub fn alw_en_spare3(&mut self) -> ALW_EN_SPARE3_W { + ALW_EN_SPARE3_W { w: self } + } + #[doc = "Bit 11"] + #[inline(always)] + pub fn alw_en_spare2(&mut self) -> ALW_EN_SPARE2_W { + ALW_EN_SPARE2_W { w: self } + } + #[doc = "Bit 10"] + #[inline(always)] + pub fn alw_en_spare1(&mut self) -> ALW_EN_SPARE1_W { + ALW_EN_SPARE1_W { w: self } + } + #[doc = "Bit 9"] + #[inline(always)] + pub fn alw_en_adpll_rdy_for_div(&mut self) -> ALW_EN_ADPLL_RDY_FOR_DIV_W { + ALW_EN_ADPLL_RDY_FOR_DIV_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn alw_en_phy_rdy4bs(&mut self) -> ALW_EN_PHY_RDY4BS_W { + ALW_EN_PHY_RDY4BS_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn alw_en_dem_sigdetect_en(&mut self) -> ALW_EN_DEM_SIGDETECT_EN_W { + ALW_EN_DEM_SIGDETECT_EN_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn alw_en_dem_agc_unfreeze_en(&mut self) -> ALW_EN_DEM_AGC_UNFREEZE_EN_W { + ALW_EN_DEM_AGC_UNFREEZE_EN_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn alw_en_dem_dc_parcal_en(&mut self) -> ALW_EN_DEM_DC_PARCAL_EN_W { + ALW_EN_DEM_DC_PARCAL_EN_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn alw_en_dem_en(&mut self) -> ALW_EN_DEM_EN_W { + ALW_EN_DEM_EN_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn alw_en_cal_en(&mut self) -> ALW_EN_CAL_EN_W { + ALW_EN_CAL_EN_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn alw_en_adpll_lobuf_pa_en(&mut self) -> ALW_EN_ADPLL_LOBUF_PA_EN_W { + ALW_EN_ADPLL_LOBUF_PA_EN_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn alw_en_adpll_pain_en(&mut self) -> ALW_EN_ADPLL_PAIN_EN_W { + ALW_EN_ADPLL_PAIN_EN_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn alw_en_adplldig_rx_en(&mut self) -> ALW_EN_ADPLLDIG_RX_EN_W { + ALW_EN_ADPLLDIG_RX_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_always_en2_reg](index.html) module"] +pub struct RF_ALWAYS_EN2_REG_SPEC; +impl crate::RegisterSpec for RF_ALWAYS_EN2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_always_en2_reg::R](R) reader structure"] +impl crate::Readable for RF_ALWAYS_EN2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_always_en2_reg::W](W) writer structure"] +impl crate::Writable for RF_ALWAYS_EN2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ALWAYS_EN2_REG to value 0"] +impl crate::Resettable for RF_ALWAYS_EN2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_10_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_10_reg.rs new file mode 100644 index 0000000..929888e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_10_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_10_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_10_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_10_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_10_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_10_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_10_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_10_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_10_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_10_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_10_REG to value 0x0c16"] +impl crate::Resettable for RF_CNTRL_TIMER_10_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0c16 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_11_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_11_reg.rs new file mode 100644 index 0000000..46509e1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_11_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_11_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_11_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_11_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_11_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_11_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_11_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_11_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_11_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_11_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_11_REG to value 0x081a"] +impl crate::Resettable for RF_CNTRL_TIMER_11_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x081a + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_12_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_12_reg.rs new file mode 100644 index 0000000..afd9e16 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_12_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_12_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_12_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_12_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_12_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_12_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_12_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_12_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_12_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_12_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_12_REG to value 0x0e1a"] +impl crate::Resettable for RF_CNTRL_TIMER_12_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0e1a + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_13_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_13_reg.rs new file mode 100644 index 0000000..a3b72a9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_13_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_13_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_13_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_13_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_13_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_13_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_13_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_13_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_13_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_13_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_13_REG to value 0x0220"] +impl crate::Resettable for RF_CNTRL_TIMER_13_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0220 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_14_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_14_reg.rs new file mode 100644 index 0000000..cdd28f0 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_14_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_14_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_14_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_14_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_14_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_14_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_14_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_14_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_14_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_14_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_14_REG to value 0x0a20"] +impl crate::Resettable for RF_CNTRL_TIMER_14_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0a20 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_15_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_15_reg.rs new file mode 100644 index 0000000..4bdf362 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_15_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_15_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_15_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_15_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_15_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_15_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_15_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_15_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_15_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_15_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_15_REG to value 0x0426"] +impl crate::Resettable for RF_CNTRL_TIMER_15_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0426 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_16_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_16_reg.rs new file mode 100644 index 0000000..1195750 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_16_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_16_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_16_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_16_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_16_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_16_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_16_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_16_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_16_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_16_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_16_REG to value 0x0430"] +impl crate::Resettable for RF_CNTRL_TIMER_16_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0430 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_17_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_17_reg.rs new file mode 100644 index 0000000..a05c434 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_17_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_17_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_17_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_17_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_17_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_17_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_17_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_17_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_17_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_17_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_17_REG to value 0x0837"] +impl crate::Resettable for RF_CNTRL_TIMER_17_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0837 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_18_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_18_reg.rs new file mode 100644 index 0000000..96834c7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_18_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_18_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_18_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_18_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_18_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_18_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_18_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_18_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_18_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_18_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_18_REG to value 0x0846"] +impl crate::Resettable for RF_CNTRL_TIMER_18_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0846 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_19_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_19_reg.rs new file mode 100644 index 0000000..a47b339 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_19_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_19_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_19_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_19_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_19_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_19_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_19_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_19_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_19_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_19_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_19_REG to value 0x0850"] +impl crate::Resettable for RF_CNTRL_TIMER_19_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0850 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_1_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_1_reg.rs new file mode 100644 index 0000000..66041b3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_1_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_1_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_1_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_1_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_1_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_1_REG to value 0x0400"] +impl crate::Resettable for RF_CNTRL_TIMER_1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0400 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_20_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_20_reg.rs new file mode 100644 index 0000000..9e3b19c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_20_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_20_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_20_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_20_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_20_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_20_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_20_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_20_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_20_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_20_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_20_REG to value 0x125a"] +impl crate::Resettable for RF_CNTRL_TIMER_20_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x125a + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_21_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_21_reg.rs new file mode 100644 index 0000000..e4c65dc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_21_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_21_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_21_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_21_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_21_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_21_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_21_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_21_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_21_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_21_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_21_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_21_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_22_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_22_reg.rs new file mode 100644 index 0000000..e134399 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_22_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_22_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_22_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_22_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_22_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_22_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_22_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_22_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_22_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_22_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_22_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_22_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_23_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_23_reg.rs new file mode 100644 index 0000000..b14d5c5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_23_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_23_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_23_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_23_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_23_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_23_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_23_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_23_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_23_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_23_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_23_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_23_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_24_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_24_reg.rs new file mode 100644 index 0000000..12283df --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_24_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_24_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_24_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_24_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_24_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_24_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_24_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_24_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_24_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_24_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_24_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_24_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_25_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_25_reg.rs new file mode 100644 index 0000000..dee84e2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_25_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_25_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_25_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_25_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_25_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_25_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_25_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_25_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_25_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_25_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_25_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_25_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_26_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_26_reg.rs new file mode 100644 index 0000000..ce5a6af --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_26_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_26_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_26_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_26_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_26_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_26_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_26_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_26_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_26_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_26_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_26_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_26_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_27_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_27_reg.rs new file mode 100644 index 0000000..6654028 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_27_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_27_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_27_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_27_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_27_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_27_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_27_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_27_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_27_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_27_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_27_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_27_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_28_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_28_reg.rs new file mode 100644 index 0000000..23f541e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_28_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_28_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_28_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_28_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_28_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_28_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_28_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_28_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_28_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_28_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_28_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_28_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_29_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_29_reg.rs new file mode 100644 index 0000000..8b630c1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_29_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_29_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_29_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_29_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_29_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_29_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_29_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_29_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_29_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_29_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_29_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_29_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_2_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_2_reg.rs new file mode 100644 index 0000000..e940dd6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_2_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_2_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_2_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_2_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_2_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_2_REG to value 0x0c00"] +impl crate::Resettable for RF_CNTRL_TIMER_2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0c00 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_30_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_30_reg.rs new file mode 100644 index 0000000..751d31e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_30_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_30_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_30_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_30_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_30_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_30_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_30_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_30_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_30_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_30_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_30_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_30_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_31_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_31_reg.rs new file mode 100644 index 0000000..14d0f4b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_31_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_31_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_31_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_31_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_31_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_31_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_31_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_31_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_31_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_31_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_31_REG to value 0"] +impl crate::Resettable for RF_CNTRL_TIMER_31_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_3_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_3_reg.rs new file mode 100644 index 0000000..9475ddb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_3_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_3_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_3_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_3_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_3_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_3_REG to value 0x0408"] +impl crate::Resettable for RF_CNTRL_TIMER_3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0408 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_4_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_4_reg.rs new file mode 100644 index 0000000..5c0356b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_4_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_4_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_4_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_4_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_4_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_4_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_4_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_4_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_4_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_4_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_4_REG to value 0x0c08"] +impl crate::Resettable for RF_CNTRL_TIMER_4_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0c08 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_5_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_5_reg.rs new file mode 100644 index 0000000..501fc15 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_5_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_5_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_5_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_5_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_5_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_5_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_5_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_5_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_5_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_5_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_5_REG to value 0x0212"] +impl crate::Resettable for RF_CNTRL_TIMER_5_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0212 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_6_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_6_reg.rs new file mode 100644 index 0000000..80872d5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_6_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_6_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_6_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_6_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_6_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_6_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_6_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_6_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_6_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_6_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_6_REG to value 0x0a12"] +impl crate::Resettable for RF_CNTRL_TIMER_6_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0a12 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_7_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_7_reg.rs new file mode 100644 index 0000000..c1952bc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_7_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_7_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_7_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_7_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_7_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_7_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_7_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_7_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_7_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_7_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_7_REG to value 0x0414"] +impl crate::Resettable for RF_CNTRL_TIMER_7_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0414 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_8_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_8_reg.rs new file mode 100644 index 0000000..69b4240 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_8_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_8_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_8_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_8_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_8_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_8_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_8_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_8_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_8_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_8_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_8_REG to value 0x0c14"] +impl crate::Resettable for RF_CNTRL_TIMER_8_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0c14 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_9_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_9_reg.rs new file mode 100644 index 0000000..ef6b264 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_cntrl_timer_9_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_CNTRL_TIMER_9_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_CNTRL_TIMER_9_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RESET_OFFSET` reader - "] +pub struct RESET_OFFSET_R(crate::FieldReader); +impl RESET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RESET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RESET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RESET_OFFSET` writer - "] +pub struct RESET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> RESET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8); + self.w + } +} +#[doc = "Field `SET_OFFSET` reader - "] +pub struct SET_OFFSET_R(crate::FieldReader); +impl SET_OFFSET_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SET_OFFSET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SET_OFFSET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SET_OFFSET` writer - "] +pub struct SET_OFFSET_W<'a> { + w: &'a mut W, +} +impl<'a> SET_OFFSET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&self) -> RESET_OFFSET_R { + RESET_OFFSET_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&self) -> SET_OFFSET_R { + SET_OFFSET_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 8:15"] + #[inline(always)] + pub fn reset_offset(&mut self) -> RESET_OFFSET_W { + RESET_OFFSET_W { w: self } + } + #[doc = "Bits 0:7"] + #[inline(always)] + pub fn set_offset(&mut self) -> SET_OFFSET_W { + SET_OFFSET_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_cntrl_timer_9_reg](index.html) module"] +pub struct RF_CNTRL_TIMER_9_REG_SPEC; +impl crate::RegisterSpec for RF_CNTRL_TIMER_9_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_cntrl_timer_9_reg::R](R) reader structure"] +impl crate::Readable for RF_CNTRL_TIMER_9_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_cntrl_timer_9_reg::W](W) writer structure"] +impl crate::Writable for RF_CNTRL_TIMER_9_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_CNTRL_TIMER_9_REG to value 0x0416"] +impl crate::Resettable for RF_CNTRL_TIMER_9_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0416 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config0_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config0_reg.rs new file mode 100644 index 0000000..3d3ce6a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config0_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFIO_LDO_EN_DCF_TX` reader - "] +pub struct RFIO_LDO_EN_DCF_TX_R(crate::FieldReader); +impl RFIO_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_LDO_EN_DCF_TX` writer - "] +pub struct RFIO_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `RFIO_LDO_EN_DCF_RX` reader - "] +pub struct RFIO_LDO_EN_DCF_RX_R(crate::FieldReader); +impl RFIO_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_LDO_EN_DCF_RX` writer - "] +pub struct RFIO_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_ldo_en_dcf_tx(&self) -> RFIO_LDO_EN_DCF_TX_R { + RFIO_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_ldo_en_dcf_rx(&self) -> RFIO_LDO_EN_DCF_RX_R { + RFIO_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_ldo_en_dcf_tx(&mut self) -> RFIO_LDO_EN_DCF_TX_W { + RFIO_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_ldo_en_dcf_rx(&mut self) -> RFIO_LDO_EN_DCF_RX_W { + RFIO_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config0_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG0_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG0_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config0_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config0_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG0_REG to value 0x83"] +impl crate::Resettable for RF_ENABLE_CONFIG0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x83 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config10_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config10_reg.rs new file mode 100644 index 0000000..ab1ce9c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config10_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG10_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG10_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LNA_LDO_ZERO_DCF_TX` reader - "] +pub struct LNA_LDO_ZERO_DCF_TX_R(crate::FieldReader); +impl LNA_LDO_ZERO_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_LDO_ZERO_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_LDO_ZERO_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_LDO_ZERO_DCF_TX` writer - "] +pub struct LNA_LDO_ZERO_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_LDO_ZERO_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `LNA_LDO_ZERO_DCF_RX` reader - "] +pub struct LNA_LDO_ZERO_DCF_RX_R(crate::FieldReader); +impl LNA_LDO_ZERO_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_LDO_ZERO_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_LDO_ZERO_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_LDO_ZERO_DCF_RX` writer - "] +pub struct LNA_LDO_ZERO_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_LDO_ZERO_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_ldo_zero_dcf_tx(&self) -> LNA_LDO_ZERO_DCF_TX_R { + LNA_LDO_ZERO_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_ldo_zero_dcf_rx(&self) -> LNA_LDO_ZERO_DCF_RX_R { + LNA_LDO_ZERO_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_ldo_zero_dcf_tx(&mut self) -> LNA_LDO_ZERO_DCF_TX_W { + LNA_LDO_ZERO_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_ldo_zero_dcf_rx(&mut self) -> LNA_LDO_ZERO_DCF_RX_W { + LNA_LDO_ZERO_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config10_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG10_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG10_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config10_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG10_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config10_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG10_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG10_REG to value 0x01"] +impl crate::Resettable for RF_ENABLE_CONFIG10_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config11_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config11_reg.rs new file mode 100644 index 0000000..1bae415 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config11_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG11_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG11_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLLDIG_LDO_ACTIVERDY_DCF_TX` reader - "] +pub struct ADPLLDIG_LDO_ACTIVERDY_DCF_TX_R(crate::FieldReader); +impl ADPLLDIG_LDO_ACTIVERDY_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_LDO_ACTIVERDY_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_ACTIVERDY_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_ACTIVERDY_DCF_TX` writer - "] +pub struct ADPLLDIG_LDO_ACTIVERDY_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_LDO_ACTIVERDY_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLLDIG_LDO_ACTIVERDY_DCF_RX` reader - "] +pub struct ADPLLDIG_LDO_ACTIVERDY_DCF_RX_R(crate::FieldReader); +impl ADPLLDIG_LDO_ACTIVERDY_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_LDO_ACTIVERDY_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_ACTIVERDY_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_ACTIVERDY_DCF_RX` writer - "] +pub struct ADPLLDIG_LDO_ACTIVERDY_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_LDO_ACTIVERDY_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_ldo_activerdy_dcf_tx(&self) -> ADPLLDIG_LDO_ACTIVERDY_DCF_TX_R { + ADPLLDIG_LDO_ACTIVERDY_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_ldo_activerdy_dcf_rx(&self) -> ADPLLDIG_LDO_ACTIVERDY_DCF_RX_R { + ADPLLDIG_LDO_ACTIVERDY_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_ldo_activerdy_dcf_tx(&mut self) -> ADPLLDIG_LDO_ACTIVERDY_DCF_TX_W { + ADPLLDIG_LDO_ACTIVERDY_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_ldo_activerdy_dcf_rx(&mut self) -> ADPLLDIG_LDO_ACTIVERDY_DCF_RX_W { + ADPLLDIG_LDO_ACTIVERDY_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config11_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG11_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG11_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config11_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG11_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config11_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG11_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG11_REG to value 0xc5"] +impl crate::Resettable for RF_ENABLE_CONFIG11_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0xc5 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config12_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config12_reg.rs new file mode 100644 index 0000000..5d5cc32 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config12_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG12_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG12_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLLDIG_LDO_LP_DCF_TX` reader - "] +pub struct ADPLLDIG_LDO_LP_DCF_TX_R(crate::FieldReader); +impl ADPLLDIG_LDO_LP_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_LDO_LP_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_LP_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_LP_DCF_TX` writer - "] +pub struct ADPLLDIG_LDO_LP_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_LDO_LP_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLLDIG_LDO_LP_DCF_RX` reader - "] +pub struct ADPLLDIG_LDO_LP_DCF_RX_R(crate::FieldReader); +impl ADPLLDIG_LDO_LP_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_LDO_LP_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_LDO_LP_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_LDO_LP_DCF_RX` writer - "] +pub struct ADPLLDIG_LDO_LP_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_LDO_LP_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_ldo_lp_dcf_tx(&self) -> ADPLLDIG_LDO_LP_DCF_TX_R { + ADPLLDIG_LDO_LP_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_ldo_lp_dcf_rx(&self) -> ADPLLDIG_LDO_LP_DCF_RX_R { + ADPLLDIG_LDO_LP_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_ldo_lp_dcf_tx(&mut self) -> ADPLLDIG_LDO_LP_DCF_TX_W { + ADPLLDIG_LDO_LP_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_ldo_lp_dcf_rx(&mut self) -> ADPLLDIG_LDO_LP_DCF_RX_W { + ADPLLDIG_LDO_LP_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config12_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG12_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG12_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config12_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG12_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config12_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG12_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG12_REG to value 0x018b"] +impl crate::Resettable for RF_ENABLE_CONFIG12_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x018b + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config13_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config13_reg.rs new file mode 100644 index 0000000..b0c4959 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config13_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG13_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG13_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFIO_RX_EN_DCF_TX` reader - "] +pub struct RFIO_RX_EN_DCF_TX_R(crate::FieldReader); +impl RFIO_RX_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_RX_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_RX_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_RX_EN_DCF_TX` writer - "] +pub struct RFIO_RX_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_RX_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `RFIO_RX_EN_DCF_RX` reader - "] +pub struct RFIO_RX_EN_DCF_RX_R(crate::FieldReader); +impl RFIO_RX_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_RX_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_RX_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_RX_EN_DCF_RX` writer - "] +pub struct RFIO_RX_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_RX_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_rx_en_dcf_tx(&self) -> RFIO_RX_EN_DCF_TX_R { + RFIO_RX_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_rx_en_dcf_rx(&self) -> RFIO_RX_EN_DCF_RX_R { + RFIO_RX_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_rx_en_dcf_tx(&mut self) -> RFIO_RX_EN_DCF_TX_W { + RFIO_RX_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_rx_en_dcf_rx(&mut self) -> RFIO_RX_EN_DCF_RX_W { + RFIO_RX_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config13_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG13_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG13_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config13_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG13_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config13_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG13_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG13_REG to value 0x0f"] +impl crate::Resettable for RF_ENABLE_CONFIG13_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config14_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config14_reg.rs new file mode 100644 index 0000000..83f23d5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config14_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG14_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG14_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFIO_TX_EN_DCF_TX` reader - "] +pub struct RFIO_TX_EN_DCF_TX_R(crate::FieldReader); +impl RFIO_TX_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_TX_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_TX_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_TX_EN_DCF_TX` writer - "] +pub struct RFIO_TX_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_TX_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `RFIO_TX_EN_DCF_RX` reader - "] +pub struct RFIO_TX_EN_DCF_RX_R(crate::FieldReader); +impl RFIO_TX_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_TX_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_TX_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_TX_EN_DCF_RX` writer - "] +pub struct RFIO_TX_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_TX_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_tx_en_dcf_tx(&self) -> RFIO_TX_EN_DCF_TX_R { + RFIO_TX_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_tx_en_dcf_rx(&self) -> RFIO_TX_EN_DCF_RX_R { + RFIO_TX_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_tx_en_dcf_tx(&mut self) -> RFIO_TX_EN_DCF_TX_W { + RFIO_TX_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_tx_en_dcf_rx(&mut self) -> RFIO_TX_EN_DCF_RX_W { + RFIO_TX_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config14_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG14_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG14_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config14_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG14_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config14_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG14_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG14_REG to value 0x01c0"] +impl crate::Resettable for RF_ENABLE_CONFIG14_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01c0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config15_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config15_reg.rs new file mode 100644 index 0000000..319e8bc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config15_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG15_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG15_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFIO_TX_HARM_EN_DCF_TX` reader - "] +pub struct RFIO_TX_HARM_EN_DCF_TX_R(crate::FieldReader); +impl RFIO_TX_HARM_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_TX_HARM_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_TX_HARM_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_TX_HARM_EN_DCF_TX` writer - "] +pub struct RFIO_TX_HARM_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_TX_HARM_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `RFIO_TX_HARM_EN_DCF_RX` reader - "] +pub struct RFIO_TX_HARM_EN_DCF_RX_R(crate::FieldReader); +impl RFIO_TX_HARM_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_TX_HARM_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_TX_HARM_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_TX_HARM_EN_DCF_RX` writer - "] +pub struct RFIO_TX_HARM_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_TX_HARM_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_tx_harm_en_dcf_tx(&self) -> RFIO_TX_HARM_EN_DCF_TX_R { + RFIO_TX_HARM_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_tx_harm_en_dcf_rx(&self) -> RFIO_TX_HARM_EN_DCF_RX_R { + RFIO_TX_HARM_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_tx_harm_en_dcf_tx(&mut self) -> RFIO_TX_HARM_EN_DCF_TX_W { + RFIO_TX_HARM_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_tx_harm_en_dcf_rx(&mut self) -> RFIO_TX_HARM_EN_DCF_RX_W { + RFIO_TX_HARM_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config15_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG15_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG15_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config15_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG15_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config15_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG15_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG15_REG to value 0x01c0"] +impl crate::Resettable for RF_ENABLE_CONFIG15_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01c0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config16_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config16_reg.rs new file mode 100644 index 0000000..fb7af7d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config16_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG16_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG16_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFIO_BIAS_EN_DCF_TX` reader - "] +pub struct RFIO_BIAS_EN_DCF_TX_R(crate::FieldReader); +impl RFIO_BIAS_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_BIAS_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_BIAS_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_BIAS_EN_DCF_TX` writer - "] +pub struct RFIO_BIAS_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_BIAS_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `RFIO_BIAS_EN_DCF_RX` reader - "] +pub struct RFIO_BIAS_EN_DCF_RX_R(crate::FieldReader); +impl RFIO_BIAS_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_BIAS_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_BIAS_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_BIAS_EN_DCF_RX` writer - "] +pub struct RFIO_BIAS_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_BIAS_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_bias_en_dcf_tx(&self) -> RFIO_BIAS_EN_DCF_TX_R { + RFIO_BIAS_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_bias_en_dcf_rx(&self) -> RFIO_BIAS_EN_DCF_RX_R { + RFIO_BIAS_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_bias_en_dcf_tx(&mut self) -> RFIO_BIAS_EN_DCF_TX_W { + RFIO_BIAS_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_bias_en_dcf_rx(&mut self) -> RFIO_BIAS_EN_DCF_RX_W { + RFIO_BIAS_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config16_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG16_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG16_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config16_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG16_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config16_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG16_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG16_REG to value 0x8f"] +impl crate::Resettable for RF_ENABLE_CONFIG16_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x8f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config17_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config17_reg.rs new file mode 100644 index 0000000..184b149 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config17_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG17_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG17_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFIO_BIAS_SH_OPEN_DCF_TX` reader - "] +pub struct RFIO_BIAS_SH_OPEN_DCF_TX_R(crate::FieldReader); +impl RFIO_BIAS_SH_OPEN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_BIAS_SH_OPEN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_BIAS_SH_OPEN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_BIAS_SH_OPEN_DCF_TX` writer - "] +pub struct RFIO_BIAS_SH_OPEN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_BIAS_SH_OPEN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `RFIO_BIAS_SH_OPEN_DCF_RX` reader - "] +pub struct RFIO_BIAS_SH_OPEN_DCF_RX_R(crate::FieldReader); +impl RFIO_BIAS_SH_OPEN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RFIO_BIAS_SH_OPEN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFIO_BIAS_SH_OPEN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFIO_BIAS_SH_OPEN_DCF_RX` writer - "] +pub struct RFIO_BIAS_SH_OPEN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RFIO_BIAS_SH_OPEN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_bias_sh_open_dcf_tx(&self) -> RFIO_BIAS_SH_OPEN_DCF_TX_R { + RFIO_BIAS_SH_OPEN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_bias_sh_open_dcf_rx(&self) -> RFIO_BIAS_SH_OPEN_DCF_RX_R { + RFIO_BIAS_SH_OPEN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn rfio_bias_sh_open_dcf_tx(&mut self) -> RFIO_BIAS_SH_OPEN_DCF_TX_W { + RFIO_BIAS_SH_OPEN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn rfio_bias_sh_open_dcf_rx(&mut self) -> RFIO_BIAS_SH_OPEN_DCF_RX_W { + RFIO_BIAS_SH_OPEN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config17_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG17_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG17_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config17_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG17_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config17_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG17_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG17_REG to value 0x0210"] +impl crate::Resettable for RF_ENABLE_CONFIG17_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0210 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config18_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config18_reg.rs new file mode 100644 index 0000000..de89ba4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config18_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG18_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG18_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PA_RAMP_EN_DCF_TX` reader - "] +pub struct PA_RAMP_EN_DCF_TX_R(crate::FieldReader); +impl PA_RAMP_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_RAMP_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_RAMP_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_RAMP_EN_DCF_TX` writer - "] +pub struct PA_RAMP_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> PA_RAMP_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `PA_RAMP_EN_DCF_RX` reader - "] +pub struct PA_RAMP_EN_DCF_RX_R(crate::FieldReader); +impl PA_RAMP_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_RAMP_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_RAMP_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_RAMP_EN_DCF_RX` writer - "] +pub struct PA_RAMP_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> PA_RAMP_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn pa_ramp_en_dcf_tx(&self) -> PA_RAMP_EN_DCF_TX_R { + PA_RAMP_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn pa_ramp_en_dcf_rx(&self) -> PA_RAMP_EN_DCF_RX_R { + PA_RAMP_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn pa_ramp_en_dcf_tx(&mut self) -> PA_RAMP_EN_DCF_TX_W { + PA_RAMP_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn pa_ramp_en_dcf_rx(&mut self) -> PA_RAMP_EN_DCF_RX_W { + PA_RAMP_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config18_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG18_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG18_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config18_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG18_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config18_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG18_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG18_REG to value 0x01a0"] +impl crate::Resettable for RF_ENABLE_CONFIG18_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01a0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config19_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config19_reg.rs new file mode 100644 index 0000000..153f834 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config19_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG19_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG19_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PA_EN_DCF_TX` reader - "] +pub struct PA_EN_DCF_TX_R(crate::FieldReader); +impl PA_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_EN_DCF_TX` writer - "] +pub struct PA_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> PA_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `PA_EN_DCF_RX` reader - "] +pub struct PA_EN_DCF_RX_R(crate::FieldReader); +impl PA_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_EN_DCF_RX` writer - "] +pub struct PA_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> PA_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn pa_en_dcf_tx(&self) -> PA_EN_DCF_TX_R { + PA_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn pa_en_dcf_rx(&self) -> PA_EN_DCF_RX_R { + PA_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn pa_en_dcf_tx(&mut self) -> PA_EN_DCF_TX_W { + PA_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn pa_en_dcf_rx(&mut self) -> PA_EN_DCF_RX_W { + PA_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config19_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG19_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG19_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config19_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG19_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config19_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG19_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG19_REG to value 0x01c0"] +impl crate::Resettable for RF_ENABLE_CONFIG19_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01c0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config1_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config1_reg.rs new file mode 100644 index 0000000..02ceaa5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config1_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PA_LDO_EN_DCF_TX` reader - "] +pub struct PA_LDO_EN_DCF_TX_R(crate::FieldReader); +impl PA_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_LDO_EN_DCF_TX` writer - "] +pub struct PA_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> PA_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `PA_LDO_EN_DCF_RX` reader - "] +pub struct PA_LDO_EN_DCF_RX_R(crate::FieldReader); +impl PA_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PA_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PA_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PA_LDO_EN_DCF_RX` writer - "] +pub struct PA_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> PA_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn pa_ldo_en_dcf_tx(&self) -> PA_LDO_EN_DCF_TX_R { + PA_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn pa_ldo_en_dcf_rx(&self) -> PA_LDO_EN_DCF_RX_R { + PA_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn pa_ldo_en_dcf_tx(&mut self) -> PA_LDO_EN_DCF_TX_W { + PA_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn pa_ldo_en_dcf_rx(&mut self) -> PA_LDO_EN_DCF_RX_W { + PA_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config1_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG1_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG1_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config1_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config1_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG1_REG to value 0x83"] +impl crate::Resettable for RF_ENABLE_CONFIG1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x83 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config20_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config20_reg.rs new file mode 100644 index 0000000..bff507c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config20_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG20_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG20_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LNA_CORE_EN_DCF_TX` reader - "] +pub struct LNA_CORE_EN_DCF_TX_R(crate::FieldReader); +impl LNA_CORE_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_CORE_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_CORE_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_CORE_EN_DCF_TX` writer - "] +pub struct LNA_CORE_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_CORE_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `LNA_CORE_EN_DCF_RX` reader - "] +pub struct LNA_CORE_EN_DCF_RX_R(crate::FieldReader); +impl LNA_CORE_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_CORE_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_CORE_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_CORE_EN_DCF_RX` writer - "] +pub struct LNA_CORE_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_CORE_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_core_en_dcf_tx(&self) -> LNA_CORE_EN_DCF_TX_R { + LNA_CORE_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_core_en_dcf_rx(&self) -> LNA_CORE_EN_DCF_RX_R { + LNA_CORE_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_core_en_dcf_tx(&mut self) -> LNA_CORE_EN_DCF_TX_W { + LNA_CORE_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_core_en_dcf_rx(&mut self) -> LNA_CORE_EN_DCF_RX_W { + LNA_CORE_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config20_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG20_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG20_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config20_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG20_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config20_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG20_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG20_REG to value 0x0f"] +impl crate::Resettable for RF_ENABLE_CONFIG20_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config21_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config21_reg.rs new file mode 100644 index 0000000..e88cb10 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config21_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG21_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG21_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LNA_CGM_EN_DCF_TX` reader - "] +pub struct LNA_CGM_EN_DCF_TX_R(crate::FieldReader); +impl LNA_CGM_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_CGM_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_CGM_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_CGM_EN_DCF_TX` writer - "] +pub struct LNA_CGM_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_CGM_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `LNA_CGM_EN_DCF_RX` reader - "] +pub struct LNA_CGM_EN_DCF_RX_R(crate::FieldReader); +impl LNA_CGM_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_CGM_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_CGM_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_CGM_EN_DCF_RX` writer - "] +pub struct LNA_CGM_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_CGM_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_cgm_en_dcf_tx(&self) -> LNA_CGM_EN_DCF_TX_R { + LNA_CGM_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_cgm_en_dcf_rx(&self) -> LNA_CGM_EN_DCF_RX_R { + LNA_CGM_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_cgm_en_dcf_tx(&mut self) -> LNA_CGM_EN_DCF_TX_W { + LNA_CGM_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_cgm_en_dcf_rx(&mut self) -> LNA_CGM_EN_DCF_RX_W { + LNA_CGM_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config21_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG21_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG21_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config21_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG21_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config21_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG21_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG21_REG to value 0x0f"] +impl crate::Resettable for RF_ENABLE_CONFIG21_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config22_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config22_reg.rs new file mode 100644 index 0000000..389c57e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config22_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG22_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG22_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MIX_EN_DCF_TX` reader - "] +pub struct MIX_EN_DCF_TX_R(crate::FieldReader); +impl MIX_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_EN_DCF_TX` writer - "] +pub struct MIX_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `MIX_EN_DCF_RX` reader - "] +pub struct MIX_EN_DCF_RX_R(crate::FieldReader); +impl MIX_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_EN_DCF_RX` writer - "] +pub struct MIX_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn mix_en_dcf_tx(&self) -> MIX_EN_DCF_TX_R { + MIX_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn mix_en_dcf_rx(&self) -> MIX_EN_DCF_RX_R { + MIX_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn mix_en_dcf_tx(&mut self) -> MIX_EN_DCF_TX_W { + MIX_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn mix_en_dcf_rx(&mut self) -> MIX_EN_DCF_RX_W { + MIX_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config22_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG22_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG22_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config22_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG22_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config22_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG22_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG22_REG to value 0x0f"] +impl crate::Resettable for RF_ENABLE_CONFIG22_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config23_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config23_reg.rs new file mode 100644 index 0000000..bd99227 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config23_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG23_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG23_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MIX_BIAS_SH_OPEN_DCF_TX` reader - "] +pub struct MIX_BIAS_SH_OPEN_DCF_TX_R(crate::FieldReader); +impl MIX_BIAS_SH_OPEN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_BIAS_SH_OPEN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_BIAS_SH_OPEN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_BIAS_SH_OPEN_DCF_TX` writer - "] +pub struct MIX_BIAS_SH_OPEN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_BIAS_SH_OPEN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `MIX_BIAS_SH_OPEN_DCF_RX` reader - "] +pub struct MIX_BIAS_SH_OPEN_DCF_RX_R(crate::FieldReader); +impl MIX_BIAS_SH_OPEN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_BIAS_SH_OPEN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_BIAS_SH_OPEN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_BIAS_SH_OPEN_DCF_RX` writer - "] +pub struct MIX_BIAS_SH_OPEN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_BIAS_SH_OPEN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn mix_bias_sh_open_dcf_tx(&self) -> MIX_BIAS_SH_OPEN_DCF_TX_R { + MIX_BIAS_SH_OPEN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn mix_bias_sh_open_dcf_rx(&self) -> MIX_BIAS_SH_OPEN_DCF_RX_R { + MIX_BIAS_SH_OPEN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn mix_bias_sh_open_dcf_tx(&mut self) -> MIX_BIAS_SH_OPEN_DCF_TX_W { + MIX_BIAS_SH_OPEN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn mix_bias_sh_open_dcf_rx(&mut self) -> MIX_BIAS_SH_OPEN_DCF_RX_W { + MIX_BIAS_SH_OPEN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config23_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG23_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG23_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config23_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG23_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config23_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG23_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG23_REG to value 0x10"] +impl crate::Resettable for RF_ENABLE_CONFIG23_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x10 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config24_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config24_reg.rs new file mode 100644 index 0000000..50ed918 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config24_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG24_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG24_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IFF_EN_DCF_TX` reader - "] +pub struct IFF_EN_DCF_TX_R(crate::FieldReader); +impl IFF_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFF_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_EN_DCF_TX` writer - "] +pub struct IFF_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `IFF_EN_DCF_RX` reader - "] +pub struct IFF_EN_DCF_RX_R(crate::FieldReader); +impl IFF_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFF_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_EN_DCF_RX` writer - "] +pub struct IFF_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iff_en_dcf_tx(&self) -> IFF_EN_DCF_TX_R { + IFF_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iff_en_dcf_rx(&self) -> IFF_EN_DCF_RX_R { + IFF_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iff_en_dcf_tx(&mut self) -> IFF_EN_DCF_TX_W { + IFF_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iff_en_dcf_rx(&mut self) -> IFF_EN_DCF_RX_W { + IFF_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config24_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG24_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG24_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config24_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG24_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config24_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG24_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG24_REG to value 0x0f"] +impl crate::Resettable for RF_ENABLE_CONFIG24_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config25_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config25_reg.rs new file mode 100644 index 0000000..ae1df94 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config25_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG25_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG25_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IFF_BIAS_SH_OPEN_DCF_TX` reader - "] +pub struct IFF_BIAS_SH_OPEN_DCF_TX_R(crate::FieldReader); +impl IFF_BIAS_SH_OPEN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFF_BIAS_SH_OPEN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_BIAS_SH_OPEN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_BIAS_SH_OPEN_DCF_TX` writer - "] +pub struct IFF_BIAS_SH_OPEN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_BIAS_SH_OPEN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `IFF_BIAS_SH_OPEN_DCF_RX` reader - "] +pub struct IFF_BIAS_SH_OPEN_DCF_RX_R(crate::FieldReader); +impl IFF_BIAS_SH_OPEN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFF_BIAS_SH_OPEN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_BIAS_SH_OPEN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_BIAS_SH_OPEN_DCF_RX` writer - "] +pub struct IFF_BIAS_SH_OPEN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_BIAS_SH_OPEN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iff_bias_sh_open_dcf_tx(&self) -> IFF_BIAS_SH_OPEN_DCF_TX_R { + IFF_BIAS_SH_OPEN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iff_bias_sh_open_dcf_rx(&self) -> IFF_BIAS_SH_OPEN_DCF_RX_R { + IFF_BIAS_SH_OPEN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iff_bias_sh_open_dcf_tx(&mut self) -> IFF_BIAS_SH_OPEN_DCF_TX_W { + IFF_BIAS_SH_OPEN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iff_bias_sh_open_dcf_rx(&mut self) -> IFF_BIAS_SH_OPEN_DCF_RX_W { + IFF_BIAS_SH_OPEN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config25_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG25_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG25_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config25_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG25_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config25_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG25_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG25_REG to value 0x10"] +impl crate::Resettable for RF_ENABLE_CONFIG25_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x10 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config26_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config26_reg.rs new file mode 100644 index 0000000..8b172e0 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config26_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG26_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG26_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADC_CLK_EN_DCF_TX` reader - "] +pub struct ADC_CLK_EN_DCF_TX_R(crate::FieldReader); +impl ADC_CLK_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADC_CLK_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_CLK_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_CLK_EN_DCF_TX` writer - "] +pub struct ADC_CLK_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_CLK_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADC_CLK_EN_DCF_RX` reader - "] +pub struct ADC_CLK_EN_DCF_RX_R(crate::FieldReader); +impl ADC_CLK_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADC_CLK_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_CLK_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_CLK_EN_DCF_RX` writer - "] +pub struct ADC_CLK_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_CLK_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adc_clk_en_dcf_tx(&self) -> ADC_CLK_EN_DCF_TX_R { + ADC_CLK_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adc_clk_en_dcf_rx(&self) -> ADC_CLK_EN_DCF_RX_R { + ADC_CLK_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adc_clk_en_dcf_tx(&mut self) -> ADC_CLK_EN_DCF_TX_W { + ADC_CLK_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adc_clk_en_dcf_rx(&mut self) -> ADC_CLK_EN_DCF_RX_W { + ADC_CLK_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config26_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG26_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG26_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config26_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG26_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config26_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG26_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG26_REG to value 0x0f"] +impl crate::Resettable for RF_ENABLE_CONFIG26_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config27_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config27_reg.rs new file mode 100644 index 0000000..77df2a5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config27_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG27_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG27_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADC_EN_DCF_TX` reader - "] +pub struct ADC_EN_DCF_TX_R(crate::FieldReader); +impl ADC_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADC_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_EN_DCF_TX` writer - "] +pub struct ADC_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADC_EN_DCF_RX` reader - "] +pub struct ADC_EN_DCF_RX_R(crate::FieldReader); +impl ADC_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADC_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADC_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADC_EN_DCF_RX` writer - "] +pub struct ADC_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADC_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adc_en_dcf_tx(&self) -> ADC_EN_DCF_TX_R { + ADC_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adc_en_dcf_rx(&self) -> ADC_EN_DCF_RX_R { + ADC_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adc_en_dcf_tx(&mut self) -> ADC_EN_DCF_TX_W { + ADC_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adc_en_dcf_rx(&mut self) -> ADC_EN_DCF_RX_W { + ADC_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config27_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG27_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG27_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config27_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG27_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config27_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG27_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG27_REG to value 0x10"] +impl crate::Resettable for RF_ENABLE_CONFIG27_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x10 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config28_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config28_reg.rs new file mode 100644 index 0000000..b5ef39c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config28_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG28_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG28_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_DCO_EN_DCF_TX` reader - "] +pub struct ADPLL_DCO_EN_DCF_TX_R(crate::FieldReader); +impl ADPLL_DCO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_DCO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_DCO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_DCO_EN_DCF_TX` writer - "] +pub struct ADPLL_DCO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_DCO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLL_DCO_EN_DCF_RX` reader - "] +pub struct ADPLL_DCO_EN_DCF_RX_R(crate::FieldReader); +impl ADPLL_DCO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_DCO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_DCO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_DCO_EN_DCF_RX` writer - "] +pub struct ADPLL_DCO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_DCO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_dco_en_dcf_tx(&self) -> ADPLL_DCO_EN_DCF_TX_R { + ADPLL_DCO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_dco_en_dcf_rx(&self) -> ADPLL_DCO_EN_DCF_RX_R { + ADPLL_DCO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_dco_en_dcf_tx(&mut self) -> ADPLL_DCO_EN_DCF_TX_W { + ADPLL_DCO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_dco_en_dcf_rx(&mut self) -> ADPLL_DCO_EN_DCF_RX_W { + ADPLL_DCO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config28_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG28_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG28_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config28_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG28_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config28_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG28_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG28_REG to value 0x41"] +impl crate::Resettable for RF_ENABLE_CONFIG28_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x41 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config29_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config29_reg.rs new file mode 100644 index 0000000..90a8d97 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config29_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG29_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG29_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_CLK_EN_DCF_TX` reader - "] +pub struct ADPLL_CLK_EN_DCF_TX_R(crate::FieldReader); +impl ADPLL_CLK_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_CLK_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_CLK_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_CLK_EN_DCF_TX` writer - "] +pub struct ADPLL_CLK_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_CLK_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLL_CLK_EN_DCF_RX` reader - "] +pub struct ADPLL_CLK_EN_DCF_RX_R(crate::FieldReader); +impl ADPLL_CLK_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_CLK_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_CLK_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_CLK_EN_DCF_RX` writer - "] +pub struct ADPLL_CLK_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_CLK_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_clk_en_dcf_tx(&self) -> ADPLL_CLK_EN_DCF_TX_R { + ADPLL_CLK_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_clk_en_dcf_rx(&self) -> ADPLL_CLK_EN_DCF_RX_R { + ADPLL_CLK_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_clk_en_dcf_tx(&mut self) -> ADPLL_CLK_EN_DCF_TX_W { + ADPLL_CLK_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_clk_en_dcf_rx(&mut self) -> ADPLL_CLK_EN_DCF_RX_W { + ADPLL_CLK_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config29_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG29_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG29_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config29_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG29_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config29_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG29_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG29_REG to value 0x41"] +impl crate::Resettable for RF_ENABLE_CONFIG29_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x41 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config2_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config2_reg.rs new file mode 100644 index 0000000..7ddfa70 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config2_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LNA_LDO_EN_DCF_TX` reader - "] +pub struct LNA_LDO_EN_DCF_TX_R(crate::FieldReader); +impl LNA_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_LDO_EN_DCF_TX` writer - "] +pub struct LNA_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `LNA_LDO_EN_DCF_RX` reader - "] +pub struct LNA_LDO_EN_DCF_RX_R(crate::FieldReader); +impl LNA_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LNA_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LNA_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LNA_LDO_EN_DCF_RX` writer - "] +pub struct LNA_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> LNA_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_ldo_en_dcf_tx(&self) -> LNA_LDO_EN_DCF_TX_R { + LNA_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_ldo_en_dcf_rx(&self) -> LNA_LDO_EN_DCF_RX_R { + LNA_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn lna_ldo_en_dcf_tx(&mut self) -> LNA_LDO_EN_DCF_TX_W { + LNA_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn lna_ldo_en_dcf_rx(&mut self) -> LNA_LDO_EN_DCF_RX_W { + LNA_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config2_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG2_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG2_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config2_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config2_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG2_REG to value 0x03"] +impl crate::Resettable for RF_ENABLE_CONFIG2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x03 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config30_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config30_reg.rs new file mode 100644 index 0000000..fce9d49 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config30_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG30_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG30_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLLDIG_RST_DCF_TX` reader - "] +pub struct ADPLLDIG_RST_DCF_TX_R(crate::FieldReader); +impl ADPLLDIG_RST_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_RST_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_RST_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_RST_DCF_TX` writer - "] +pub struct ADPLLDIG_RST_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_RST_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLLDIG_RST_DCF_RX` reader - "] +pub struct ADPLLDIG_RST_DCF_RX_R(crate::FieldReader); +impl ADPLLDIG_RST_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_RST_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_RST_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_RST_DCF_RX` writer - "] +pub struct ADPLLDIG_RST_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_RST_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_rst_dcf_tx(&self) -> ADPLLDIG_RST_DCF_TX_R { + ADPLLDIG_RST_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_rst_dcf_rx(&self) -> ADPLLDIG_RST_DCF_RX_R { + ADPLLDIG_RST_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_rst_dcf_tx(&mut self) -> ADPLLDIG_RST_DCF_TX_W { + ADPLLDIG_RST_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_rst_dcf_rx(&mut self) -> ADPLLDIG_RST_DCF_RX_W { + ADPLLDIG_RST_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config30_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG30_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG30_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config30_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG30_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config30_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG30_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG30_REG to value 0x0107"] +impl crate::Resettable for RF_ENABLE_CONFIG30_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0107 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config31_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config31_reg.rs new file mode 100644 index 0000000..864fe53 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config31_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG31_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG31_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLLDIG_EN_DCF_TX` reader - "] +pub struct ADPLLDIG_EN_DCF_TX_R(crate::FieldReader); +impl ADPLLDIG_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_EN_DCF_TX` writer - "] +pub struct ADPLLDIG_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLLDIG_EN_DCF_RX` reader - "] +pub struct ADPLLDIG_EN_DCF_RX_R(crate::FieldReader); +impl ADPLLDIG_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_EN_DCF_RX` writer - "] +pub struct ADPLLDIG_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_en_dcf_tx(&self) -> ADPLLDIG_EN_DCF_TX_R { + ADPLLDIG_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_en_dcf_rx(&self) -> ADPLLDIG_EN_DCF_RX_R { + ADPLLDIG_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_en_dcf_tx(&mut self) -> ADPLLDIG_EN_DCF_TX_W { + ADPLLDIG_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_en_dcf_rx(&mut self) -> ADPLLDIG_EN_DCF_RX_W { + ADPLLDIG_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config31_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG31_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG31_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config31_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG31_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config31_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG31_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG31_REG to value 0x0149"] +impl crate::Resettable for RF_ENABLE_CONFIG31_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0149 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config32_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config32_reg.rs new file mode 100644 index 0000000..68e7071 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config32_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG32_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG32_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLLDIG_RX_EN_DCF_TX` reader - "] +pub struct ADPLLDIG_RX_EN_DCF_TX_R(crate::FieldReader); +impl ADPLLDIG_RX_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_RX_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_RX_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_RX_EN_DCF_TX` writer - "] +pub struct ADPLLDIG_RX_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_RX_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLLDIG_RX_EN_DCF_RX` reader - "] +pub struct ADPLLDIG_RX_EN_DCF_RX_R(crate::FieldReader); +impl ADPLLDIG_RX_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_RX_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_RX_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_RX_EN_DCF_RX` writer - "] +pub struct ADPLLDIG_RX_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_RX_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_rx_en_dcf_tx(&self) -> ADPLLDIG_RX_EN_DCF_TX_R { + ADPLLDIG_RX_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_rx_en_dcf_rx(&self) -> ADPLLDIG_RX_EN_DCF_RX_R { + ADPLLDIG_RX_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_rx_en_dcf_tx(&mut self) -> ADPLLDIG_RX_EN_DCF_TX_W { + ADPLLDIG_RX_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_rx_en_dcf_rx(&mut self) -> ADPLLDIG_RX_EN_DCF_RX_W { + ADPLLDIG_RX_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config32_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG32_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG32_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config32_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG32_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config32_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG32_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG32_REG to value 0x01"] +impl crate::Resettable for RF_ENABLE_CONFIG32_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config33_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config33_reg.rs new file mode 100644 index 0000000..eae78ae --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config33_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG33_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG33_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLLDIG_PAIN_EN_DCF_TX` reader - "] +pub struct ADPLLDIG_PAIN_EN_DCF_TX_R(crate::FieldReader); +impl ADPLLDIG_PAIN_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_PAIN_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_PAIN_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_PAIN_EN_DCF_TX` writer - "] +pub struct ADPLLDIG_PAIN_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_PAIN_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLLDIG_PAIN_EN_DCF_RX` reader - "] +pub struct ADPLLDIG_PAIN_EN_DCF_RX_R(crate::FieldReader); +impl ADPLLDIG_PAIN_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLLDIG_PAIN_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLLDIG_PAIN_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLLDIG_PAIN_EN_DCF_RX` writer - "] +pub struct ADPLLDIG_PAIN_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLLDIG_PAIN_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_pain_en_dcf_tx(&self) -> ADPLLDIG_PAIN_EN_DCF_TX_R { + ADPLLDIG_PAIN_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_pain_en_dcf_rx(&self) -> ADPLLDIG_PAIN_EN_DCF_RX_R { + ADPLLDIG_PAIN_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adplldig_pain_en_dcf_tx(&mut self) -> ADPLLDIG_PAIN_EN_DCF_TX_W { + ADPLLDIG_PAIN_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adplldig_pain_en_dcf_rx(&mut self) -> ADPLLDIG_PAIN_EN_DCF_RX_W { + ADPLLDIG_PAIN_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config33_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG33_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG33_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config33_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG33_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config33_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG33_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG33_REG to value 0x01e0"] +impl crate::Resettable for RF_ENABLE_CONFIG33_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01e0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config34_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config34_reg.rs new file mode 100644 index 0000000..57307b6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config34_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG34_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG34_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_LOBUF_PA_EN_DCF_TX` reader - "] +pub struct ADPLL_LOBUF_PA_EN_DCF_TX_R(crate::FieldReader); +impl ADPLL_LOBUF_PA_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_LOBUF_PA_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_LOBUF_PA_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_LOBUF_PA_EN_DCF_TX` writer - "] +pub struct ADPLL_LOBUF_PA_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_LOBUF_PA_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLL_LOBUF_PA_EN_DCF_RX` reader - "] +pub struct ADPLL_LOBUF_PA_EN_DCF_RX_R(crate::FieldReader); +impl ADPLL_LOBUF_PA_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_LOBUF_PA_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_LOBUF_PA_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_LOBUF_PA_EN_DCF_RX` writer - "] +pub struct ADPLL_LOBUF_PA_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_LOBUF_PA_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_lobuf_pa_en_dcf_tx(&self) -> ADPLL_LOBUF_PA_EN_DCF_TX_R { + ADPLL_LOBUF_PA_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_lobuf_pa_en_dcf_rx(&self) -> ADPLL_LOBUF_PA_EN_DCF_RX_R { + ADPLL_LOBUF_PA_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_lobuf_pa_en_dcf_tx(&mut self) -> ADPLL_LOBUF_PA_EN_DCF_TX_W { + ADPLL_LOBUF_PA_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_lobuf_pa_en_dcf_rx(&mut self) -> ADPLL_LOBUF_PA_EN_DCF_RX_W { + ADPLL_LOBUF_PA_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config34_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG34_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG34_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config34_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG34_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config34_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG34_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG34_REG to value 0x01c0"] +impl crate::Resettable for RF_ENABLE_CONFIG34_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01c0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config35_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config35_reg.rs new file mode 100644 index 0000000..076889d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config35_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG35_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG35_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CAL_EN_DCF_TX` reader - "] +pub struct CAL_EN_DCF_TX_R(crate::FieldReader); +impl CAL_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CAL_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CAL_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CAL_EN_DCF_TX` writer - "] +pub struct CAL_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> CAL_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `CAL_EN_DCF_RX` reader - "] +pub struct CAL_EN_DCF_RX_R(crate::FieldReader); +impl CAL_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + CAL_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CAL_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CAL_EN_DCF_RX` writer - "] +pub struct CAL_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> CAL_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn cal_en_dcf_tx(&self) -> CAL_EN_DCF_TX_R { + CAL_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn cal_en_dcf_rx(&self) -> CAL_EN_DCF_RX_R { + CAL_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn cal_en_dcf_tx(&mut self) -> CAL_EN_DCF_TX_W { + CAL_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn cal_en_dcf_rx(&mut self) -> CAL_EN_DCF_RX_W { + CAL_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config35_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG35_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG35_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config35_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG35_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config35_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG35_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG35_REG to value 0x0294"] +impl crate::Resettable for RF_ENABLE_CONFIG35_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0294 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config36_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config36_reg.rs new file mode 100644 index 0000000..98fc572 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config36_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG36_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG36_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DEM_EN_DCF_TX` reader - "] +pub struct DEM_EN_DCF_TX_R(crate::FieldReader); +impl DEM_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEM_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEM_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEM_EN_DCF_TX` writer - "] +pub struct DEM_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> DEM_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `DEM_EN_DCF_RX` reader - "] +pub struct DEM_EN_DCF_RX_R(crate::FieldReader); +impl DEM_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEM_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEM_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEM_EN_DCF_RX` writer - "] +pub struct DEM_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> DEM_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn dem_en_dcf_tx(&self) -> DEM_EN_DCF_TX_R { + DEM_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_en_dcf_rx(&self) -> DEM_EN_DCF_RX_R { + DEM_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn dem_en_dcf_tx(&mut self) -> DEM_EN_DCF_TX_W { + DEM_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_en_dcf_rx(&mut self) -> DEM_EN_DCF_RX_W { + DEM_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config36_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG36_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG36_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config36_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG36_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config36_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG36_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG36_REG to value 0x11"] +impl crate::Resettable for RF_ENABLE_CONFIG36_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x11 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config37_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config37_reg.rs new file mode 100644 index 0000000..46549e5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config37_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG37_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG37_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE_DEM_DC_PARCAL_DCF_TX` reader - "] +pub struct SPARE_DEM_DC_PARCAL_DCF_TX_R(crate::FieldReader); +impl SPARE_DEM_DC_PARCAL_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE_DEM_DC_PARCAL_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE_DEM_DC_PARCAL_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE_DEM_DC_PARCAL_DCF_TX` writer - "] +pub struct SPARE_DEM_DC_PARCAL_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE_DEM_DC_PARCAL_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `DEM_DC_PARCAL_EN_DCF_RX` reader - "] +pub struct DEM_DC_PARCAL_EN_DCF_RX_R(crate::FieldReader); +impl DEM_DC_PARCAL_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEM_DC_PARCAL_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEM_DC_PARCAL_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEM_DC_PARCAL_EN_DCF_RX` writer - "] +pub struct DEM_DC_PARCAL_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> DEM_DC_PARCAL_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare_dem_dc_parcal_dcf_tx(&self) -> SPARE_DEM_DC_PARCAL_DCF_TX_R { + SPARE_DEM_DC_PARCAL_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_dc_parcal_en_dcf_rx(&self) -> DEM_DC_PARCAL_EN_DCF_RX_R { + DEM_DC_PARCAL_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare_dem_dc_parcal_dcf_tx(&mut self) -> SPARE_DEM_DC_PARCAL_DCF_TX_W { + SPARE_DEM_DC_PARCAL_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_dc_parcal_en_dcf_rx(&mut self) -> DEM_DC_PARCAL_EN_DCF_RX_W { + DEM_DC_PARCAL_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config37_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG37_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG37_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config37_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG37_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config37_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG37_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG37_REG to value 0"] +impl crate::Resettable for RF_ENABLE_CONFIG37_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config38_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config38_reg.rs new file mode 100644 index 0000000..58d73ae --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config38_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG38_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG38_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX` reader - "] +pub struct SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_R(crate::FieldReader); +impl SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX` writer - "] +pub struct SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `DEM_AGC_UNFREEZE_EN_DCF_RX` reader - "] +pub struct DEM_AGC_UNFREEZE_EN_DCF_RX_R(crate::FieldReader); +impl DEM_AGC_UNFREEZE_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEM_AGC_UNFREEZE_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEM_AGC_UNFREEZE_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEM_AGC_UNFREEZE_EN_DCF_RX` writer - "] +pub struct DEM_AGC_UNFREEZE_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> DEM_AGC_UNFREEZE_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare_dem_agc_unfreeze_en_dcf_tx(&self) -> SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_R { + SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_agc_unfreeze_en_dcf_rx(&self) -> DEM_AGC_UNFREEZE_EN_DCF_RX_R { + DEM_AGC_UNFREEZE_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare_dem_agc_unfreeze_en_dcf_tx(&mut self) -> SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_W { + SPARE_DEM_AGC_UNFREEZE_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_agc_unfreeze_en_dcf_rx(&mut self) -> DEM_AGC_UNFREEZE_EN_DCF_RX_W { + DEM_AGC_UNFREEZE_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config38_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG38_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG38_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config38_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG38_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config38_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG38_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG38_REG to value 0x11"] +impl crate::Resettable for RF_ENABLE_CONFIG38_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x11 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config39_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config39_reg.rs new file mode 100644 index 0000000..e962e8e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config39_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG39_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG39_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE_DEM_SIGDETECT_EN_DCF_TX` reader - "] +pub struct SPARE_DEM_SIGDETECT_EN_DCF_TX_R(crate::FieldReader); +impl SPARE_DEM_SIGDETECT_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE_DEM_SIGDETECT_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE_DEM_SIGDETECT_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE_DEM_SIGDETECT_EN_DCF_TX` writer - "] +pub struct SPARE_DEM_SIGDETECT_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE_DEM_SIGDETECT_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `DEM_SIGDETECT_EN_DCF_RX` reader - "] +pub struct DEM_SIGDETECT_EN_DCF_RX_R(crate::FieldReader); +impl DEM_SIGDETECT_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DEM_SIGDETECT_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DEM_SIGDETECT_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `DEM_SIGDETECT_EN_DCF_RX` writer - "] +pub struct DEM_SIGDETECT_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> DEM_SIGDETECT_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare_dem_sigdetect_en_dcf_tx(&self) -> SPARE_DEM_SIGDETECT_EN_DCF_TX_R { + SPARE_DEM_SIGDETECT_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_sigdetect_en_dcf_rx(&self) -> DEM_SIGDETECT_EN_DCF_RX_R { + DEM_SIGDETECT_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare_dem_sigdetect_en_dcf_tx(&mut self) -> SPARE_DEM_SIGDETECT_EN_DCF_TX_W { + SPARE_DEM_SIGDETECT_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn dem_sigdetect_en_dcf_rx(&mut self) -> DEM_SIGDETECT_EN_DCF_RX_W { + DEM_SIGDETECT_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config39_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG39_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG39_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config39_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG39_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config39_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG39_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG39_REG to value 0x13"] +impl crate::Resettable for RF_ENABLE_CONFIG39_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x13 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config3_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config3_reg.rs new file mode 100644 index 0000000..19f2d70 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config3_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `MIX_LDO_EN_DCF_TX` reader - "] +pub struct MIX_LDO_EN_DCF_TX_R(crate::FieldReader); +impl MIX_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_LDO_EN_DCF_TX` writer - "] +pub struct MIX_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `MIX_LDO_EN_DCF_RX` reader - "] +pub struct MIX_LDO_EN_DCF_RX_R(crate::FieldReader); +impl MIX_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + MIX_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for MIX_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `MIX_LDO_EN_DCF_RX` writer - "] +pub struct MIX_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> MIX_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn mix_ldo_en_dcf_tx(&self) -> MIX_LDO_EN_DCF_TX_R { + MIX_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn mix_ldo_en_dcf_rx(&self) -> MIX_LDO_EN_DCF_RX_R { + MIX_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn mix_ldo_en_dcf_tx(&mut self) -> MIX_LDO_EN_DCF_TX_W { + MIX_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn mix_ldo_en_dcf_rx(&mut self) -> MIX_LDO_EN_DCF_RX_W { + MIX_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config3_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG3_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG3_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config3_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config3_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG3_REG to value 0x03"] +impl crate::Resettable for RF_ENABLE_CONFIG3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x03 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config40_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config40_reg.rs new file mode 100644 index 0000000..33a7f59 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config40_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG40_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG40_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PHY_RDY4BS_DCF_TX` reader - "] +pub struct PHY_RDY4BS_DCF_TX_R(crate::FieldReader); +impl PHY_RDY4BS_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PHY_RDY4BS_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PHY_RDY4BS_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PHY_RDY4BS_DCF_TX` writer - "] +pub struct PHY_RDY4BS_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> PHY_RDY4BS_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `PHY_RDY4BS_DCF_RX` reader - "] +pub struct PHY_RDY4BS_DCF_RX_R(crate::FieldReader); +impl PHY_RDY4BS_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + PHY_RDY4BS_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PHY_RDY4BS_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PHY_RDY4BS_DCF_RX` writer - "] +pub struct PHY_RDY4BS_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> PHY_RDY4BS_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn phy_rdy4bs_dcf_tx(&self) -> PHY_RDY4BS_DCF_TX_R { + PHY_RDY4BS_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn phy_rdy4bs_dcf_rx(&self) -> PHY_RDY4BS_DCF_RX_R { + PHY_RDY4BS_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn phy_rdy4bs_dcf_tx(&mut self) -> PHY_RDY4BS_DCF_TX_W { + PHY_RDY4BS_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn phy_rdy4bs_dcf_rx(&mut self) -> PHY_RDY4BS_DCF_RX_W { + PHY_RDY4BS_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config40_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG40_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG40_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config40_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG40_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config40_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG40_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG40_REG to value 0x0253"] +impl crate::Resettable for RF_ENABLE_CONFIG40_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0253 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config41_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config41_reg.rs new file mode 100644 index 0000000..9bcaac9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config41_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG41_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG41_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_RDY_FOR_DIV_DCF_TX` reader - "] +pub struct ADPLL_RDY_FOR_DIV_DCF_TX_R(crate::FieldReader); +impl ADPLL_RDY_FOR_DIV_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_RDY_FOR_DIV_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_RDY_FOR_DIV_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_RDY_FOR_DIV_DCF_TX` writer - "] +pub struct ADPLL_RDY_FOR_DIV_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_RDY_FOR_DIV_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLL_RDY_FOR_DIV_DCF_RX` reader - "] +pub struct ADPLL_RDY_FOR_DIV_DCF_RX_R(crate::FieldReader); +impl ADPLL_RDY_FOR_DIV_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_RDY_FOR_DIV_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_RDY_FOR_DIV_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_RDY_FOR_DIV_DCF_RX` writer - "] +pub struct ADPLL_RDY_FOR_DIV_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_RDY_FOR_DIV_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_rdy_for_div_dcf_tx(&self) -> ADPLL_RDY_FOR_DIV_DCF_TX_R { + ADPLL_RDY_FOR_DIV_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_rdy_for_div_dcf_rx(&self) -> ADPLL_RDY_FOR_DIV_DCF_RX_R { + ADPLL_RDY_FOR_DIV_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_rdy_for_div_dcf_tx(&mut self) -> ADPLL_RDY_FOR_DIV_DCF_TX_W { + ADPLL_RDY_FOR_DIV_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_rdy_for_div_dcf_rx(&mut self) -> ADPLL_RDY_FOR_DIV_DCF_RX_W { + ADPLL_RDY_FOR_DIV_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config41_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG41_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG41_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config41_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG41_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config41_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG41_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG41_REG to value 0xc5"] +impl crate::Resettable for RF_ENABLE_CONFIG41_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0xc5 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config42_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config42_reg.rs new file mode 100644 index 0000000..a9f2452 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config42_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG42_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG42_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE1_DCF_TX` reader - "] +pub struct SPARE1_DCF_TX_R(crate::FieldReader); +impl SPARE1_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE1_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE1_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE1_DCF_TX` writer - "] +pub struct SPARE1_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE1_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `SPARE1_DCF_RX` reader - "] +pub struct SPARE1_DCF_RX_R(crate::FieldReader); +impl SPARE1_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE1_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE1_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE1_DCF_RX` writer - "] +pub struct SPARE1_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE1_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare1_dcf_tx(&self) -> SPARE1_DCF_TX_R { + SPARE1_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare1_dcf_rx(&self) -> SPARE1_DCF_RX_R { + SPARE1_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare1_dcf_tx(&mut self) -> SPARE1_DCF_TX_W { + SPARE1_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare1_dcf_rx(&mut self) -> SPARE1_DCF_RX_W { + SPARE1_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config42_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG42_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG42_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config42_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG42_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config42_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG42_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG42_REG to value 0"] +impl crate::Resettable for RF_ENABLE_CONFIG42_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config43_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config43_reg.rs new file mode 100644 index 0000000..3a50062 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config43_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG43_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG43_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE2_DCF_TX` reader - "] +pub struct SPARE2_DCF_TX_R(crate::FieldReader); +impl SPARE2_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE2_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE2_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE2_DCF_TX` writer - "] +pub struct SPARE2_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE2_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `SPARE2_DCF_RX` reader - "] +pub struct SPARE2_DCF_RX_R(crate::FieldReader); +impl SPARE2_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE2_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE2_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE2_DCF_RX` writer - "] +pub struct SPARE2_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE2_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare2_dcf_tx(&self) -> SPARE2_DCF_TX_R { + SPARE2_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare2_dcf_rx(&self) -> SPARE2_DCF_RX_R { + SPARE2_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare2_dcf_tx(&mut self) -> SPARE2_DCF_TX_W { + SPARE2_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare2_dcf_rx(&mut self) -> SPARE2_DCF_RX_W { + SPARE2_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config43_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG43_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG43_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config43_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG43_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config43_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG43_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG43_REG to value 0"] +impl crate::Resettable for RF_ENABLE_CONFIG43_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config44_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config44_reg.rs new file mode 100644 index 0000000..4b26a11 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config44_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG44_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG44_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE3_DCF_TX` reader - "] +pub struct SPARE3_DCF_TX_R(crate::FieldReader); +impl SPARE3_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE3_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE3_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE3_DCF_TX` writer - "] +pub struct SPARE3_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE3_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `SPARE3_DCF_RX` reader - "] +pub struct SPARE3_DCF_RX_R(crate::FieldReader); +impl SPARE3_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE3_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE3_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE3_DCF_RX` writer - "] +pub struct SPARE3_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE3_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare3_dcf_tx(&self) -> SPARE3_DCF_TX_R { + SPARE3_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare3_dcf_rx(&self) -> SPARE3_DCF_RX_R { + SPARE3_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare3_dcf_tx(&mut self) -> SPARE3_DCF_TX_W { + SPARE3_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare3_dcf_rx(&mut self) -> SPARE3_DCF_RX_W { + SPARE3_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config44_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG44_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG44_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config44_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG44_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config44_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG44_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG44_REG to value 0"] +impl crate::Resettable for RF_ENABLE_CONFIG44_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config45_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config45_reg.rs new file mode 100644 index 0000000..682730d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config45_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG45_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG45_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE4_DCF_TX` reader - "] +pub struct SPARE4_DCF_TX_R(crate::FieldReader); +impl SPARE4_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE4_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE4_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE4_DCF_TX` writer - "] +pub struct SPARE4_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE4_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `SPARE4_DCF_RX` reader - "] +pub struct SPARE4_DCF_RX_R(crate::FieldReader); +impl SPARE4_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE4_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE4_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE4_DCF_RX` writer - "] +pub struct SPARE4_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE4_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare4_dcf_tx(&self) -> SPARE4_DCF_TX_R { + SPARE4_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare4_dcf_rx(&self) -> SPARE4_DCF_RX_R { + SPARE4_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare4_dcf_tx(&mut self) -> SPARE4_DCF_TX_W { + SPARE4_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare4_dcf_rx(&mut self) -> SPARE4_DCF_RX_W { + SPARE4_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config45_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG45_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG45_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config45_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG45_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config45_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG45_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG45_REG to value 0"] +impl crate::Resettable for RF_ENABLE_CONFIG45_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config46_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config46_reg.rs new file mode 100644 index 0000000..44379da --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config46_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG46_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG46_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPARE5_DCF_TX` reader - "] +pub struct SPARE5_DCF_TX_R(crate::FieldReader); +impl SPARE5_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE5_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE5_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE5_DCF_TX` writer - "] +pub struct SPARE5_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE5_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `SPARE5_DCF_RX` reader - "] +pub struct SPARE5_DCF_RX_R(crate::FieldReader); +impl SPARE5_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPARE5_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPARE5_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPARE5_DCF_RX` writer - "] +pub struct SPARE5_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> SPARE5_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare5_dcf_tx(&self) -> SPARE5_DCF_TX_R { + SPARE5_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare5_dcf_rx(&self) -> SPARE5_DCF_RX_R { + SPARE5_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn spare5_dcf_tx(&mut self) -> SPARE5_DCF_TX_W { + SPARE5_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn spare5_dcf_rx(&mut self) -> SPARE5_DCF_RX_W { + SPARE5_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config46_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG46_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG46_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config46_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG46_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config46_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG46_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG46_REG to value 0"] +impl crate::Resettable for RF_ENABLE_CONFIG46_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config4_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config4_reg.rs new file mode 100644 index 0000000..9875dce --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config4_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG4_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG4_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IFF_LDO_EN_DCF_TX` reader - "] +pub struct IFF_LDO_EN_DCF_TX_R(crate::FieldReader); +impl IFF_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFF_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_LDO_EN_DCF_TX` writer - "] +pub struct IFF_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `IFF_LDO_EN_DCF_RX` reader - "] +pub struct IFF_LDO_EN_DCF_RX_R(crate::FieldReader); +impl IFF_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFF_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFF_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFF_LDO_EN_DCF_RX` writer - "] +pub struct IFF_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> IFF_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iff_ldo_en_dcf_tx(&self) -> IFF_LDO_EN_DCF_TX_R { + IFF_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iff_ldo_en_dcf_rx(&self) -> IFF_LDO_EN_DCF_RX_R { + IFF_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iff_ldo_en_dcf_tx(&mut self) -> IFF_LDO_EN_DCF_TX_W { + IFF_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iff_ldo_en_dcf_rx(&mut self) -> IFF_LDO_EN_DCF_RX_W { + IFF_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config4_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG4_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG4_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config4_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG4_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config4_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG4_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG4_REG to value 0x03"] +impl crate::Resettable for RF_ENABLE_CONFIG4_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x03 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config5_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config5_reg.rs new file mode 100644 index 0000000..0d62ef6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config5_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG5_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG5_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `IFFADC_LDO_EN_DCF_TX` reader - "] +pub struct IFFADC_LDO_EN_DCF_TX_R(crate::FieldReader); +impl IFFADC_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFFADC_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFFADC_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFFADC_LDO_EN_DCF_TX` writer - "] +pub struct IFFADC_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> IFFADC_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `IFFADC_LDO_EN_DCF_RX` reader - "] +pub struct IFFADC_LDO_EN_DCF_RX_R(crate::FieldReader); +impl IFFADC_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + IFFADC_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for IFFADC_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `IFFADC_LDO_EN_DCF_RX` writer - "] +pub struct IFFADC_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> IFFADC_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iffadc_ldo_en_dcf_tx(&self) -> IFFADC_LDO_EN_DCF_TX_R { + IFFADC_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iffadc_ldo_en_dcf_rx(&self) -> IFFADC_LDO_EN_DCF_RX_R { + IFFADC_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn iffadc_ldo_en_dcf_tx(&mut self) -> IFFADC_LDO_EN_DCF_TX_W { + IFFADC_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn iffadc_ldo_en_dcf_rx(&mut self) -> IFFADC_LDO_EN_DCF_RX_W { + IFFADC_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config5_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG5_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG5_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config5_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG5_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config5_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG5_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG5_REG to value 0x03"] +impl crate::Resettable for RF_ENABLE_CONFIG5_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x03 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config6_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config6_reg.rs new file mode 100644 index 0000000..0a2850b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config6_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG6_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG6_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_TDC_LDO_EN_DCF_TX` reader - "] +pub struct ADPLL_TDC_LDO_EN_DCF_TX_R(crate::FieldReader); +impl ADPLL_TDC_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_TDC_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_TDC_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_TDC_LDO_EN_DCF_TX` writer - "] +pub struct ADPLL_TDC_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_TDC_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLL_TDC_LDO_EN_DCF_RX` reader - "] +pub struct ADPLL_TDC_LDO_EN_DCF_RX_R(crate::FieldReader); +impl ADPLL_TDC_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_TDC_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_TDC_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_TDC_LDO_EN_DCF_RX` writer - "] +pub struct ADPLL_TDC_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_TDC_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_tdc_ldo_en_dcf_tx(&self) -> ADPLL_TDC_LDO_EN_DCF_TX_R { + ADPLL_TDC_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_tdc_ldo_en_dcf_rx(&self) -> ADPLL_TDC_LDO_EN_DCF_RX_R { + ADPLL_TDC_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_tdc_ldo_en_dcf_tx(&mut self) -> ADPLL_TDC_LDO_EN_DCF_TX_W { + ADPLL_TDC_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_tdc_ldo_en_dcf_rx(&mut self) -> ADPLL_TDC_LDO_EN_DCF_RX_W { + ADPLL_TDC_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config6_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG6_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG6_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config6_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG6_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config6_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG6_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG6_REG to value 0x83"] +impl crate::Resettable for RF_ENABLE_CONFIG6_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x83 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config7_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config7_reg.rs new file mode 100644 index 0000000..d4ae1e8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config7_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG7_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG7_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_DTC_LDO_EN_DCF_TX` reader - "] +pub struct ADPLL_DTC_LDO_EN_DCF_TX_R(crate::FieldReader); +impl ADPLL_DTC_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_DTC_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_DTC_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_DTC_LDO_EN_DCF_TX` writer - "] +pub struct ADPLL_DTC_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_DTC_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLL_DTC_LDO_EN_DCF_RX` reader - "] +pub struct ADPLL_DTC_LDO_EN_DCF_RX_R(crate::FieldReader); +impl ADPLL_DTC_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_DTC_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_DTC_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_DTC_LDO_EN_DCF_RX` writer - "] +pub struct ADPLL_DTC_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_DTC_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_dtc_ldo_en_dcf_tx(&self) -> ADPLL_DTC_LDO_EN_DCF_TX_R { + ADPLL_DTC_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_dtc_ldo_en_dcf_rx(&self) -> ADPLL_DTC_LDO_EN_DCF_RX_R { + ADPLL_DTC_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_dtc_ldo_en_dcf_tx(&mut self) -> ADPLL_DTC_LDO_EN_DCF_TX_W { + ADPLL_DTC_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_dtc_ldo_en_dcf_rx(&mut self) -> ADPLL_DTC_LDO_EN_DCF_RX_W { + ADPLL_DTC_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config7_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG7_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG7_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config7_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG7_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config7_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG7_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG7_REG to value 0x83"] +impl crate::Resettable for RF_ENABLE_CONFIG7_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x83 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config8_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config8_reg.rs new file mode 100644 index 0000000..d33eed4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config8_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG8_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG8_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ADPLL_DCO_LDO_EN_DCF_TX` reader - "] +pub struct ADPLL_DCO_LDO_EN_DCF_TX_R(crate::FieldReader); +impl ADPLL_DCO_LDO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_DCO_LDO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_DCO_LDO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_DCO_LDO_EN_DCF_TX` writer - "] +pub struct ADPLL_DCO_LDO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_DCO_LDO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `ADPLL_DCO_LDO_EN_DCF_RX` reader - "] +pub struct ADPLL_DCO_LDO_EN_DCF_RX_R(crate::FieldReader); +impl ADPLL_DCO_LDO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + ADPLL_DCO_LDO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ADPLL_DCO_LDO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ADPLL_DCO_LDO_EN_DCF_RX` writer - "] +pub struct ADPLL_DCO_LDO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> ADPLL_DCO_LDO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_dco_ldo_en_dcf_tx(&self) -> ADPLL_DCO_LDO_EN_DCF_TX_R { + ADPLL_DCO_LDO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_dco_ldo_en_dcf_rx(&self) -> ADPLL_DCO_LDO_EN_DCF_RX_R { + ADPLL_DCO_LDO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn adpll_dco_ldo_en_dcf_tx(&mut self) -> ADPLL_DCO_LDO_EN_DCF_TX_W { + ADPLL_DCO_LDO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn adpll_dco_ldo_en_dcf_rx(&mut self) -> ADPLL_DCO_LDO_EN_DCF_RX_W { + ADPLL_DCO_LDO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config8_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG8_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG8_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config8_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG8_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config8_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG8_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG8_REG to value 0x83"] +impl crate::Resettable for RF_ENABLE_CONFIG8_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x83 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config9_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config9_reg.rs new file mode 100644 index 0000000..8c9b6e3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_enable_config9_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `RF_ENABLE_CONFIG9_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_ENABLE_CONFIG9_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `LDO_ZERO_EN_DCF_TX` reader - "] +pub struct LDO_ZERO_EN_DCF_TX_R(crate::FieldReader); +impl LDO_ZERO_EN_DCF_TX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_ZERO_EN_DCF_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_ZERO_EN_DCF_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_ZERO_EN_DCF_TX` writer - "] +pub struct LDO_ZERO_EN_DCF_TX_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_ZERO_EN_DCF_TX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 5)) | ((value as u32 & 0x1f) << 5); + self.w + } +} +#[doc = "Field `LDO_ZERO_EN_DCF_RX` reader - "] +pub struct LDO_ZERO_EN_DCF_RX_R(crate::FieldReader); +impl LDO_ZERO_EN_DCF_RX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + LDO_ZERO_EN_DCF_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for LDO_ZERO_EN_DCF_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `LDO_ZERO_EN_DCF_RX` writer - "] +pub struct LDO_ZERO_EN_DCF_RX_W<'a> { + w: &'a mut W, +} +impl<'a> LDO_ZERO_EN_DCF_RX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f); + self.w + } +} +impl R { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn ldo_zero_en_dcf_tx(&self) -> LDO_ZERO_EN_DCF_TX_R { + LDO_ZERO_EN_DCF_TX_R::new(((self.bits >> 5) & 0x1f) as u8) + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn ldo_zero_en_dcf_rx(&self) -> LDO_ZERO_EN_DCF_RX_R { + LDO_ZERO_EN_DCF_RX_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Bits 5:9"] + #[inline(always)] + pub fn ldo_zero_en_dcf_tx(&mut self) -> LDO_ZERO_EN_DCF_TX_W { + LDO_ZERO_EN_DCF_TX_W { w: self } + } + #[doc = "Bits 0:4"] + #[inline(always)] + pub fn ldo_zero_en_dcf_rx(&mut self) -> LDO_ZERO_EN_DCF_RX_W { + LDO_ZERO_EN_DCF_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_enable_config9_reg](index.html) module"] +pub struct RF_ENABLE_CONFIG9_REG_SPEC; +impl crate::RegisterSpec for RF_ENABLE_CONFIG9_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_enable_config9_reg::R](R) reader structure"] +impl crate::Readable for RF_ENABLE_CONFIG9_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_enable_config9_reg::W](W) writer structure"] +impl crate::Writable for RF_ENABLE_CONFIG9_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_ENABLE_CONFIG9_REG to value 0x41"] +impl crate::Resettable for RF_ENABLE_CONFIG9_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x41 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_en_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_en_reg.rs new file mode 100644 index 0000000..534a74a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_en_reg.rs @@ -0,0 +1,536 @@ +#[doc = "Register `RF_PORT_EN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_PORT_EN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RF_PORT4_TX` reader - "] +pub struct RF_PORT4_TX_R(crate::FieldReader); +impl RF_PORT4_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT4_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT4_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT4_TX` writer - "] +pub struct RF_PORT4_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT4_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 9)) | ((value as u32 & 1) << 9); + self.w + } +} +#[doc = "Field `RF_PORT4_RX` reader - "] +pub struct RF_PORT4_RX_R(crate::FieldReader); +impl RF_PORT4_RX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT4_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT4_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT4_RX` writer - "] +pub struct RF_PORT4_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT4_RX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u32 & 1) << 8); + self.w + } +} +#[doc = "Field `RF_PORT3_TX` reader - "] +pub struct RF_PORT3_TX_R(crate::FieldReader); +impl RF_PORT3_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT3_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT3_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT3_TX` writer - "] +pub struct RF_PORT3_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT3_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `RF_PORT3_RX` reader - "] +pub struct RF_PORT3_RX_R(crate::FieldReader); +impl RF_PORT3_RX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT3_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT3_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT3_RX` writer - "] +pub struct RF_PORT3_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT3_RX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `RF_PORT2_TX` reader - "] +pub struct RF_PORT2_TX_R(crate::FieldReader); +impl RF_PORT2_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT2_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT2_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT2_TX` writer - "] +pub struct RF_PORT2_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT2_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `RF_PORT2_RX` reader - "] +pub struct RF_PORT2_RX_R(crate::FieldReader); +impl RF_PORT2_RX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT2_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT2_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT2_RX` writer - "] +pub struct RF_PORT2_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT2_RX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `RF_PORT1_TX` reader - "] +pub struct RF_PORT1_TX_R(crate::FieldReader); +impl RF_PORT1_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT1_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT1_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT1_TX` writer - "] +pub struct RF_PORT1_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT1_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `RF_PORT1_RX` reader - "] +pub struct RF_PORT1_RX_R(crate::FieldReader); +impl RF_PORT1_RX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT1_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT1_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT1_RX` writer - "] +pub struct RF_PORT1_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT1_RX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RF_PORT0_TX` reader - "] +pub struct RF_PORT0_TX_R(crate::FieldReader); +impl RF_PORT0_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT0_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT0_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT0_TX` writer - "] +pub struct RF_PORT0_TX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT0_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RF_PORT0_RX` reader - "] +pub struct RF_PORT0_RX_R(crate::FieldReader); +impl RF_PORT0_RX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT0_RX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT0_RX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT0_RX` writer - "] +pub struct RF_PORT0_RX_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT0_RX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 9"] + #[inline(always)] + pub fn rf_port4_tx(&self) -> RF_PORT4_TX_R { + RF_PORT4_TX_R::new(((self.bits >> 9) & 1) != 0) + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn rf_port4_rx(&self) -> RF_PORT4_RX_R { + RF_PORT4_RX_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn rf_port3_tx(&self) -> RF_PORT3_TX_R { + RF_PORT3_TX_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn rf_port3_rx(&self) -> RF_PORT3_RX_R { + RF_PORT3_RX_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn rf_port2_tx(&self) -> RF_PORT2_TX_R { + RF_PORT2_TX_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn rf_port2_rx(&self) -> RF_PORT2_RX_R { + RF_PORT2_RX_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn rf_port1_tx(&self) -> RF_PORT1_TX_R { + RF_PORT1_TX_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_port1_rx(&self) -> RF_PORT1_RX_R { + RF_PORT1_RX_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rf_port0_tx(&self) -> RF_PORT0_TX_R { + RF_PORT0_TX_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_port0_rx(&self) -> RF_PORT0_RX_R { + RF_PORT0_RX_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 9"] + #[inline(always)] + pub fn rf_port4_tx(&mut self) -> RF_PORT4_TX_W { + RF_PORT4_TX_W { w: self } + } + #[doc = "Bit 8"] + #[inline(always)] + pub fn rf_port4_rx(&mut self) -> RF_PORT4_RX_W { + RF_PORT4_RX_W { w: self } + } + #[doc = "Bit 7"] + #[inline(always)] + pub fn rf_port3_tx(&mut self) -> RF_PORT3_TX_W { + RF_PORT3_TX_W { w: self } + } + #[doc = "Bit 6"] + #[inline(always)] + pub fn rf_port3_rx(&mut self) -> RF_PORT3_RX_W { + RF_PORT3_RX_W { w: self } + } + #[doc = "Bit 5"] + #[inline(always)] + pub fn rf_port2_tx(&mut self) -> RF_PORT2_TX_W { + RF_PORT2_TX_W { w: self } + } + #[doc = "Bit 4"] + #[inline(always)] + pub fn rf_port2_rx(&mut self) -> RF_PORT2_RX_W { + RF_PORT2_RX_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn rf_port1_tx(&mut self) -> RF_PORT1_TX_W { + RF_PORT1_TX_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_port1_rx(&mut self) -> RF_PORT1_RX_W { + RF_PORT1_RX_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rf_port0_tx(&mut self) -> RF_PORT0_TX_W { + RF_PORT0_TX_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_port0_rx(&mut self) -> RF_PORT0_RX_W { + RF_PORT0_RX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_port_en_reg](index.html) module"] +pub struct RF_PORT_EN_REG_SPEC; +impl crate::RegisterSpec for RF_PORT_EN_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_port_en_reg::R](R) reader structure"] +impl crate::Readable for RF_PORT_EN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_port_en_reg::W](W) writer structure"] +impl crate::Writable for RF_PORT_EN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_PORT_EN_REG to value 0"] +impl crate::Resettable for RF_PORT_EN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_pol_reg.rs b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_pol_reg.rs new file mode 100644 index 0000000..d23261f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfcu_power/rf_port_pol_reg.rs @@ -0,0 +1,301 @@ +#[doc = "Register `RF_PORT_POL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RF_PORT_POL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RF_PORT4_POL` reader - "] +pub struct RF_PORT4_POL_R(crate::FieldReader); +impl RF_PORT4_POL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT4_POL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT4_POL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT4_POL` writer - "] +pub struct RF_PORT4_POL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT4_POL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `RF_PORT3_POL` reader - "] +pub struct RF_PORT3_POL_R(crate::FieldReader); +impl RF_PORT3_POL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT3_POL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT3_POL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT3_POL` writer - "] +pub struct RF_PORT3_POL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT3_POL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `RF_PORT2_POL` reader - "] +pub struct RF_PORT2_POL_R(crate::FieldReader); +impl RF_PORT2_POL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT2_POL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT2_POL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT2_POL` writer - "] +pub struct RF_PORT2_POL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT2_POL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RF_PORT1_POL` reader - "] +pub struct RF_PORT1_POL_R(crate::FieldReader); +impl RF_PORT1_POL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT1_POL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT1_POL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT1_POL` writer - "] +pub struct RF_PORT1_POL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT1_POL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RF_PORT0_POL` reader - "] +pub struct RF_PORT0_POL_R(crate::FieldReader); +impl RF_PORT0_POL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RF_PORT0_POL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RF_PORT0_POL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RF_PORT0_POL` writer - "] +pub struct RF_PORT0_POL_W<'a> { + w: &'a mut W, +} +impl<'a> RF_PORT0_POL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 4"] + #[inline(always)] + pub fn rf_port4_pol(&self) -> RF_PORT4_POL_R { + RF_PORT4_POL_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn rf_port3_pol(&self) -> RF_PORT3_POL_R { + RF_PORT3_POL_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_port2_pol(&self) -> RF_PORT2_POL_R { + RF_PORT2_POL_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rf_port1_pol(&self) -> RF_PORT1_POL_R { + RF_PORT1_POL_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_port0_pol(&self) -> RF_PORT0_POL_R { + RF_PORT0_POL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 4"] + #[inline(always)] + pub fn rf_port4_pol(&mut self) -> RF_PORT4_POL_W { + RF_PORT4_POL_W { w: self } + } + #[doc = "Bit 3"] + #[inline(always)] + pub fn rf_port3_pol(&mut self) -> RF_PORT3_POL_W { + RF_PORT3_POL_W { w: self } + } + #[doc = "Bit 2"] + #[inline(always)] + pub fn rf_port2_pol(&mut self) -> RF_PORT2_POL_W { + RF_PORT2_POL_W { w: self } + } + #[doc = "Bit 1"] + #[inline(always)] + pub fn rf_port1_pol(&mut self) -> RF_PORT1_POL_W { + RF_PORT1_POL_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rf_port0_pol(&mut self) -> RF_PORT0_POL_W { + RF_PORT0_POL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_port_pol_reg](index.html) module"] +pub struct RF_PORT_POL_REG_SPEC; +impl crate::RegisterSpec for RF_PORT_POL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rf_port_pol_reg::R](R) reader structure"] +impl crate::Readable for RF_PORT_POL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rf_port_pol_reg::W](W) writer structure"] +impl crate::Writable for RF_PORT_POL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RF_PORT_POL_REG to value 0"] +impl crate::Resettable for RF_PORT_POL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfmon.rs b/bitbox02-bt/vendor/da14531/src/rfmon.rs new file mode 100644 index 0000000..c7a8909 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfmon.rs @@ -0,0 +1,45 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - "] + pub rfmon_ctrl_reg: crate::Reg, + _reserved1: [u8; 0x02], + #[doc = "0x04 - "] + pub rfmon_addr_reg: crate::Reg, + _reserved2: [u8; 0x02], + #[doc = "0x08 - "] + pub rfmon_len_reg: crate::Reg, + _reserved3: [u8; 0x02], + #[doc = "0x0c - "] + pub rfmon_stat_reg: crate::Reg, + _reserved4: [u8; 0x02], + #[doc = "0x10 - "] + pub rfmon_crv_addr_reg: crate::Reg, + _reserved5: [u8; 0x02], + #[doc = "0x14 - "] + pub rfmon_crv_len_reg: crate::Reg, +} +#[doc = "RFMON_ADDR_REG register accessor: an alias for `Reg`"] +pub type RFMON_ADDR_REG = crate::Reg; +#[doc = ""] +pub mod rfmon_addr_reg; +#[doc = "RFMON_CRV_ADDR_REG register accessor: an alias for `Reg`"] +pub type RFMON_CRV_ADDR_REG = crate::Reg; +#[doc = ""] +pub mod rfmon_crv_addr_reg; +#[doc = "RFMON_CRV_LEN_REG register accessor: an alias for `Reg`"] +pub type RFMON_CRV_LEN_REG = crate::Reg; +#[doc = ""] +pub mod rfmon_crv_len_reg; +#[doc = "RFMON_CTRL_REG register accessor: an alias for `Reg`"] +pub type RFMON_CTRL_REG = crate::Reg; +#[doc = ""] +pub mod rfmon_ctrl_reg; +#[doc = "RFMON_LEN_REG register accessor: an alias for `Reg`"] +pub type RFMON_LEN_REG = crate::Reg; +#[doc = ""] +pub mod rfmon_len_reg; +#[doc = "RFMON_STAT_REG register accessor: an alias for `Reg`"] +pub type RFMON_STAT_REG = crate::Reg; +#[doc = ""] +pub mod rfmon_stat_reg; diff --git a/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_addr_reg.rs b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_addr_reg.rs new file mode 100644 index 0000000..b483973 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_addr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `RFMON_ADDR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RFMON_ADDR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFMON_ADDR` reader - "] +pub struct RFMON_ADDR_R(crate::FieldReader); +impl RFMON_ADDR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RFMON_ADDR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_ADDR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFMON_ADDR` writer - "] +pub struct RFMON_ADDR_W<'a> { + w: &'a mut W, +} +impl<'a> RFMON_ADDR_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3fff << 2)) | ((value as u16 & 0x3fff) << 2); + self.w + } +} +impl R { + #[doc = "Bits 2:15"] + #[inline(always)] + pub fn rfmon_addr(&self) -> RFMON_ADDR_R { + RFMON_ADDR_R::new(((self.bits >> 2) & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 2:15"] + #[inline(always)] + pub fn rfmon_addr(&mut self) -> RFMON_ADDR_W { + RFMON_ADDR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rfmon_addr_reg](index.html) module"] +pub struct RFMON_ADDR_REG_SPEC; +impl crate::RegisterSpec for RFMON_ADDR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rfmon_addr_reg::R](R) reader structure"] +impl crate::Readable for RFMON_ADDR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rfmon_addr_reg::W](W) writer structure"] +impl crate::Writable for RFMON_ADDR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RFMON_ADDR_REG to value 0"] +impl crate::Resettable for RFMON_ADDR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_addr_reg.rs b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_addr_reg.rs new file mode 100644 index 0000000..3cf1304 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_addr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `RFMON_CRV_ADDR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RFMON_CRV_ADDR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFMON_CRV_ADDR` reader - "] +pub struct RFMON_CRV_ADDR_R(crate::FieldReader); +impl RFMON_CRV_ADDR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RFMON_CRV_ADDR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_CRV_ADDR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 2:15"] + #[inline(always)] + pub fn rfmon_crv_addr(&self) -> RFMON_CRV_ADDR_R { + RFMON_CRV_ADDR_R::new(((self.bits >> 2) & 0x3fff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rfmon_crv_addr_reg](index.html) module"] +pub struct RFMON_CRV_ADDR_REG_SPEC; +impl crate::RegisterSpec for RFMON_CRV_ADDR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rfmon_crv_addr_reg::R](R) reader structure"] +impl crate::Readable for RFMON_CRV_ADDR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rfmon_crv_addr_reg::W](W) writer structure"] +impl crate::Writable for RFMON_CRV_ADDR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RFMON_CRV_ADDR_REG to value 0"] +impl crate::Resettable for RFMON_CRV_ADDR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_len_reg.rs b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_len_reg.rs new file mode 100644 index 0000000..e2b7c3d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_crv_len_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `RFMON_CRV_LEN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RFMON_CRV_LEN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFMON_CRV_LEN` reader - "] +pub struct RFMON_CRV_LEN_R(crate::FieldReader); +impl RFMON_CRV_LEN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RFMON_CRV_LEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_CRV_LEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:13"] + #[inline(always)] + pub fn rfmon_crv_len(&self) -> RFMON_CRV_LEN_R { + RFMON_CRV_LEN_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rfmon_crv_len_reg](index.html) module"] +pub struct RFMON_CRV_LEN_REG_SPEC; +impl crate::RegisterSpec for RFMON_CRV_LEN_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rfmon_crv_len_reg::R](R) reader structure"] +impl crate::Readable for RFMON_CRV_LEN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rfmon_crv_len_reg::W](W) writer structure"] +impl crate::Writable for RFMON_CRV_LEN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RFMON_CRV_LEN_REG to value 0"] +impl crate::Resettable for RFMON_CRV_LEN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_ctrl_reg.rs new file mode 100644 index 0000000..f29610a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_ctrl_reg.rs @@ -0,0 +1,160 @@ +#[doc = "Register `RFMON_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RFMON_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFMON_CIRC_EN` reader - "] +pub struct RFMON_CIRC_EN_R(crate::FieldReader); +impl RFMON_CIRC_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFMON_CIRC_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_CIRC_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFMON_CIRC_EN` writer - "] +pub struct RFMON_CIRC_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RFMON_CIRC_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `RFMON_PACK_EN` reader - "] +pub struct RFMON_PACK_EN_R(crate::FieldReader); +impl RFMON_PACK_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFMON_PACK_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_PACK_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFMON_PACK_EN` writer - "] +pub struct RFMON_PACK_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RFMON_PACK_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1"] + #[inline(always)] + pub fn rfmon_circ_en(&self) -> RFMON_CIRC_EN_R { + RFMON_CIRC_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rfmon_pack_en(&self) -> RFMON_PACK_EN_R { + RFMON_PACK_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1"] + #[inline(always)] + pub fn rfmon_circ_en(&mut self) -> RFMON_CIRC_EN_W { + RFMON_CIRC_EN_W { w: self } + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rfmon_pack_en(&mut self) -> RFMON_PACK_EN_W { + RFMON_PACK_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rfmon_ctrl_reg](index.html) module"] +pub struct RFMON_CTRL_REG_SPEC; +impl crate::RegisterSpec for RFMON_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rfmon_ctrl_reg::R](R) reader structure"] +impl crate::Readable for RFMON_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rfmon_ctrl_reg::W](W) writer structure"] +impl crate::Writable for RFMON_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RFMON_CTRL_REG to value 0"] +impl crate::Resettable for RFMON_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_len_reg.rs b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_len_reg.rs new file mode 100644 index 0000000..7715dd5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_len_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `RFMON_LEN_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RFMON_LEN_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFMON_LEN` reader - "] +pub struct RFMON_LEN_R(crate::FieldReader); +impl RFMON_LEN_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + RFMON_LEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_LEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFMON_LEN` writer - "] +pub struct RFMON_LEN_W<'a> { + w: &'a mut W, +} +impl<'a> RFMON_LEN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13"] + #[inline(always)] + pub fn rfmon_len(&self) -> RFMON_LEN_R { + RFMON_LEN_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13"] + #[inline(always)] + pub fn rfmon_len(&mut self) -> RFMON_LEN_W { + RFMON_LEN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rfmon_len_reg](index.html) module"] +pub struct RFMON_LEN_REG_SPEC; +impl crate::RegisterSpec for RFMON_LEN_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rfmon_len_reg::R](R) reader structure"] +impl crate::Readable for RFMON_LEN_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rfmon_len_reg::W](W) writer structure"] +impl crate::Writable for RFMON_LEN_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RFMON_LEN_REG to value 0"] +impl crate::Resettable for RFMON_LEN_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_stat_reg.rs b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_stat_reg.rs new file mode 100644 index 0000000..62f96c8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rfmon/rfmon_stat_reg.rs @@ -0,0 +1,133 @@ +#[doc = "Register `RFMON_STAT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RFMON_STAT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RFMON_OFLOW_STK` reader - "] +pub struct RFMON_OFLOW_STK_R(crate::FieldReader); +impl RFMON_OFLOW_STK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFMON_OFLOW_STK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_OFLOW_STK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RFMON_OFLOW_STK` writer - "] +pub struct RFMON_OFLOW_STK_W<'a> { + w: &'a mut W, +} +impl<'a> RFMON_OFLOW_STK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `RFMON_ACTIVE` reader - "] +pub struct RFMON_ACTIVE_R(crate::FieldReader); +impl RFMON_ACTIVE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RFMON_ACTIVE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RFMON_ACTIVE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 1"] + #[inline(always)] + pub fn rfmon_oflow_stk(&self) -> RFMON_OFLOW_STK_R { + RFMON_OFLOW_STK_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0"] + #[inline(always)] + pub fn rfmon_active(&self) -> RFMON_ACTIVE_R { + RFMON_ACTIVE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1"] + #[inline(always)] + pub fn rfmon_oflow_stk(&mut self) -> RFMON_OFLOW_STK_W { + RFMON_OFLOW_STK_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rfmon_stat_reg](index.html) module"] +pub struct RFMON_STAT_REG_SPEC; +impl crate::RegisterSpec for RFMON_STAT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [rfmon_stat_reg::R](R) reader structure"] +impl crate::Readable for RFMON_STAT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rfmon_stat_reg::W](W) writer structure"] +impl crate::Writable for RFMON_STAT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RFMON_STAT_REG to value 0"] +impl crate::Resettable for RFMON_STAT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc.rs b/bitbox02-bt/vendor/da14531/src/rtc.rs new file mode 100644 index 0000000..53efef7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc.rs @@ -0,0 +1,86 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - RTC Control Register"] + pub rtc_control_reg: crate::Reg, + #[doc = "0x04 - RTC Hour Mode Register"] + pub rtc_hour_mode_reg: crate::Reg, + #[doc = "0x08 - RTC Time Register"] + pub rtc_time_reg: crate::Reg, + #[doc = "0x0c - RTC Calendar Register"] + pub rtc_calendar_reg: crate::Reg, + #[doc = "0x10 - RTC Time Alarm Register"] + pub rtc_time_alarm_reg: crate::Reg, + #[doc = "0x14 - RTC Calendar Alram Register"] + pub rtc_calendar_alarm_reg: crate::Reg, + #[doc = "0x18 - RTC Alarm Enable Register"] + pub rtc_alarm_enable_reg: crate::Reg, + #[doc = "0x1c - RTC Event Flags Register"] + pub rtc_event_flags_reg: crate::Reg, + #[doc = "0x20 - RTC Interrupt Enable Register"] + pub rtc_interrupt_enable_reg: + crate::Reg, + #[doc = "0x24 - RTC Interrupt Disable Register"] + pub rtc_interrupt_disable_reg: + crate::Reg, + #[doc = "0x28 - RTC Interrupt Mask Register"] + pub rtc_interrupt_mask_reg: crate::Reg, + #[doc = "0x2c - RTC Status Register"] + pub rtc_status_reg: crate::Reg, + #[doc = "0x30 - RTC Keep RTC Register"] + pub rtc_keep_rtc_reg: crate::Reg, +} +#[doc = "RTC_ALARM_ENABLE_REG register accessor: an alias for `Reg`"] +pub type RTC_ALARM_ENABLE_REG = crate::Reg; +#[doc = "RTC Alarm Enable Register"] +pub mod rtc_alarm_enable_reg; +#[doc = "RTC_CALENDAR_ALARM_REG register accessor: an alias for `Reg`"] +pub type RTC_CALENDAR_ALARM_REG = crate::Reg; +#[doc = "RTC Calendar Alram Register"] +pub mod rtc_calendar_alarm_reg; +#[doc = "RTC_CALENDAR_REG register accessor: an alias for `Reg`"] +pub type RTC_CALENDAR_REG = crate::Reg; +#[doc = "RTC Calendar Register"] +pub mod rtc_calendar_reg; +#[doc = "RTC_CONTROL_REG register accessor: an alias for `Reg`"] +pub type RTC_CONTROL_REG = crate::Reg; +#[doc = "RTC Control Register"] +pub mod rtc_control_reg; +#[doc = "RTC_EVENT_FLAGS_REG register accessor: an alias for `Reg`"] +pub type RTC_EVENT_FLAGS_REG = crate::Reg; +#[doc = "RTC Event Flags Register"] +pub mod rtc_event_flags_reg; +#[doc = "RTC_HOUR_MODE_REG register accessor: an alias for `Reg`"] +pub type RTC_HOUR_MODE_REG = crate::Reg; +#[doc = "RTC Hour Mode Register"] +pub mod rtc_hour_mode_reg; +#[doc = "RTC_INTERRUPT_DISABLE_REG register accessor: an alias for `Reg`"] +pub type RTC_INTERRUPT_DISABLE_REG = + crate::Reg; +#[doc = "RTC Interrupt Disable Register"] +pub mod rtc_interrupt_disable_reg; +#[doc = "RTC_INTERRUPT_ENABLE_REG register accessor: an alias for `Reg`"] +pub type RTC_INTERRUPT_ENABLE_REG = + crate::Reg; +#[doc = "RTC Interrupt Enable Register"] +pub mod rtc_interrupt_enable_reg; +#[doc = "RTC_INTERRUPT_MASK_REG register accessor: an alias for `Reg`"] +pub type RTC_INTERRUPT_MASK_REG = crate::Reg; +#[doc = "RTC Interrupt Mask Register"] +pub mod rtc_interrupt_mask_reg; +#[doc = "RTC_KEEP_RTC_REG register accessor: an alias for `Reg`"] +pub type RTC_KEEP_RTC_REG = crate::Reg; +#[doc = "RTC Keep RTC Register"] +pub mod rtc_keep_rtc_reg; +#[doc = "RTC_STATUS_REG register accessor: an alias for `Reg`"] +pub type RTC_STATUS_REG = crate::Reg; +#[doc = "RTC Status Register"] +pub mod rtc_status_reg; +#[doc = "RTC_TIME_ALARM_REG register accessor: an alias for `Reg`"] +pub type RTC_TIME_ALARM_REG = crate::Reg; +#[doc = "RTC Time Alarm Register"] +pub mod rtc_time_alarm_reg; +#[doc = "RTC_TIME_REG register accessor: an alias for `Reg`"] +pub type RTC_TIME_REG = crate::Reg; +#[doc = "RTC Time Register"] +pub mod rtc_time_reg; diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_alarm_enable_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_alarm_enable_reg.rs new file mode 100644 index 0000000..65f1fac --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_alarm_enable_reg.rs @@ -0,0 +1,348 @@ +#[doc = "Register `RTC_ALARM_ENABLE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_ALARM_ENABLE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_ALARM_MNTH_EN` reader - Alarm on month enable. Enable to trigger alarm when data specified in Calendar Alarm Register (M_T and M_U) has been reached."] +pub struct RTC_ALARM_MNTH_EN_R(crate::FieldReader); +impl RTC_ALARM_MNTH_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_ALARM_MNTH_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_ALARM_MNTH_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_ALARM_MNTH_EN` writer - Alarm on month enable. Enable to trigger alarm when data specified in Calendar Alarm Register (M_T and M_U) has been reached."] +pub struct RTC_ALARM_MNTH_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALARM_MNTH_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `RTC_ALARM_DATE_EN` reader - Alarm on date enable. Enable to trigger alarm when data specified in Calendar Alarm Register (D_T and D_U) has been reached."] +pub struct RTC_ALARM_DATE_EN_R(crate::FieldReader); +impl RTC_ALARM_DATE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_ALARM_DATE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_ALARM_DATE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_ALARM_DATE_EN` writer - Alarm on date enable. Enable to trigger alarm when data specified in Calendar Alarm Register (D_T and D_U) has been reached."] +pub struct RTC_ALARM_DATE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALARM_DATE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `RTC_ALARM_HOUR_EN` reader - Alarm on hour enable. Enable to trigger alarm when data specified in Time Alarm Register (PM, HR_T and HR_U) has been reached."] +pub struct RTC_ALARM_HOUR_EN_R(crate::FieldReader); +impl RTC_ALARM_HOUR_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_ALARM_HOUR_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_ALARM_HOUR_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_ALARM_HOUR_EN` writer - Alarm on hour enable. Enable to trigger alarm when data specified in Time Alarm Register (PM, HR_T and HR_U) has been reached."] +pub struct RTC_ALARM_HOUR_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALARM_HOUR_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `RTC_ALARM_MIN_EN` reader - Alarm on minute enable. Enable to trigger alarm when data specified in Time Alarm Register (M_T and M_U) has been reached."] +pub struct RTC_ALARM_MIN_EN_R(crate::FieldReader); +impl RTC_ALARM_MIN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_ALARM_MIN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_ALARM_MIN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_ALARM_MIN_EN` writer - Alarm on minute enable. Enable to trigger alarm when data specified in Time Alarm Register (M_T and M_U) has been reached."] +pub struct RTC_ALARM_MIN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALARM_MIN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RTC_ALARM_SEC_EN` reader - Alarm on second enable. Enable to trigger alarm when data specified in Time Alarm Register (S_T and S_U) has been reached."] +pub struct RTC_ALARM_SEC_EN_R(crate::FieldReader); +impl RTC_ALARM_SEC_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_ALARM_SEC_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_ALARM_SEC_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_ALARM_SEC_EN` writer - Alarm on second enable. Enable to trigger alarm when data specified in Time Alarm Register (S_T and S_U) has been reached."] +pub struct RTC_ALARM_SEC_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALARM_SEC_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RTC_ALARM_HOS_EN` reader - Alarm on hundredths of a second enable. Enable to trigger alarm when data specified in Time Alarm Register (H_T and H_U) has been reached."] +pub struct RTC_ALARM_HOS_EN_R(crate::FieldReader); +impl RTC_ALARM_HOS_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_ALARM_HOS_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_ALARM_HOS_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_ALARM_HOS_EN` writer - Alarm on hundredths of a second enable. Enable to trigger alarm when data specified in Time Alarm Register (H_T and H_U) has been reached."] +pub struct RTC_ALARM_HOS_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALARM_HOS_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 5 - Alarm on month enable. Enable to trigger alarm when data specified in Calendar Alarm Register (M_T and M_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_mnth_en(&self) -> RTC_ALARM_MNTH_EN_R { + RTC_ALARM_MNTH_EN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Alarm on date enable. Enable to trigger alarm when data specified in Calendar Alarm Register (D_T and D_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_date_en(&self) -> RTC_ALARM_DATE_EN_R { + RTC_ALARM_DATE_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Alarm on hour enable. Enable to trigger alarm when data specified in Time Alarm Register (PM, HR_T and HR_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_hour_en(&self) -> RTC_ALARM_HOUR_EN_R { + RTC_ALARM_HOUR_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Alarm on minute enable. Enable to trigger alarm when data specified in Time Alarm Register (M_T and M_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_min_en(&self) -> RTC_ALARM_MIN_EN_R { + RTC_ALARM_MIN_EN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Alarm on second enable. Enable to trigger alarm when data specified in Time Alarm Register (S_T and S_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_sec_en(&self) -> RTC_ALARM_SEC_EN_R { + RTC_ALARM_SEC_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Alarm on hundredths of a second enable. Enable to trigger alarm when data specified in Time Alarm Register (H_T and H_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_hos_en(&self) -> RTC_ALARM_HOS_EN_R { + RTC_ALARM_HOS_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 5 - Alarm on month enable. Enable to trigger alarm when data specified in Calendar Alarm Register (M_T and M_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_mnth_en(&mut self) -> RTC_ALARM_MNTH_EN_W { + RTC_ALARM_MNTH_EN_W { w: self } + } + #[doc = "Bit 4 - Alarm on date enable. Enable to trigger alarm when data specified in Calendar Alarm Register (D_T and D_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_date_en(&mut self) -> RTC_ALARM_DATE_EN_W { + RTC_ALARM_DATE_EN_W { w: self } + } + #[doc = "Bit 3 - Alarm on hour enable. Enable to trigger alarm when data specified in Time Alarm Register (PM, HR_T and HR_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_hour_en(&mut self) -> RTC_ALARM_HOUR_EN_W { + RTC_ALARM_HOUR_EN_W { w: self } + } + #[doc = "Bit 2 - Alarm on minute enable. Enable to trigger alarm when data specified in Time Alarm Register (M_T and M_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_min_en(&mut self) -> RTC_ALARM_MIN_EN_W { + RTC_ALARM_MIN_EN_W { w: self } + } + #[doc = "Bit 1 - Alarm on second enable. Enable to trigger alarm when data specified in Time Alarm Register (S_T and S_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_sec_en(&mut self) -> RTC_ALARM_SEC_EN_W { + RTC_ALARM_SEC_EN_W { w: self } + } + #[doc = "Bit 0 - Alarm on hundredths of a second enable. Enable to trigger alarm when data specified in Time Alarm Register (H_T and H_U) has been reached."] + #[inline(always)] + pub fn rtc_alarm_hos_en(&mut self) -> RTC_ALARM_HOS_EN_W { + RTC_ALARM_HOS_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Alarm Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_alarm_enable_reg](index.html) module"] +pub struct RTC_ALARM_ENABLE_REG_SPEC; +impl crate::RegisterSpec for RTC_ALARM_ENABLE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_alarm_enable_reg::R](R) reader structure"] +impl crate::Readable for RTC_ALARM_ENABLE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_alarm_enable_reg::W](W) writer structure"] +impl crate::Writable for RTC_ALARM_ENABLE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_ALARM_ENABLE_REG to value 0"] +impl crate::Resettable for RTC_ALARM_ENABLE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_alarm_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_alarm_reg.rs new file mode 100644 index 0000000..b81da58 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_alarm_reg.rs @@ -0,0 +1,224 @@ +#[doc = "Register `RTC_CALENDAR_ALARM_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_CALENDAR_ALARM_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_CAL_D_T` reader - Date tens. Represented in BCD digit (0-3)."] +pub struct RTC_CAL_D_T_R(crate::FieldReader); +impl RTC_CAL_D_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_D_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_D_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_D_T` writer - Date tens. Represented in BCD digit (0-3)."] +pub struct RTC_CAL_D_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_D_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 12)) | ((value as u32 & 3) << 12); + self.w + } +} +#[doc = "Field `RTC_CAL_D_U` reader - Date units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_D_U_R(crate::FieldReader); +impl RTC_CAL_D_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_D_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_D_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_D_U` writer - Date units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_D_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_D_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `RTC_CAL_M_T` reader - Month tens. Represented in BCD digit (0-1)."] +pub struct RTC_CAL_M_T_R(crate::FieldReader); +impl RTC_CAL_M_T_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_CAL_M_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_M_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_M_T` writer - Month tens. Represented in BCD digit (0-1)."] +pub struct RTC_CAL_M_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_M_T_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `RTC_CAL_M_U` reader - Month units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_M_U_R(crate::FieldReader); +impl RTC_CAL_M_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_M_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_M_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_M_U` writer - Month units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_M_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_M_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 3)) | ((value as u32 & 0x0f) << 3); + self.w + } +} +impl R { + #[doc = "Bits 12:13 - Date tens. Represented in BCD digit (0-3)."] + #[inline(always)] + pub fn rtc_cal_d_t(&self) -> RTC_CAL_D_T_R { + RTC_CAL_D_T_R::new(((self.bits >> 12) & 3) as u8) + } + #[doc = "Bits 8:11 - Date units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_d_u(&self) -> RTC_CAL_D_U_R { + RTC_CAL_D_U_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bit 7 - Month tens. Represented in BCD digit (0-1)."] + #[inline(always)] + pub fn rtc_cal_m_t(&self) -> RTC_CAL_M_T_R { + RTC_CAL_M_T_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 3:6 - Month units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_m_u(&self) -> RTC_CAL_M_U_R { + RTC_CAL_M_U_R::new(((self.bits >> 3) & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 12:13 - Date tens. Represented in BCD digit (0-3)."] + #[inline(always)] + pub fn rtc_cal_d_t(&mut self) -> RTC_CAL_D_T_W { + RTC_CAL_D_T_W { w: self } + } + #[doc = "Bits 8:11 - Date units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_d_u(&mut self) -> RTC_CAL_D_U_W { + RTC_CAL_D_U_W { w: self } + } + #[doc = "Bit 7 - Month tens. Represented in BCD digit (0-1)."] + #[inline(always)] + pub fn rtc_cal_m_t(&mut self) -> RTC_CAL_M_T_W { + RTC_CAL_M_T_W { w: self } + } + #[doc = "Bits 3:6 - Month units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_m_u(&mut self) -> RTC_CAL_M_U_W { + RTC_CAL_M_U_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Calendar Alram Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_calendar_alarm_reg](index.html) module"] +pub struct RTC_CALENDAR_ALARM_REG_SPEC; +impl crate::RegisterSpec for RTC_CALENDAR_ALARM_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_calendar_alarm_reg::R](R) reader structure"] +impl crate::Readable for RTC_CALENDAR_ALARM_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_calendar_alarm_reg::W](W) writer structure"] +impl crate::Writable for RTC_CALENDAR_ALARM_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_CALENDAR_ALARM_REG to value 0"] +impl crate::Resettable for RTC_CALENDAR_ALARM_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_reg.rs new file mode 100644 index 0000000..741973f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_calendar_reg.rs @@ -0,0 +1,456 @@ +#[doc = "Register `RTC_CALENDAR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_CALENDAR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_CAL_CH` reader - The value in this register has altered since last read. Read and clear"] +pub struct RTC_CAL_CH_R(crate::FieldReader); +impl RTC_CAL_CH_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_CAL_CH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_CH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_CH` writer - The value in this register has altered since last read. Read and clear"] +pub struct RTC_CAL_CH_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_CH_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `RTC_CAL_C_T` reader - Century tens. Represented in BCD digit (1-2)."] +pub struct RTC_CAL_C_T_R(crate::FieldReader); +impl RTC_CAL_C_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_C_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_C_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_C_T` writer - Century tens. Represented in BCD digit (1-2)."] +pub struct RTC_CAL_C_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_C_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 28)) | ((value as u32 & 3) << 28); + self.w + } +} +#[doc = "Field `RTC_CAL_C_U` reader - Century units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_C_U_R(crate::FieldReader); +impl RTC_CAL_C_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_C_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_C_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_C_U` writer - Century units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_C_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_C_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 24)) | ((value as u32 & 0x0f) << 24); + self.w + } +} +#[doc = "Field `RTC_CAL_Y_T` reader - Year tens. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_Y_T_R(crate::FieldReader); +impl RTC_CAL_Y_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_Y_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_Y_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_Y_T` writer - Year tens. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_Y_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_Y_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 20)) | ((value as u32 & 0x0f) << 20); + self.w + } +} +#[doc = "Field `RTC_CAL_Y_U` reader - Year units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_Y_U_R(crate::FieldReader); +impl RTC_CAL_Y_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_Y_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_Y_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_Y_U` writer - Year units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_Y_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_Y_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); + self.w + } +} +#[doc = "Field `RTC_CAL_D_T` reader - Date tens. Represented in BCD digit (0-3)."] +pub struct RTC_CAL_D_T_R(crate::FieldReader); +impl RTC_CAL_D_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_D_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_D_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_D_T` writer - Date tens. Represented in BCD digit (0-3)."] +pub struct RTC_CAL_D_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_D_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 12)) | ((value as u32 & 3) << 12); + self.w + } +} +#[doc = "Field `RTC_CAL_D_U` reader - Date units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_D_U_R(crate::FieldReader); +impl RTC_CAL_D_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_D_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_D_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_D_U` writer - Date units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_D_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_D_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `RTC_CAL_M_T` reader - Month tens. Represented in BCD digit (0-1)."] +pub struct RTC_CAL_M_T_R(crate::FieldReader); +impl RTC_CAL_M_T_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_CAL_M_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_M_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_M_T` writer - Month tens. Represented in BCD digit (0-1)."] +pub struct RTC_CAL_M_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_M_T_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u32 & 1) << 7); + self.w + } +} +#[doc = "Field `RTC_CAL_M_U` reader - Month units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_M_U_R(crate::FieldReader); +impl RTC_CAL_M_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_CAL_M_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_M_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_M_U` writer - Month units. Represented in BCD digit (0-9)."] +pub struct RTC_CAL_M_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_M_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 3)) | ((value as u32 & 0x0f) << 3); + self.w + } +} +#[doc = "Field `RTC_DAY` reader - Day of the week (arbitrary) units. Represented in BCD digit (0-7)."] +pub struct RTC_DAY_R(crate::FieldReader); +impl RTC_DAY_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_DAY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_DAY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_DAY` writer - Day of the week (arbitrary) units. Represented in BCD digit (0-7)."] +pub struct RTC_DAY_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_DAY_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u32 & 7); + self.w + } +} +impl R { + #[doc = "Bit 31 - The value in this register has altered since last read. Read and clear"] + #[inline(always)] + pub fn rtc_cal_ch(&self) -> RTC_CAL_CH_R { + RTC_CAL_CH_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bits 28:29 - Century tens. Represented in BCD digit (1-2)."] + #[inline(always)] + pub fn rtc_cal_c_t(&self) -> RTC_CAL_C_T_R { + RTC_CAL_C_T_R::new(((self.bits >> 28) & 3) as u8) + } + #[doc = "Bits 24:27 - Century units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_c_u(&self) -> RTC_CAL_C_U_R { + RTC_CAL_C_U_R::new(((self.bits >> 24) & 0x0f) as u8) + } + #[doc = "Bits 20:23 - Year tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_y_t(&self) -> RTC_CAL_Y_T_R { + RTC_CAL_Y_T_R::new(((self.bits >> 20) & 0x0f) as u8) + } + #[doc = "Bits 16:19 - Year units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_y_u(&self) -> RTC_CAL_Y_U_R { + RTC_CAL_Y_U_R::new(((self.bits >> 16) & 0x0f) as u8) + } + #[doc = "Bits 12:13 - Date tens. Represented in BCD digit (0-3)."] + #[inline(always)] + pub fn rtc_cal_d_t(&self) -> RTC_CAL_D_T_R { + RTC_CAL_D_T_R::new(((self.bits >> 12) & 3) as u8) + } + #[doc = "Bits 8:11 - Date units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_d_u(&self) -> RTC_CAL_D_U_R { + RTC_CAL_D_U_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bit 7 - Month tens. Represented in BCD digit (0-1)."] + #[inline(always)] + pub fn rtc_cal_m_t(&self) -> RTC_CAL_M_T_R { + RTC_CAL_M_T_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 3:6 - Month units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_m_u(&self) -> RTC_CAL_M_U_R { + RTC_CAL_M_U_R::new(((self.bits >> 3) & 0x0f) as u8) + } + #[doc = "Bits 0:2 - Day of the week (arbitrary) units. Represented in BCD digit (0-7)."] + #[inline(always)] + pub fn rtc_day(&self) -> RTC_DAY_R { + RTC_DAY_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bit 31 - The value in this register has altered since last read. Read and clear"] + #[inline(always)] + pub fn rtc_cal_ch(&mut self) -> RTC_CAL_CH_W { + RTC_CAL_CH_W { w: self } + } + #[doc = "Bits 28:29 - Century tens. Represented in BCD digit (1-2)."] + #[inline(always)] + pub fn rtc_cal_c_t(&mut self) -> RTC_CAL_C_T_W { + RTC_CAL_C_T_W { w: self } + } + #[doc = "Bits 24:27 - Century units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_c_u(&mut self) -> RTC_CAL_C_U_W { + RTC_CAL_C_U_W { w: self } + } + #[doc = "Bits 20:23 - Year tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_y_t(&mut self) -> RTC_CAL_Y_T_W { + RTC_CAL_Y_T_W { w: self } + } + #[doc = "Bits 16:19 - Year units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_y_u(&mut self) -> RTC_CAL_Y_U_W { + RTC_CAL_Y_U_W { w: self } + } + #[doc = "Bits 12:13 - Date tens. Represented in BCD digit (0-3)."] + #[inline(always)] + pub fn rtc_cal_d_t(&mut self) -> RTC_CAL_D_T_W { + RTC_CAL_D_T_W { w: self } + } + #[doc = "Bits 8:11 - Date units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_d_u(&mut self) -> RTC_CAL_D_U_W { + RTC_CAL_D_U_W { w: self } + } + #[doc = "Bit 7 - Month tens. Represented in BCD digit (0-1)."] + #[inline(always)] + pub fn rtc_cal_m_t(&mut self) -> RTC_CAL_M_T_W { + RTC_CAL_M_T_W { w: self } + } + #[doc = "Bits 3:6 - Month units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_cal_m_u(&mut self) -> RTC_CAL_M_U_W { + RTC_CAL_M_U_W { w: self } + } + #[doc = "Bits 0:2 - Day of the week (arbitrary) units. Represented in BCD digit (0-7)."] + #[inline(always)] + pub fn rtc_day(&mut self) -> RTC_DAY_W { + RTC_DAY_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Calendar Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_calendar_reg](index.html) module"] +pub struct RTC_CALENDAR_REG_SPEC; +impl crate::RegisterSpec for RTC_CALENDAR_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_calendar_reg::R](R) reader structure"] +impl crate::Readable for RTC_CALENDAR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_calendar_reg::W](W) writer structure"] +impl crate::Writable for RTC_CALENDAR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_CALENDAR_REG to value 0x2000_010f"] +impl crate::Resettable for RTC_CALENDAR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x2000_010f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_control_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_control_reg.rs new file mode 100644 index 0000000..e8e6a1d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_control_reg.rs @@ -0,0 +1,160 @@ +#[doc = "Register `RTC_CONTROL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_CONTROL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_CAL_DISABLE` reader - When this field is set high the RTC stops incrementing the calendar value."] +pub struct RTC_CAL_DISABLE_R(crate::FieldReader); +impl RTC_CAL_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_CAL_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_CAL_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_CAL_DISABLE` writer - When this field is set high the RTC stops incrementing the calendar value."] +pub struct RTC_CAL_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_CAL_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RTC_TIME_DISABLE` reader - When this field is set high the RTC stops incrementing the time value."] +pub struct RTC_TIME_DISABLE_R(crate::FieldReader); +impl RTC_TIME_DISABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_TIME_DISABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_DISABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_DISABLE` writer - When this field is set high the RTC stops incrementing the time value."] +pub struct RTC_TIME_DISABLE_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_DISABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1 - When this field is set high the RTC stops incrementing the calendar value."] + #[inline(always)] + pub fn rtc_cal_disable(&self) -> RTC_CAL_DISABLE_R { + RTC_CAL_DISABLE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - When this field is set high the RTC stops incrementing the time value."] + #[inline(always)] + pub fn rtc_time_disable(&self) -> RTC_TIME_DISABLE_R { + RTC_TIME_DISABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1 - When this field is set high the RTC stops incrementing the calendar value."] + #[inline(always)] + pub fn rtc_cal_disable(&mut self) -> RTC_CAL_DISABLE_W { + RTC_CAL_DISABLE_W { w: self } + } + #[doc = "Bit 0 - When this field is set high the RTC stops incrementing the time value."] + #[inline(always)] + pub fn rtc_time_disable(&mut self) -> RTC_TIME_DISABLE_W { + RTC_TIME_DISABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_control_reg](index.html) module"] +pub struct RTC_CONTROL_REG_SPEC; +impl crate::RegisterSpec for RTC_CONTROL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_control_reg::R](R) reader structure"] +impl crate::Readable for RTC_CONTROL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_control_reg::W](W) writer structure"] +impl crate::Writable for RTC_CONTROL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_CONTROL_REG to value 0x03"] +impl crate::Resettable for RTC_CONTROL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x03 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_event_flags_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_event_flags_reg.rs new file mode 100644 index 0000000..c0ee48b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_event_flags_reg.rs @@ -0,0 +1,206 @@ +#[doc = "Register `RTC_EVENT_FLAGS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_EVENT_FLAGS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_EVENT_ALRM` reader - Alarm event flag. Indicate that alarm event occurred since the last reset."] +pub struct RTC_EVENT_ALRM_R(crate::FieldReader); +impl RTC_EVENT_ALRM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_EVENT_ALRM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_EVENT_ALRM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_EVENT_MNTH` reader - Month rolls over event flag. Indicate that month rolls over event occurred since the last reset."] +pub struct RTC_EVENT_MNTH_R(crate::FieldReader); +impl RTC_EVENT_MNTH_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_EVENT_MNTH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_EVENT_MNTH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_EVENT_DATE` reader - Date rolls over event flag. Indicate that date rolls over event occurred since the last reset."] +pub struct RTC_EVENT_DATE_R(crate::FieldReader); +impl RTC_EVENT_DATE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_EVENT_DATE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_EVENT_DATE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_EVENT_HOUR` reader - Hour rolls over event flag. Indicate that hour rolls over event occurred since the last reset."] +pub struct RTC_EVENT_HOUR_R(crate::FieldReader); +impl RTC_EVENT_HOUR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_EVENT_HOUR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_EVENT_HOUR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_EVENT_MIN` reader - Minute rolls over event flag. Indicate that minute rolls over event occurred since the last reset."] +pub struct RTC_EVENT_MIN_R(crate::FieldReader); +impl RTC_EVENT_MIN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_EVENT_MIN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_EVENT_MIN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_EVENT_SEC` reader - Second rolls over event flag. Indicate that second rolls over event occurred since the last reset."] +pub struct RTC_EVENT_SEC_R(crate::FieldReader); +impl RTC_EVENT_SEC_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_EVENT_SEC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_EVENT_SEC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_EVENT_HOS` reader - Hundredths of a second event flag. Indicate that hundredths of a second rolls over event occurred since the last reset."] +pub struct RTC_EVENT_HOS_R(crate::FieldReader); +impl RTC_EVENT_HOS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_EVENT_HOS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_EVENT_HOS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 6 - Alarm event flag. Indicate that alarm event occurred since the last reset."] + #[inline(always)] + pub fn rtc_event_alrm(&self) -> RTC_EVENT_ALRM_R { + RTC_EVENT_ALRM_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Month rolls over event flag. Indicate that month rolls over event occurred since the last reset."] + #[inline(always)] + pub fn rtc_event_mnth(&self) -> RTC_EVENT_MNTH_R { + RTC_EVENT_MNTH_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Date rolls over event flag. Indicate that date rolls over event occurred since the last reset."] + #[inline(always)] + pub fn rtc_event_date(&self) -> RTC_EVENT_DATE_R { + RTC_EVENT_DATE_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Hour rolls over event flag. Indicate that hour rolls over event occurred since the last reset."] + #[inline(always)] + pub fn rtc_event_hour(&self) -> RTC_EVENT_HOUR_R { + RTC_EVENT_HOUR_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Minute rolls over event flag. Indicate that minute rolls over event occurred since the last reset."] + #[inline(always)] + pub fn rtc_event_min(&self) -> RTC_EVENT_MIN_R { + RTC_EVENT_MIN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Second rolls over event flag. Indicate that second rolls over event occurred since the last reset."] + #[inline(always)] + pub fn rtc_event_sec(&self) -> RTC_EVENT_SEC_R { + RTC_EVENT_SEC_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Hundredths of a second event flag. Indicate that hundredths of a second rolls over event occurred since the last reset."] + #[inline(always)] + pub fn rtc_event_hos(&self) -> RTC_EVENT_HOS_R { + RTC_EVENT_HOS_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Event Flags Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_event_flags_reg](index.html) module"] +pub struct RTC_EVENT_FLAGS_REG_SPEC; +impl crate::RegisterSpec for RTC_EVENT_FLAGS_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_event_flags_reg::R](R) reader structure"] +impl crate::Readable for RTC_EVENT_FLAGS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_event_flags_reg::W](W) writer structure"] +impl crate::Writable for RTC_EVENT_FLAGS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_EVENT_FLAGS_REG to value 0"] +impl crate::Resettable for RTC_EVENT_FLAGS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_hour_mode_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_hour_mode_reg.rs new file mode 100644 index 0000000..f917691 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_hour_mode_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `RTC_HOUR_MODE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_HOUR_MODE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_HMS` reader - When this field is set high the RTC operates in 12 hour clock mode; otherwise, times are in 24 hour clock format."] +pub struct RTC_HMS_R(crate::FieldReader); +impl RTC_HMS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_HMS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_HMS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_HMS` writer - When this field is set high the RTC operates in 12 hour clock mode; otherwise, times are in 24 hour clock format."] +pub struct RTC_HMS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_HMS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - When this field is set high the RTC operates in 12 hour clock mode; otherwise, times are in 24 hour clock format."] + #[inline(always)] + pub fn rtc_hms(&self) -> RTC_HMS_R { + RTC_HMS_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - When this field is set high the RTC operates in 12 hour clock mode; otherwise, times are in 24 hour clock format."] + #[inline(always)] + pub fn rtc_hms(&mut self) -> RTC_HMS_W { + RTC_HMS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Hour Mode Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_hour_mode_reg](index.html) module"] +pub struct RTC_HOUR_MODE_REG_SPEC; +impl crate::RegisterSpec for RTC_HOUR_MODE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_hour_mode_reg::R](R) reader structure"] +impl crate::Readable for RTC_HOUR_MODE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_hour_mode_reg::W](W) writer structure"] +impl crate::Writable for RTC_HOUR_MODE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_HOUR_MODE_REG to value 0"] +impl crate::Resettable for RTC_HOUR_MODE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_disable_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_disable_reg.rs new file mode 100644 index 0000000..bbcd278 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_disable_reg.rs @@ -0,0 +1,253 @@ +#[doc = "Register `RTC_INTERRUPT_DISABLE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_INTERRUPT_DISABLE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_ALRM_INT_DIS` writer - Interrupt on alarm disable. Disable to issue the interrupt when alarm event occurred."] +pub struct RTC_ALRM_INT_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALRM_INT_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `RTC_MNTH_INT_DIS` writer - Interrupt on month disable. Disable to issue the interrupt when month event occurred."] +pub struct RTC_MNTH_INT_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_MNTH_INT_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `RTC_DATE_INT_DIS` writer - Interrupt on date disable. Disable to issue the interrupt when date event occurred."] +pub struct RTC_DATE_INT_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_DATE_INT_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `RTC_HOUR_INT_DIS` writer - IInterrupt on hour disable. Disable to issue the interrupt when hour event occurred."] +pub struct RTC_HOUR_INT_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_HOUR_INT_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `RTC_MIN_INT_DIS` writer - Interrupt on minute disable. Disable to issue the interrupt when minute event occurred."] +pub struct RTC_MIN_INT_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_MIN_INT_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RTC_SEC_INT_DIS` writer - Interrupt on second disable. Disable to issue the interrupt when second event occurred."] +pub struct RTC_SEC_INT_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_SEC_INT_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RTC_HOS_INT_DIS` writer - Interrupt on hundredths of a second disable. Disable to issue the interrupt when hundredths of a second event occurred."] +pub struct RTC_HOS_INT_DIS_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_HOS_INT_DIS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl W { + #[doc = "Bit 6 - Interrupt on alarm disable. Disable to issue the interrupt when alarm event occurred."] + #[inline(always)] + pub fn rtc_alrm_int_dis(&mut self) -> RTC_ALRM_INT_DIS_W { + RTC_ALRM_INT_DIS_W { w: self } + } + #[doc = "Bit 5 - Interrupt on month disable. Disable to issue the interrupt when month event occurred."] + #[inline(always)] + pub fn rtc_mnth_int_dis(&mut self) -> RTC_MNTH_INT_DIS_W { + RTC_MNTH_INT_DIS_W { w: self } + } + #[doc = "Bit 4 - Interrupt on date disable. Disable to issue the interrupt when date event occurred."] + #[inline(always)] + pub fn rtc_date_int_dis(&mut self) -> RTC_DATE_INT_DIS_W { + RTC_DATE_INT_DIS_W { w: self } + } + #[doc = "Bit 3 - IInterrupt on hour disable. Disable to issue the interrupt when hour event occurred."] + #[inline(always)] + pub fn rtc_hour_int_dis(&mut self) -> RTC_HOUR_INT_DIS_W { + RTC_HOUR_INT_DIS_W { w: self } + } + #[doc = "Bit 2 - Interrupt on minute disable. Disable to issue the interrupt when minute event occurred."] + #[inline(always)] + pub fn rtc_min_int_dis(&mut self) -> RTC_MIN_INT_DIS_W { + RTC_MIN_INT_DIS_W { w: self } + } + #[doc = "Bit 1 - Interrupt on second disable. Disable to issue the interrupt when second event occurred."] + #[inline(always)] + pub fn rtc_sec_int_dis(&mut self) -> RTC_SEC_INT_DIS_W { + RTC_SEC_INT_DIS_W { w: self } + } + #[doc = "Bit 0 - Interrupt on hundredths of a second disable. Disable to issue the interrupt when hundredths of a second event occurred."] + #[inline(always)] + pub fn rtc_hos_int_dis(&mut self) -> RTC_HOS_INT_DIS_W { + RTC_HOS_INT_DIS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Interrupt Disable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_interrupt_disable_reg](index.html) module"] +pub struct RTC_INTERRUPT_DISABLE_REG_SPEC; +impl crate::RegisterSpec for RTC_INTERRUPT_DISABLE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_interrupt_disable_reg::R](R) reader structure"] +impl crate::Readable for RTC_INTERRUPT_DISABLE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_interrupt_disable_reg::W](W) writer structure"] +impl crate::Writable for RTC_INTERRUPT_DISABLE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_INTERRUPT_DISABLE_REG to value 0"] +impl crate::Resettable for RTC_INTERRUPT_DISABLE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_enable_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_enable_reg.rs new file mode 100644 index 0000000..cca50e1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_enable_reg.rs @@ -0,0 +1,253 @@ +#[doc = "Register `RTC_INTERRUPT_ENABLE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_INTERRUPT_ENABLE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_ALRM_INT_EN` writer - Interrupt on alarm enable. Enable to issue the interrupt when alarm event occurred."] +pub struct RTC_ALRM_INT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_ALRM_INT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `RTC_MNTH_INT_EN` writer - Interrupt on month enable. Enable to issue the interrupt when month event occurred."] +pub struct RTC_MNTH_INT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_MNTH_INT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `RTC_DATE_INT_EN` writer - Interrupt on date enable. Enable to issue the interrupt when date event occurred."] +pub struct RTC_DATE_INT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_DATE_INT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `RTC_HOUR_INT_EN` writer - Interrupt on hour enable. Enable to issue the interrupt when hour event occurred."] +pub struct RTC_HOUR_INT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_HOUR_INT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u32 & 1) << 3); + self.w + } +} +#[doc = "Field `RTC_MIN_INT_EN` writer - Interrupt on minute enable. Enable to issue the interrupt when minute event occurred."] +pub struct RTC_MIN_INT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_MIN_INT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `RTC_SEC_INT_EN` writer - Interrupt on second enable. Enable to issue the interrupt when second event occurred."] +pub struct RTC_SEC_INT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_SEC_INT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `RTC_HOS_INT_EN` writer - Interrupt on hundredths of a second enable. Enable to issue the interrupt when hundredths of a second event occurred."] +pub struct RTC_HOS_INT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_HOS_INT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl W { + #[doc = "Bit 6 - Interrupt on alarm enable. Enable to issue the interrupt when alarm event occurred."] + #[inline(always)] + pub fn rtc_alrm_int_en(&mut self) -> RTC_ALRM_INT_EN_W { + RTC_ALRM_INT_EN_W { w: self } + } + #[doc = "Bit 5 - Interrupt on month enable. Enable to issue the interrupt when month event occurred."] + #[inline(always)] + pub fn rtc_mnth_int_en(&mut self) -> RTC_MNTH_INT_EN_W { + RTC_MNTH_INT_EN_W { w: self } + } + #[doc = "Bit 4 - Interrupt on date enable. Enable to issue the interrupt when date event occurred."] + #[inline(always)] + pub fn rtc_date_int_en(&mut self) -> RTC_DATE_INT_EN_W { + RTC_DATE_INT_EN_W { w: self } + } + #[doc = "Bit 3 - Interrupt on hour enable. Enable to issue the interrupt when hour event occurred."] + #[inline(always)] + pub fn rtc_hour_int_en(&mut self) -> RTC_HOUR_INT_EN_W { + RTC_HOUR_INT_EN_W { w: self } + } + #[doc = "Bit 2 - Interrupt on minute enable. Enable to issue the interrupt when minute event occurred."] + #[inline(always)] + pub fn rtc_min_int_en(&mut self) -> RTC_MIN_INT_EN_W { + RTC_MIN_INT_EN_W { w: self } + } + #[doc = "Bit 1 - Interrupt on second enable. Enable to issue the interrupt when second event occurred."] + #[inline(always)] + pub fn rtc_sec_int_en(&mut self) -> RTC_SEC_INT_EN_W { + RTC_SEC_INT_EN_W { w: self } + } + #[doc = "Bit 0 - Interrupt on hundredths of a second enable. Enable to issue the interrupt when hundredths of a second event occurred."] + #[inline(always)] + pub fn rtc_hos_int_en(&mut self) -> RTC_HOS_INT_EN_W { + RTC_HOS_INT_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_interrupt_enable_reg](index.html) module"] +pub struct RTC_INTERRUPT_ENABLE_REG_SPEC; +impl crate::RegisterSpec for RTC_INTERRUPT_ENABLE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_interrupt_enable_reg::R](R) reader structure"] +impl crate::Readable for RTC_INTERRUPT_ENABLE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_interrupt_enable_reg::W](W) writer structure"] +impl crate::Writable for RTC_INTERRUPT_ENABLE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_INTERRUPT_ENABLE_REG to value 0"] +impl crate::Resettable for RTC_INTERRUPT_ENABLE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_mask_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_mask_reg.rs new file mode 100644 index 0000000..2c31ea7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_interrupt_mask_reg.rs @@ -0,0 +1,206 @@ +#[doc = "Register `RTC_INTERRUPT_MASK_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_INTERRUPT_MASK_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_ALRM_INT_MSK` reader - Mask alarm interrupt. It can be cleared (set) by setting corresponding bit (ALRM) in Interrupt Enable Register (Interrupt Disable Register)."] +pub struct RTC_ALRM_INT_MSK_R(crate::FieldReader); +impl RTC_ALRM_INT_MSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_ALRM_INT_MSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_ALRM_INT_MSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_MNTH_INT_MSK` reader - Mask month interrupt. It can be cleared (set) by setting corresponding bit (MNTH) in Interrupt Enable Register (Interrupt Disable Register)."] +pub struct RTC_MNTH_INT_MSK_R(crate::FieldReader); +impl RTC_MNTH_INT_MSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_MNTH_INT_MSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_MNTH_INT_MSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_DATE_INT_MSK` reader - Mask date interrupt. It can be cleared (set) by setting corresponding bit (DATE) in Interrupt Enable Register (Interrupt Disable Register)."] +pub struct RTC_DATE_INT_MSK_R(crate::FieldReader); +impl RTC_DATE_INT_MSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_DATE_INT_MSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_DATE_INT_MSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_HOUR_INT_MSK` reader - Mask hour interrupt. It can be cleared (set) by setting corresponding bit (HOUR) in Interrupt Enable Register (Interrupt Disable Register)."] +pub struct RTC_HOUR_INT_MSK_R(crate::FieldReader); +impl RTC_HOUR_INT_MSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_HOUR_INT_MSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_HOUR_INT_MSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_MIN_INT_MSK` reader - Mask minute interrupt. It can be cleared (set) by setting corresponding bit (MIN) in Interrupt Enable Register (Interrupt Disable Register)."] +pub struct RTC_MIN_INT_MSK_R(crate::FieldReader); +impl RTC_MIN_INT_MSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_MIN_INT_MSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_MIN_INT_MSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_SEC_INT_MSK` reader - Mask second interrupt. It can be cleared (set) by setting corresponding bit (SEC) in Interrupt Enable Register (Interrupt Disable Register)."] +pub struct RTC_SEC_INT_MSK_R(crate::FieldReader); +impl RTC_SEC_INT_MSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_SEC_INT_MSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_SEC_INT_MSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_HOS_INT_MSK` reader - Mask hundredths of a second interrupt. It can be cleared (set) by setting corresponding bit (HOS) in Interrupt Enable Register (Interrupt Disable Register)."] +pub struct RTC_HOS_INT_MSK_R(crate::FieldReader); +impl RTC_HOS_INT_MSK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_HOS_INT_MSK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_HOS_INT_MSK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 6 - Mask alarm interrupt. It can be cleared (set) by setting corresponding bit (ALRM) in Interrupt Enable Register (Interrupt Disable Register)."] + #[inline(always)] + pub fn rtc_alrm_int_msk(&self) -> RTC_ALRM_INT_MSK_R { + RTC_ALRM_INT_MSK_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Mask month interrupt. It can be cleared (set) by setting corresponding bit (MNTH) in Interrupt Enable Register (Interrupt Disable Register)."] + #[inline(always)] + pub fn rtc_mnth_int_msk(&self) -> RTC_MNTH_INT_MSK_R { + RTC_MNTH_INT_MSK_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Mask date interrupt. It can be cleared (set) by setting corresponding bit (DATE) in Interrupt Enable Register (Interrupt Disable Register)."] + #[inline(always)] + pub fn rtc_date_int_msk(&self) -> RTC_DATE_INT_MSK_R { + RTC_DATE_INT_MSK_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Mask hour interrupt. It can be cleared (set) by setting corresponding bit (HOUR) in Interrupt Enable Register (Interrupt Disable Register)."] + #[inline(always)] + pub fn rtc_hour_int_msk(&self) -> RTC_HOUR_INT_MSK_R { + RTC_HOUR_INT_MSK_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Mask minute interrupt. It can be cleared (set) by setting corresponding bit (MIN) in Interrupt Enable Register (Interrupt Disable Register)."] + #[inline(always)] + pub fn rtc_min_int_msk(&self) -> RTC_MIN_INT_MSK_R { + RTC_MIN_INT_MSK_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Mask second interrupt. It can be cleared (set) by setting corresponding bit (SEC) in Interrupt Enable Register (Interrupt Disable Register)."] + #[inline(always)] + pub fn rtc_sec_int_msk(&self) -> RTC_SEC_INT_MSK_R { + RTC_SEC_INT_MSK_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Mask hundredths of a second interrupt. It can be cleared (set) by setting corresponding bit (HOS) in Interrupt Enable Register (Interrupt Disable Register)."] + #[inline(always)] + pub fn rtc_hos_int_msk(&self) -> RTC_HOS_INT_MSK_R { + RTC_HOS_INT_MSK_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_interrupt_mask_reg](index.html) module"] +pub struct RTC_INTERRUPT_MASK_REG_SPEC; +impl crate::RegisterSpec for RTC_INTERRUPT_MASK_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_interrupt_mask_reg::R](R) reader structure"] +impl crate::Readable for RTC_INTERRUPT_MASK_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_interrupt_mask_reg::W](W) writer structure"] +impl crate::Writable for RTC_INTERRUPT_MASK_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_INTERRUPT_MASK_REG to value 0x7f"] +impl crate::Resettable for RTC_INTERRUPT_MASK_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x7f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_keep_rtc_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_keep_rtc_reg.rs new file mode 100644 index 0000000..d3984f4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_keep_rtc_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `RTC_KEEP_RTC_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_KEEP_RTC_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_KEEP` reader - Keep RTC. When high, the time and calendar registers and any other registers which directly affect or are affected by the time and calendar registers are NOT reset when software reset is applied. When low, the software reset will reset every register except the keep RTC and control registers."] +pub struct RTC_KEEP_R(crate::FieldReader); +impl RTC_KEEP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_KEEP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_KEEP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_KEEP` writer - Keep RTC. When high, the time and calendar registers and any other registers which directly affect or are affected by the time and calendar registers are NOT reset when software reset is applied. When low, the software reset will reset every register except the keep RTC and control registers."] +pub struct RTC_KEEP_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_KEEP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Keep RTC. When high, the time and calendar registers and any other registers which directly affect or are affected by the time and calendar registers are NOT reset when software reset is applied. When low, the software reset will reset every register except the keep RTC and control registers."] + #[inline(always)] + pub fn rtc_keep(&self) -> RTC_KEEP_R { + RTC_KEEP_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Keep RTC. When high, the time and calendar registers and any other registers which directly affect or are affected by the time and calendar registers are NOT reset when software reset is applied. When low, the software reset will reset every register except the keep RTC and control registers."] + #[inline(always)] + pub fn rtc_keep(&mut self) -> RTC_KEEP_W { + RTC_KEEP_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Keep RTC Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_keep_rtc_reg](index.html) module"] +pub struct RTC_KEEP_RTC_REG_SPEC; +impl crate::RegisterSpec for RTC_KEEP_RTC_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_keep_rtc_reg::R](R) reader structure"] +impl crate::Readable for RTC_KEEP_RTC_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_keep_rtc_reg::W](W) writer structure"] +impl crate::Writable for RTC_KEEP_RTC_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_KEEP_RTC_REG to value 0x01"] +impl crate::Resettable for RTC_KEEP_RTC_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_status_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_status_reg.rs new file mode 100644 index 0000000..bbe2769 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_status_reg.rs @@ -0,0 +1,146 @@ +#[doc = "Register `RTC_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_VALID_CAL_ALM` reader - Valid Calendar Alarm. If cleared then indicates that invalid entry occurred when writing to Calendar Alarm Register."] +pub struct RTC_VALID_CAL_ALM_R(crate::FieldReader); +impl RTC_VALID_CAL_ALM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_VALID_CAL_ALM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_VALID_CAL_ALM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_VALID_TIME_ALM` reader - Valid Time Alarm. If cleared then indicates that invalid entry occurred when writing to Time Alarm Register."] +pub struct RTC_VALID_TIME_ALM_R(crate::FieldReader); +impl RTC_VALID_TIME_ALM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_VALID_TIME_ALM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_VALID_TIME_ALM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_VALID_CAL` reader - Valid Calendar. If cleared then indicates that invalid entry occurred when writing to Calendar Register."] +pub struct RTC_VALID_CAL_R(crate::FieldReader); +impl RTC_VALID_CAL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_VALID_CAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_VALID_CAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_VALID_TIME` reader - Valid Time. If cleared then indicates that invalid entry occurred when writing to Time Register."] +pub struct RTC_VALID_TIME_R(crate::FieldReader); +impl RTC_VALID_TIME_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_VALID_TIME_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_VALID_TIME_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 3 - Valid Calendar Alarm. If cleared then indicates that invalid entry occurred when writing to Calendar Alarm Register."] + #[inline(always)] + pub fn rtc_valid_cal_alm(&self) -> RTC_VALID_CAL_ALM_R { + RTC_VALID_CAL_ALM_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Valid Time Alarm. If cleared then indicates that invalid entry occurred when writing to Time Alarm Register."] + #[inline(always)] + pub fn rtc_valid_time_alm(&self) -> RTC_VALID_TIME_ALM_R { + RTC_VALID_TIME_ALM_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Valid Calendar. If cleared then indicates that invalid entry occurred when writing to Calendar Register."] + #[inline(always)] + pub fn rtc_valid_cal(&self) -> RTC_VALID_CAL_R { + RTC_VALID_CAL_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Valid Time. If cleared then indicates that invalid entry occurred when writing to Time Register."] + #[inline(always)] + pub fn rtc_valid_time(&self) -> RTC_VALID_TIME_R { + RTC_VALID_TIME_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_status_reg](index.html) module"] +pub struct RTC_STATUS_REG_SPEC; +impl crate::RegisterSpec for RTC_STATUS_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_status_reg::R](R) reader structure"] +impl crate::Readable for RTC_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_status_reg::W](W) writer structure"] +impl crate::Writable for RTC_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_STATUS_REG to value 0x0f"] +impl crate::Resettable for RTC_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0f + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_time_alarm_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_time_alarm_reg.rs new file mode 100644 index 0000000..13e06c4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_time_alarm_reg.rs @@ -0,0 +1,409 @@ +#[doc = "Register `RTC_TIME_ALARM_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_TIME_ALARM_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_TIME_PM` reader - In 12 hour clock mode, indicates PM when set."] +pub struct RTC_TIME_PM_R(crate::FieldReader); +impl RTC_TIME_PM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_TIME_PM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_PM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_PM` writer - In 12 hour clock mode, indicates PM when set."] +pub struct RTC_TIME_PM_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_PM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 30)) | ((value as u32 & 1) << 30); + self.w + } +} +#[doc = "Field `RTC_TIME_HR_T` reader - Hours tens. Represented in BCD digit (0-2)."] +pub struct RTC_TIME_HR_T_R(crate::FieldReader); +impl RTC_TIME_HR_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_HR_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_HR_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_HR_T` writer - Hours tens. Represented in BCD digit (0-2)."] +pub struct RTC_TIME_HR_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_HR_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 28)) | ((value as u32 & 3) << 28); + self.w + } +} +#[doc = "Field `RTC_TIME_HR_U` reader - Hours units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_HR_U_R(crate::FieldReader); +impl RTC_TIME_HR_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_HR_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_HR_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_HR_U` writer - Hours units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_HR_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_HR_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 24)) | ((value as u32 & 0x0f) << 24); + self.w + } +} +#[doc = "Field `RTC_TIME_M_T` reader - Minutes tens. Represented in BCD digit (0-5)."] +pub struct RTC_TIME_M_T_R(crate::FieldReader); +impl RTC_TIME_M_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_M_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_M_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_M_T` writer - Minutes tens. Represented in BCD digit (0-5)."] +pub struct RTC_TIME_M_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_M_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 20)) | ((value as u32 & 7) << 20); + self.w + } +} +#[doc = "Field `RTC_TIME_M_U` reader - Minutes units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_M_U_R(crate::FieldReader); +impl RTC_TIME_M_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_M_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_M_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_M_U` writer - Minutes units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_M_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_M_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); + self.w + } +} +#[doc = "Field `RTC_TIME_S_T` reader - Seconds tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_T_R(crate::FieldReader); +impl RTC_TIME_S_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_S_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_S_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_S_T` writer - Seconds tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_S_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 12)) | ((value as u32 & 7) << 12); + self.w + } +} +#[doc = "Field `RTC_TIME_S_U` reader - Seconds units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_U_R(crate::FieldReader); +impl RTC_TIME_S_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_S_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_S_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_S_U` writer - Seconds units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_S_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `RTC_TIME_H_T` reader - Hundredths of a second tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_T_R(crate::FieldReader); +impl RTC_TIME_H_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_H_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_H_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_H_T` writer - Hundredths of a second tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_H_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u32 & 0x0f) << 4); + self.w + } +} +#[doc = "Field `RTC_TIME_H_U` reader - Hundredths of a second units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_U_R(crate::FieldReader); +impl RTC_TIME_H_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_H_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_H_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_H_U` writer - Hundredths of a second units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_H_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 30 - In 12 hour clock mode, indicates PM when set."] + #[inline(always)] + pub fn rtc_time_pm(&self) -> RTC_TIME_PM_R { + RTC_TIME_PM_R::new(((self.bits >> 30) & 1) != 0) + } + #[doc = "Bits 28:29 - Hours tens. Represented in BCD digit (0-2)."] + #[inline(always)] + pub fn rtc_time_hr_t(&self) -> RTC_TIME_HR_T_R { + RTC_TIME_HR_T_R::new(((self.bits >> 28) & 3) as u8) + } + #[doc = "Bits 24:27 - Hours units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_hr_u(&self) -> RTC_TIME_HR_U_R { + RTC_TIME_HR_U_R::new(((self.bits >> 24) & 0x0f) as u8) + } + #[doc = "Bits 20:22 - Minutes tens. Represented in BCD digit (0-5)."] + #[inline(always)] + pub fn rtc_time_m_t(&self) -> RTC_TIME_M_T_R { + RTC_TIME_M_T_R::new(((self.bits >> 20) & 7) as u8) + } + #[doc = "Bits 16:19 - Minutes units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_m_u(&self) -> RTC_TIME_M_U_R { + RTC_TIME_M_U_R::new(((self.bits >> 16) & 0x0f) as u8) + } + #[doc = "Bits 12:14 - Seconds tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_t(&self) -> RTC_TIME_S_T_R { + RTC_TIME_S_T_R::new(((self.bits >> 12) & 7) as u8) + } + #[doc = "Bits 8:11 - Seconds units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_u(&self) -> RTC_TIME_S_U_R { + RTC_TIME_S_U_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bits 4:7 - Hundredths of a second tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_t(&self) -> RTC_TIME_H_T_R { + RTC_TIME_H_T_R::new(((self.bits >> 4) & 0x0f) as u8) + } + #[doc = "Bits 0:3 - Hundredths of a second units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_u(&self) -> RTC_TIME_H_U_R { + RTC_TIME_H_U_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bit 30 - In 12 hour clock mode, indicates PM when set."] + #[inline(always)] + pub fn rtc_time_pm(&mut self) -> RTC_TIME_PM_W { + RTC_TIME_PM_W { w: self } + } + #[doc = "Bits 28:29 - Hours tens. Represented in BCD digit (0-2)."] + #[inline(always)] + pub fn rtc_time_hr_t(&mut self) -> RTC_TIME_HR_T_W { + RTC_TIME_HR_T_W { w: self } + } + #[doc = "Bits 24:27 - Hours units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_hr_u(&mut self) -> RTC_TIME_HR_U_W { + RTC_TIME_HR_U_W { w: self } + } + #[doc = "Bits 20:22 - Minutes tens. Represented in BCD digit (0-5)."] + #[inline(always)] + pub fn rtc_time_m_t(&mut self) -> RTC_TIME_M_T_W { + RTC_TIME_M_T_W { w: self } + } + #[doc = "Bits 16:19 - Minutes units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_m_u(&mut self) -> RTC_TIME_M_U_W { + RTC_TIME_M_U_W { w: self } + } + #[doc = "Bits 12:14 - Seconds tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_t(&mut self) -> RTC_TIME_S_T_W { + RTC_TIME_S_T_W { w: self } + } + #[doc = "Bits 8:11 - Seconds units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_u(&mut self) -> RTC_TIME_S_U_W { + RTC_TIME_S_U_W { w: self } + } + #[doc = "Bits 4:7 - Hundredths of a second tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_t(&mut self) -> RTC_TIME_H_T_W { + RTC_TIME_H_T_W { w: self } + } + #[doc = "Bits 0:3 - Hundredths of a second units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_u(&mut self) -> RTC_TIME_H_U_W { + RTC_TIME_H_U_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Time Alarm Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_time_alarm_reg](index.html) module"] +pub struct RTC_TIME_ALARM_REG_SPEC; +impl crate::RegisterSpec for RTC_TIME_ALARM_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_time_alarm_reg::R](R) reader structure"] +impl crate::Readable for RTC_TIME_ALARM_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_time_alarm_reg::W](W) writer structure"] +impl crate::Writable for RTC_TIME_ALARM_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_TIME_ALARM_REG to value 0"] +impl crate::Resettable for RTC_TIME_ALARM_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/rtc/rtc_time_reg.rs b/bitbox02-bt/vendor/da14531/src/rtc/rtc_time_reg.rs new file mode 100644 index 0000000..5c50bd2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/rtc/rtc_time_reg.rs @@ -0,0 +1,456 @@ +#[doc = "Register `RTC_TIME_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `RTC_TIME_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RTC_TIME_CH` reader - The value in this register has altered since last read. Read and clear."] +pub struct RTC_TIME_CH_R(crate::FieldReader); +impl RTC_TIME_CH_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_TIME_CH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_CH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_CH` writer - The value in this register has altered since last read. Read and clear."] +pub struct RTC_TIME_CH_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_CH_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); + self.w + } +} +#[doc = "Field `RTC_TIME_PM` reader - In 12 hour clock mode, indicates PM when set."] +pub struct RTC_TIME_PM_R(crate::FieldReader); +impl RTC_TIME_PM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + RTC_TIME_PM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_PM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_PM` writer - In 12 hour clock mode, indicates PM when set."] +pub struct RTC_TIME_PM_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_PM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 30)) | ((value as u32 & 1) << 30); + self.w + } +} +#[doc = "Field `RTC_TIME_HR_T` reader - Hours tens. Represented in BCD digit (0-2)."] +pub struct RTC_TIME_HR_T_R(crate::FieldReader); +impl RTC_TIME_HR_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_HR_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_HR_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_HR_T` writer - Hours tens. Represented in BCD digit (0-2)."] +pub struct RTC_TIME_HR_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_HR_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 28)) | ((value as u32 & 3) << 28); + self.w + } +} +#[doc = "Field `RTC_TIME_HR_U` reader - Hours units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_HR_U_R(crate::FieldReader); +impl RTC_TIME_HR_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_HR_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_HR_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_HR_U` writer - Hours units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_HR_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_HR_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 24)) | ((value as u32 & 0x0f) << 24); + self.w + } +} +#[doc = "Field `RTC_TIME_M_T` reader - Minutes tens. Represented in BCD digit (0-5)."] +pub struct RTC_TIME_M_T_R(crate::FieldReader); +impl RTC_TIME_M_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_M_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_M_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_M_T` writer - Minutes tens. Represented in BCD digit (0-5)."] +pub struct RTC_TIME_M_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_M_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 20)) | ((value as u32 & 7) << 20); + self.w + } +} +#[doc = "Field `RTC_TIME_M_U` reader - Minutes units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_M_U_R(crate::FieldReader); +impl RTC_TIME_M_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_M_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_M_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_M_U` writer - Minutes units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_M_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_M_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); + self.w + } +} +#[doc = "Field `RTC_TIME_S_T` reader - Seconds tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_T_R(crate::FieldReader); +impl RTC_TIME_S_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_S_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_S_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_S_T` writer - Seconds tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_S_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 12)) | ((value as u32 & 7) << 12); + self.w + } +} +#[doc = "Field `RTC_TIME_S_U` reader - Seconds units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_U_R(crate::FieldReader); +impl RTC_TIME_S_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_S_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_S_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_S_U` writer - Seconds units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_S_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_S_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8); + self.w + } +} +#[doc = "Field `RTC_TIME_H_T` reader - Hundredths of a second tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_T_R(crate::FieldReader); +impl RTC_TIME_H_T_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_H_T_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_H_T_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_H_T` writer - Hundredths of a second tens. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_T_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_H_T_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u32 & 0x0f) << 4); + self.w + } +} +#[doc = "Field `RTC_TIME_H_U` reader - Hundredths of a second units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_U_R(crate::FieldReader); +impl RTC_TIME_H_U_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RTC_TIME_H_U_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RTC_TIME_H_U_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RTC_TIME_H_U` writer - Hundredths of a second units. Represented in BCD digit (0-9)."] +pub struct RTC_TIME_H_U_W<'a> { + w: &'a mut W, +} +impl<'a> RTC_TIME_H_U_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 31 - The value in this register has altered since last read. Read and clear."] + #[inline(always)] + pub fn rtc_time_ch(&self) -> RTC_TIME_CH_R { + RTC_TIME_CH_R::new(((self.bits >> 31) & 1) != 0) + } + #[doc = "Bit 30 - In 12 hour clock mode, indicates PM when set."] + #[inline(always)] + pub fn rtc_time_pm(&self) -> RTC_TIME_PM_R { + RTC_TIME_PM_R::new(((self.bits >> 30) & 1) != 0) + } + #[doc = "Bits 28:29 - Hours tens. Represented in BCD digit (0-2)."] + #[inline(always)] + pub fn rtc_time_hr_t(&self) -> RTC_TIME_HR_T_R { + RTC_TIME_HR_T_R::new(((self.bits >> 28) & 3) as u8) + } + #[doc = "Bits 24:27 - Hours units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_hr_u(&self) -> RTC_TIME_HR_U_R { + RTC_TIME_HR_U_R::new(((self.bits >> 24) & 0x0f) as u8) + } + #[doc = "Bits 20:22 - Minutes tens. Represented in BCD digit (0-5)."] + #[inline(always)] + pub fn rtc_time_m_t(&self) -> RTC_TIME_M_T_R { + RTC_TIME_M_T_R::new(((self.bits >> 20) & 7) as u8) + } + #[doc = "Bits 16:19 - Minutes units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_m_u(&self) -> RTC_TIME_M_U_R { + RTC_TIME_M_U_R::new(((self.bits >> 16) & 0x0f) as u8) + } + #[doc = "Bits 12:14 - Seconds tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_t(&self) -> RTC_TIME_S_T_R { + RTC_TIME_S_T_R::new(((self.bits >> 12) & 7) as u8) + } + #[doc = "Bits 8:11 - Seconds units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_u(&self) -> RTC_TIME_S_U_R { + RTC_TIME_S_U_R::new(((self.bits >> 8) & 0x0f) as u8) + } + #[doc = "Bits 4:7 - Hundredths of a second tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_t(&self) -> RTC_TIME_H_T_R { + RTC_TIME_H_T_R::new(((self.bits >> 4) & 0x0f) as u8) + } + #[doc = "Bits 0:3 - Hundredths of a second units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_u(&self) -> RTC_TIME_H_U_R { + RTC_TIME_H_U_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bit 31 - The value in this register has altered since last read. Read and clear."] + #[inline(always)] + pub fn rtc_time_ch(&mut self) -> RTC_TIME_CH_W { + RTC_TIME_CH_W { w: self } + } + #[doc = "Bit 30 - In 12 hour clock mode, indicates PM when set."] + #[inline(always)] + pub fn rtc_time_pm(&mut self) -> RTC_TIME_PM_W { + RTC_TIME_PM_W { w: self } + } + #[doc = "Bits 28:29 - Hours tens. Represented in BCD digit (0-2)."] + #[inline(always)] + pub fn rtc_time_hr_t(&mut self) -> RTC_TIME_HR_T_W { + RTC_TIME_HR_T_W { w: self } + } + #[doc = "Bits 24:27 - Hours units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_hr_u(&mut self) -> RTC_TIME_HR_U_W { + RTC_TIME_HR_U_W { w: self } + } + #[doc = "Bits 20:22 - Minutes tens. Represented in BCD digit (0-5)."] + #[inline(always)] + pub fn rtc_time_m_t(&mut self) -> RTC_TIME_M_T_W { + RTC_TIME_M_T_W { w: self } + } + #[doc = "Bits 16:19 - Minutes units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_m_u(&mut self) -> RTC_TIME_M_U_W { + RTC_TIME_M_U_W { w: self } + } + #[doc = "Bits 12:14 - Seconds tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_t(&mut self) -> RTC_TIME_S_T_W { + RTC_TIME_S_T_W { w: self } + } + #[doc = "Bits 8:11 - Seconds units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_s_u(&mut self) -> RTC_TIME_S_U_W { + RTC_TIME_S_U_W { w: self } + } + #[doc = "Bits 4:7 - Hundredths of a second tens. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_t(&mut self) -> RTC_TIME_H_T_W { + RTC_TIME_H_T_W { w: self } + } + #[doc = "Bits 0:3 - Hundredths of a second units. Represented in BCD digit (0-9)."] + #[inline(always)] + pub fn rtc_time_h_u(&mut self) -> RTC_TIME_H_U_W { + RTC_TIME_H_U_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "RTC Time Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_time_reg](index.html) module"] +pub struct RTC_TIME_REG_SPEC; +impl crate::RegisterSpec for RTC_TIME_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [rtc_time_reg::R](R) reader structure"] +impl crate::Readable for RTC_TIME_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [rtc_time_reg::W](W) writer structure"] +impl crate::Writable for RTC_TIME_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets RTC_TIME_REG to value 0"] +impl crate::Resettable for RTC_TIME_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi.rs b/bitbox02-bt/vendor/da14531/src/spi.rs new file mode 100644 index 0000000..ef53dfb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi.rs @@ -0,0 +1,98 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Spi control register"] + pub spi_ctrl_reg: crate::Reg, + _reserved1: [u8; 0x02], + #[doc = "0x04 - Spi control register"] + pub spi_config_reg: crate::Reg, + _reserved2: [u8; 0x02], + #[doc = "0x08 - Spi clock register"] + pub spi_clock_reg: crate::Reg, + _reserved3: [u8; 0x02], + #[doc = "0x0c - Spi fifo configuration register"] + pub spi_fifo_config_reg: crate::Reg, + _reserved4: [u8; 0x02], + #[doc = "0x10 - Spi interrupt mask register"] + pub spi_irq_mask_reg: crate::Reg, + _reserved5: [u8; 0x02], + #[doc = "0x14 - Spi status register"] + pub spi_status_reg: crate::Reg, + _reserved6: [u8; 0x02], + #[doc = "0x18 - SPI RX/TX fifo status register"] + pub spi_fifo_status_reg: crate::Reg, + _reserved7: [u8; 0x02], + #[doc = "0x1c - Spi RX fifo read register"] + pub spi_fifo_read_reg: crate::Reg, + _reserved8: [u8; 0x02], + #[doc = "0x20 - Spi TX fifo wtite register"] + pub spi_fifo_write_reg: crate::Reg, + _reserved9: [u8; 0x02], + #[doc = "0x24 - Spi cs configuration register"] + pub spi_cs_config_reg: crate::Reg, + _reserved10: [u8; 0x02], + #[doc = "0x28 - Spi TX/RX High 16bit word"] + pub spi_fifo_high_reg: crate::Reg, + _reserved11: [u8; 0x02], + #[doc = "0x2c - SPI TX buffer force low value"] + pub spi_txbuffer_force_l_reg: + crate::Reg, + _reserved12: [u8; 0x02], + #[doc = "0x30 - SPI TX buffer force high value"] + pub spi_txbuffer_force_h_reg: + crate::Reg, +} +#[doc = "SPI_CLOCK_REG register accessor: an alias for `Reg`"] +pub type SPI_CLOCK_REG = crate::Reg; +#[doc = "Spi clock register"] +pub mod spi_clock_reg; +#[doc = "SPI_CONFIG_REG register accessor: an alias for `Reg`"] +pub type SPI_CONFIG_REG = crate::Reg; +#[doc = "Spi control register"] +pub mod spi_config_reg; +#[doc = "SPI_CS_CONFIG_REG register accessor: an alias for `Reg`"] +pub type SPI_CS_CONFIG_REG = crate::Reg; +#[doc = "Spi cs configuration register"] +pub mod spi_cs_config_reg; +#[doc = "SPI_CTRL_REG register accessor: an alias for `Reg`"] +pub type SPI_CTRL_REG = crate::Reg; +#[doc = "Spi control register"] +pub mod spi_ctrl_reg; +#[doc = "SPI_FIFO_CONFIG_REG register accessor: an alias for `Reg`"] +pub type SPI_FIFO_CONFIG_REG = crate::Reg; +#[doc = "Spi fifo configuration register"] +pub mod spi_fifo_config_reg; +#[doc = "SPI_FIFO_HIGH_REG register accessor: an alias for `Reg`"] +pub type SPI_FIFO_HIGH_REG = crate::Reg; +#[doc = "Spi TX/RX High 16bit word"] +pub mod spi_fifo_high_reg; +#[doc = "SPI_FIFO_READ_REG register accessor: an alias for `Reg`"] +pub type SPI_FIFO_READ_REG = crate::Reg; +#[doc = "Spi RX fifo read register"] +pub mod spi_fifo_read_reg; +#[doc = "SPI_FIFO_STATUS_REG register accessor: an alias for `Reg`"] +pub type SPI_FIFO_STATUS_REG = crate::Reg; +#[doc = "SPI RX/TX fifo status register"] +pub mod spi_fifo_status_reg; +#[doc = "SPI_FIFO_WRITE_REG register accessor: an alias for `Reg`"] +pub type SPI_FIFO_WRITE_REG = crate::Reg; +#[doc = "Spi TX fifo wtite register"] +pub mod spi_fifo_write_reg; +#[doc = "SPI_IRQ_MASK_REG register accessor: an alias for `Reg`"] +pub type SPI_IRQ_MASK_REG = crate::Reg; +#[doc = "Spi interrupt mask register"] +pub mod spi_irq_mask_reg; +#[doc = "SPI_STATUS_REG register accessor: an alias for `Reg`"] +pub type SPI_STATUS_REG = crate::Reg; +#[doc = "Spi status register"] +pub mod spi_status_reg; +#[doc = "SPI_TXBUFFER_FORCE_H_REG register accessor: an alias for `Reg`"] +pub type SPI_TXBUFFER_FORCE_H_REG = + crate::Reg; +#[doc = "SPI TX buffer force high value"] +pub mod spi_txbuffer_force_h_reg; +#[doc = "SPI_TXBUFFER_FORCE_L_REG register accessor: an alias for `Reg`"] +pub type SPI_TXBUFFER_FORCE_L_REG = + crate::Reg; +#[doc = "SPI TX buffer force low value"] +pub mod spi_txbuffer_force_l_reg; diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_clock_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_clock_reg.rs new file mode 100644 index 0000000..fb92535 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_clock_reg.rs @@ -0,0 +1,150 @@ +#[doc = "Register `SPI_CLOCK_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_CLOCK_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_MASTER_CLK_MODE` reader - Should be always 1"] +pub struct SPI_MASTER_CLK_MODE_R(crate::FieldReader); +impl SPI_MASTER_CLK_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_MASTER_CLK_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_MASTER_CLK_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_MASTER_CLK_MODE` writer - Should be always 1"] +pub struct SPI_MASTER_CLK_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_MASTER_CLK_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `SPI_CLK_DIV` reader - Applicable only in master mode Defines the spi clock frequency in master only mode SPI_CLK = module_clk / 2*(SPI_CLK_DIV+1) when SPI_CLK_DIV not 0x7F if SPI_CLK_DIV=0x7F then SPI_CLK=module_clk"] +pub struct SPI_CLK_DIV_R(crate::FieldReader); +impl SPI_CLK_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_CLK_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_CLK_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_CLK_DIV` writer - Applicable only in master mode Defines the spi clock frequency in master only mode SPI_CLK = module_clk / 2*(SPI_CLK_DIV+1) when SPI_CLK_DIV not 0x7F if SPI_CLK_DIV=0x7F then SPI_CLK=module_clk"] +pub struct SPI_CLK_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_CLK_DIV_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x7f) | (value as u16 & 0x7f); + self.w + } +} +impl R { + #[doc = "Bit 7 - Should be always 1"] + #[inline(always)] + pub fn spi_master_clk_mode(&self) -> SPI_MASTER_CLK_MODE_R { + SPI_MASTER_CLK_MODE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 0:6 - Applicable only in master mode Defines the spi clock frequency in master only mode SPI_CLK = module_clk / 2*(SPI_CLK_DIV+1) when SPI_CLK_DIV not 0x7F if SPI_CLK_DIV=0x7F then SPI_CLK=module_clk"] + #[inline(always)] + pub fn spi_clk_div(&self) -> SPI_CLK_DIV_R { + SPI_CLK_DIV_R::new((self.bits & 0x7f) as u8) + } +} +impl W { + #[doc = "Bit 7 - Should be always 1"] + #[inline(always)] + pub fn spi_master_clk_mode(&mut self) -> SPI_MASTER_CLK_MODE_W { + SPI_MASTER_CLK_MODE_W { w: self } + } + #[doc = "Bits 0:6 - Applicable only in master mode Defines the spi clock frequency in master only mode SPI_CLK = module_clk / 2*(SPI_CLK_DIV+1) when SPI_CLK_DIV not 0x7F if SPI_CLK_DIV=0x7F then SPI_CLK=module_clk"] + #[inline(always)] + pub fn spi_clk_div(&mut self) -> SPI_CLK_DIV_W { + SPI_CLK_DIV_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi clock register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_clock_reg](index.html) module"] +pub struct SPI_CLOCK_REG_SPEC; +impl crate::RegisterSpec for SPI_CLOCK_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_clock_reg::R](R) reader structure"] +impl crate::Readable for SPI_CLOCK_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_clock_reg::W](W) writer structure"] +impl crate::Writable for SPI_CLOCK_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_CLOCK_REG to value 0"] +impl crate::Resettable for SPI_CLOCK_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_config_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_config_reg.rs new file mode 100644 index 0000000..efa9029 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_config_reg.rs @@ -0,0 +1,187 @@ +#[doc = "Register `SPI_CONFIG_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_CONFIG_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_SLAVE_EN` reader - 0 = SPI module master mode 1 = SPI module slave mode"] +pub struct SPI_SLAVE_EN_R(crate::FieldReader); +impl SPI_SLAVE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_SLAVE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_SLAVE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_SLAVE_EN` writer - 0 = SPI module master mode 1 = SPI module slave mode"] +pub struct SPI_SLAVE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_SLAVE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `SPI_WORD_LENGTH` reader - Define the spi word length = 1+ SPI_WORD_LENGTH (range 4 to 32)"] +pub struct SPI_WORD_LENGTH_R(crate::FieldReader); +impl SPI_WORD_LENGTH_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_WORD_LENGTH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_WORD_LENGTH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_WORD_LENGTH` writer - Define the spi word length = 1+ SPI_WORD_LENGTH (range 4 to 32)"] +pub struct SPI_WORD_LENGTH_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_WORD_LENGTH_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x1f << 2)) | ((value as u16 & 0x1f) << 2); + self.w + } +} +#[doc = "Field `SPI_MODE` reader - Define the spi mode (CPOL, CPHA) 0 = new data on falling, capture on rising, clk low in idle state 1 = new data on rising, capture on falling, Clk low in idle state 2 = new data on rising, capture on falling, Clk high in idle state 3 = new data on falling, capture on rising Clk high in idle state"] +pub struct SPI_MODE_R(crate::FieldReader); +impl SPI_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_MODE` writer - Define the spi mode (CPOL, CPHA) 0 = new data on falling, capture on rising, clk low in idle state 1 = new data on rising, capture on falling, Clk low in idle state 2 = new data on rising, capture on falling, Clk high in idle state 3 = new data on falling, capture on rising Clk high in idle state"] +pub struct SPI_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_MODE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 7 - 0 = SPI module master mode 1 = SPI module slave mode"] + #[inline(always)] + pub fn spi_slave_en(&self) -> SPI_SLAVE_EN_R { + SPI_SLAVE_EN_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 2:6 - Define the spi word length = 1+ SPI_WORD_LENGTH (range 4 to 32)"] + #[inline(always)] + pub fn spi_word_length(&self) -> SPI_WORD_LENGTH_R { + SPI_WORD_LENGTH_R::new(((self.bits >> 2) & 0x1f) as u8) + } + #[doc = "Bits 0:1 - Define the spi mode (CPOL, CPHA) 0 = new data on falling, capture on rising, clk low in idle state 1 = new data on rising, capture on falling, Clk low in idle state 2 = new data on rising, capture on falling, Clk high in idle state 3 = new data on falling, capture on rising Clk high in idle state"] + #[inline(always)] + pub fn spi_mode(&self) -> SPI_MODE_R { + SPI_MODE_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 7 - 0 = SPI module master mode 1 = SPI module slave mode"] + #[inline(always)] + pub fn spi_slave_en(&mut self) -> SPI_SLAVE_EN_W { + SPI_SLAVE_EN_W { w: self } + } + #[doc = "Bits 2:6 - Define the spi word length = 1+ SPI_WORD_LENGTH (range 4 to 32)"] + #[inline(always)] + pub fn spi_word_length(&mut self) -> SPI_WORD_LENGTH_W { + SPI_WORD_LENGTH_W { w: self } + } + #[doc = "Bits 0:1 - Define the spi mode (CPOL, CPHA) 0 = new data on falling, capture on rising, clk low in idle state 1 = new data on rising, capture on falling, Clk low in idle state 2 = new data on rising, capture on falling, Clk high in idle state 3 = new data on falling, capture on rising Clk high in idle state"] + #[inline(always)] + pub fn spi_mode(&mut self) -> SPI_MODE_W { + SPI_MODE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_config_reg](index.html) module"] +pub struct SPI_CONFIG_REG_SPEC; +impl crate::RegisterSpec for SPI_CONFIG_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_config_reg::R](R) reader structure"] +impl crate::Readable for SPI_CONFIG_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_config_reg::W](W) writer structure"] +impl crate::Writable for SPI_CONFIG_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_CONFIG_REG to value 0"] +impl crate::Resettable for SPI_CONFIG_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_cs_config_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_cs_config_reg.rs new file mode 100644 index 0000000..f065e35 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_cs_config_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `SPI_CS_CONFIG_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_CS_CONFIG_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_CS_SELECT` reader - Control the cs output in master mode 0 = none slave device selected 1 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS0 2 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS1 4 = selected slave device connected to GPIO with FUNC_MODE=GPIO"] +pub struct SPI_CS_SELECT_R(crate::FieldReader); +impl SPI_CS_SELECT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_CS_SELECT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_CS_SELECT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_CS_SELECT` writer - Control the cs output in master mode 0 = none slave device selected 1 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS0 2 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS1 4 = selected slave device connected to GPIO with FUNC_MODE=GPIO"] +pub struct SPI_CS_SELECT_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_CS_SELECT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !7) | (value as u16 & 7); + self.w + } +} +impl R { + #[doc = "Bits 0:2 - Control the cs output in master mode 0 = none slave device selected 1 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS0 2 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS1 4 = selected slave device connected to GPIO with FUNC_MODE=GPIO"] + #[inline(always)] + pub fn spi_cs_select(&self) -> SPI_CS_SELECT_R { + SPI_CS_SELECT_R::new((self.bits & 7) as u8) + } +} +impl W { + #[doc = "Bits 0:2 - Control the cs output in master mode 0 = none slave device selected 1 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS0 2 = selected slave device connected to GPIO with FUNC_MODE=SPI_CS1 4 = selected slave device connected to GPIO with FUNC_MODE=GPIO"] + #[inline(always)] + pub fn spi_cs_select(&mut self) -> SPI_CS_SELECT_W { + SPI_CS_SELECT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi cs configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_cs_config_reg](index.html) module"] +pub struct SPI_CS_CONFIG_REG_SPEC; +impl crate::RegisterSpec for SPI_CS_CONFIG_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_cs_config_reg::R](R) reader structure"] +impl crate::Readable for SPI_CS_CONFIG_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_cs_config_reg::W](W) writer structure"] +impl crate::Writable for SPI_CS_CONFIG_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_CS_CONFIG_REG to value 0"] +impl crate::Resettable for SPI_CS_CONFIG_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_ctrl_reg.rs new file mode 100644 index 0000000..9792959 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_ctrl_reg.rs @@ -0,0 +1,442 @@ +#[doc = "Register `SPI_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_SWAP_BYTES` reader - 0 = normal operation 1 = LSB and MSB are swaped in APB interface In case of 8bit spi interface, DMA/SPI can be configured in 16bit mode to off load the bus. Enabling SPI_SWAP_BYTES bytes will read/wrte correctly"] +pub struct SPI_SWAP_BYTES_R(crate::FieldReader); +impl SPI_SWAP_BYTES_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_SWAP_BYTES_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_SWAP_BYTES_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_SWAP_BYTES` writer - 0 = normal operation 1 = LSB and MSB are swaped in APB interface In case of 8bit spi interface, DMA/SPI can be configured in 16bit mode to off load the bus. Enabling SPI_SWAP_BYTES bytes will read/wrte correctly"] +pub struct SPI_SWAP_BYTES_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_SWAP_BYTES_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `SPI_CAPTURE_AT_NEXT_EDGE` reader - 0 = SPI captures data at correct clock edge 1 = SPI captures data at next clock edge. (only for Master mode and high clock)"] +pub struct SPI_CAPTURE_AT_NEXT_EDGE_R(crate::FieldReader); +impl SPI_CAPTURE_AT_NEXT_EDGE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_CAPTURE_AT_NEXT_EDGE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_CAPTURE_AT_NEXT_EDGE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_CAPTURE_AT_NEXT_EDGE` writer - 0 = SPI captures data at correct clock edge 1 = SPI captures data at next clock edge. (only for Master mode and high clock)"] +pub struct SPI_CAPTURE_AT_NEXT_EDGE_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_CAPTURE_AT_NEXT_EDGE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `SPI_FIFO_RESET` reader - 0 = Fifo normal operation 1 = Fifo in reset state"] +pub struct SPI_FIFO_RESET_R(crate::FieldReader); +impl SPI_FIFO_RESET_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_FIFO_RESET_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_FIFO_RESET_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_FIFO_RESET` writer - 0 = Fifo normal operation 1 = Fifo in reset state"] +pub struct SPI_FIFO_RESET_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_FIFO_RESET_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `SPI_DMA_RX_EN` reader - applicable only when SPI_RX_EN=1 0 = No DMA request for RX 1 = DMA request when SPI_STATUS_RX_FULL='1'"] +pub struct SPI_DMA_RX_EN_R(crate::FieldReader); +impl SPI_DMA_RX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_DMA_RX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_DMA_RX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_DMA_RX_EN` writer - applicable only when SPI_RX_EN=1 0 = No DMA request for RX 1 = DMA request when SPI_STATUS_RX_FULL='1'"] +pub struct SPI_DMA_RX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_DMA_RX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `SPI_DMA_TX_EN` reader - applicable only when SPI_TX_EN=1 0 = No DMA request for TX 1 = DMA request when SPI_STATUS_TX_EMPTY='1'"] +pub struct SPI_DMA_TX_EN_R(crate::FieldReader); +impl SPI_DMA_TX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_DMA_TX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_DMA_TX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_DMA_TX_EN` writer - applicable only when SPI_TX_EN=1 0 = No DMA request for TX 1 = DMA request when SPI_STATUS_TX_EMPTY='1'"] +pub struct SPI_DMA_TX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_DMA_TX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `SPI_RX_EN` reader - 0 = RX path is disabled 1 = RX path is enabled Note: if master clk async or spi mode=1 or spi mode=3 readonly is not supported"] +pub struct SPI_RX_EN_R(crate::FieldReader); +impl SPI_RX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_RX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_RX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_RX_EN` writer - 0 = RX path is disabled 1 = RX path is enabled Note: if master clk async or spi mode=1 or spi mode=3 readonly is not supported"] +pub struct SPI_RX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_RX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `SPI_TX_EN` reader - 0 = TX path is disabled 1 = TX path is enabled"] +pub struct SPI_TX_EN_R(crate::FieldReader); +impl SPI_TX_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_TX_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_TX_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_TX_EN` writer - 0 = TX path is disabled 1 = TX path is enabled"] +pub struct SPI_TX_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_TX_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `SPI_EN` reader - 0 = SPI module is disable 1 = SPI module is enable"] +pub struct SPI_EN_R(crate::FieldReader); +impl SPI_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_EN` writer - 0 = SPI module is disable 1 = SPI module is enable"] +pub struct SPI_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 7 - 0 = normal operation 1 = LSB and MSB are swaped in APB interface In case of 8bit spi interface, DMA/SPI can be configured in 16bit mode to off load the bus. Enabling SPI_SWAP_BYTES bytes will read/wrte correctly"] + #[inline(always)] + pub fn spi_swap_bytes(&self) -> SPI_SWAP_BYTES_R { + SPI_SWAP_BYTES_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - 0 = SPI captures data at correct clock edge 1 = SPI captures data at next clock edge. (only for Master mode and high clock)"] + #[inline(always)] + pub fn spi_capture_at_next_edge(&self) -> SPI_CAPTURE_AT_NEXT_EDGE_R { + SPI_CAPTURE_AT_NEXT_EDGE_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - 0 = Fifo normal operation 1 = Fifo in reset state"] + #[inline(always)] + pub fn spi_fifo_reset(&self) -> SPI_FIFO_RESET_R { + SPI_FIFO_RESET_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - applicable only when SPI_RX_EN=1 0 = No DMA request for RX 1 = DMA request when SPI_STATUS_RX_FULL='1'"] + #[inline(always)] + pub fn spi_dma_rx_en(&self) -> SPI_DMA_RX_EN_R { + SPI_DMA_RX_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - applicable only when SPI_TX_EN=1 0 = No DMA request for TX 1 = DMA request when SPI_STATUS_TX_EMPTY='1'"] + #[inline(always)] + pub fn spi_dma_tx_en(&self) -> SPI_DMA_TX_EN_R { + SPI_DMA_TX_EN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - 0 = RX path is disabled 1 = RX path is enabled Note: if master clk async or spi mode=1 or spi mode=3 readonly is not supported"] + #[inline(always)] + pub fn spi_rx_en(&self) -> SPI_RX_EN_R { + SPI_RX_EN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - 0 = TX path is disabled 1 = TX path is enabled"] + #[inline(always)] + pub fn spi_tx_en(&self) -> SPI_TX_EN_R { + SPI_TX_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 0 = SPI module is disable 1 = SPI module is enable"] + #[inline(always)] + pub fn spi_en(&self) -> SPI_EN_R { + SPI_EN_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 7 - 0 = normal operation 1 = LSB and MSB are swaped in APB interface In case of 8bit spi interface, DMA/SPI can be configured in 16bit mode to off load the bus. Enabling SPI_SWAP_BYTES bytes will read/wrte correctly"] + #[inline(always)] + pub fn spi_swap_bytes(&mut self) -> SPI_SWAP_BYTES_W { + SPI_SWAP_BYTES_W { w: self } + } + #[doc = "Bit 6 - 0 = SPI captures data at correct clock edge 1 = SPI captures data at next clock edge. (only for Master mode and high clock)"] + #[inline(always)] + pub fn spi_capture_at_next_edge(&mut self) -> SPI_CAPTURE_AT_NEXT_EDGE_W { + SPI_CAPTURE_AT_NEXT_EDGE_W { w: self } + } + #[doc = "Bit 5 - 0 = Fifo normal operation 1 = Fifo in reset state"] + #[inline(always)] + pub fn spi_fifo_reset(&mut self) -> SPI_FIFO_RESET_W { + SPI_FIFO_RESET_W { w: self } + } + #[doc = "Bit 4 - applicable only when SPI_RX_EN=1 0 = No DMA request for RX 1 = DMA request when SPI_STATUS_RX_FULL='1'"] + #[inline(always)] + pub fn spi_dma_rx_en(&mut self) -> SPI_DMA_RX_EN_W { + SPI_DMA_RX_EN_W { w: self } + } + #[doc = "Bit 3 - applicable only when SPI_TX_EN=1 0 = No DMA request for TX 1 = DMA request when SPI_STATUS_TX_EMPTY='1'"] + #[inline(always)] + pub fn spi_dma_tx_en(&mut self) -> SPI_DMA_TX_EN_W { + SPI_DMA_TX_EN_W { w: self } + } + #[doc = "Bit 2 - 0 = RX path is disabled 1 = RX path is enabled Note: if master clk async or spi mode=1 or spi mode=3 readonly is not supported"] + #[inline(always)] + pub fn spi_rx_en(&mut self) -> SPI_RX_EN_W { + SPI_RX_EN_W { w: self } + } + #[doc = "Bit 1 - 0 = TX path is disabled 1 = TX path is enabled"] + #[inline(always)] + pub fn spi_tx_en(&mut self) -> SPI_TX_EN_W { + SPI_TX_EN_W { w: self } + } + #[doc = "Bit 0 - 0 = SPI module is disable 1 = SPI module is enable"] + #[inline(always)] + pub fn spi_en(&mut self) -> SPI_EN_W { + SPI_EN_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_ctrl_reg](index.html) module"] +pub struct SPI_CTRL_REG_SPEC; +impl crate::RegisterSpec for SPI_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_ctrl_reg::R](R) reader structure"] +impl crate::Readable for SPI_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_ctrl_reg::W](W) writer structure"] +impl crate::Writable for SPI_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_CTRL_REG to value 0"] +impl crate::Resettable for SPI_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_config_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_config_reg.rs new file mode 100644 index 0000000..08ab6cd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_config_reg.rs @@ -0,0 +1,140 @@ +#[doc = "Register `SPI_FIFO_CONFIG_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_FIFO_CONFIG_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_RX_TL` reader - Receive FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the RX_FULL interrupt. IRQ is occurred when fifo level is more or equal to SPI_RX_TL+1. Fifo level is from 0 to 4"] +pub struct SPI_RX_TL_R(crate::FieldReader); +impl SPI_RX_TL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_RX_TL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_RX_TL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_RX_TL` writer - Receive FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the RX_FULL interrupt. IRQ is occurred when fifo level is more or equal to SPI_RX_TL+1. Fifo level is from 0 to 4"] +pub struct SPI_RX_TL_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_RX_TL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u16 & 0x0f) << 4); + self.w + } +} +#[doc = "Field `SPI_TX_TL` reader - Transmit FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the TX_EMPTY interrupt. IRQ is occurred when fifo level is less or equal to SPI_TX_TL. Fifo level is from 0 to 4"] +pub struct SPI_TX_TL_R(crate::FieldReader); +impl SPI_TX_TL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_TX_TL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_TX_TL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_TX_TL` writer - Transmit FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the TX_EMPTY interrupt. IRQ is occurred when fifo level is less or equal to SPI_TX_TL. Fifo level is from 0 to 4"] +pub struct SPI_TX_TL_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_TX_TL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 4:7 - Receive FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the RX_FULL interrupt. IRQ is occurred when fifo level is more or equal to SPI_RX_TL+1. Fifo level is from 0 to 4"] + #[inline(always)] + pub fn spi_rx_tl(&self) -> SPI_RX_TL_R { + SPI_RX_TL_R::new(((self.bits >> 4) & 0x0f) as u8) + } + #[doc = "Bits 0:3 - Transmit FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the TX_EMPTY interrupt. IRQ is occurred when fifo level is less or equal to SPI_TX_TL. Fifo level is from 0 to 4"] + #[inline(always)] + pub fn spi_tx_tl(&self) -> SPI_TX_TL_R { + SPI_TX_TL_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 4:7 - Receive FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the RX_FULL interrupt. IRQ is occurred when fifo level is more or equal to SPI_RX_TL+1. Fifo level is from 0 to 4"] + #[inline(always)] + pub fn spi_rx_tl(&mut self) -> SPI_RX_TL_W { + SPI_RX_TL_W { w: self } + } + #[doc = "Bits 0:3 - Transmit FIFO threshold level in bytes. Control the level of bytes in fifo that triggers the TX_EMPTY interrupt. IRQ is occurred when fifo level is less or equal to SPI_TX_TL. Fifo level is from 0 to 4"] + #[inline(always)] + pub fn spi_tx_tl(&mut self) -> SPI_TX_TL_W { + SPI_TX_TL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi fifo configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_fifo_config_reg](index.html) module"] +pub struct SPI_FIFO_CONFIG_REG_SPEC; +impl crate::RegisterSpec for SPI_FIFO_CONFIG_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_fifo_config_reg::R](R) reader structure"] +impl crate::Readable for SPI_FIFO_CONFIG_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_fifo_config_reg::W](W) writer structure"] +impl crate::Writable for SPI_FIFO_CONFIG_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_FIFO_CONFIG_REG to value 0"] +impl crate::Resettable for SPI_FIFO_CONFIG_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_high_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_high_reg.rs new file mode 100644 index 0000000..adad0af --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_high_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `SPI_FIFO_HIGH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_FIFO_HIGH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_FIFO_HIGH` reader - RX/TX fifo data. 16 MSb when spi word is larger than 16bits This register has to be written before the SPI_FIFO_WRITE_REG This register has to be read after the SPI_FIFO_READ_REG"] +pub struct SPI_FIFO_HIGH_R(crate::FieldReader); +impl SPI_FIFO_HIGH_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + SPI_FIFO_HIGH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_FIFO_HIGH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_FIFO_HIGH` writer - RX/TX fifo data. 16 MSb when spi word is larger than 16bits This register has to be written before the SPI_FIFO_WRITE_REG This register has to be read after the SPI_FIFO_READ_REG"] +pub struct SPI_FIFO_HIGH_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_FIFO_HIGH_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - RX/TX fifo data. 16 MSb when spi word is larger than 16bits This register has to be written before the SPI_FIFO_WRITE_REG This register has to be read after the SPI_FIFO_READ_REG"] + #[inline(always)] + pub fn spi_fifo_high(&self) -> SPI_FIFO_HIGH_R { + SPI_FIFO_HIGH_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - RX/TX fifo data. 16 MSb when spi word is larger than 16bits This register has to be written before the SPI_FIFO_WRITE_REG This register has to be read after the SPI_FIFO_READ_REG"] + #[inline(always)] + pub fn spi_fifo_high(&mut self) -> SPI_FIFO_HIGH_W { + SPI_FIFO_HIGH_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi TX/RX High 16bit word\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_fifo_high_reg](index.html) module"] +pub struct SPI_FIFO_HIGH_REG_SPEC; +impl crate::RegisterSpec for SPI_FIFO_HIGH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_fifo_high_reg::R](R) reader structure"] +impl crate::Readable for SPI_FIFO_HIGH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_fifo_high_reg::W](W) writer structure"] +impl crate::Writable for SPI_FIFO_HIGH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_FIFO_HIGH_REG to value 0"] +impl crate::Resettable for SPI_FIFO_HIGH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_read_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_read_reg.rs new file mode 100644 index 0000000..691ac08 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_read_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `SPI_FIFO_READ_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_FIFO_READ_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_FIFO_READ` reader - Read from RX fifo. Read access is permit only if SPI_STATUS_RX_EMPTY=0. Returns the 16 LSb"] +pub struct SPI_FIFO_READ_R(crate::FieldReader); +impl SPI_FIFO_READ_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + SPI_FIFO_READ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_FIFO_READ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Read from RX fifo. Read access is permit only if SPI_STATUS_RX_EMPTY=0. Returns the 16 LSb"] + #[inline(always)] + pub fn spi_fifo_read(&self) -> SPI_FIFO_READ_R { + SPI_FIFO_READ_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi RX fifo read register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_fifo_read_reg](index.html) module"] +pub struct SPI_FIFO_READ_REG_SPEC; +impl crate::RegisterSpec for SPI_FIFO_READ_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_fifo_read_reg::R](R) reader structure"] +impl crate::Readable for SPI_FIFO_READ_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_fifo_read_reg::W](W) writer structure"] +impl crate::Writable for SPI_FIFO_READ_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_FIFO_READ_REG to value 0"] +impl crate::Resettable for SPI_FIFO_READ_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_status_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_status_reg.rs new file mode 100644 index 0000000..e0fab6a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_status_reg.rs @@ -0,0 +1,186 @@ +#[doc = "Register `SPI_FIFO_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_FIFO_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_TRANSACTION_ACTIVE` reader - In master mode 0 = spi transaction is inactive 1 = spi transaction is active"] +pub struct SPI_TRANSACTION_ACTIVE_R(crate::FieldReader); +impl SPI_TRANSACTION_ACTIVE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_TRANSACTION_ACTIVE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_TRANSACTION_ACTIVE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_RX_FIFO_OVFL` reader - When 1, receive data is not written to fifo because fifo was full and interrupt is generated. It clears with SPI_CTRL_REG.SPI_FIFO_RESET"] +pub struct SPI_RX_FIFO_OVFL_R(crate::FieldReader); +impl SPI_RX_FIFO_OVFL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_RX_FIFO_OVFL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_RX_FIFO_OVFL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_STATUS_TX_FULL` reader - 0 = TX fifo is not full 1 = TX fifo is full"] +pub struct SPI_STATUS_TX_FULL_R(crate::FieldReader); +impl SPI_STATUS_TX_FULL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_STATUS_TX_FULL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_STATUS_TX_FULL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_STATUS_RX_EMPTY` reader - 0 = RX fifo is not empty 1 = RX fifo is empty"] +pub struct SPI_STATUS_RX_EMPTY_R(crate::FieldReader); +impl SPI_STATUS_RX_EMPTY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_STATUS_RX_EMPTY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_STATUS_RX_EMPTY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_TX_FIFO_LEVEL` reader - Gives the number of bytes in TX fifo"] +pub struct SPI_TX_FIFO_LEVEL_R(crate::FieldReader); +impl SPI_TX_FIFO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_TX_FIFO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_TX_FIFO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_RX_FIFO_LEVEL` reader - Gives the number of bytes in RX fifo"] +pub struct SPI_RX_FIFO_LEVEL_R(crate::FieldReader); +impl SPI_RX_FIFO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SPI_RX_FIFO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_RX_FIFO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 15 - In master mode 0 = spi transaction is inactive 1 = spi transaction is active"] + #[inline(always)] + pub fn spi_transaction_active(&self) -> SPI_TRANSACTION_ACTIVE_R { + SPI_TRANSACTION_ACTIVE_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14 - When 1, receive data is not written to fifo because fifo was full and interrupt is generated. It clears with SPI_CTRL_REG.SPI_FIFO_RESET"] + #[inline(always)] + pub fn spi_rx_fifo_ovfl(&self) -> SPI_RX_FIFO_OVFL_R { + SPI_RX_FIFO_OVFL_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13 - 0 = TX fifo is not full 1 = TX fifo is full"] + #[inline(always)] + pub fn spi_status_tx_full(&self) -> SPI_STATUS_TX_FULL_R { + SPI_STATUS_TX_FULL_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12 - 0 = RX fifo is not empty 1 = RX fifo is empty"] + #[inline(always)] + pub fn spi_status_rx_empty(&self) -> SPI_STATUS_RX_EMPTY_R { + SPI_STATUS_RX_EMPTY_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bits 6:11 - Gives the number of bytes in TX fifo"] + #[inline(always)] + pub fn spi_tx_fifo_level(&self) -> SPI_TX_FIFO_LEVEL_R { + SPI_TX_FIFO_LEVEL_R::new(((self.bits >> 6) & 0x3f) as u8) + } + #[doc = "Bits 0:5 - Gives the number of bytes in RX fifo"] + #[inline(always)] + pub fn spi_rx_fifo_level(&self) -> SPI_RX_FIFO_LEVEL_R { + SPI_RX_FIFO_LEVEL_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "SPI RX/TX fifo status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_fifo_status_reg](index.html) module"] +pub struct SPI_FIFO_STATUS_REG_SPEC; +impl crate::RegisterSpec for SPI_FIFO_STATUS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_fifo_status_reg::R](R) reader structure"] +impl crate::Readable for SPI_FIFO_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_fifo_status_reg::W](W) writer structure"] +impl crate::Writable for SPI_FIFO_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_FIFO_STATUS_REG to value 0x1000"] +impl crate::Resettable for SPI_FIFO_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x1000 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_write_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_write_reg.rs new file mode 100644 index 0000000..d93abba --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_fifo_write_reg.rs @@ -0,0 +1,81 @@ +#[doc = "Register `SPI_FIFO_WRITE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_FIFO_WRITE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_FIFO_WRITE` writer - Write to TX fifo. Write access is permit only if SPI_STATUS_TX_FULL is 0"] +pub struct SPI_FIFO_WRITE_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_FIFO_WRITE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl W { + #[doc = "Bits 0:15 - Write to TX fifo. Write access is permit only if SPI_STATUS_TX_FULL is 0"] + #[inline(always)] + pub fn spi_fifo_write(&mut self) -> SPI_FIFO_WRITE_W { + SPI_FIFO_WRITE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi TX fifo wtite register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_fifo_write_reg](index.html) module"] +pub struct SPI_FIFO_WRITE_REG_SPEC; +impl crate::RegisterSpec for SPI_FIFO_WRITE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_fifo_write_reg::R](R) reader structure"] +impl crate::Readable for SPI_FIFO_WRITE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_fifo_write_reg::W](W) writer structure"] +impl crate::Writable for SPI_FIFO_WRITE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_FIFO_WRITE_REG to value 0"] +impl crate::Resettable for SPI_FIFO_WRITE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_irq_mask_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_irq_mask_reg.rs new file mode 100644 index 0000000..17fdc89 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_irq_mask_reg.rs @@ -0,0 +1,160 @@ +#[doc = "Register `SPI_IRQ_MASK_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_IRQ_MASK_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_IRQ_MASK_RX_FULL` reader - 0 = FIFO RX full irq is masked 1 = FIFO RX full irq is enabled"] +pub struct SPI_IRQ_MASK_RX_FULL_R(crate::FieldReader); +impl SPI_IRQ_MASK_RX_FULL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_IRQ_MASK_RX_FULL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_IRQ_MASK_RX_FULL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_IRQ_MASK_RX_FULL` writer - 0 = FIFO RX full irq is masked 1 = FIFO RX full irq is enabled"] +pub struct SPI_IRQ_MASK_RX_FULL_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_IRQ_MASK_RX_FULL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `SPI_IRQ_MASK_TX_EMPTY` reader - 0 = FIFO TX empty irq is masked 1 = FIFO TX empy irq is enabled"] +pub struct SPI_IRQ_MASK_TX_EMPTY_R(crate::FieldReader); +impl SPI_IRQ_MASK_TX_EMPTY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_IRQ_MASK_TX_EMPTY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_IRQ_MASK_TX_EMPTY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_IRQ_MASK_TX_EMPTY` writer - 0 = FIFO TX empty irq is masked 1 = FIFO TX empy irq is enabled"] +pub struct SPI_IRQ_MASK_TX_EMPTY_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_IRQ_MASK_TX_EMPTY_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1 - 0 = FIFO RX full irq is masked 1 = FIFO RX full irq is enabled"] + #[inline(always)] + pub fn spi_irq_mask_rx_full(&self) -> SPI_IRQ_MASK_RX_FULL_R { + SPI_IRQ_MASK_RX_FULL_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 0 = FIFO TX empty irq is masked 1 = FIFO TX empy irq is enabled"] + #[inline(always)] + pub fn spi_irq_mask_tx_empty(&self) -> SPI_IRQ_MASK_TX_EMPTY_R { + SPI_IRQ_MASK_TX_EMPTY_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 1 - 0 = FIFO RX full irq is masked 1 = FIFO RX full irq is enabled"] + #[inline(always)] + pub fn spi_irq_mask_rx_full(&mut self) -> SPI_IRQ_MASK_RX_FULL_W { + SPI_IRQ_MASK_RX_FULL_W { w: self } + } + #[doc = "Bit 0 - 0 = FIFO TX empty irq is masked 1 = FIFO TX empy irq is enabled"] + #[inline(always)] + pub fn spi_irq_mask_tx_empty(&mut self) -> SPI_IRQ_MASK_TX_EMPTY_W { + SPI_IRQ_MASK_TX_EMPTY_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_irq_mask_reg](index.html) module"] +pub struct SPI_IRQ_MASK_REG_SPEC; +impl crate::RegisterSpec for SPI_IRQ_MASK_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_irq_mask_reg::R](R) reader structure"] +impl crate::Readable for SPI_IRQ_MASK_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_irq_mask_reg::W](W) writer structure"] +impl crate::Writable for SPI_IRQ_MASK_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_IRQ_MASK_REG to value 0"] +impl crate::Resettable for SPI_IRQ_MASK_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_status_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_status_reg.rs new file mode 100644 index 0000000..7c86919 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_status_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `SPI_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_STATUS_RX_FULL` reader - Auto clear 0 = RX fifo level is less than SPI_RX_TL+1 1 = RX fifo level is more or equal to SPI_RX_TL+1"] +pub struct SPI_STATUS_RX_FULL_R(crate::FieldReader); +impl SPI_STATUS_RX_FULL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_STATUS_RX_FULL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_STATUS_RX_FULL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SPI_STATUS_TX_EMPTY` reader - Auto clear 0 = TX fifo level is larger than SPI_TX_TL 1 = TX fifo level is less or equal to SPI_TX_TL"] +pub struct SPI_STATUS_TX_EMPTY_R(crate::FieldReader); +impl SPI_STATUS_TX_EMPTY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SPI_STATUS_TX_EMPTY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SPI_STATUS_TX_EMPTY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 1 - Auto clear 0 = RX fifo level is less than SPI_RX_TL+1 1 = RX fifo level is more or equal to SPI_RX_TL+1"] + #[inline(always)] + pub fn spi_status_rx_full(&self) -> SPI_STATUS_RX_FULL_R { + SPI_STATUS_RX_FULL_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Auto clear 0 = TX fifo level is larger than SPI_TX_TL 1 = TX fifo level is less or equal to SPI_TX_TL"] + #[inline(always)] + pub fn spi_status_tx_empty(&self) -> SPI_STATUS_TX_EMPTY_R { + SPI_STATUS_TX_EMPTY_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Spi status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_status_reg](index.html) module"] +pub struct SPI_STATUS_REG_SPEC; +impl crate::RegisterSpec for SPI_STATUS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_status_reg::R](R) reader structure"] +impl crate::Readable for SPI_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_status_reg::W](W) writer structure"] +impl crate::Writable for SPI_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_STATUS_REG to value 0x01"] +impl crate::Resettable for SPI_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_h_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_h_reg.rs new file mode 100644 index 0000000..87c47bd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_h_reg.rs @@ -0,0 +1,81 @@ +#[doc = "Register `SPI_TXBUFFER_FORCE_H_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_TXBUFFER_FORCE_H_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_TXBUFFER_FORCE_H` writer - Write directly the tx buffer (2 MSB). It must to be used only in slave mode. This register has to be written before the SPI_FIFO_WRITE_REG"] +pub struct SPI_TXBUFFER_FORCE_H_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_TXBUFFER_FORCE_H_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl W { + #[doc = "Bits 0:15 - Write directly the tx buffer (2 MSB). It must to be used only in slave mode. This register has to be written before the SPI_FIFO_WRITE_REG"] + #[inline(always)] + pub fn spi_txbuffer_force_h(&mut self) -> SPI_TXBUFFER_FORCE_H_W { + SPI_TXBUFFER_FORCE_H_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "SPI TX buffer force high value\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_txbuffer_force_h_reg](index.html) module"] +pub struct SPI_TXBUFFER_FORCE_H_REG_SPEC; +impl crate::RegisterSpec for SPI_TXBUFFER_FORCE_H_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_txbuffer_force_h_reg::R](R) reader structure"] +impl crate::Readable for SPI_TXBUFFER_FORCE_H_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_txbuffer_force_h_reg::W](W) writer structure"] +impl crate::Writable for SPI_TXBUFFER_FORCE_H_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_TXBUFFER_FORCE_H_REG to value 0"] +impl crate::Resettable for SPI_TXBUFFER_FORCE_H_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_l_reg.rs b/bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_l_reg.rs new file mode 100644 index 0000000..d925b05 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/spi/spi_txbuffer_force_l_reg.rs @@ -0,0 +1,81 @@ +#[doc = "Register `SPI_TXBUFFER_FORCE_L_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `SPI_TXBUFFER_FORCE_L_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SPI_TXBUFFER_FORCE_L` writer - Write directly the tx buffer (2 LSB). It must to be used only in slave mode"] +pub struct SPI_TXBUFFER_FORCE_L_W<'a> { + w: &'a mut W, +} +impl<'a> SPI_TXBUFFER_FORCE_L_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl W { + #[doc = "Bits 0:15 - Write directly the tx buffer (2 LSB). It must to be used only in slave mode"] + #[inline(always)] + pub fn spi_txbuffer_force_l(&mut self) -> SPI_TXBUFFER_FORCE_L_W { + SPI_TXBUFFER_FORCE_L_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "SPI TX buffer force low value\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spi_txbuffer_force_l_reg](index.html) module"] +pub struct SPI_TXBUFFER_FORCE_L_REG_SPEC; +impl crate::RegisterSpec for SPI_TXBUFFER_FORCE_L_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [spi_txbuffer_force_l_reg::R](R) reader structure"] +impl crate::Readable for SPI_TXBUFFER_FORCE_L_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [spi_txbuffer_force_l_reg::W](W) writer structure"] +impl crate::Writable for SPI_TXBUFFER_FORCE_L_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets SPI_TXBUFFER_FORCE_L_REG to value 0"] +impl crate::Resettable for SPI_TXBUFFER_FORCE_L_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/sys_tick.rs b/bitbox02-bt/vendor/da14531/src/sys_tick.rs new file mode 100644 index 0000000..2b531ad --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_tick.rs @@ -0,0 +1,28 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - SysTick Control and Status register"] + pub ctrl: crate::Reg, + #[doc = "0x04 - SysTick Reload value register"] + pub load: crate::Reg, + #[doc = "0x08 - SysTick Current value register"] + pub val: crate::Reg, + #[doc = "0x0c - SysTick Calibration value register"] + pub calib: crate::Reg, +} +#[doc = "CTRL register accessor: an alias for `Reg`"] +pub type CTRL = crate::Reg; +#[doc = "SysTick Control and Status register"] +pub mod ctrl; +#[doc = "LOAD register accessor: an alias for `Reg`"] +pub type LOAD = crate::Reg; +#[doc = "SysTick Reload value register"] +pub mod load; +#[doc = "VAL register accessor: an alias for `Reg`"] +pub type VAL = crate::Reg; +#[doc = "SysTick Current value register"] +pub mod val; +#[doc = "CALIB register accessor: an alias for `Reg`"] +pub type CALIB = crate::Reg; +#[doc = "SysTick Calibration value register"] +pub mod calib; diff --git a/bitbox02-bt/vendor/da14531/src/sys_tick/calib.rs b/bitbox02-bt/vendor/da14531/src/sys_tick/calib.rs new file mode 100644 index 0000000..df4a23a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_tick/calib.rs @@ -0,0 +1,95 @@ +#[doc = "Register `CALIB` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Field `TENMS` reader - TENMS\\[23:0\\] +bits (Calibration value)"] +pub struct TENMS_R(crate::FieldReader); +impl TENMS_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + TENMS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TENMS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SKEW` reader - Indicates whether the TENMS value is exact"] +pub struct SKEW_R(crate::FieldReader); +impl SKEW_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SKEW_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SKEW_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `NOREF` reader - Indicates that a separate reference clock is provided"] +pub struct NOREF_R(crate::FieldReader); +impl NOREF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + NOREF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for NOREF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:23 - TENMS\\[23:0\\] +bits (Calibration value)"] + #[inline(always)] + pub fn tenms(&self) -> TENMS_R { + TENMS_R::new((self.bits & 0x00ff_ffff) as u32) + } + #[doc = "Bit 30 - Indicates whether the TENMS value is exact"] + #[inline(always)] + pub fn skew(&self) -> SKEW_R { + SKEW_R::new(((self.bits >> 30) & 1) != 0) + } + #[doc = "Bit 31 - Indicates that a separate reference clock is provided"] + #[inline(always)] + pub fn noref(&self) -> NOREF_R { + NOREF_R::new(((self.bits >> 31) & 1) != 0) + } +} +#[doc = "SysTick Calibration value register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [calib](index.html) module"] +pub struct CALIB_SPEC; +impl crate::RegisterSpec for CALIB_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [calib::R](R) reader structure"] +impl crate::Readable for CALIB_SPEC { + type Reader = R; +} +#[doc = "`reset()` method sets CALIB to value 0x2328"] +impl crate::Resettable for CALIB_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x2328 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/sys_tick/ctrl.rs b/bitbox02-bt/vendor/da14531/src/sys_tick/ctrl.rs new file mode 100644 index 0000000..39906d2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_tick/ctrl.rs @@ -0,0 +1,254 @@ +#[doc = "Register `CTRL` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `CTRL` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `ENABLE` reader - SysTick Counter enable"] +pub struct ENABLE_R(crate::FieldReader); +impl ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ENABLE` writer - SysTick Counter enable"] +pub struct ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +#[doc = "Field `TICKINT` reader - SysTick exception request enable"] +pub struct TICKINT_R(crate::FieldReader); +impl TICKINT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TICKINT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TICKINT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TICKINT` writer - SysTick exception request enable"] +pub struct TICKINT_W<'a> { + w: &'a mut W, +} +impl<'a> TICKINT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `CLKSOURCE` reader - Clock source selection"] +pub struct CLKSOURCE_R(crate::FieldReader); +impl CLKSOURCE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + CLKSOURCE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CLKSOURCE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CLKSOURCE` writer - Clock source selection"] +pub struct CLKSOURCE_W<'a> { + w: &'a mut W, +} +impl<'a> CLKSOURCE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `COUNTFLAG` reader - Timer counted to 0 since last time this was read"] +pub struct COUNTFLAG_R(crate::FieldReader); +impl COUNTFLAG_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + COUNTFLAG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for COUNTFLAG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `COUNTFLAG` writer - Timer counted to 0 since last time this was read"] +pub struct COUNTFLAG_W<'a> { + w: &'a mut W, +} +impl<'a> COUNTFLAG_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +impl R { + #[doc = "Bit 0 - SysTick Counter enable"] + #[inline(always)] + pub fn enable(&self) -> ENABLE_R { + ENABLE_R::new((self.bits & 1) != 0) + } + #[doc = "Bit 1 - SysTick exception request enable"] + #[inline(always)] + pub fn tickint(&self) -> TICKINT_R { + TICKINT_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 2 - Clock source selection"] + #[inline(always)] + pub fn clksource(&self) -> CLKSOURCE_R { + CLKSOURCE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 16 - Timer counted to 0 since last time this was read"] + #[inline(always)] + pub fn countflag(&self) -> COUNTFLAG_R { + COUNTFLAG_R::new(((self.bits >> 16) & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - SysTick Counter enable"] + #[inline(always)] + pub fn enable(&mut self) -> ENABLE_W { + ENABLE_W { w: self } + } + #[doc = "Bit 1 - SysTick exception request enable"] + #[inline(always)] + pub fn tickint(&mut self) -> TICKINT_W { + TICKINT_W { w: self } + } + #[doc = "Bit 2 - Clock source selection"] + #[inline(always)] + pub fn clksource(&mut self) -> CLKSOURCE_W { + CLKSOURCE_W { w: self } + } + #[doc = "Bit 16 - Timer counted to 0 since last time this was read"] + #[inline(always)] + pub fn countflag(&mut self) -> COUNTFLAG_W { + COUNTFLAG_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "SysTick Control and Status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ctrl](index.html) module"] +pub struct CTRL_SPEC; +impl crate::RegisterSpec for CTRL_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [ctrl::R](R) reader structure"] +impl crate::Readable for CTRL_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [ctrl::W](W) writer structure"] +impl crate::Writable for CTRL_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets CTRL to value 0x04"] +impl crate::Resettable for CTRL_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x04 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/sys_tick/load.rs b/bitbox02-bt/vendor/da14531/src/sys_tick/load.rs new file mode 100644 index 0000000..628bb7f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_tick/load.rs @@ -0,0 +1,107 @@ +#[doc = "Register `LOAD` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `LOAD` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RELOAD` reader - RELOAD\\[23:0\\] +bits (Reload value)"] +pub struct RELOAD_R(crate::FieldReader); +impl RELOAD_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + RELOAD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RELOAD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RELOAD` writer - RELOAD\\[23:0\\] +bits (Reload value)"] +pub struct RELOAD_W<'a> { + w: &'a mut W, +} +impl<'a> RELOAD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !0x00ff_ffff) | (value as u32 & 0x00ff_ffff); + self.w + } +} +impl R { + #[doc = "Bits 0:23 - RELOAD\\[23:0\\] +bits (Reload value)"] + #[inline(always)] + pub fn reload(&self) -> RELOAD_R { + RELOAD_R::new((self.bits & 0x00ff_ffff) as u32) + } +} +impl W { + #[doc = "Bits 0:23 - RELOAD\\[23:0\\] +bits (Reload value)"] + #[inline(always)] + pub fn reload(&mut self) -> RELOAD_W { + RELOAD_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "SysTick Reload value register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [load](index.html) module"] +pub struct LOAD_SPEC; +impl crate::RegisterSpec for LOAD_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [load::R](R) reader structure"] +impl crate::Readable for LOAD_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [load::W](W) writer structure"] +impl crate::Writable for LOAD_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets LOAD to value 0"] +impl crate::Resettable for LOAD_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/sys_tick/val.rs b/bitbox02-bt/vendor/da14531/src/sys_tick/val.rs new file mode 100644 index 0000000..719333d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_tick/val.rs @@ -0,0 +1,107 @@ +#[doc = "Register `VAL` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `VAL` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CURRENT` reader - CURRENT\\[23:0\\] +bits (Current counter value)"] +pub struct CURRENT_R(crate::FieldReader); +impl CURRENT_R { + #[inline(always)] + pub(crate) fn new(bits: u32) -> Self { + CURRENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CURRENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `CURRENT` writer - CURRENT\\[23:0\\] +bits (Current counter value)"] +pub struct CURRENT_W<'a> { + w: &'a mut W, +} +impl<'a> CURRENT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits = (self.w.bits & !0x00ff_ffff) | (value as u32 & 0x00ff_ffff); + self.w + } +} +impl R { + #[doc = "Bits 0:23 - CURRENT\\[23:0\\] +bits (Current counter value)"] + #[inline(always)] + pub fn current(&self) -> CURRENT_R { + CURRENT_R::new((self.bits & 0x00ff_ffff) as u32) + } +} +impl W { + #[doc = "Bits 0:23 - CURRENT\\[23:0\\] +bits (Current counter value)"] + #[inline(always)] + pub fn current(&mut self) -> CURRENT_W { + CURRENT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "SysTick Current value register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [val](index.html) module"] +pub struct VAL_SPEC; +impl crate::RegisterSpec for VAL_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [val::R](R) reader structure"] +impl crate::Readable for VAL_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [val::W](W) writer structure"] +impl crate::Writable for VAL_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets VAL to value 0"] +impl crate::Resettable for VAL_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/sys_wdog.rs b/bitbox02-bt/vendor/da14531/src/sys_wdog.rs new file mode 100644 index 0000000..0bdca0f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_wdog.rs @@ -0,0 +1,16 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Watchdog timer register."] + pub watchdog_reg: crate::Reg, + #[doc = "0x02 - Watchdog control register."] + pub watchdog_ctrl_reg: crate::Reg, +} +#[doc = "WATCHDOG_CTRL_REG register accessor: an alias for `Reg`"] +pub type WATCHDOG_CTRL_REG = crate::Reg; +#[doc = "Watchdog control register."] +pub mod watchdog_ctrl_reg; +#[doc = "WATCHDOG_REG register accessor: an alias for `Reg`"] +pub type WATCHDOG_REG = crate::Reg; +#[doc = "Watchdog timer register."] +pub mod watchdog_reg; diff --git a/bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_ctrl_reg.rs new file mode 100644 index 0000000..4745794 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_ctrl_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `WATCHDOG_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WATCHDOG_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `NMI_RST` reader - 0 = Watchdog timer generates NMI at value 0, and WDOG (SYS) reset at <=-16. Timer can be frozen /resumed using SET_FREEZE_REG\\[FRZ_WDOG\\]/ RESET_FREEZE_REG\\[FRZ_WDOG\\]. 1 = Watchdog timer generates a WDOG (SYS) reset at value 0 and can not be frozen by Software. Note that this bit can only be set to 1 by SW and only be reset with a WDOG (SYS) reset or SW reset. The watchdog is always frozen when the Cortex-M0 is halted in DEBUG State."] +pub struct NMI_RST_R(crate::FieldReader); +impl NMI_RST_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + NMI_RST_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for NMI_RST_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `NMI_RST` writer - 0 = Watchdog timer generates NMI at value 0, and WDOG (SYS) reset at <=-16. Timer can be frozen /resumed using SET_FREEZE_REG\\[FRZ_WDOG\\]/ RESET_FREEZE_REG\\[FRZ_WDOG\\]. 1 = Watchdog timer generates a WDOG (SYS) reset at value 0 and can not be frozen by Software. Note that this bit can only be set to 1 by SW and only be reset with a WDOG (SYS) reset or SW reset. The watchdog is always frozen when the Cortex-M0 is halted in DEBUG State."] +pub struct NMI_RST_W<'a> { + w: &'a mut W, +} +impl<'a> NMI_RST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - 0 = Watchdog timer generates NMI at value 0, and WDOG (SYS) reset at <=-16. Timer can be frozen /resumed using SET_FREEZE_REG\\[FRZ_WDOG\\]/ RESET_FREEZE_REG\\[FRZ_WDOG\\]. 1 = Watchdog timer generates a WDOG (SYS) reset at value 0 and can not be frozen by Software. Note that this bit can only be set to 1 by SW and only be reset with a WDOG (SYS) reset or SW reset. The watchdog is always frozen when the Cortex-M0 is halted in DEBUG State."] + #[inline(always)] + pub fn nmi_rst(&self) -> NMI_RST_R { + NMI_RST_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - 0 = Watchdog timer generates NMI at value 0, and WDOG (SYS) reset at <=-16. Timer can be frozen /resumed using SET_FREEZE_REG\\[FRZ_WDOG\\]/ RESET_FREEZE_REG\\[FRZ_WDOG\\]. 1 = Watchdog timer generates a WDOG (SYS) reset at value 0 and can not be frozen by Software. Note that this bit can only be set to 1 by SW and only be reset with a WDOG (SYS) reset or SW reset. The watchdog is always frozen when the Cortex-M0 is halted in DEBUG State."] + #[inline(always)] + pub fn nmi_rst(&mut self) -> NMI_RST_W { + NMI_RST_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Watchdog control register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [watchdog_ctrl_reg](index.html) module"] +pub struct WATCHDOG_CTRL_REG_SPEC; +impl crate::RegisterSpec for WATCHDOG_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [watchdog_ctrl_reg::R](R) reader structure"] +impl crate::Readable for WATCHDOG_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [watchdog_ctrl_reg::W](W) writer structure"] +impl crate::Writable for WATCHDOG_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WATCHDOG_CTRL_REG to value 0"] +impl crate::Resettable for WATCHDOG_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_reg.rs b/bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_reg.rs new file mode 100644 index 0000000..53e61eb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/sys_wdog/watchdog_reg.rs @@ -0,0 +1,175 @@ +#[doc = "Register `WATCHDOG_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WATCHDOG_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WDOG_WEN` writer - 0000.000 = Write enable for Watchdog timer else Write disable. This filter prevents unintentional presetting the watchdog with a SW run-away."] +pub struct WDOG_WEN_W<'a> { + w: &'a mut W, +} +impl<'a> WDOG_WEN_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x7f << 9)) | ((value as u16 & 0x7f) << 9); + self.w + } +} +#[doc = "Field `WDOG_VAL_NEG` reader - 0 = Watchdog timer value is positive. 1 = Watchdog timer value is negative."] +pub struct WDOG_VAL_NEG_R(crate::FieldReader); +impl WDOG_VAL_NEG_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WDOG_VAL_NEG_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WDOG_VAL_NEG_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WDOG_VAL_NEG` writer - 0 = Watchdog timer value is positive. 1 = Watchdog timer value is negative."] +pub struct WDOG_VAL_NEG_W<'a> { + w: &'a mut W, +} +impl<'a> WDOG_VAL_NEG_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `WDOG_VAL` reader - Write: Watchdog timer reload value. Note that all bits 15-9 must be 0 to reload this register. Read: Actual Watchdog timer value. Decremented by 1 every 10.24 msec. Bit 8 indicates a negative counter value. 2, 1, 0, 1FF16, 1FE16 etc. An NMI or WDOG (SYS) reset is generated under the following conditions: If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 0 then If WDOG_VAL = 0 -> NMI (Non Maskable Interrupt) if WDOG_VAL = 1F016 -> WDOG reset -> reload FF16 If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 1 then if WDOG_VAL <= 0 -> WDOG reset -> reload FF16"] +pub struct WDOG_VAL_R(crate::FieldReader); +impl WDOG_VAL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WDOG_VAL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WDOG_VAL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WDOG_VAL` writer - Write: Watchdog timer reload value. Note that all bits 15-9 must be 0 to reload this register. Read: Actual Watchdog timer value. Decremented by 1 every 10.24 msec. Bit 8 indicates a negative counter value. 2, 1, 0, 1FF16, 1FE16 etc. An NMI or WDOG (SYS) reset is generated under the following conditions: If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 0 then If WDOG_VAL = 0 -> NMI (Non Maskable Interrupt) if WDOG_VAL = 1F016 -> WDOG reset -> reload FF16 If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 1 then if WDOG_VAL <= 0 -> WDOG reset -> reload FF16"] +pub struct WDOG_VAL_W<'a> { + w: &'a mut W, +} +impl<'a> WDOG_VAL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bit 8 - 0 = Watchdog timer value is positive. 1 = Watchdog timer value is negative."] + #[inline(always)] + pub fn wdog_val_neg(&self) -> WDOG_VAL_NEG_R { + WDOG_VAL_NEG_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bits 0:7 - Write: Watchdog timer reload value. Note that all bits 15-9 must be 0 to reload this register. Read: Actual Watchdog timer value. Decremented by 1 every 10.24 msec. Bit 8 indicates a negative counter value. 2, 1, 0, 1FF16, 1FE16 etc. An NMI or WDOG (SYS) reset is generated under the following conditions: If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 0 then If WDOG_VAL = 0 -> NMI (Non Maskable Interrupt) if WDOG_VAL = 1F016 -> WDOG reset -> reload FF16 If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 1 then if WDOG_VAL <= 0 -> WDOG reset -> reload FF16"] + #[inline(always)] + pub fn wdog_val(&self) -> WDOG_VAL_R { + WDOG_VAL_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 9:15 - 0000.000 = Write enable for Watchdog timer else Write disable. This filter prevents unintentional presetting the watchdog with a SW run-away."] + #[inline(always)] + pub fn wdog_wen(&mut self) -> WDOG_WEN_W { + WDOG_WEN_W { w: self } + } + #[doc = "Bit 8 - 0 = Watchdog timer value is positive. 1 = Watchdog timer value is negative."] + #[inline(always)] + pub fn wdog_val_neg(&mut self) -> WDOG_VAL_NEG_W { + WDOG_VAL_NEG_W { w: self } + } + #[doc = "Bits 0:7 - Write: Watchdog timer reload value. Note that all bits 15-9 must be 0 to reload this register. Read: Actual Watchdog timer value. Decremented by 1 every 10.24 msec. Bit 8 indicates a negative counter value. 2, 1, 0, 1FF16, 1FE16 etc. An NMI or WDOG (SYS) reset is generated under the following conditions: If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 0 then If WDOG_VAL = 0 -> NMI (Non Maskable Interrupt) if WDOG_VAL = 1F016 -> WDOG reset -> reload FF16 If WATCHDOG_CTRL_REG\\[NMI_RST\\] += 1 then if WDOG_VAL <= 0 -> WDOG reset -> reload FF16"] + #[inline(always)] + pub fn wdog_val(&mut self) -> WDOG_VAL_W { + WDOG_VAL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Watchdog timer register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [watchdog_reg](index.html) module"] +pub struct WATCHDOG_REG_SPEC; +impl crate::RegisterSpec for WATCHDOG_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [watchdog_reg::R](R) reader structure"] +impl crate::Readable for WATCHDOG_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [watchdog_reg::W](W) writer structure"] +impl crate::Writable for WATCHDOG_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WATCHDOG_REG to value 0xff"] +impl crate::Resettable for WATCHDOG_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0xff + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0.rs b/bitbox02-bt/vendor/da14531/src/timer0.rs new file mode 100644 index 0000000..1ee6879 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0.rs @@ -0,0 +1,112 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Timer0 control register"] + pub timer0_ctrl_reg: crate::Reg, + #[doc = "0x02 - Timer0 on control register"] + pub timer0_on_reg: crate::Reg, + #[doc = "0x04 - 16 bits reload value for Timer0"] + pub timer0_reload_m_reg: crate::Reg, + #[doc = "0x06 - 16 bits reload value for Timer0"] + pub timer0_reload_n_reg: crate::Reg, + #[doc = "0x08 - Frequency for PWM 2,3,4,5,6 and 7"] + pub triple_pwm_frequency: crate::Reg, + #[doc = "0x0a - Defines start Cycle for PWM2"] + pub pwm2_start_cycle: crate::Reg, + #[doc = "0x0c - Defines start Cycle for PWM3"] + pub pwm3_start_cycle: crate::Reg, + #[doc = "0x0e - Defines start Cycle for PWM4"] + pub pwm4_start_cycle: crate::Reg, + #[doc = "0x10 - Defines start Cycle for PWM5"] + pub pwm5_start_cycle: crate::Reg, + #[doc = "0x12 - Defines start Cycle for PWM6"] + pub pwm6_start_cycle: crate::Reg, + #[doc = "0x14 - Defines start Cycle for PWM7"] + pub pwm7_start_cycle: crate::Reg, + #[doc = "0x16 - Defines end Cycle for PWM2"] + pub pwm2_end_cycle: crate::Reg, + #[doc = "0x18 - Defines end Cycle for PWM3"] + pub pwm3_end_cycle: crate::Reg, + #[doc = "0x1a - Defines end Cycle for PWM4"] + pub pwm4_end_cycle: crate::Reg, + #[doc = "0x1c - Defines end Cycle for PWM5"] + pub pwm5_end_cycle: crate::Reg, + #[doc = "0x1e - Defines end Cycle for PWM6"] + pub pwm6_end_cycle: crate::Reg, + #[doc = "0x20 - Defines end Cycle for PWM7"] + pub pwm7_end_cycle: crate::Reg, + #[doc = "0x22 - PWM 2,3,4,5,6,7 Control"] + pub triple_pwm_ctrl_reg: crate::Reg, +} +#[doc = "PWM2_END_CYCLE register accessor: an alias for `Reg`"] +pub type PWM2_END_CYCLE = crate::Reg; +#[doc = "Defines end Cycle for PWM2"] +pub mod pwm2_end_cycle; +#[doc = "PWM2_START_CYCLE register accessor: an alias for `Reg`"] +pub type PWM2_START_CYCLE = crate::Reg; +#[doc = "Defines start Cycle for PWM2"] +pub mod pwm2_start_cycle; +#[doc = "PWM3_END_CYCLE register accessor: an alias for `Reg`"] +pub type PWM3_END_CYCLE = crate::Reg; +#[doc = "Defines end Cycle for PWM3"] +pub mod pwm3_end_cycle; +#[doc = "PWM3_START_CYCLE register accessor: an alias for `Reg`"] +pub type PWM3_START_CYCLE = crate::Reg; +#[doc = "Defines start Cycle for PWM3"] +pub mod pwm3_start_cycle; +#[doc = "PWM4_END_CYCLE register accessor: an alias for `Reg`"] +pub type PWM4_END_CYCLE = crate::Reg; +#[doc = "Defines end Cycle for PWM4"] +pub mod pwm4_end_cycle; +#[doc = "PWM4_START_CYCLE register accessor: an alias for `Reg`"] +pub type PWM4_START_CYCLE = crate::Reg; +#[doc = "Defines start Cycle for PWM4"] +pub mod pwm4_start_cycle; +#[doc = "PWM5_END_CYCLE register accessor: an alias for `Reg`"] +pub type PWM5_END_CYCLE = crate::Reg; +#[doc = "Defines end Cycle for PWM5"] +pub mod pwm5_end_cycle; +#[doc = "PWM5_START_CYCLE register accessor: an alias for `Reg`"] +pub type PWM5_START_CYCLE = crate::Reg; +#[doc = "Defines start Cycle for PWM5"] +pub mod pwm5_start_cycle; +#[doc = "PWM6_END_CYCLE register accessor: an alias for `Reg`"] +pub type PWM6_END_CYCLE = crate::Reg; +#[doc = "Defines end Cycle for PWM6"] +pub mod pwm6_end_cycle; +#[doc = "PWM6_START_CYCLE register accessor: an alias for `Reg`"] +pub type PWM6_START_CYCLE = crate::Reg; +#[doc = "Defines start Cycle for PWM6"] +pub mod pwm6_start_cycle; +#[doc = "PWM7_END_CYCLE register accessor: an alias for `Reg`"] +pub type PWM7_END_CYCLE = crate::Reg; +#[doc = "Defines end Cycle for PWM7"] +pub mod pwm7_end_cycle; +#[doc = "PWM7_START_CYCLE register accessor: an alias for `Reg`"] +pub type PWM7_START_CYCLE = crate::Reg; +#[doc = "Defines start Cycle for PWM7"] +pub mod pwm7_start_cycle; +#[doc = "TIMER0_CTRL_REG register accessor: an alias for `Reg`"] +pub type TIMER0_CTRL_REG = crate::Reg; +#[doc = "Timer0 control register"] +pub mod timer0_ctrl_reg; +#[doc = "TIMER0_ON_REG register accessor: an alias for `Reg`"] +pub type TIMER0_ON_REG = crate::Reg; +#[doc = "Timer0 on control register"] +pub mod timer0_on_reg; +#[doc = "TIMER0_RELOAD_M_REG register accessor: an alias for `Reg`"] +pub type TIMER0_RELOAD_M_REG = crate::Reg; +#[doc = "16 bits reload value for Timer0"] +pub mod timer0_reload_m_reg; +#[doc = "TIMER0_RELOAD_N_REG register accessor: an alias for `Reg`"] +pub type TIMER0_RELOAD_N_REG = crate::Reg; +#[doc = "16 bits reload value for Timer0"] +pub mod timer0_reload_n_reg; +#[doc = "TRIPLE_PWM_CTRL_REG register accessor: an alias for `Reg`"] +pub type TRIPLE_PWM_CTRL_REG = crate::Reg; +#[doc = "PWM 2,3,4,5,6,7 Control"] +pub mod triple_pwm_ctrl_reg; +#[doc = "TRIPLE_PWM_FREQUENCY register accessor: an alias for `Reg`"] +pub type TRIPLE_PWM_FREQUENCY = crate::Reg; +#[doc = "Frequency for PWM 2,3,4,5,6 and 7"] +pub mod triple_pwm_frequency; diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm2_end_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm2_end_cycle.rs new file mode 100644 index 0000000..f3dfbc8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm2_end_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM2_END_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM2_END_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `END_CYCLE` reader - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_R(crate::FieldReader); +impl END_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + END_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for END_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `END_CYCLE` writer - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> END_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&self) -> END_CYCLE_R { + END_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&mut self) -> END_CYCLE_W { + END_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines end Cycle for PWM2\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm2_end_cycle](index.html) module"] +pub struct PWM2_END_CYCLE_SPEC; +impl crate::RegisterSpec for PWM2_END_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm2_end_cycle::R](R) reader structure"] +impl crate::Readable for PWM2_END_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm2_end_cycle::W](W) writer structure"] +impl crate::Writable for PWM2_END_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM2_END_CYCLE to value 0"] +impl crate::Resettable for PWM2_END_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm2_start_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm2_start_cycle.rs new file mode 100644 index 0000000..05e3c70 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm2_start_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM2_START_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM2_START_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `START_CYCLE` reader - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_R(crate::FieldReader); +impl START_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + START_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for START_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `START_CYCLE` writer - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> START_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&self) -> START_CYCLE_R { + START_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&mut self) -> START_CYCLE_W { + START_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines start Cycle for PWM2\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm2_start_cycle](index.html) module"] +pub struct PWM2_START_CYCLE_SPEC; +impl crate::RegisterSpec for PWM2_START_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm2_start_cycle::R](R) reader structure"] +impl crate::Readable for PWM2_START_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm2_start_cycle::W](W) writer structure"] +impl crate::Writable for PWM2_START_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM2_START_CYCLE to value 0"] +impl crate::Resettable for PWM2_START_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm3_end_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm3_end_cycle.rs new file mode 100644 index 0000000..a0dc96d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm3_end_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM3_END_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM3_END_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `END_CYCLE` reader - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_R(crate::FieldReader); +impl END_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + END_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for END_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `END_CYCLE` writer - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> END_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&self) -> END_CYCLE_R { + END_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&mut self) -> END_CYCLE_W { + END_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines end Cycle for PWM3\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm3_end_cycle](index.html) module"] +pub struct PWM3_END_CYCLE_SPEC; +impl crate::RegisterSpec for PWM3_END_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm3_end_cycle::R](R) reader structure"] +impl crate::Readable for PWM3_END_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm3_end_cycle::W](W) writer structure"] +impl crate::Writable for PWM3_END_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM3_END_CYCLE to value 0"] +impl crate::Resettable for PWM3_END_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm3_start_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm3_start_cycle.rs new file mode 100644 index 0000000..5af3fd1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm3_start_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM3_START_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM3_START_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `START_CYCLE` reader - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_R(crate::FieldReader); +impl START_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + START_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for START_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `START_CYCLE` writer - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> START_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&self) -> START_CYCLE_R { + START_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&mut self) -> START_CYCLE_W { + START_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines start Cycle for PWM3\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm3_start_cycle](index.html) module"] +pub struct PWM3_START_CYCLE_SPEC; +impl crate::RegisterSpec for PWM3_START_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm3_start_cycle::R](R) reader structure"] +impl crate::Readable for PWM3_START_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm3_start_cycle::W](W) writer structure"] +impl crate::Writable for PWM3_START_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM3_START_CYCLE to value 0"] +impl crate::Resettable for PWM3_START_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm4_end_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm4_end_cycle.rs new file mode 100644 index 0000000..9fbb4e0 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm4_end_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM4_END_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM4_END_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `END_CYCLE` reader - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_R(crate::FieldReader); +impl END_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + END_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for END_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `END_CYCLE` writer - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> END_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&self) -> END_CYCLE_R { + END_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&mut self) -> END_CYCLE_W { + END_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines end Cycle for PWM4\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm4_end_cycle](index.html) module"] +pub struct PWM4_END_CYCLE_SPEC; +impl crate::RegisterSpec for PWM4_END_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm4_end_cycle::R](R) reader structure"] +impl crate::Readable for PWM4_END_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm4_end_cycle::W](W) writer structure"] +impl crate::Writable for PWM4_END_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM4_END_CYCLE to value 0"] +impl crate::Resettable for PWM4_END_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm4_start_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm4_start_cycle.rs new file mode 100644 index 0000000..05ee3c1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm4_start_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM4_START_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM4_START_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `START_CYCLE` reader - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_R(crate::FieldReader); +impl START_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + START_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for START_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `START_CYCLE` writer - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> START_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&self) -> START_CYCLE_R { + START_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&mut self) -> START_CYCLE_W { + START_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines start Cycle for PWM4\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm4_start_cycle](index.html) module"] +pub struct PWM4_START_CYCLE_SPEC; +impl crate::RegisterSpec for PWM4_START_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm4_start_cycle::R](R) reader structure"] +impl crate::Readable for PWM4_START_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm4_start_cycle::W](W) writer structure"] +impl crate::Writable for PWM4_START_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM4_START_CYCLE to value 0"] +impl crate::Resettable for PWM4_START_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm5_end_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm5_end_cycle.rs new file mode 100644 index 0000000..ef3c7d1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm5_end_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM5_END_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM5_END_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `END_CYCLE` reader - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_R(crate::FieldReader); +impl END_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + END_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for END_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `END_CYCLE` writer - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> END_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&self) -> END_CYCLE_R { + END_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&mut self) -> END_CYCLE_W { + END_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines end Cycle for PWM5\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm5_end_cycle](index.html) module"] +pub struct PWM5_END_CYCLE_SPEC; +impl crate::RegisterSpec for PWM5_END_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm5_end_cycle::R](R) reader structure"] +impl crate::Readable for PWM5_END_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm5_end_cycle::W](W) writer structure"] +impl crate::Writable for PWM5_END_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM5_END_CYCLE to value 0"] +impl crate::Resettable for PWM5_END_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm5_start_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm5_start_cycle.rs new file mode 100644 index 0000000..a8babc8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm5_start_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM5_START_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM5_START_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `START_CYCLE` reader - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_R(crate::FieldReader); +impl START_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + START_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for START_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `START_CYCLE` writer - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> START_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&self) -> START_CYCLE_R { + START_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&mut self) -> START_CYCLE_W { + START_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines start Cycle for PWM5\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm5_start_cycle](index.html) module"] +pub struct PWM5_START_CYCLE_SPEC; +impl crate::RegisterSpec for PWM5_START_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm5_start_cycle::R](R) reader structure"] +impl crate::Readable for PWM5_START_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm5_start_cycle::W](W) writer structure"] +impl crate::Writable for PWM5_START_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM5_START_CYCLE to value 0"] +impl crate::Resettable for PWM5_START_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm6_end_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm6_end_cycle.rs new file mode 100644 index 0000000..5754461 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm6_end_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM6_END_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM6_END_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `END_CYCLE` reader - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_R(crate::FieldReader); +impl END_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + END_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for END_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `END_CYCLE` writer - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> END_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&self) -> END_CYCLE_R { + END_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&mut self) -> END_CYCLE_W { + END_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines end Cycle for PWM6\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm6_end_cycle](index.html) module"] +pub struct PWM6_END_CYCLE_SPEC; +impl crate::RegisterSpec for PWM6_END_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm6_end_cycle::R](R) reader structure"] +impl crate::Readable for PWM6_END_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm6_end_cycle::W](W) writer structure"] +impl crate::Writable for PWM6_END_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM6_END_CYCLE to value 0"] +impl crate::Resettable for PWM6_END_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm6_start_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm6_start_cycle.rs new file mode 100644 index 0000000..e211507 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm6_start_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM6_START_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM6_START_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `START_CYCLE` reader - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_R(crate::FieldReader); +impl START_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + START_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for START_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `START_CYCLE` writer - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> START_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&self) -> START_CYCLE_R { + START_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&mut self) -> START_CYCLE_W { + START_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines start Cycle for PWM6\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm6_start_cycle](index.html) module"] +pub struct PWM6_START_CYCLE_SPEC; +impl crate::RegisterSpec for PWM6_START_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm6_start_cycle::R](R) reader structure"] +impl crate::Readable for PWM6_START_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm6_start_cycle::W](W) writer structure"] +impl crate::Writable for PWM6_START_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM6_START_CYCLE to value 0"] +impl crate::Resettable for PWM6_START_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm7_end_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm7_end_cycle.rs new file mode 100644 index 0000000..6fa0f7f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm7_end_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM7_END_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM7_END_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `END_CYCLE` reader - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_R(crate::FieldReader); +impl END_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + END_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for END_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `END_CYCLE` writer - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] +pub struct END_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> END_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&self) -> END_CYCLE_R { + END_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes low. If end_cycle is larger then freq and start_cycle is not larger then freq, output is always 1"] + #[inline(always)] + pub fn end_cycle(&mut self) -> END_CYCLE_W { + END_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines end Cycle for PWM7\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm7_end_cycle](index.html) module"] +pub struct PWM7_END_CYCLE_SPEC; +impl crate::RegisterSpec for PWM7_END_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm7_end_cycle::R](R) reader structure"] +impl crate::Readable for PWM7_END_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm7_end_cycle::W](W) writer structure"] +impl crate::Writable for PWM7_END_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM7_END_CYCLE to value 0"] +impl crate::Resettable for PWM7_END_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/pwm7_start_cycle.rs b/bitbox02-bt/vendor/da14531/src/timer0/pwm7_start_cycle.rs new file mode 100644 index 0000000..c15e515 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/pwm7_start_cycle.rs @@ -0,0 +1,103 @@ +#[doc = "Register `PWM7_START_CYCLE` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `PWM7_START_CYCLE` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `START_CYCLE` reader - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_R(crate::FieldReader); +impl START_CYCLE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + START_CYCLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for START_CYCLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `START_CYCLE` writer - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] +pub struct START_CYCLE_W<'a> { + w: &'a mut W, +} +impl<'a> START_CYCLE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&self) -> START_CYCLE_R { + START_CYCLE_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the cycle in which the PWM becomes high. if start_cycle is larger than freq or end_cycle is equal to start_cycle, pwm out is always 0"] + #[inline(always)] + pub fn start_cycle(&mut self) -> START_CYCLE_W { + START_CYCLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Defines start Cycle for PWM7\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwm7_start_cycle](index.html) module"] +pub struct PWM7_START_CYCLE_SPEC; +impl crate::RegisterSpec for PWM7_START_CYCLE_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [pwm7_start_cycle::R](R) reader structure"] +impl crate::Readable for PWM7_START_CYCLE_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [pwm7_start_cycle::W](W) writer structure"] +impl crate::Writable for PWM7_START_CYCLE_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets PWM7_START_CYCLE to value 0"] +impl crate::Resettable for PWM7_START_CYCLE_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/timer0_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/timer0/timer0_ctrl_reg.rs new file mode 100644 index 0000000..fca355b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/timer0_ctrl_reg.rs @@ -0,0 +1,254 @@ +#[doc = "Register `TIMER0_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER0_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PWM_MODE` reader - 0 = PWM signals are '1' during high time. 1 = PWM signals send out the (fast) clock divided by 2 during high time. So it will be in the range of 1 to 8 MHz."] +pub struct PWM_MODE_R(crate::FieldReader); +impl PWM_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PWM_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PWM_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PWM_MODE` writer - 0 = PWM signals are '1' during high time. 1 = PWM signals send out the (fast) clock divided by 2 during high time. So it will be in the range of 1 to 8 MHz."] +pub struct PWM_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> PWM_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `TIM0_CLK_DIV` reader - 1 = Timer0 uses selected clock frequency as is. 0 = Timer0 uses selected clock frequency divided by 10. Note that this applies only to the ON-counter."] +pub struct TIM0_CLK_DIV_R(crate::FieldReader); +impl TIM0_CLK_DIV_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIM0_CLK_DIV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM0_CLK_DIV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM0_CLK_DIV` writer - 1 = Timer0 uses selected clock frequency as is. 0 = Timer0 uses selected clock frequency divided by 10. Note that this applies only to the ON-counter."] +pub struct TIM0_CLK_DIV_W<'a> { + w: &'a mut W, +} +impl<'a> TIM0_CLK_DIV_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `TIM0_CLK_SEL` reader - 1 = Timer0 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer0 uses LP clock"] +pub struct TIM0_CLK_SEL_R(crate::FieldReader); +impl TIM0_CLK_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIM0_CLK_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM0_CLK_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM0_CLK_SEL` writer - 1 = Timer0 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer0 uses LP clock"] +pub struct TIM0_CLK_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> TIM0_CLK_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `TIM0_CTRL` reader - 0 = Timer0 is off and in reset state. 1 = Timer0 is running."] +pub struct TIM0_CTRL_R(crate::FieldReader); +impl TIM0_CTRL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIM0_CTRL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM0_CTRL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM0_CTRL` writer - 0 = Timer0 is off and in reset state. 1 = Timer0 is running."] +pub struct TIM0_CTRL_W<'a> { + w: &'a mut W, +} +impl<'a> TIM0_CTRL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 3 - 0 = PWM signals are '1' during high time. 1 = PWM signals send out the (fast) clock divided by 2 during high time. So it will be in the range of 1 to 8 MHz."] + #[inline(always)] + pub fn pwm_mode(&self) -> PWM_MODE_R { + PWM_MODE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - 1 = Timer0 uses selected clock frequency as is. 0 = Timer0 uses selected clock frequency divided by 10. Note that this applies only to the ON-counter."] + #[inline(always)] + pub fn tim0_clk_div(&self) -> TIM0_CLK_DIV_R { + TIM0_CLK_DIV_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - 1 = Timer0 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer0 uses LP clock"] + #[inline(always)] + pub fn tim0_clk_sel(&self) -> TIM0_CLK_SEL_R { + TIM0_CLK_SEL_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - 0 = Timer0 is off and in reset state. 1 = Timer0 is running."] + #[inline(always)] + pub fn tim0_ctrl(&self) -> TIM0_CTRL_R { + TIM0_CTRL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 3 - 0 = PWM signals are '1' during high time. 1 = PWM signals send out the (fast) clock divided by 2 during high time. So it will be in the range of 1 to 8 MHz."] + #[inline(always)] + pub fn pwm_mode(&mut self) -> PWM_MODE_W { + PWM_MODE_W { w: self } + } + #[doc = "Bit 2 - 1 = Timer0 uses selected clock frequency as is. 0 = Timer0 uses selected clock frequency divided by 10. Note that this applies only to the ON-counter."] + #[inline(always)] + pub fn tim0_clk_div(&mut self) -> TIM0_CLK_DIV_W { + TIM0_CLK_DIV_W { w: self } + } + #[doc = "Bit 1 - 1 = Timer0 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer0 uses LP clock"] + #[inline(always)] + pub fn tim0_clk_sel(&mut self) -> TIM0_CLK_SEL_W { + TIM0_CLK_SEL_W { w: self } + } + #[doc = "Bit 0 - 0 = Timer0 is off and in reset state. 1 = Timer0 is running."] + #[inline(always)] + pub fn tim0_ctrl(&mut self) -> TIM0_CTRL_W { + TIM0_CTRL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timer0 control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer0_ctrl_reg](index.html) module"] +pub struct TIMER0_CTRL_REG_SPEC; +impl crate::RegisterSpec for TIMER0_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [timer0_ctrl_reg::R](R) reader structure"] +impl crate::Readable for TIMER0_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer0_ctrl_reg::W](W) writer structure"] +impl crate::Writable for TIMER0_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER0_CTRL_REG to value 0"] +impl crate::Resettable for TIMER0_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/timer0_on_reg.rs b/bitbox02-bt/vendor/da14531/src/timer0/timer0_on_reg.rs new file mode 100644 index 0000000..0faeab3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/timer0_on_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `TIMER0_ON_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER0_ON_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIM0_ON` reader - Timer0 On reload value: If read the actual ON-counter value is returned"] +pub struct TIM0_ON_R(crate::FieldReader); +impl TIM0_ON_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIM0_ON_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM0_ON_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM0_ON` writer - Timer0 On reload value: If read the actual ON-counter value is returned"] +pub struct TIM0_ON_W<'a> { + w: &'a mut W, +} +impl<'a> TIM0_ON_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - Timer0 On reload value: If read the actual ON-counter value is returned"] + #[inline(always)] + pub fn tim0_on(&self) -> TIM0_ON_R { + TIM0_ON_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - Timer0 On reload value: If read the actual ON-counter value is returned"] + #[inline(always)] + pub fn tim0_on(&mut self) -> TIM0_ON_W { + TIM0_ON_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timer0 on control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer0_on_reg](index.html) module"] +pub struct TIMER0_ON_REG_SPEC; +impl crate::RegisterSpec for TIMER0_ON_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [timer0_on_reg::R](R) reader structure"] +impl crate::Readable for TIMER0_ON_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer0_on_reg::W](W) writer structure"] +impl crate::Writable for TIMER0_ON_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER0_ON_REG to value 0"] +impl crate::Resettable for TIMER0_ON_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_m_reg.rs b/bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_m_reg.rs new file mode 100644 index 0000000..66722e5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_m_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `TIMER0_RELOAD_M_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER0_RELOAD_M_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIM0_M` reader - Timer0 'high' reload value If read the actual T0-counter value is returned"] +pub struct TIM0_M_R(crate::FieldReader); +impl TIM0_M_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIM0_M_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM0_M_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM0_M` writer - Timer0 'high' reload value If read the actual T0-counter value is returned"] +pub struct TIM0_M_W<'a> { + w: &'a mut W, +} +impl<'a> TIM0_M_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - Timer0 'high' reload value If read the actual T0-counter value is returned"] + #[inline(always)] + pub fn tim0_m(&self) -> TIM0_M_R { + TIM0_M_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - Timer0 'high' reload value If read the actual T0-counter value is returned"] + #[inline(always)] + pub fn tim0_m(&mut self) -> TIM0_M_W { + TIM0_M_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "16 bits reload value for Timer0\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer0_reload_m_reg](index.html) module"] +pub struct TIMER0_RELOAD_M_REG_SPEC; +impl crate::RegisterSpec for TIMER0_RELOAD_M_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [timer0_reload_m_reg::R](R) reader structure"] +impl crate::Readable for TIMER0_RELOAD_M_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer0_reload_m_reg::W](W) writer structure"] +impl crate::Writable for TIMER0_RELOAD_M_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER0_RELOAD_M_REG to value 0"] +impl crate::Resettable for TIMER0_RELOAD_M_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_n_reg.rs b/bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_n_reg.rs new file mode 100644 index 0000000..9eebeed --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/timer0_reload_n_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `TIMER0_RELOAD_N_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER0_RELOAD_N_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIM0_N` reader - Timer0 'low' reload value: If read the actual T0-counter value is returned"] +pub struct TIM0_N_R(crate::FieldReader); +impl TIM0_N_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIM0_N_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIM0_N_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIM0_N` writer - Timer0 'low' reload value: If read the actual T0-counter value is returned"] +pub struct TIM0_N_W<'a> { + w: &'a mut W, +} +impl<'a> TIM0_N_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = value; + self.w + } +} +impl R { + #[doc = "Bits 0:15 - Timer0 'low' reload value: If read the actual T0-counter value is returned"] + #[inline(always)] + pub fn tim0_n(&self) -> TIM0_N_R { + TIM0_N_R::new(self.bits) + } +} +impl W { + #[doc = "Bits 0:15 - Timer0 'low' reload value: If read the actual T0-counter value is returned"] + #[inline(always)] + pub fn tim0_n(&mut self) -> TIM0_N_W { + TIM0_N_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "16 bits reload value for Timer0\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer0_reload_n_reg](index.html) module"] +pub struct TIMER0_RELOAD_N_REG_SPEC; +impl crate::RegisterSpec for TIMER0_RELOAD_N_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [timer0_reload_n_reg::R](R) reader structure"] +impl crate::Readable for TIMER0_RELOAD_N_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer0_reload_n_reg::W](W) writer structure"] +impl crate::Writable for TIMER0_RELOAD_N_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER0_RELOAD_N_REG to value 0"] +impl crate::Resettable for TIMER0_RELOAD_N_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_ctrl_reg.rs new file mode 100644 index 0000000..69d1d4d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_ctrl_reg.rs @@ -0,0 +1,254 @@ +#[doc = "Register `TRIPLE_PWM_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TRIPLE_PWM_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TRIPLE_PWM_CLK_SEL` reader - 1 = Timer2 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer2 uses LP clock"] +pub struct TRIPLE_PWM_CLK_SEL_R(crate::FieldReader); +impl TRIPLE_PWM_CLK_SEL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TRIPLE_PWM_CLK_SEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TRIPLE_PWM_CLK_SEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TRIPLE_PWM_CLK_SEL` writer - 1 = Timer2 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer2 uses LP clock"] +pub struct TRIPLE_PWM_CLK_SEL_W<'a> { + w: &'a mut W, +} +impl<'a> TRIPLE_PWM_CLK_SEL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `HW_PAUSE_EN` reader - '1' = HW can pause PWM 2,3,4,5,6,7"] +pub struct HW_PAUSE_EN_R(crate::FieldReader); +impl HW_PAUSE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + HW_PAUSE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for HW_PAUSE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `HW_PAUSE_EN` writer - '1' = HW can pause PWM 2,3,4,5,6,7"] +pub struct HW_PAUSE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> HW_PAUSE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `SW_PAUSE_EN` reader - '1' = PWM 2 3 4 5 6 7 are paused"] +pub struct SW_PAUSE_EN_R(crate::FieldReader); +impl SW_PAUSE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + SW_PAUSE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SW_PAUSE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SW_PAUSE_EN` writer - '1' = PWM 2 3 4 5 6 7 are paused"] +pub struct SW_PAUSE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> SW_PAUSE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `TRIPLE_PWM_ENABLE` reader - '1' = enable PWM 2 3 4 5 6 7"] +pub struct TRIPLE_PWM_ENABLE_R(crate::FieldReader); +impl TRIPLE_PWM_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TRIPLE_PWM_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TRIPLE_PWM_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TRIPLE_PWM_ENABLE` writer - '1' = enable PWM 2 3 4 5 6 7"] +pub struct TRIPLE_PWM_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> TRIPLE_PWM_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 3 - 1 = Timer2 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer2 uses LP clock"] + #[inline(always)] + pub fn triple_pwm_clk_sel(&self) -> TRIPLE_PWM_CLK_SEL_R { + TRIPLE_PWM_CLK_SEL_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - '1' = HW can pause PWM 2,3,4,5,6,7"] + #[inline(always)] + pub fn hw_pause_en(&self) -> HW_PAUSE_EN_R { + HW_PAUSE_EN_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - '1' = PWM 2 3 4 5 6 7 are paused"] + #[inline(always)] + pub fn sw_pause_en(&self) -> SW_PAUSE_EN_R { + SW_PAUSE_EN_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - '1' = enable PWM 2 3 4 5 6 7"] + #[inline(always)] + pub fn triple_pwm_enable(&self) -> TRIPLE_PWM_ENABLE_R { + TRIPLE_PWM_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 3 - 1 = Timer2 uses 16, 8, 4 or 2 MHz (fast) clock frequency. 0 = Timer2 uses LP clock"] + #[inline(always)] + pub fn triple_pwm_clk_sel(&mut self) -> TRIPLE_PWM_CLK_SEL_W { + TRIPLE_PWM_CLK_SEL_W { w: self } + } + #[doc = "Bit 2 - '1' = HW can pause PWM 2,3,4,5,6,7"] + #[inline(always)] + pub fn hw_pause_en(&mut self) -> HW_PAUSE_EN_W { + HW_PAUSE_EN_W { w: self } + } + #[doc = "Bit 1 - '1' = PWM 2 3 4 5 6 7 are paused"] + #[inline(always)] + pub fn sw_pause_en(&mut self) -> SW_PAUSE_EN_W { + SW_PAUSE_EN_W { w: self } + } + #[doc = "Bit 0 - '1' = enable PWM 2 3 4 5 6 7"] + #[inline(always)] + pub fn triple_pwm_enable(&mut self) -> TRIPLE_PWM_ENABLE_W { + TRIPLE_PWM_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "PWM 2,3,4,5,6,7 Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [triple_pwm_ctrl_reg](index.html) module"] +pub struct TRIPLE_PWM_CTRL_REG_SPEC; +impl crate::RegisterSpec for TRIPLE_PWM_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [triple_pwm_ctrl_reg::R](R) reader structure"] +impl crate::Readable for TRIPLE_PWM_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [triple_pwm_ctrl_reg::W](W) writer structure"] +impl crate::Writable for TRIPLE_PWM_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TRIPLE_PWM_CTRL_REG to value 0x04"] +impl crate::Resettable for TRIPLE_PWM_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x04 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_frequency.rs b/bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_frequency.rs new file mode 100644 index 0000000..0844e47 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer0/triple_pwm_frequency.rs @@ -0,0 +1,103 @@ +#[doc = "Register `TRIPLE_PWM_FREQUENCY` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TRIPLE_PWM_FREQUENCY` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PWM_FREQ` reader - Defines the frequeancy of PWM 2,3,4,5,,6 and 7. pwm freq = module Frequency / (value+1) module frequency is the LP_CLK when TRIPLE_PWM_CLK_SEL=0 else is the sys_clk divided by TMR_DIV"] +pub struct PWM_FREQ_R(crate::FieldReader); +impl PWM_FREQ_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + PWM_FREQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PWM_FREQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PWM_FREQ` writer - Defines the frequeancy of PWM 2,3,4,5,,6 and 7. pwm freq = module Frequency / (value+1) module frequency is the LP_CLK when TRIPLE_PWM_CLK_SEL=0 else is the sys_clk divided by TMR_DIV"] +pub struct PWM_FREQ_W<'a> { + w: &'a mut W, +} +impl<'a> PWM_FREQ_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3fff) | (value as u16 & 0x3fff); + self.w + } +} +impl R { + #[doc = "Bits 0:13 - Defines the frequeancy of PWM 2,3,4,5,,6 and 7. pwm freq = module Frequency / (value+1) module frequency is the LP_CLK when TRIPLE_PWM_CLK_SEL=0 else is the sys_clk divided by TMR_DIV"] + #[inline(always)] + pub fn pwm_freq(&self) -> PWM_FREQ_R { + PWM_FREQ_R::new((self.bits & 0x3fff) as u16) + } +} +impl W { + #[doc = "Bits 0:13 - Defines the frequeancy of PWM 2,3,4,5,,6 and 7. pwm freq = module Frequency / (value+1) module frequency is the LP_CLK when TRIPLE_PWM_CLK_SEL=0 else is the sys_clk divided by TMR_DIV"] + #[inline(always)] + pub fn pwm_freq(&mut self) -> PWM_FREQ_W { + PWM_FREQ_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Frequency for PWM 2,3,4,5,6 and 7\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [triple_pwm_frequency](index.html) module"] +pub struct TRIPLE_PWM_FREQUENCY_SPEC; +impl crate::RegisterSpec for TRIPLE_PWM_FREQUENCY_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [triple_pwm_frequency::R](R) reader structure"] +impl crate::Readable for TRIPLE_PWM_FREQUENCY_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [triple_pwm_frequency::W](W) writer structure"] +impl crate::Writable for TRIPLE_PWM_FREQUENCY_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TRIPLE_PWM_FREQUENCY to value 0"] +impl crate::Resettable for TRIPLE_PWM_FREQUENCY_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer1.rs b/bitbox02-bt/vendor/da14531/src/timer1.rs new file mode 100644 index 0000000..249ab77 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer1.rs @@ -0,0 +1,44 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Timer1 control register"] + pub timer1_ctrl_reg: crate::Reg, + #[doc = "0x04 - Timer1 Capture control register"] + pub timer1_capture_reg: crate::Reg, + #[doc = "0x08 - Timer1 counter value"] + pub timer1_status_reg: crate::Reg, + #[doc = "0x0c - Timer1 value for event on GPIO1"] + pub timer1_capcnt1_value_reg: + crate::Reg, + #[doc = "0x10 - Timer1 value for event on GPIO2"] + pub timer1_capcnt2_value_reg: + crate::Reg, + #[doc = "0x14 - Clear event register"] + pub timer1_clr_event_reg: crate::Reg, +} +#[doc = "TIMER1_CAPCNT1_VALUE_REG register accessor: an alias for `Reg`"] +pub type TIMER1_CAPCNT1_VALUE_REG = + crate::Reg; +#[doc = "Timer1 value for event on GPIO1"] +pub mod timer1_capcnt1_value_reg; +#[doc = "TIMER1_CAPCNT2_VALUE_REG register accessor: an alias for `Reg`"] +pub type TIMER1_CAPCNT2_VALUE_REG = + crate::Reg; +#[doc = "Timer1 value for event on GPIO2"] +pub mod timer1_capcnt2_value_reg; +#[doc = "TIMER1_CAPTURE_REG register accessor: an alias for `Reg`"] +pub type TIMER1_CAPTURE_REG = crate::Reg; +#[doc = "Timer1 Capture control register"] +pub mod timer1_capture_reg; +#[doc = "TIMER1_CLR_EVENT_REG register accessor: an alias for `Reg`"] +pub type TIMER1_CLR_EVENT_REG = crate::Reg; +#[doc = "Clear event register"] +pub mod timer1_clr_event_reg; +#[doc = "TIMER1_CTRL_REG register accessor: an alias for `Reg`"] +pub type TIMER1_CTRL_REG = crate::Reg; +#[doc = "Timer1 control register"] +pub mod timer1_ctrl_reg; +#[doc = "TIMER1_STATUS_REG register accessor: an alias for `Reg`"] +pub type TIMER1_STATUS_REG = crate::Reg; +#[doc = "Timer1 counter value"] +pub mod timer1_status_reg; diff --git a/bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt1_value_reg.rs b/bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt1_value_reg.rs new file mode 100644 index 0000000..cdd7bf2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt1_value_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `TIMER1_CAPCNT1_VALUE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER1_CAPCNT1_VALUE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIMER1_CAPCNT1_RTC_HIGH` reader - In Counter mode : Not used In Capture mode: Gives the RTC time stamp (high part) when an IN1 event was occurred"] +pub struct TIMER1_CAPCNT1_RTC_HIGH_R(crate::FieldReader); +impl TIMER1_CAPCNT1_RTC_HIGH_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIMER1_CAPCNT1_RTC_HIGH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CAPCNT1_RTC_HIGH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_CAPCNT1_VALUE` reader - In Counter mode : Gives the number of timer clock cycles minus 1 which was measured during TIMER1_IN1_PERIOD_MAX periods of IN1 In Capture mode (TIMER1_IN1_STAMP_TYPE=0) : Gives the Counter value when an IN1 event was occurred In Capture mode (TIMER1_IN1_STAMP_TYPE=1) : Gives the RTC time stamp (low part) when an IN1 event was occurred"] +pub struct TIMER1_CAPCNT1_VALUE_R(crate::FieldReader); +impl TIMER1_CAPCNT1_VALUE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIMER1_CAPCNT1_VALUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CAPCNT1_VALUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 11:21 - In Counter mode : Not used In Capture mode: Gives the RTC time stamp (high part) when an IN1 event was occurred"] + #[inline(always)] + pub fn timer1_capcnt1_rtc_high(&self) -> TIMER1_CAPCNT1_RTC_HIGH_R { + TIMER1_CAPCNT1_RTC_HIGH_R::new(((self.bits >> 11) & 0x07ff) as u16) + } + #[doc = "Bits 0:10 - In Counter mode : Gives the number of timer clock cycles minus 1 which was measured during TIMER1_IN1_PERIOD_MAX periods of IN1 In Capture mode (TIMER1_IN1_STAMP_TYPE=0) : Gives the Counter value when an IN1 event was occurred In Capture mode (TIMER1_IN1_STAMP_TYPE=1) : Gives the RTC time stamp (low part) when an IN1 event was occurred"] + #[inline(always)] + pub fn timer1_capcnt1_value(&self) -> TIMER1_CAPCNT1_VALUE_R { + TIMER1_CAPCNT1_VALUE_R::new((self.bits & 0x07ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timer1 value for event on GPIO1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer1_capcnt1_value_reg](index.html) module"] +pub struct TIMER1_CAPCNT1_VALUE_REG_SPEC; +impl crate::RegisterSpec for TIMER1_CAPCNT1_VALUE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [timer1_capcnt1_value_reg::R](R) reader structure"] +impl crate::Readable for TIMER1_CAPCNT1_VALUE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer1_capcnt1_value_reg::W](W) writer structure"] +impl crate::Writable for TIMER1_CAPCNT1_VALUE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER1_CAPCNT1_VALUE_REG to value 0"] +impl crate::Resettable for TIMER1_CAPCNT1_VALUE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt2_value_reg.rs b/bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt2_value_reg.rs new file mode 100644 index 0000000..7aa23ab --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer1/timer1_capcnt2_value_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `TIMER1_CAPCNT2_VALUE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER1_CAPCNT2_VALUE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIMER1_CAPCNT2_RTC_HIGH` reader - In Counter mode : Not used In Capture mode: Gives the RTC time stamp (high part) when an IN2 event was occurred"] +pub struct TIMER1_CAPCNT2_RTC_HIGH_R(crate::FieldReader); +impl TIMER1_CAPCNT2_RTC_HIGH_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIMER1_CAPCNT2_RTC_HIGH_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CAPCNT2_RTC_HIGH_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_CAPCNT2_VALUE` reader - In Counter mode : Gives the number of timer clock cycles minus 1 which was measured during TIMER1_IN2_PERIOD_MAX periods of IN2 In Capture mode (TIMER1_IN2_STAMP_TYPE=0) : Gives the Counter value when an IN2 event was occurred In Capture mode (TIMER1_IN2_STAMP_TYPE=1) : Gives the RTC time stamp (low part) when an IN2 event was occurred"] +pub struct TIMER1_CAPCNT2_VALUE_R(crate::FieldReader); +impl TIMER1_CAPCNT2_VALUE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIMER1_CAPCNT2_VALUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CAPCNT2_VALUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 11:21 - In Counter mode : Not used In Capture mode: Gives the RTC time stamp (high part) when an IN2 event was occurred"] + #[inline(always)] + pub fn timer1_capcnt2_rtc_high(&self) -> TIMER1_CAPCNT2_RTC_HIGH_R { + TIMER1_CAPCNT2_RTC_HIGH_R::new(((self.bits >> 11) & 0x07ff) as u16) + } + #[doc = "Bits 0:10 - In Counter mode : Gives the number of timer clock cycles minus 1 which was measured during TIMER1_IN2_PERIOD_MAX periods of IN2 In Capture mode (TIMER1_IN2_STAMP_TYPE=0) : Gives the Counter value when an IN2 event was occurred In Capture mode (TIMER1_IN2_STAMP_TYPE=1) : Gives the RTC time stamp (low part) when an IN2 event was occurred"] + #[inline(always)] + pub fn timer1_capcnt2_value(&self) -> TIMER1_CAPCNT2_VALUE_R { + TIMER1_CAPCNT2_VALUE_R::new((self.bits & 0x07ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timer1 value for event on GPIO2\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer1_capcnt2_value_reg](index.html) module"] +pub struct TIMER1_CAPCNT2_VALUE_REG_SPEC; +impl crate::RegisterSpec for TIMER1_CAPCNT2_VALUE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [timer1_capcnt2_value_reg::R](R) reader structure"] +impl crate::Readable for TIMER1_CAPCNT2_VALUE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer1_capcnt2_value_reg::W](W) writer structure"] +impl crate::Writable for TIMER1_CAPCNT2_VALUE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER1_CAPCNT2_VALUE_REG to value 0"] +impl crate::Resettable for TIMER1_CAPCNT2_VALUE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer1/timer1_capture_reg.rs b/bitbox02-bt/vendor/da14531/src/timer1/timer1_capture_reg.rs new file mode 100644 index 0000000..55b4bed --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer1/timer1_capture_reg.rs @@ -0,0 +1,590 @@ +#[doc = "Register `TIMER1_CAPTURE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER1_CAPTURE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIMER1_IN2_STAMP_TYPE` reader - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] +pub struct TIMER1_IN2_STAMP_TYPE_R(crate::FieldReader); +impl TIMER1_IN2_STAMP_TYPE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN2_STAMP_TYPE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN2_STAMP_TYPE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN2_STAMP_TYPE` writer - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] +pub struct TIMER1_IN2_STAMP_TYPE_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN2_STAMP_TYPE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 27)) | ((value as u32 & 1) << 27); + self.w + } +} +#[doc = "Field `TIMER1_IN2_PERIOD_MAX` reader - Gives the number of periods +1 of IN2, in which module counts"] +pub struct TIMER1_IN2_PERIOD_MAX_R(crate::FieldReader); +impl TIMER1_IN2_PERIOD_MAX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TIMER1_IN2_PERIOD_MAX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN2_PERIOD_MAX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN2_PERIOD_MAX` writer - Gives the number of periods +1 of IN2, in which module counts"] +pub struct TIMER1_IN2_PERIOD_MAX_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN2_PERIOD_MAX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 21)) | ((value as u32 & 0x3f) << 21); + self.w + } +} +#[doc = "Field `TIMER1_IN2_IRQ_EN` reader - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN2_PERIOD_MAX 0 = Interrupt is masked"] +pub struct TIMER1_IN2_IRQ_EN_R(crate::FieldReader); +impl TIMER1_IN2_IRQ_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN2_IRQ_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN2_IRQ_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN2_IRQ_EN` writer - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN2_PERIOD_MAX 0 = Interrupt is masked"] +pub struct TIMER1_IN2_IRQ_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN2_IRQ_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 20)) | ((value as u32 & 1) << 20); + self.w + } +} +#[doc = "Field `TIMER1_IN2_COUNT_EN` reader - 0 = Capture mode 1 = Count mode"] +pub struct TIMER1_IN2_COUNT_EN_R(crate::FieldReader); +impl TIMER1_IN2_COUNT_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN2_COUNT_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN2_COUNT_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN2_COUNT_EN` writer - 0 = Capture mode 1 = Count mode"] +pub struct TIMER1_IN2_COUNT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN2_COUNT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 19)) | ((value as u32 & 1) << 19); + self.w + } +} +#[doc = "Field `TIMER1_IN2_EVENT_FALL_EN` reader - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO2_CONF=0 to prevent false events"] +pub struct TIMER1_IN2_EVENT_FALL_EN_R(crate::FieldReader); +impl TIMER1_IN2_EVENT_FALL_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN2_EVENT_FALL_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN2_EVENT_FALL_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN2_EVENT_FALL_EN` writer - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO2_CONF=0 to prevent false events"] +pub struct TIMER1_IN2_EVENT_FALL_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN2_EVENT_FALL_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 18)) | ((value as u32 & 1) << 18); + self.w + } +} +#[doc = "Field `TIMER1_GPIO2_CONF` reader - 0,13,14,15 = IN2 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN2"] +pub struct TIMER1_GPIO2_CONF_R(crate::FieldReader); +impl TIMER1_GPIO2_CONF_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TIMER1_GPIO2_CONF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_GPIO2_CONF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_GPIO2_CONF` writer - 0,13,14,15 = IN2 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN2"] +pub struct TIMER1_GPIO2_CONF_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_GPIO2_CONF_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x0f << 14)) | ((value as u32 & 0x0f) << 14); + self.w + } +} +#[doc = "Field `TIMER1_IN1_STAMP_TYPE` reader - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] +pub struct TIMER1_IN1_STAMP_TYPE_R(crate::FieldReader); +impl TIMER1_IN1_STAMP_TYPE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN1_STAMP_TYPE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN1_STAMP_TYPE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN1_STAMP_TYPE` writer - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] +pub struct TIMER1_IN1_STAMP_TYPE_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN1_STAMP_TYPE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u32 & 1) << 13); + self.w + } +} +#[doc = "Field `TIMER1_IN1_PERIOD_MAX` reader - Gives the number of periods +1 of IN1, in which module counts"] +pub struct TIMER1_IN1_PERIOD_MAX_R(crate::FieldReader); +impl TIMER1_IN1_PERIOD_MAX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TIMER1_IN1_PERIOD_MAX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN1_PERIOD_MAX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN1_PERIOD_MAX` writer - Gives the number of periods +1 of IN1, in which module counts"] +pub struct TIMER1_IN1_PERIOD_MAX_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN1_PERIOD_MAX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x3f << 7)) | ((value as u32 & 0x3f) << 7); + self.w + } +} +#[doc = "Field `TIMER1_IN1_IRQ_EN` reader - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN1_PERIOD_MAX 0 = Interrupt is masked"] +pub struct TIMER1_IN1_IRQ_EN_R(crate::FieldReader); +impl TIMER1_IN1_IRQ_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN1_IRQ_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN1_IRQ_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN1_IRQ_EN` writer - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN1_PERIOD_MAX 0 = Interrupt is masked"] +pub struct TIMER1_IN1_IRQ_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN1_IRQ_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u32 & 1) << 6); + self.w + } +} +#[doc = "Field `TIMER1_IN1_COUNT_EN` reader - 0 = Capture mode 1 = Count mode"] +pub struct TIMER1_IN1_COUNT_EN_R(crate::FieldReader); +impl TIMER1_IN1_COUNT_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN1_COUNT_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN1_COUNT_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN1_COUNT_EN` writer - 0 = Capture mode 1 = Count mode"] +pub struct TIMER1_IN1_COUNT_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN1_COUNT_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u32 & 1) << 5); + self.w + } +} +#[doc = "Field `TIMER1_IN1_EVENT_FALL_EN` reader - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO1_CONF=0 to prevent false events"] +pub struct TIMER1_IN1_EVENT_FALL_EN_R(crate::FieldReader); +impl TIMER1_IN1_EVENT_FALL_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN1_EVENT_FALL_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN1_EVENT_FALL_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN1_EVENT_FALL_EN` writer - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO1_CONF=0 to prevent false events"] +pub struct TIMER1_IN1_EVENT_FALL_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IN1_EVENT_FALL_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u32 & 1) << 4); + self.w + } +} +#[doc = "Field `TIMER1_GPIO1_CONF` reader - 0,13,14,15 = IN1 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN1"] +pub struct TIMER1_GPIO1_CONF_R(crate::FieldReader); +impl TIMER1_GPIO1_CONF_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + TIMER1_GPIO1_CONF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_GPIO1_CONF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_GPIO1_CONF` writer - 0,13,14,15 = IN1 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN1"] +pub struct TIMER1_GPIO1_CONF_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_GPIO1_CONF_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bit 27 - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] + #[inline(always)] + pub fn timer1_in2_stamp_type(&self) -> TIMER1_IN2_STAMP_TYPE_R { + TIMER1_IN2_STAMP_TYPE_R::new(((self.bits >> 27) & 1) != 0) + } + #[doc = "Bits 21:26 - Gives the number of periods +1 of IN2, in which module counts"] + #[inline(always)] + pub fn timer1_in2_period_max(&self) -> TIMER1_IN2_PERIOD_MAX_R { + TIMER1_IN2_PERIOD_MAX_R::new(((self.bits >> 21) & 0x3f) as u8) + } + #[doc = "Bit 20 - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN2_PERIOD_MAX 0 = Interrupt is masked"] + #[inline(always)] + pub fn timer1_in2_irq_en(&self) -> TIMER1_IN2_IRQ_EN_R { + TIMER1_IN2_IRQ_EN_R::new(((self.bits >> 20) & 1) != 0) + } + #[doc = "Bit 19 - 0 = Capture mode 1 = Count mode"] + #[inline(always)] + pub fn timer1_in2_count_en(&self) -> TIMER1_IN2_COUNT_EN_R { + TIMER1_IN2_COUNT_EN_R::new(((self.bits >> 19) & 1) != 0) + } + #[doc = "Bit 18 - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO2_CONF=0 to prevent false events"] + #[inline(always)] + pub fn timer1_in2_event_fall_en(&self) -> TIMER1_IN2_EVENT_FALL_EN_R { + TIMER1_IN2_EVENT_FALL_EN_R::new(((self.bits >> 18) & 1) != 0) + } + #[doc = "Bits 14:17 - 0,13,14,15 = IN2 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN2"] + #[inline(always)] + pub fn timer1_gpio2_conf(&self) -> TIMER1_GPIO2_CONF_R { + TIMER1_GPIO2_CONF_R::new(((self.bits >> 14) & 0x0f) as u8) + } + #[doc = "Bit 13 - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] + #[inline(always)] + pub fn timer1_in1_stamp_type(&self) -> TIMER1_IN1_STAMP_TYPE_R { + TIMER1_IN1_STAMP_TYPE_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bits 7:12 - Gives the number of periods +1 of IN1, in which module counts"] + #[inline(always)] + pub fn timer1_in1_period_max(&self) -> TIMER1_IN1_PERIOD_MAX_R { + TIMER1_IN1_PERIOD_MAX_R::new(((self.bits >> 7) & 0x3f) as u8) + } + #[doc = "Bit 6 - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN1_PERIOD_MAX 0 = Interrupt is masked"] + #[inline(always)] + pub fn timer1_in1_irq_en(&self) -> TIMER1_IN1_IRQ_EN_R { + TIMER1_IN1_IRQ_EN_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - 0 = Capture mode 1 = Count mode"] + #[inline(always)] + pub fn timer1_in1_count_en(&self) -> TIMER1_IN1_COUNT_EN_R { + TIMER1_IN1_COUNT_EN_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO1_CONF=0 to prevent false events"] + #[inline(always)] + pub fn timer1_in1_event_fall_en(&self) -> TIMER1_IN1_EVENT_FALL_EN_R { + TIMER1_IN1_EVENT_FALL_EN_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bits 0:3 - 0,13,14,15 = IN1 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN1"] + #[inline(always)] + pub fn timer1_gpio1_conf(&self) -> TIMER1_GPIO1_CONF_R { + TIMER1_GPIO1_CONF_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bit 27 - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] + #[inline(always)] + pub fn timer1_in2_stamp_type(&mut self) -> TIMER1_IN2_STAMP_TYPE_W { + TIMER1_IN2_STAMP_TYPE_W { w: self } + } + #[doc = "Bits 21:26 - Gives the number of periods +1 of IN2, in which module counts"] + #[inline(always)] + pub fn timer1_in2_period_max(&mut self) -> TIMER1_IN2_PERIOD_MAX_W { + TIMER1_IN2_PERIOD_MAX_W { w: self } + } + #[doc = "Bit 20 - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN2_PERIOD_MAX 0 = Interrupt is masked"] + #[inline(always)] + pub fn timer1_in2_irq_en(&mut self) -> TIMER1_IN2_IRQ_EN_W { + TIMER1_IN2_IRQ_EN_W { w: self } + } + #[doc = "Bit 19 - 0 = Capture mode 1 = Count mode"] + #[inline(always)] + pub fn timer1_in2_count_en(&mut self) -> TIMER1_IN2_COUNT_EN_W { + TIMER1_IN2_COUNT_EN_W { w: self } + } + #[doc = "Bit 18 - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO2_CONF=0 to prevent false events"] + #[inline(always)] + pub fn timer1_in2_event_fall_en(&mut self) -> TIMER1_IN2_EVENT_FALL_EN_W { + TIMER1_IN2_EVENT_FALL_EN_W { w: self } + } + #[doc = "Bits 14:17 - 0,13,14,15 = IN2 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN2"] + #[inline(always)] + pub fn timer1_gpio2_conf(&mut self) -> TIMER1_GPIO2_CONF_W { + TIMER1_GPIO2_CONF_W { w: self } + } + #[doc = "Bit 13 - 0 = On each event store the counter value 1 = On each event store the RTC time stamp"] + #[inline(always)] + pub fn timer1_in1_stamp_type(&mut self) -> TIMER1_IN1_STAMP_TYPE_W { + TIMER1_IN1_STAMP_TYPE_W { w: self } + } + #[doc = "Bits 7:12 - Gives the number of periods +1 of IN1, in which module counts"] + #[inline(always)] + pub fn timer1_in1_period_max(&mut self) -> TIMER1_IN1_PERIOD_MAX_W { + TIMER1_IN1_PERIOD_MAX_W { w: self } + } + #[doc = "Bit 6 - 1 = Interrupt is generated when capture is occurred or was counted TIMER1_IN1_PERIOD_MAX 0 = Interrupt is masked"] + #[inline(always)] + pub fn timer1_in1_irq_en(&mut self) -> TIMER1_IN1_IRQ_EN_W { + TIMER1_IN1_IRQ_EN_W { w: self } + } + #[doc = "Bit 5 - 0 = Capture mode 1 = Count mode"] + #[inline(always)] + pub fn timer1_in1_count_en(&mut self) -> TIMER1_IN1_COUNT_EN_W { + TIMER1_IN1_COUNT_EN_W { w: self } + } + #[doc = "Bit 4 - 0 = Rising edge event 1 = Falling edge event it should be written when TIMER1_GPIO1_CONF=0 to prevent false events"] + #[inline(always)] + pub fn timer1_in1_event_fall_en(&mut self) -> TIMER1_IN1_EVENT_FALL_EN_W { + TIMER1_IN1_EVENT_FALL_EN_W { w: self } + } + #[doc = "Bits 0:3 - 0,13,14,15 = IN1 is not used 1..12 = Defines the P0 pin (0..11) module will use as IN1"] + #[inline(always)] + pub fn timer1_gpio1_conf(&mut self) -> TIMER1_GPIO1_CONF_W { + TIMER1_GPIO1_CONF_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timer1 Capture control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer1_capture_reg](index.html) module"] +pub struct TIMER1_CAPTURE_REG_SPEC; +impl crate::RegisterSpec for TIMER1_CAPTURE_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [timer1_capture_reg::R](R) reader structure"] +impl crate::Readable for TIMER1_CAPTURE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer1_capture_reg::W](W) writer structure"] +impl crate::Writable for TIMER1_CAPTURE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER1_CAPTURE_REG to value 0"] +impl crate::Resettable for TIMER1_CAPTURE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer1/timer1_clr_event_reg.rs b/bitbox02-bt/vendor/da14531/src/timer1/timer1_clr_event_reg.rs new file mode 100644 index 0000000..3a8d241 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer1/timer1_clr_event_reg.rs @@ -0,0 +1,207 @@ +#[doc = "Register `TIMER1_CLR_EVENT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER1_CLR_EVENT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIMER1_CLR_IN2_EVENT` reader - Write 1 to clear the TIMER1_IN2_EVENT and TIMER1_IN2_OVRFLW"] +pub struct TIMER1_CLR_IN2_EVENT_R(crate::FieldReader); +impl TIMER1_CLR_IN2_EVENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_CLR_IN2_EVENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CLR_IN2_EVENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_CLR_IN2_EVENT` writer - Write 1 to clear the TIMER1_IN2_EVENT and TIMER1_IN2_OVRFLW"] +pub struct TIMER1_CLR_IN2_EVENT_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_CLR_IN2_EVENT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u32 & 1) << 2); + self.w + } +} +#[doc = "Field `TIMER1_CLR_IN1_EVENT` reader - Write 1 to clear the TIMER1_IN1_EVENT and TIMER1_IN1_OVRFLW"] +pub struct TIMER1_CLR_IN1_EVENT_R(crate::FieldReader); +impl TIMER1_CLR_IN1_EVENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_CLR_IN1_EVENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CLR_IN1_EVENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_CLR_IN1_EVENT` writer - Write 1 to clear the TIMER1_IN1_EVENT and TIMER1_IN1_OVRFLW"] +pub struct TIMER1_CLR_IN1_EVENT_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_CLR_IN1_EVENT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u32 & 1) << 1); + self.w + } +} +#[doc = "Field `TIMER1_CLR_TIMER_EVENT` reader - Write 1 to clear the TIMER1_TIMER_EVENT"] +pub struct TIMER1_CLR_TIMER_EVENT_R(crate::FieldReader); +impl TIMER1_CLR_TIMER_EVENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_CLR_TIMER_EVENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CLR_TIMER_EVENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_CLR_TIMER_EVENT` writer - Write 1 to clear the TIMER1_TIMER_EVENT"] +pub struct TIMER1_CLR_TIMER_EVENT_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_CLR_TIMER_EVENT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u32 & 1); + self.w + } +} +impl R { + #[doc = "Bit 2 - Write 1 to clear the TIMER1_IN2_EVENT and TIMER1_IN2_OVRFLW"] + #[inline(always)] + pub fn timer1_clr_in2_event(&self) -> TIMER1_CLR_IN2_EVENT_R { + TIMER1_CLR_IN2_EVENT_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Write 1 to clear the TIMER1_IN1_EVENT and TIMER1_IN1_OVRFLW"] + #[inline(always)] + pub fn timer1_clr_in1_event(&self) -> TIMER1_CLR_IN1_EVENT_R { + TIMER1_CLR_IN1_EVENT_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Write 1 to clear the TIMER1_TIMER_EVENT"] + #[inline(always)] + pub fn timer1_clr_timer_event(&self) -> TIMER1_CLR_TIMER_EVENT_R { + TIMER1_CLR_TIMER_EVENT_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 2 - Write 1 to clear the TIMER1_IN2_EVENT and TIMER1_IN2_OVRFLW"] + #[inline(always)] + pub fn timer1_clr_in2_event(&mut self) -> TIMER1_CLR_IN2_EVENT_W { + TIMER1_CLR_IN2_EVENT_W { w: self } + } + #[doc = "Bit 1 - Write 1 to clear the TIMER1_IN1_EVENT and TIMER1_IN1_OVRFLW"] + #[inline(always)] + pub fn timer1_clr_in1_event(&mut self) -> TIMER1_CLR_IN1_EVENT_W { + TIMER1_CLR_IN1_EVENT_W { w: self } + } + #[doc = "Bit 0 - Write 1 to clear the TIMER1_TIMER_EVENT"] + #[inline(always)] + pub fn timer1_clr_timer_event(&mut self) -> TIMER1_CLR_TIMER_EVENT_W { + TIMER1_CLR_TIMER_EVENT_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Clear event register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer1_clr_event_reg](index.html) module"] +pub struct TIMER1_CLR_EVENT_REG_SPEC; +impl crate::RegisterSpec for TIMER1_CLR_EVENT_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [timer1_clr_event_reg::R](R) reader structure"] +impl crate::Readable for TIMER1_CLR_EVENT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer1_clr_event_reg::W](W) writer structure"] +impl crate::Writable for TIMER1_CLR_EVENT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER1_CLR_EVENT_REG to value 0"] +impl crate::Resettable for TIMER1_CLR_EVENT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer1/timer1_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/timer1/timer1_ctrl_reg.rs new file mode 100644 index 0000000..959c6ac --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer1/timer1_ctrl_reg.rs @@ -0,0 +1,385 @@ +#[doc = "Register `TIMER1_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER1_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIMER1_CLK_EN` reader - 0 = timer1 clock is disabled 1 = timer1 clock is enabled"] +pub struct TIMER1_CLK_EN_R(crate::FieldReader); +impl TIMER1_CLK_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_CLK_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_CLK_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_CLK_EN` writer - 0 = timer1 clock is disabled 1 = timer1 clock is enabled"] +pub struct TIMER1_CLK_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_CLK_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 16)) | ((value as u32 & 1) << 16); + self.w + } +} +#[doc = "Field `TIMER1_USE_SYS_CLK` reader - 0 = Timer1 use the clock LP clock 1 = Timer1 use the system clock"] +pub struct TIMER1_USE_SYS_CLK_R(crate::FieldReader); +impl TIMER1_USE_SYS_CLK_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_USE_SYS_CLK_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_USE_SYS_CLK_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_USE_SYS_CLK` writer - 0 = Timer1 use the clock LP clock 1 = Timer1 use the system clock"] +pub struct TIMER1_USE_SYS_CLK_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_USE_SYS_CLK_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 15)) | ((value as u32 & 1) << 15); + self.w + } +} +#[doc = "Field `TIMER1_FREE_RUN_MODE_EN` reader - Applicable when timer counts up 1 = timer1 goes to zero when it reaches the max value. 0 = timer1 goes to zero when it reaches the reload value."] +pub struct TIMER1_FREE_RUN_MODE_EN_R(crate::FieldReader); +impl TIMER1_FREE_RUN_MODE_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_FREE_RUN_MODE_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_FREE_RUN_MODE_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_FREE_RUN_MODE_EN` writer - Applicable when timer counts up 1 = timer1 goes to zero when it reaches the max value. 0 = timer1 goes to zero when it reaches the reload value."] +pub struct TIMER1_FREE_RUN_MODE_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_FREE_RUN_MODE_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 14)) | ((value as u32 & 1) << 14); + self.w + } +} +#[doc = "Field `TIMER1_IRQ_EN` reader - 0 = timer1 IRQ masked 1 = timer1 IRQ unmasked"] +pub struct TIMER1_IRQ_EN_R(crate::FieldReader); +impl TIMER1_IRQ_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IRQ_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IRQ_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IRQ_EN` writer - 0 = timer1 IRQ masked 1 = timer1 IRQ unmasked"] +pub struct TIMER1_IRQ_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_IRQ_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 13)) | ((value as u32 & 1) << 13); + self.w + } +} +#[doc = "Field `TIMER1_COUNT_DOWN_EN` reader - 0 = timer1 counts up 1 = timer1 counts down"] +pub struct TIMER1_COUNT_DOWN_EN_R(crate::FieldReader); +impl TIMER1_COUNT_DOWN_EN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_COUNT_DOWN_EN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_COUNT_DOWN_EN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_COUNT_DOWN_EN` writer - 0 = timer1 counts up 1 = timer1 counts down"] +pub struct TIMER1_COUNT_DOWN_EN_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_COUNT_DOWN_EN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 12)) | ((value as u32 & 1) << 12); + self.w + } +} +#[doc = "Field `TIMER1_ENABLE` reader - 0 = Timer1 disabled 1 = Timer1 enabled"] +pub struct TIMER1_ENABLE_R(crate::FieldReader); +impl TIMER1_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_ENABLE` writer - 0 = Timer1 disabled 1 = Timer1 enabled"] +pub struct TIMER1_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 11)) | ((value as u32 & 1) << 11); + self.w + } +} +#[doc = "Field `TIMER1_RELOAD` reader - Reload or max value in timer mode. Actual delay is the register value plus synchronization time (3 clock cycles)"] +pub struct TIMER1_RELOAD_R(crate::FieldReader); +impl TIMER1_RELOAD_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIMER1_RELOAD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_RELOAD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_RELOAD` writer - Reload or max value in timer mode. Actual delay is the register value plus synchronization time (3 clock cycles)"] +pub struct TIMER1_RELOAD_W<'a> { + w: &'a mut W, +} +impl<'a> TIMER1_RELOAD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x07ff) | (value as u32 & 0x07ff); + self.w + } +} +impl R { + #[doc = "Bit 16 - 0 = timer1 clock is disabled 1 = timer1 clock is enabled"] + #[inline(always)] + pub fn timer1_clk_en(&self) -> TIMER1_CLK_EN_R { + TIMER1_CLK_EN_R::new(((self.bits >> 16) & 1) != 0) + } + #[doc = "Bit 15 - 0 = Timer1 use the clock LP clock 1 = Timer1 use the system clock"] + #[inline(always)] + pub fn timer1_use_sys_clk(&self) -> TIMER1_USE_SYS_CLK_R { + TIMER1_USE_SYS_CLK_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14 - Applicable when timer counts up 1 = timer1 goes to zero when it reaches the max value. 0 = timer1 goes to zero when it reaches the reload value."] + #[inline(always)] + pub fn timer1_free_run_mode_en(&self) -> TIMER1_FREE_RUN_MODE_EN_R { + TIMER1_FREE_RUN_MODE_EN_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13 - 0 = timer1 IRQ masked 1 = timer1 IRQ unmasked"] + #[inline(always)] + pub fn timer1_irq_en(&self) -> TIMER1_IRQ_EN_R { + TIMER1_IRQ_EN_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12 - 0 = timer1 counts up 1 = timer1 counts down"] + #[inline(always)] + pub fn timer1_count_down_en(&self) -> TIMER1_COUNT_DOWN_EN_R { + TIMER1_COUNT_DOWN_EN_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11 - 0 = Timer1 disabled 1 = Timer1 enabled"] + #[inline(always)] + pub fn timer1_enable(&self) -> TIMER1_ENABLE_R { + TIMER1_ENABLE_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bits 0:10 - Reload or max value in timer mode. Actual delay is the register value plus synchronization time (3 clock cycles)"] + #[inline(always)] + pub fn timer1_reload(&self) -> TIMER1_RELOAD_R { + TIMER1_RELOAD_R::new((self.bits & 0x07ff) as u16) + } +} +impl W { + #[doc = "Bit 16 - 0 = timer1 clock is disabled 1 = timer1 clock is enabled"] + #[inline(always)] + pub fn timer1_clk_en(&mut self) -> TIMER1_CLK_EN_W { + TIMER1_CLK_EN_W { w: self } + } + #[doc = "Bit 15 - 0 = Timer1 use the clock LP clock 1 = Timer1 use the system clock"] + #[inline(always)] + pub fn timer1_use_sys_clk(&mut self) -> TIMER1_USE_SYS_CLK_W { + TIMER1_USE_SYS_CLK_W { w: self } + } + #[doc = "Bit 14 - Applicable when timer counts up 1 = timer1 goes to zero when it reaches the max value. 0 = timer1 goes to zero when it reaches the reload value."] + #[inline(always)] + pub fn timer1_free_run_mode_en(&mut self) -> TIMER1_FREE_RUN_MODE_EN_W { + TIMER1_FREE_RUN_MODE_EN_W { w: self } + } + #[doc = "Bit 13 - 0 = timer1 IRQ masked 1 = timer1 IRQ unmasked"] + #[inline(always)] + pub fn timer1_irq_en(&mut self) -> TIMER1_IRQ_EN_W { + TIMER1_IRQ_EN_W { w: self } + } + #[doc = "Bit 12 - 0 = timer1 counts up 1 = timer1 counts down"] + #[inline(always)] + pub fn timer1_count_down_en(&mut self) -> TIMER1_COUNT_DOWN_EN_W { + TIMER1_COUNT_DOWN_EN_W { w: self } + } + #[doc = "Bit 11 - 0 = Timer1 disabled 1 = Timer1 enabled"] + #[inline(always)] + pub fn timer1_enable(&mut self) -> TIMER1_ENABLE_W { + TIMER1_ENABLE_W { w: self } + } + #[doc = "Bits 0:10 - Reload or max value in timer mode. Actual delay is the register value plus synchronization time (3 clock cycles)"] + #[inline(always)] + pub fn timer1_reload(&mut self) -> TIMER1_RELOAD_W { + TIMER1_RELOAD_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timer1 control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer1_ctrl_reg](index.html) module"] +pub struct TIMER1_CTRL_REG_SPEC; +impl crate::RegisterSpec for TIMER1_CTRL_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [timer1_ctrl_reg::R](R) reader structure"] +impl crate::Readable for TIMER1_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer1_ctrl_reg::W](W) writer structure"] +impl crate::Writable for TIMER1_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER1_CTRL_REG to value 0"] +impl crate::Resettable for TIMER1_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/timer1/timer1_status_reg.rs b/bitbox02-bt/vendor/da14531/src/timer1/timer1_status_reg.rs new file mode 100644 index 0000000..632c369 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/timer1/timer1_status_reg.rs @@ -0,0 +1,186 @@ +#[doc = "Register `TIMER1_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `TIMER1_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `TIMER1_IN2_OVRFLW` reader - 1 = New IN2 event occurred while Interrupt was pending. TIMER1_CAPCNT2_VALUE_REG gives the time stamp of the first event."] +pub struct TIMER1_IN2_OVRFLW_R(crate::FieldReader); +impl TIMER1_IN2_OVRFLW_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN2_OVRFLW_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN2_OVRFLW_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN1_OVRFLW` reader - 1 = New IN1 event occurred while Interrupt was pending. TIMER1_CAPCNT1_VALUE_REG gives the time stamp of the first event."] +pub struct TIMER1_IN1_OVRFLW_R(crate::FieldReader); +impl TIMER1_IN1_OVRFLW_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN1_OVRFLW_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN1_OVRFLW_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN2_EVENT` reader - 1 = Pending Capture 2 interrupt. It has be clear writing 1 to TIMER1_CLR_IN2_EVENT"] +pub struct TIMER1_IN2_EVENT_R(crate::FieldReader); +impl TIMER1_IN2_EVENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN2_EVENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN2_EVENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_IN1_EVENT` reader - 1 = Pending Capture 1 interrupt. It has be clear writing 1 to TIMER1_CLR_IN1_EVENT"] +pub struct TIMER1_IN1_EVENT_R(crate::FieldReader); +impl TIMER1_IN1_EVENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_IN1_EVENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_IN1_EVENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_TIMER_EVENT` reader - 1 = Pending Timer interrupt. it has be clear writing 1' to TIMER1_CLR_TIMER_EVENT"] +pub struct TIMER1_TIMER_EVENT_R(crate::FieldReader); +impl TIMER1_TIMER_EVENT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + TIMER1_TIMER_EVENT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_TIMER_EVENT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `TIMER1_TIMER_VALUE` reader - Gives the current timer value"] +pub struct TIMER1_TIMER_VALUE_R(crate::FieldReader); +impl TIMER1_TIMER_VALUE_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + TIMER1_TIMER_VALUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for TIMER1_TIMER_VALUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 15 - 1 = New IN2 event occurred while Interrupt was pending. TIMER1_CAPCNT2_VALUE_REG gives the time stamp of the first event."] + #[inline(always)] + pub fn timer1_in2_ovrflw(&self) -> TIMER1_IN2_OVRFLW_R { + TIMER1_IN2_OVRFLW_R::new(((self.bits >> 15) & 1) != 0) + } + #[doc = "Bit 14 - 1 = New IN1 event occurred while Interrupt was pending. TIMER1_CAPCNT1_VALUE_REG gives the time stamp of the first event."] + #[inline(always)] + pub fn timer1_in1_ovrflw(&self) -> TIMER1_IN1_OVRFLW_R { + TIMER1_IN1_OVRFLW_R::new(((self.bits >> 14) & 1) != 0) + } + #[doc = "Bit 13 - 1 = Pending Capture 2 interrupt. It has be clear writing 1 to TIMER1_CLR_IN2_EVENT"] + #[inline(always)] + pub fn timer1_in2_event(&self) -> TIMER1_IN2_EVENT_R { + TIMER1_IN2_EVENT_R::new(((self.bits >> 13) & 1) != 0) + } + #[doc = "Bit 12 - 1 = Pending Capture 1 interrupt. It has be clear writing 1 to TIMER1_CLR_IN1_EVENT"] + #[inline(always)] + pub fn timer1_in1_event(&self) -> TIMER1_IN1_EVENT_R { + TIMER1_IN1_EVENT_R::new(((self.bits >> 12) & 1) != 0) + } + #[doc = "Bit 11 - 1 = Pending Timer interrupt. it has be clear writing 1' to TIMER1_CLR_TIMER_EVENT"] + #[inline(always)] + pub fn timer1_timer_event(&self) -> TIMER1_TIMER_EVENT_R { + TIMER1_TIMER_EVENT_R::new(((self.bits >> 11) & 1) != 0) + } + #[doc = "Bits 0:10 - Gives the current timer value"] + #[inline(always)] + pub fn timer1_timer_value(&self) -> TIMER1_TIMER_VALUE_R { + TIMER1_TIMER_VALUE_R::new((self.bits & 0x07ff) as u16) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Timer1 counter value\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timer1_status_reg](index.html) module"] +pub struct TIMER1_STATUS_REG_SPEC; +impl crate::RegisterSpec for TIMER1_STATUS_REG_SPEC { + type Ux = u32; +} +#[doc = "`read()` method returns [timer1_status_reg::R](R) reader structure"] +impl crate::Readable for TIMER1_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [timer1_status_reg::W](W) writer structure"] +impl crate::Writable for TIMER1_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets TIMER1_STATUS_REG to value 0"] +impl crate::Resettable for TIMER1_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart.rs b/bitbox02-bt/vendor/da14531/src/uart.rs new file mode 100644 index 0000000..a83c307 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart.rs @@ -0,0 +1,294 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Receive Buffer Register/Transmit Holding Register/Divisor Latch Low"] + pub uart_rbr_thr_dll_reg: crate::Reg, + _reserved1: [u8; 0x02], + #[doc = "0x04 - Interrupt Enable Register/Divisor Latch High"] + pub uart_ier_dlh_reg: crate::Reg, + _reserved2: [u8; 0x02], + #[doc = "0x08 - Interrupt Identification Register/FIFO Control Register"] + pub uart_iir_fcr_reg: crate::Reg, + _reserved3: [u8; 0x02], + #[doc = "0x0c - Line Control Register"] + pub uart_lcr_reg: crate::Reg, + _reserved4: [u8; 0x02], + #[doc = "0x10 - Modem Control Register"] + pub uart_mcr_reg: crate::Reg, + _reserved5: [u8; 0x02], + #[doc = "0x14 - Line Status Register"] + pub uart_lsr_reg: crate::Reg, + _reserved6: [u8; 0x02], + #[doc = "0x18 - Modem Status Register"] + pub uart_msr_reg: crate::Reg, + _reserved7: [u8; 0x02], + #[doc = "0x1c - Scratchpad Register"] + pub uart_scr_reg: crate::Reg, + _reserved8: [u8; 0x12], + #[doc = "0x30 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr0_reg: crate::Reg, + _reserved9: [u8; 0x02], + #[doc = "0x34 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr1_reg: crate::Reg, + _reserved10: [u8; 0x02], + #[doc = "0x38 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr2_reg: crate::Reg, + _reserved11: [u8; 0x02], + #[doc = "0x3c - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr3_reg: crate::Reg, + _reserved12: [u8; 0x02], + #[doc = "0x40 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr4_reg: crate::Reg, + _reserved13: [u8; 0x02], + #[doc = "0x44 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr5_reg: crate::Reg, + _reserved14: [u8; 0x02], + #[doc = "0x48 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr6_reg: crate::Reg, + _reserved15: [u8; 0x02], + #[doc = "0x4c - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr7_reg: crate::Reg, + _reserved16: [u8; 0x02], + #[doc = "0x50 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr8_reg: crate::Reg, + _reserved17: [u8; 0x02], + #[doc = "0x54 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr9_reg: crate::Reg, + _reserved18: [u8; 0x02], + #[doc = "0x58 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr10_reg: crate::Reg, + _reserved19: [u8; 0x02], + #[doc = "0x5c - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr11_reg: crate::Reg, + _reserved20: [u8; 0x02], + #[doc = "0x60 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr12_reg: crate::Reg, + _reserved21: [u8; 0x02], + #[doc = "0x64 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr13_reg: crate::Reg, + _reserved22: [u8; 0x02], + #[doc = "0x68 - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr14_reg: crate::Reg, + _reserved23: [u8; 0x02], + #[doc = "0x6c - Shadow Receive/Transmit Buffer Register"] + pub uart_srbr_sthr15_reg: crate::Reg, + _reserved24: [u8; 0x02], + #[doc = "0x70 - FIFO Access Register"] + pub uart_far_reg: crate::Reg, + _reserved25: [u8; 0x0a], + #[doc = "0x7c - UART Status Register"] + pub uart_usr_reg: crate::Reg, + _reserved26: [u8; 0x02], + #[doc = "0x80 - Transmit FIFO Level"] + pub uart_tfl_reg: crate::Reg, + _reserved27: [u8; 0x02], + #[doc = "0x84 - Receive FIFO Level"] + pub uart_rfl_reg: crate::Reg, + _reserved28: [u8; 0x02], + #[doc = "0x88 - Software Reset Register."] + pub uart_srr_reg: crate::Reg, + _reserved29: [u8; 0x02], + #[doc = "0x8c - Shadow Request to Send"] + pub uart_srts_reg: crate::Reg, + _reserved30: [u8; 0x02], + #[doc = "0x90 - Shadow Break Control Register"] + pub uart_sbcr_reg: crate::Reg, + _reserved31: [u8; 0x02], + #[doc = "0x94 - Shadow DMA Mode"] + pub uart_sdmam_reg: crate::Reg, + _reserved32: [u8; 0x02], + #[doc = "0x98 - Shadow FIFO Enable"] + pub uart_sfe_reg: crate::Reg, + _reserved33: [u8; 0x02], + #[doc = "0x9c - Shadow RCVR Trigger"] + pub uart_srt_reg: crate::Reg, + _reserved34: [u8; 0x02], + #[doc = "0xa0 - Shadow TX Empty Trigger"] + pub uart_stet_reg: crate::Reg, + _reserved35: [u8; 0x02], + #[doc = "0xa4 - Halt TX"] + pub uart_htx_reg: crate::Reg, + _reserved36: [u8; 0x02], + #[doc = "0xa8 - DMA Software Acknowledge"] + pub uart_dmasa_reg: crate::Reg, + _reserved37: [u8; 0x16], + #[doc = "0xc0 - Divisor Latch Fraction Register"] + pub uart_dlf_reg: crate::Reg, + _reserved38: [u8; 0x36], + #[doc = "0xf8 - Component Version"] + pub uart_ucv_reg: crate::Reg, + #[doc = "0xfa - Component Version"] + pub uart_ucv_high_reg: crate::Reg, + #[doc = "0xfc - Component Type Register"] + pub uart_ctr_reg: crate::Reg, + #[doc = "0xfe - Component Type Register"] + pub uart_ctr_high_reg: crate::Reg, +} +#[doc = "UART_CTR_HIGH_REG register accessor: an alias for `Reg`"] +pub type UART_CTR_HIGH_REG = crate::Reg; +#[doc = "Component Type Register"] +pub mod uart_ctr_high_reg; +#[doc = "UART_CTR_REG register accessor: an alias for `Reg`"] +pub type UART_CTR_REG = crate::Reg; +#[doc = "Component Type Register"] +pub mod uart_ctr_reg; +#[doc = "UART_DLF_REG register accessor: an alias for `Reg`"] +pub type UART_DLF_REG = crate::Reg; +#[doc = "Divisor Latch Fraction Register"] +pub mod uart_dlf_reg; +#[doc = "UART_DMASA_REG register accessor: an alias for `Reg`"] +pub type UART_DMASA_REG = crate::Reg; +#[doc = "DMA Software Acknowledge"] +pub mod uart_dmasa_reg; +#[doc = "UART_FAR_REG register accessor: an alias for `Reg`"] +pub type UART_FAR_REG = crate::Reg; +#[doc = "FIFO Access Register"] +pub mod uart_far_reg; +#[doc = "UART_HTX_REG register accessor: an alias for `Reg`"] +pub type UART_HTX_REG = crate::Reg; +#[doc = "Halt TX"] +pub mod uart_htx_reg; +#[doc = "UART_IER_DLH_REG register accessor: an alias for `Reg`"] +pub type UART_IER_DLH_REG = crate::Reg; +#[doc = "Interrupt Enable Register/Divisor Latch High"] +pub mod uart_ier_dlh_reg; +#[doc = "UART_IIR_FCR_REG register accessor: an alias for `Reg`"] +pub type UART_IIR_FCR_REG = crate::Reg; +#[doc = "Interrupt Identification Register/FIFO Control Register"] +pub mod uart_iir_fcr_reg; +#[doc = "UART_LCR_REG register accessor: an alias for `Reg`"] +pub type UART_LCR_REG = crate::Reg; +#[doc = "Line Control Register"] +pub mod uart_lcr_reg; +#[doc = "UART_LSR_REG register accessor: an alias for `Reg`"] +pub type UART_LSR_REG = crate::Reg; +#[doc = "Line Status Register"] +pub mod uart_lsr_reg; +#[doc = "UART_MCR_REG register accessor: an alias for `Reg`"] +pub type UART_MCR_REG = crate::Reg; +#[doc = "Modem Control Register"] +pub mod uart_mcr_reg; +#[doc = "UART_MSR_REG register accessor: an alias for `Reg`"] +pub type UART_MSR_REG = crate::Reg; +#[doc = "Modem Status Register"] +pub mod uart_msr_reg; +#[doc = "UART_RBR_THR_DLL_REG register accessor: an alias for `Reg`"] +pub type UART_RBR_THR_DLL_REG = crate::Reg; +#[doc = "Receive Buffer Register/Transmit Holding Register/Divisor Latch Low"] +pub mod uart_rbr_thr_dll_reg; +#[doc = "UART_RFL_REG register accessor: an alias for `Reg`"] +pub type UART_RFL_REG = crate::Reg; +#[doc = "Receive FIFO Level"] +pub mod uart_rfl_reg; +#[doc = "UART_SBCR_REG register accessor: an alias for `Reg`"] +pub type UART_SBCR_REG = crate::Reg; +#[doc = "Shadow Break Control Register"] +pub mod uart_sbcr_reg; +#[doc = "UART_SCR_REG register accessor: an alias for `Reg`"] +pub type UART_SCR_REG = crate::Reg; +#[doc = "Scratchpad Register"] +pub mod uart_scr_reg; +#[doc = "UART_SDMAM_REG register accessor: an alias for `Reg`"] +pub type UART_SDMAM_REG = crate::Reg; +#[doc = "Shadow DMA Mode"] +pub mod uart_sdmam_reg; +#[doc = "UART_SFE_REG register accessor: an alias for `Reg`"] +pub type UART_SFE_REG = crate::Reg; +#[doc = "Shadow FIFO Enable"] +pub mod uart_sfe_reg; +#[doc = "UART_SRBR_STHR0_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR0_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr0_reg; +#[doc = "UART_SRBR_STHR10_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR10_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr10_reg; +#[doc = "UART_SRBR_STHR11_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR11_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr11_reg; +#[doc = "UART_SRBR_STHR12_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR12_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr12_reg; +#[doc = "UART_SRBR_STHR13_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR13_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr13_reg; +#[doc = "UART_SRBR_STHR14_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR14_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr14_reg; +#[doc = "UART_SRBR_STHR15_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR15_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr15_reg; +#[doc = "UART_SRBR_STHR1_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR1_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr1_reg; +#[doc = "UART_SRBR_STHR2_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR2_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr2_reg; +#[doc = "UART_SRBR_STHR3_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR3_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr3_reg; +#[doc = "UART_SRBR_STHR4_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR4_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr4_reg; +#[doc = "UART_SRBR_STHR5_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR5_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr5_reg; +#[doc = "UART_SRBR_STHR6_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR6_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr6_reg; +#[doc = "UART_SRBR_STHR7_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR7_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr7_reg; +#[doc = "UART_SRBR_STHR8_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR8_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr8_reg; +#[doc = "UART_SRBR_STHR9_REG register accessor: an alias for `Reg`"] +pub type UART_SRBR_STHR9_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart_srbr_sthr9_reg; +#[doc = "UART_SRR_REG register accessor: an alias for `Reg`"] +pub type UART_SRR_REG = crate::Reg; +#[doc = "Software Reset Register."] +pub mod uart_srr_reg; +#[doc = "UART_SRTS_REG register accessor: an alias for `Reg`"] +pub type UART_SRTS_REG = crate::Reg; +#[doc = "Shadow Request to Send"] +pub mod uart_srts_reg; +#[doc = "UART_SRT_REG register accessor: an alias for `Reg`"] +pub type UART_SRT_REG = crate::Reg; +#[doc = "Shadow RCVR Trigger"] +pub mod uart_srt_reg; +#[doc = "UART_STET_REG register accessor: an alias for `Reg`"] +pub type UART_STET_REG = crate::Reg; +#[doc = "Shadow TX Empty Trigger"] +pub mod uart_stet_reg; +#[doc = "UART_TFL_REG register accessor: an alias for `Reg`"] +pub type UART_TFL_REG = crate::Reg; +#[doc = "Transmit FIFO Level"] +pub mod uart_tfl_reg; +#[doc = "UART_UCV_HIGH_REG register accessor: an alias for `Reg`"] +pub type UART_UCV_HIGH_REG = crate::Reg; +#[doc = "Component Version"] +pub mod uart_ucv_high_reg; +#[doc = "UART_UCV_REG register accessor: an alias for `Reg`"] +pub type UART_UCV_REG = crate::Reg; +#[doc = "Component Version"] +pub mod uart_ucv_reg; +#[doc = "UART_USR_REG register accessor: an alias for `Reg`"] +pub type UART_USR_REG = crate::Reg; +#[doc = "UART Status Register"] +pub mod uart_usr_reg; diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_ctr_high_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_ctr_high_reg.rs new file mode 100644 index 0000000..8c8e0e0 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_ctr_high_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART_CTR_HIGH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_CTR_HIGH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CTR` reader - Component Type Register"] +pub struct CTR_R(crate::FieldReader); +impl CTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Type Register"] + #[inline(always)] + pub fn ctr(&self) -> CTR_R { + CTR_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Type Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_ctr_high_reg](index.html) module"] +pub struct UART_CTR_HIGH_REG_SPEC; +impl crate::RegisterSpec for UART_CTR_HIGH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_ctr_high_reg::R](R) reader structure"] +impl crate::Readable for UART_CTR_HIGH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_ctr_high_reg::W](W) writer structure"] +impl crate::Writable for UART_CTR_HIGH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_CTR_HIGH_REG to value 0x4457"] +impl crate::Resettable for UART_CTR_HIGH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x4457 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_ctr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_ctr_reg.rs new file mode 100644 index 0000000..ca6183c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_ctr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART_CTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_CTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CTR` reader - Component Type Register"] +pub struct CTR_R(crate::FieldReader); +impl CTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Type Register"] + #[inline(always)] + pub fn ctr(&self) -> CTR_R { + CTR_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Type Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_ctr_reg](index.html) module"] +pub struct UART_CTR_REG_SPEC; +impl crate::RegisterSpec for UART_CTR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_ctr_reg::R](R) reader structure"] +impl crate::Readable for UART_CTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_ctr_reg::W](W) writer structure"] +impl crate::Writable for UART_CTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_CTR_REG to value 0x0110"] +impl crate::Resettable for UART_CTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0110 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_dlf_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_dlf_reg.rs new file mode 100644 index 0000000..6237543 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_dlf_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART_DLF_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_DLF_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_DLF` reader - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] +pub struct UART_DLF_R(crate::FieldReader); +impl UART_DLF_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_DLF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DLF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DLF` writer - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] +pub struct UART_DLF_W<'a> { + w: &'a mut W, +} +impl<'a> UART_DLF_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 0:3 - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] + #[inline(always)] + pub fn uart_dlf(&self) -> UART_DLF_R { + UART_DLF_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 0:3 - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] + #[inline(always)] + pub fn uart_dlf(&mut self) -> UART_DLF_W { + UART_DLF_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Divisor Latch Fraction Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_dlf_reg](index.html) module"] +pub struct UART_DLF_REG_SPEC; +impl crate::RegisterSpec for UART_DLF_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_dlf_reg::R](R) reader structure"] +impl crate::Readable for UART_DLF_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_dlf_reg::W](W) writer structure"] +impl crate::Writable for UART_DLF_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_DLF_REG to value 0"] +impl crate::Resettable for UART_DLF_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_dmasa_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_dmasa_reg.rs new file mode 100644 index 0000000..7968e01 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_dmasa_reg.rs @@ -0,0 +1,91 @@ +#[doc = "Register `UART_DMASA_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_DMASA_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DMASA` writer - This register is use to perform DMA software acknowledge if a transfer needs to be terminated due to an error condition. For example, if the DMA disables the channel, then the DW_apb_uart should clear its request. This will cause the TX request, TX single, RX request and RX single signals to de-assert. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct DMASA_W<'a> { + w: &'a mut W, +} +impl<'a> DMASA_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl W { + #[doc = "Bit 0 - This register is use to perform DMA software acknowledge if a transfer needs to be terminated due to an error condition. For example, if the DMA disables the channel, then the DW_apb_uart should clear its request. This will cause the TX request, TX single, RX request and RX single signals to de-assert. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn dmasa(&mut self) -> DMASA_W { + DMASA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "DMA Software Acknowledge\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_dmasa_reg](index.html) module"] +pub struct UART_DMASA_REG_SPEC; +impl crate::RegisterSpec for UART_DMASA_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_dmasa_reg::R](R) reader structure"] +impl crate::Readable for UART_DMASA_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_dmasa_reg::W](W) writer structure"] +impl crate::Writable for UART_DMASA_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_DMASA_REG to value 0"] +impl crate::Resettable for UART_DMASA_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_far_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_far_reg.rs new file mode 100644 index 0000000..b53d3fc --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_far_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART_FAR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_FAR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_FAR` reader - Description: Writes will have no effect when FIFO_ACCESS == No, always readable. This register is use to enable a FIFO access mode for testing, so that the receive FIFO can be written by the master and the transmit FIFO can be read by the master when FIFO's are implemented and enabled. When FIFO's are not implemented or not enabled it allows the RBR to be written by the master and the THR to be read by the master. 0 = FIFO access mode disabled 1 = FIFO access mode enabled Note, that when the FIFO access mode is enabled/disabled, the control portion of the receive FIFO and transmit FIFO is reset and the FIFO's are treated as empty."] +pub struct UART_FAR_R(crate::FieldReader); +impl UART_FAR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_FAR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_FAR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Description: Writes will have no effect when FIFO_ACCESS == No, always readable. This register is use to enable a FIFO access mode for testing, so that the receive FIFO can be written by the master and the transmit FIFO can be read by the master when FIFO's are implemented and enabled. When FIFO's are not implemented or not enabled it allows the RBR to be written by the master and the THR to be read by the master. 0 = FIFO access mode disabled 1 = FIFO access mode enabled Note, that when the FIFO access mode is enabled/disabled, the control portion of the receive FIFO and transmit FIFO is reset and the FIFO's are treated as empty."] + #[inline(always)] + pub fn uart_far(&self) -> UART_FAR_R { + UART_FAR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "FIFO Access Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_far_reg](index.html) module"] +pub struct UART_FAR_REG_SPEC; +impl crate::RegisterSpec for UART_FAR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_far_reg::R](R) reader structure"] +impl crate::Readable for UART_FAR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_far_reg::W](W) writer structure"] +impl crate::Writable for UART_FAR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_FAR_REG to value 0"] +impl crate::Resettable for UART_FAR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_htx_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_htx_reg.rs new file mode 100644 index 0000000..3102732 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_htx_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `UART_HTX_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_HTX_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_HALT_TX` reader - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] +pub struct UART_HALT_TX_R(crate::FieldReader); +impl UART_HALT_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_HALT_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_HALT_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_HALT_TX` writer - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] +pub struct UART_HALT_TX_W<'a> { + w: &'a mut W, +} +impl<'a> UART_HALT_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] + #[inline(always)] + pub fn uart_halt_tx(&self) -> UART_HALT_TX_R { + UART_HALT_TX_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] + #[inline(always)] + pub fn uart_halt_tx(&mut self) -> UART_HALT_TX_W { + UART_HALT_TX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Halt TX\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_htx_reg](index.html) module"] +pub struct UART_HTX_REG_SPEC; +impl crate::RegisterSpec for UART_HTX_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_htx_reg::R](R) reader structure"] +impl crate::Readable for UART_HTX_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_htx_reg::W](W) writer structure"] +impl crate::Writable for UART_HTX_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_HTX_REG to value 0"] +impl crate::Resettable for UART_HTX_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_ier_dlh_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_ier_dlh_reg.rs new file mode 100644 index 0000000..e012272 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_ier_dlh_reg.rs @@ -0,0 +1,338 @@ +#[doc = "Register `UART_IER_DLH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_IER_DLH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PTIME_dlh7` reader - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct PTIME_DLH7_R(crate::FieldReader); +impl PTIME_DLH7_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PTIME_DLH7_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PTIME_DLH7_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PTIME_dlh7` writer - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct PTIME_DLH7_W<'a> { + w: &'a mut W, +} +impl<'a> PTIME_DLH7_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `dlh6_4` reader - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] +pub struct DLH6_4_R(crate::FieldReader); +impl DLH6_4_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DLH6_4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DLH6_4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `dlh6_4` writer - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] +pub struct DLH6_4_W<'a> { + w: &'a mut W, +} +impl<'a> DLH6_4_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u16 & 7) << 4); + self.w + } +} +#[doc = "Field `EDSSI_dlh3` reader - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct EDSSI_DLH3_R(crate::FieldReader); +impl EDSSI_DLH3_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EDSSI_DLH3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EDSSI_DLH3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EDSSI_dlh3` writer - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct EDSSI_DLH3_W<'a> { + w: &'a mut W, +} +impl<'a> EDSSI_DLH3_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `ELSI_dhl2` reader - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ELSI_DHL2_R(crate::FieldReader); +impl ELSI_DHL2_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ELSI_DHL2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ELSI_DHL2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ELSI_dhl2` writer - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ELSI_DHL2_W<'a> { + w: &'a mut W, +} +impl<'a> ELSI_DHL2_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `ETBEI_dlh1` reader - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ETBEI_DLH1_R(crate::FieldReader); +impl ETBEI_DLH1_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ETBEI_DLH1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ETBEI_DLH1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ETBEI_dlh1` writer - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ETBEI_DLH1_W<'a> { + w: &'a mut W, +} +impl<'a> ETBEI_DLH1_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `ERBFI_dlh0` reader - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ERBFI_DLH0_R(crate::FieldReader); +impl ERBFI_DLH0_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ERBFI_DLH0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ERBFI_DLH0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ERBFI_dlh0` writer - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ERBFI_DLH0_W<'a> { + w: &'a mut W, +} +impl<'a> ERBFI_DLH0_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 7 - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn ptime_dlh7(&self) -> PTIME_DLH7_R { + PTIME_DLH7_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 4:6 - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn dlh6_4(&self) -> DLH6_4_R { + DLH6_4_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bit 3 - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn edssi_dlh3(&self) -> EDSSI_DLH3_R { + EDSSI_DLH3_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn elsi_dhl2(&self) -> ELSI_DHL2_R { + ELSI_DHL2_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn etbei_dlh1(&self) -> ETBEI_DLH1_R { + ETBEI_DLH1_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn erbfi_dlh0(&self) -> ERBFI_DLH0_R { + ERBFI_DLH0_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 7 - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn ptime_dlh7(&mut self) -> PTIME_DLH7_W { + PTIME_DLH7_W { w: self } + } + #[doc = "Bits 4:6 - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn dlh6_4(&mut self) -> DLH6_4_W { + DLH6_4_W { w: self } + } + #[doc = "Bit 3 - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn edssi_dlh3(&mut self) -> EDSSI_DLH3_W { + EDSSI_DLH3_W { w: self } + } + #[doc = "Bit 2 - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn elsi_dhl2(&mut self) -> ELSI_DHL2_W { + ELSI_DHL2_W { w: self } + } + #[doc = "Bit 1 - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn etbei_dlh1(&mut self) -> ETBEI_DLH1_W { + ETBEI_DLH1_W { w: self } + } + #[doc = "Bit 0 - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn erbfi_dlh0(&mut self) -> ERBFI_DLH0_W { + ERBFI_DLH0_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt Enable Register/Divisor Latch High\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_ier_dlh_reg](index.html) module"] +pub struct UART_IER_DLH_REG_SPEC; +impl crate::RegisterSpec for UART_IER_DLH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_ier_dlh_reg::R](R) reader structure"] +impl crate::Readable for UART_IER_DLH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_ier_dlh_reg::W](W) writer structure"] +impl crate::Writable for UART_IER_DLH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_IER_DLH_REG to value 0"] +impl crate::Resettable for UART_IER_DLH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_iir_fcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_iir_fcr_reg.rs new file mode 100644 index 0000000..bba19c3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_iir_fcr_reg.rs @@ -0,0 +1,308 @@ +#[doc = "Register `UART_IIR_FCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_IIR_FCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_FIFOSE_RT` reader - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] +pub struct UART_FIFOSE_RT_R(crate::FieldReader); +impl UART_FIFOSE_RT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_FIFOSE_RT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_FIFOSE_RT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_FIFOSE_RT` writer - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] +pub struct UART_FIFOSE_RT_W<'a> { + w: &'a mut W, +} +impl<'a> UART_FIFOSE_RT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 6)) | ((value as u16 & 3) << 6); + self.w + } +} +#[doc = "Field `UART_TET` writer - On read reserved On Write TX Empty Trigger (or TET): This is used to select the empty threshold level at which the THRE Interrupts will be generated when the mode is active. It also determines when the dma_tx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO 1/4 full 11 = FIFO 1/2 full"] +pub struct UART_TET_W<'a> { + w: &'a mut W, +} +impl<'a> UART_TET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u16 & 3) << 4); + self.w + } +} +#[doc = "Field `UART_IID3_DMAM` reader - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_IID3_DMAM_R(crate::FieldReader); +impl UART_IID3_DMAM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID3_DMAM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID3_DMAM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID3_DMAM` writer - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_IID3_DMAM_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID3_DMAM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `UART_IID2_XFIFOR` reader - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID2_XFIFOR_R(crate::FieldReader); +impl UART_IID2_XFIFOR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID2_XFIFOR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID2_XFIFOR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID2_XFIFOR` writer - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID2_XFIFOR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID2_XFIFOR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `UART_IID1_RFIFOE` reader - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID1_RFIFOE_R(crate::FieldReader); +impl UART_IID1_RFIFOE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID1_RFIFOE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID1_RFIFOE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID1_RFIFOE` writer - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID1_RFIFOE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID1_RFIFOE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `UART_IID0_FIFOE` reader - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] +pub struct UART_IID0_FIFOE_R(crate::FieldReader); +impl UART_IID0_FIFOE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID0_FIFOE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID0_FIFOE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID0_FIFOE` writer - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] +pub struct UART_IID0_FIFOE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID0_FIFOE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 6:7 - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_fifose_rt(&self) -> UART_FIFOSE_RT_R { + UART_FIFOSE_RT_R::new(((self.bits >> 6) & 3) as u8) + } + #[doc = "Bit 3 - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_iid3_dmam(&self) -> UART_IID3_DMAM_R { + UART_IID3_DMAM_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid2_xfifor(&self) -> UART_IID2_XFIFOR_R { + UART_IID2_XFIFOR_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid1_rfifoe(&self) -> UART_IID1_RFIFOE_R { + UART_IID1_RFIFOE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] + #[inline(always)] + pub fn uart_iid0_fifoe(&self) -> UART_IID0_FIFOE_R { + UART_IID0_FIFOE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 6:7 - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_fifose_rt(&mut self) -> UART_FIFOSE_RT_W { + UART_FIFOSE_RT_W { w: self } + } + #[doc = "Bits 4:5 - On read reserved On Write TX Empty Trigger (or TET): This is used to select the empty threshold level at which the THRE Interrupts will be generated when the mode is active. It also determines when the dma_tx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO 1/4 full 11 = FIFO 1/2 full"] + #[inline(always)] + pub fn uart_tet(&mut self) -> UART_TET_W { + UART_TET_W { w: self } + } + #[doc = "Bit 3 - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_iid3_dmam(&mut self) -> UART_IID3_DMAM_W { + UART_IID3_DMAM_W { w: self } + } + #[doc = "Bit 2 - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid2_xfifor(&mut self) -> UART_IID2_XFIFOR_W { + UART_IID2_XFIFOR_W { w: self } + } + #[doc = "Bit 1 - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid1_rfifoe(&mut self) -> UART_IID1_RFIFOE_W { + UART_IID1_RFIFOE_W { w: self } + } + #[doc = "Bit 0 - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] + #[inline(always)] + pub fn uart_iid0_fifoe(&mut self) -> UART_IID0_FIFOE_W { + UART_IID0_FIFOE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt Identification Register/FIFO Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_iir_fcr_reg](index.html) module"] +pub struct UART_IIR_FCR_REG_SPEC; +impl crate::RegisterSpec for UART_IIR_FCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_iir_fcr_reg::R](R) reader structure"] +impl crate::Readable for UART_IIR_FCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_iir_fcr_reg::W](W) writer structure"] +impl crate::Writable for UART_IIR_FCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_IIR_FCR_REG to value 0x01"] +impl crate::Resettable for UART_IIR_FCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_lcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_lcr_reg.rs new file mode 100644 index 0000000..eb187df --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_lcr_reg.rs @@ -0,0 +1,366 @@ +#[doc = "Register `UART_LCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_LCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_DLAB` reader - Divisor Latch Access Bit. Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] +pub struct UART_DLAB_R(crate::FieldReader); +impl UART_DLAB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_DLAB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DLAB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DLAB` writer - Divisor Latch Access Bit. Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] +pub struct UART_DLAB_W<'a> { + w: &'a mut W, +} +impl<'a> UART_DLAB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `UART_BC` reader - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] +pub struct UART_BC_R(crate::FieldReader); +impl UART_BC_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_BC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_BC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_BC` writer - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] +pub struct UART_BC_W<'a> { + w: &'a mut W, +} +impl<'a> UART_BC_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `UART_EPS` reader - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] +pub struct UART_EPS_R(crate::FieldReader); +impl UART_EPS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_EPS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_EPS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_EPS` writer - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] +pub struct UART_EPS_W<'a> { + w: &'a mut W, +} +impl<'a> UART_EPS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `UART_PEN` reader - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] +pub struct UART_PEN_R(crate::FieldReader); +impl UART_PEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_PEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_PEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_PEN` writer - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] +pub struct UART_PEN_W<'a> { + w: &'a mut W, +} +impl<'a> UART_PEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `UART_STOP` reader - Number of stop bits.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] +pub struct UART_STOP_R(crate::FieldReader); +impl UART_STOP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_STOP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_STOP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_STOP` writer - Number of stop bits.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] +pub struct UART_STOP_W<'a> { + w: &'a mut W, +} +impl<'a> UART_STOP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `UART_DLS` reader - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] +pub struct UART_DLS_R(crate::FieldReader); +impl UART_DLS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_DLS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DLS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DLS` writer - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] +pub struct UART_DLS_W<'a> { + w: &'a mut W, +} +impl<'a> UART_DLS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 7 - Divisor Latch Access Bit. Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] + #[inline(always)] + pub fn uart_dlab(&self) -> UART_DLAB_R { + UART_DLAB_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] + #[inline(always)] + pub fn uart_bc(&self) -> UART_BC_R { + UART_BC_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 4 - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] + #[inline(always)] + pub fn uart_eps(&self) -> UART_EPS_R { + UART_EPS_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] + #[inline(always)] + pub fn uart_pen(&self) -> UART_PEN_R { + UART_PEN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Number of stop bits.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] + #[inline(always)] + pub fn uart_stop(&self) -> UART_STOP_R { + UART_STOP_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1 - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] + #[inline(always)] + pub fn uart_dls(&self) -> UART_DLS_R { + UART_DLS_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 7 - Divisor Latch Access Bit. Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] + #[inline(always)] + pub fn uart_dlab(&mut self) -> UART_DLAB_W { + UART_DLAB_W { w: self } + } + #[doc = "Bit 6 - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] + #[inline(always)] + pub fn uart_bc(&mut self) -> UART_BC_W { + UART_BC_W { w: self } + } + #[doc = "Bit 4 - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] + #[inline(always)] + pub fn uart_eps(&mut self) -> UART_EPS_W { + UART_EPS_W { w: self } + } + #[doc = "Bit 3 - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] + #[inline(always)] + pub fn uart_pen(&mut self) -> UART_PEN_W { + UART_PEN_W { w: self } + } + #[doc = "Bit 2 - Number of stop bits.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] + #[inline(always)] + pub fn uart_stop(&mut self) -> UART_STOP_W { + UART_STOP_W { w: self } + } + #[doc = "Bits 0:1 - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] + #[inline(always)] + pub fn uart_dls(&mut self) -> UART_DLS_W { + UART_DLS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Line Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_lcr_reg](index.html) module"] +pub struct UART_LCR_REG_SPEC; +impl crate::RegisterSpec for UART_LCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_lcr_reg::R](R) reader structure"] +impl crate::Readable for UART_LCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_lcr_reg::W](W) writer structure"] +impl crate::Writable for UART_LCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_LCR_REG to value 0"] +impl crate::Resettable for UART_LCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_lsr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_lsr_reg.rs new file mode 100644 index 0000000..ab6c489 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_lsr_reg.rs @@ -0,0 +1,238 @@ +#[doc = "Register `UART_LSR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_LSR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_RFE` reader - Receiver FIFO Error bit. This bit is only relevant when FIFOs are enabled (FCR\\[0\\] +set to one). This is used to indicate if there is at least one parity error, framing error, or break indication in the FIFO. 0 = no error in RX FIFO 1 = error in RX FIFO This bit is cleared when the LSR is read and the character with the error is at the top of the receiver FIFO and there are no subsequent errors in the FIFO."] +pub struct UART_RFE_R(crate::FieldReader); +impl UART_RFE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_RFE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RFE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_TEMT` reader - Transmitter Empty bit. If FIFOs enabled (FCR\\[0\\] +set to one), this bit is set whenever the Transmitter Shift Register and the FIFO are both empty. If FIFOs are disabled, this bit is set whenever the Transmitter Holding Register(THR) and the Transmitter Shift Register are both empty."] +pub struct UART_TEMT_R(crate::FieldReader); +impl UART_TEMT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_TEMT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TEMT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_THRE` reader - Transmit Holding Register Empty bit. If THRE mode is disabled (IER\\[7\\] +set to zero) and regardless of FIFO's being implemented/enabled or not, this bit indicates that the THR or TX FIFO is empty. This bit is set whenever data is transferred from the THR or TX FIFO to the transmitter shift register and no new data has been written to the THR or TX FIFO. This also causes a THRE Interrupt to occur, if the THRE Interrupt is enabled. If both modes are active (IER\\[7\\] +set to one and FCR\\[0\\] +set to one respectively), the functionality is switched to indicate the transmitter FIFO is full, and no longer controls THRE interrupts, which are then controlled by the FCR\\[5:4\\] +threshold setting."] +pub struct UART_THRE_R(crate::FieldReader); +impl UART_THRE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_THRE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_THRE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_BI` reader - Break Interrupt bit. This is used to indicate the detection of a break sequence on the serial input data. If in UART mode (SIR_MODE == Disabled), it is set whenever the serial input, sin, is held in a logic '0' state for longer than the sum of start time + data bits + parity + stop bits. If in infrared mode (SIR_MODE == Enabled), it is set whenever the serial input, sir_in, is continuously pulsed to logic '0' for longer than the sum of start time + data bits + parity + stop bits. A break condition on serial input causes one and only one character, consisting of all zeros, to be received by the UART. In the FIFO mode, the character associated with the break condition is carried through the FIFO and is revealed when the character is at the top of the FIFO. Reading the LSR clears the BI bit. In the non-FIFO mode, the BI indication occurs immediately and persists until the LSR is read."] +pub struct UART_BI_R(crate::FieldReader); +impl UART_BI_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_BI_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_BI_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_FE` reader - Framing Error bit. This is used to indicate the occurrence of a framing error in the receiver. A framing error occurs when the receiver does not detect a valid STOP bit in the received data. In the FIFO mode, since the framing error is associated with a character received, it is revealed when the character with the framing error is at the top of the FIFO. When a framing error occurs, the UART tries to resynchronize. It does this by assuming that the error was due to the start bit of the next character and then continues receiving the other bit i.e. data, and/or parity and stop. It should be noted that the Framing Error (FE) bit (LSR\\[3\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no framing error 1 = framing error Reading the LSR clears the FE bit."] +pub struct UART_FE_R(crate::FieldReader); +impl UART_FE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_FE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_FE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_PE` reader - Parity Error bit. This is used to indicate the occurrence of a parity error in the receiver if the Parity Enable (PEN) bit (LCR\\[3\\]) is set. In the FIFO mode, since the parity error is associated with a character received, it is revealed when the character with the parity error arrives at the top of the FIFO. It should be noted that the Parity Error (PE) bit (LSR\\[2\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no parity error 1 = parity error Reading the LSR clears the PE bit."] +pub struct UART_PE_R(crate::FieldReader); +impl UART_PE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_PE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_PE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_OE` reader - Overrun error bit. This is used to indicate the occurrence of an overrun error. This occurs if a new data character was received before the previous data was read. In the non-FIFO mode, the OE bit is set when a new character arrives in the receiver before the previous character was read from the RBR. When this happens, the data in the RBR is overwritten. In the FIFO mode, an overrun error occurs when the FIFO is full and a new character arrives at the receiver. The data in the FIFO is retained and the data in the receive shift register is lost. 0 = no overrun error 1 = overrun error Reading the LSR clears the OE bit."] +pub struct UART_OE_R(crate::FieldReader); +impl UART_OE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_OE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_OE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DR` reader - Data Ready bit. This is used to indicate that the receiver contains at least one character in the RBR or the receiver FIFO. 0 = no data ready 1 = data ready This bit is cleared when the RBR is read in non-FIFO mode, or when the receiver FIFO is empty, in FIFO mode."] +pub struct UART_DR_R(crate::FieldReader); +impl UART_DR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_DR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 7 - Receiver FIFO Error bit. This bit is only relevant when FIFOs are enabled (FCR\\[0\\] +set to one). This is used to indicate if there is at least one parity error, framing error, or break indication in the FIFO. 0 = no error in RX FIFO 1 = error in RX FIFO This bit is cleared when the LSR is read and the character with the error is at the top of the receiver FIFO and there are no subsequent errors in the FIFO."] + #[inline(always)] + pub fn uart_rfe(&self) -> UART_RFE_R { + UART_RFE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Transmitter Empty bit. If FIFOs enabled (FCR\\[0\\] +set to one), this bit is set whenever the Transmitter Shift Register and the FIFO are both empty. If FIFOs are disabled, this bit is set whenever the Transmitter Holding Register(THR) and the Transmitter Shift Register are both empty."] + #[inline(always)] + pub fn uart_temt(&self) -> UART_TEMT_R { + UART_TEMT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Transmit Holding Register Empty bit. If THRE mode is disabled (IER\\[7\\] +set to zero) and regardless of FIFO's being implemented/enabled or not, this bit indicates that the THR or TX FIFO is empty. This bit is set whenever data is transferred from the THR or TX FIFO to the transmitter shift register and no new data has been written to the THR or TX FIFO. This also causes a THRE Interrupt to occur, if the THRE Interrupt is enabled. If both modes are active (IER\\[7\\] +set to one and FCR\\[0\\] +set to one respectively), the functionality is switched to indicate the transmitter FIFO is full, and no longer controls THRE interrupts, which are then controlled by the FCR\\[5:4\\] +threshold setting."] + #[inline(always)] + pub fn uart_thre(&self) -> UART_THRE_R { + UART_THRE_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Break Interrupt bit. This is used to indicate the detection of a break sequence on the serial input data. If in UART mode (SIR_MODE == Disabled), it is set whenever the serial input, sin, is held in a logic '0' state for longer than the sum of start time + data bits + parity + stop bits. If in infrared mode (SIR_MODE == Enabled), it is set whenever the serial input, sir_in, is continuously pulsed to logic '0' for longer than the sum of start time + data bits + parity + stop bits. A break condition on serial input causes one and only one character, consisting of all zeros, to be received by the UART. In the FIFO mode, the character associated with the break condition is carried through the FIFO and is revealed when the character is at the top of the FIFO. Reading the LSR clears the BI bit. In the non-FIFO mode, the BI indication occurs immediately and persists until the LSR is read."] + #[inline(always)] + pub fn uart_bi(&self) -> UART_BI_R { + UART_BI_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Framing Error bit. This is used to indicate the occurrence of a framing error in the receiver. A framing error occurs when the receiver does not detect a valid STOP bit in the received data. In the FIFO mode, since the framing error is associated with a character received, it is revealed when the character with the framing error is at the top of the FIFO. When a framing error occurs, the UART tries to resynchronize. It does this by assuming that the error was due to the start bit of the next character and then continues receiving the other bit i.e. data, and/or parity and stop. It should be noted that the Framing Error (FE) bit (LSR\\[3\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no framing error 1 = framing error Reading the LSR clears the FE bit."] + #[inline(always)] + pub fn uart_fe(&self) -> UART_FE_R { + UART_FE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Parity Error bit. This is used to indicate the occurrence of a parity error in the receiver if the Parity Enable (PEN) bit (LCR\\[3\\]) is set. In the FIFO mode, since the parity error is associated with a character received, it is revealed when the character with the parity error arrives at the top of the FIFO. It should be noted that the Parity Error (PE) bit (LSR\\[2\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no parity error 1 = parity error Reading the LSR clears the PE bit."] + #[inline(always)] + pub fn uart_pe(&self) -> UART_PE_R { + UART_PE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Overrun error bit. This is used to indicate the occurrence of an overrun error. This occurs if a new data character was received before the previous data was read. In the non-FIFO mode, the OE bit is set when a new character arrives in the receiver before the previous character was read from the RBR. When this happens, the data in the RBR is overwritten. In the FIFO mode, an overrun error occurs when the FIFO is full and a new character arrives at the receiver. The data in the FIFO is retained and the data in the receive shift register is lost. 0 = no overrun error 1 = overrun error Reading the LSR clears the OE bit."] + #[inline(always)] + pub fn uart_oe(&self) -> UART_OE_R { + UART_OE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Data Ready bit. This is used to indicate that the receiver contains at least one character in the RBR or the receiver FIFO. 0 = no data ready 1 = data ready This bit is cleared when the RBR is read in non-FIFO mode, or when the receiver FIFO is empty, in FIFO mode."] + #[inline(always)] + pub fn uart_dr(&self) -> UART_DR_R { + UART_DR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Line Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_lsr_reg](index.html) module"] +pub struct UART_LSR_REG_SPEC; +impl crate::RegisterSpec for UART_LSR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_lsr_reg::R](R) reader structure"] +impl crate::Readable for UART_LSR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_lsr_reg::W](W) writer structure"] +impl crate::Writable for UART_LSR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_LSR_REG to value 0x60"] +impl crate::Resettable for UART_LSR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x60 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_mcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_mcr_reg.rs new file mode 100644 index 0000000..d51a58b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_mcr_reg.rs @@ -0,0 +1,239 @@ +#[doc = "Register `UART_MCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_MCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_AFCE` reader - Auto Flow Control Enable. When FIFOs are enabled and the Auto Flow Control Enable (AFCE) bit is set, Auto Flow Control features are enabled. 0 = Auto Flow Control Mode disabled 1 = Auto Flow Control Mode enabled"] +pub struct UART_AFCE_R(crate::FieldReader); +impl UART_AFCE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_AFCE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_AFCE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_AFCE` writer - Auto Flow Control Enable. When FIFOs are enabled and the Auto Flow Control Enable (AFCE) bit is set, Auto Flow Control features are enabled. 0 = Auto Flow Control Mode disabled 1 = Auto Flow Control Mode enabled"] +pub struct UART_AFCE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_AFCE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 5)) | ((value as u16 & 1) << 5); + self.w + } +} +#[doc = "Field `UART_LB` reader - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] +pub struct UART_LB_R(crate::FieldReader); +impl UART_LB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_LB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_LB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_LB` writer - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] +pub struct UART_LB_W<'a> { + w: &'a mut W, +} +impl<'a> UART_LB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `UART_RTS` reader - Request to Send. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] +set to zero), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high.In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] +set to one) and FIFOs enable (FCR\\[0\\] +set to one), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). The rts_n signal is de-asserted when MCR\\[1\\] +is set low. Note that in Loopback mode (MCR\\[4\\] +set to one), the rts_n output is held inactive high while the value of this location is internally looped back to an input."] +pub struct UART_RTS_R(crate::FieldReader); +impl UART_RTS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_RTS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RTS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_RTS` writer - Request to Send. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] +set to zero), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high.In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] +set to one) and FIFOs enable (FCR\\[0\\] +set to one), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). The rts_n signal is de-asserted when MCR\\[1\\] +is set low. Note that in Loopback mode (MCR\\[4\\] +set to one), the rts_n output is held inactive high while the value of this location is internally looped back to an input."] +pub struct UART_RTS_W<'a> { + w: &'a mut W, +} +impl<'a> UART_RTS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +impl R { + #[doc = "Bit 5 - Auto Flow Control Enable. When FIFOs are enabled and the Auto Flow Control Enable (AFCE) bit is set, Auto Flow Control features are enabled. 0 = Auto Flow Control Mode disabled 1 = Auto Flow Control Mode enabled"] + #[inline(always)] + pub fn uart_afce(&self) -> UART_AFCE_R { + UART_AFCE_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] + #[inline(always)] + pub fn uart_lb(&self) -> UART_LB_R { + UART_LB_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 1 - Request to Send. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] +set to zero), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high.In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] +set to one) and FIFOs enable (FCR\\[0\\] +set to one), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). The rts_n signal is de-asserted when MCR\\[1\\] +is set low. Note that in Loopback mode (MCR\\[4\\] +set to one), the rts_n output is held inactive high while the value of this location is internally looped back to an input."] + #[inline(always)] + pub fn uart_rts(&self) -> UART_RTS_R { + UART_RTS_R::new(((self.bits >> 1) & 1) != 0) + } +} +impl W { + #[doc = "Bit 5 - Auto Flow Control Enable. When FIFOs are enabled and the Auto Flow Control Enable (AFCE) bit is set, Auto Flow Control features are enabled. 0 = Auto Flow Control Mode disabled 1 = Auto Flow Control Mode enabled"] + #[inline(always)] + pub fn uart_afce(&mut self) -> UART_AFCE_W { + UART_AFCE_W { w: self } + } + #[doc = "Bit 4 - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] + #[inline(always)] + pub fn uart_lb(&mut self) -> UART_LB_W { + UART_LB_W { w: self } + } + #[doc = "Bit 1 - Request to Send. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] +set to zero), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high.In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] +set to one) and FIFOs enable (FCR\\[0\\] +set to one), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). The rts_n signal is de-asserted when MCR\\[1\\] +is set low. Note that in Loopback mode (MCR\\[4\\] +set to one), the rts_n output is held inactive high while the value of this location is internally looped back to an input."] + #[inline(always)] + pub fn uart_rts(&mut self) -> UART_RTS_W { + UART_RTS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Modem Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_mcr_reg](index.html) module"] +pub struct UART_MCR_REG_SPEC; +impl crate::RegisterSpec for UART_MCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_mcr_reg::R](R) reader structure"] +impl crate::Readable for UART_MCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_mcr_reg::W](W) writer structure"] +impl crate::Writable for UART_MCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_MCR_REG to value 0"] +impl crate::Resettable for UART_MCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_msr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_msr_reg.rs new file mode 100644 index 0000000..d357015 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_msr_reg.rs @@ -0,0 +1,90 @@ +#[doc = "Register `UART_MSR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_MSR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_CTS` reader - Clear to Send. This is used to indicate the current state of the modem control line cts_n. This bit is the complement of cts_n. When the Clear to Send input (cts_n) is asserted it is an indication that the modem or data set is ready to exchange data with the UART Ctrl. 0 = cts_n input is de-asserted (logic 1) 1 = cts_n input is asserted (logic 0) In Loopback Mode (MCR\\[4\\] += 1), CTS is the same as MCR\\[1\\] +(RTS)."] +pub struct UART_CTS_R(crate::FieldReader); +impl UART_CTS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_CTS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_CTS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 4 - Clear to Send. This is used to indicate the current state of the modem control line cts_n. This bit is the complement of cts_n. When the Clear to Send input (cts_n) is asserted it is an indication that the modem or data set is ready to exchange data with the UART Ctrl. 0 = cts_n input is de-asserted (logic 1) 1 = cts_n input is asserted (logic 0) In Loopback Mode (MCR\\[4\\] += 1), CTS is the same as MCR\\[1\\] +(RTS)."] + #[inline(always)] + pub fn uart_cts(&self) -> UART_CTS_R { + UART_CTS_R::new(((self.bits >> 4) & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Modem Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_msr_reg](index.html) module"] +pub struct UART_MSR_REG_SPEC; +impl crate::RegisterSpec for UART_MSR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_msr_reg::R](R) reader structure"] +impl crate::Readable for UART_MSR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_msr_reg::W](W) writer structure"] +impl crate::Writable for UART_MSR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_MSR_REG to value 0x10"] +impl crate::Resettable for UART_MSR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x10 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_rbr_thr_dll_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_rbr_thr_dll_reg.rs new file mode 100644 index 0000000..e152a7e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_rbr_thr_dll_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_RBR_THR_DLL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_RBR_THR_DLL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RBR_THR_DLL` reader - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] +pub struct RBR_THR_DLL_R(crate::FieldReader); +impl RBR_THR_DLL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RBR_THR_DLL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RBR_THR_DLL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RBR_THR_DLL` writer - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] +pub struct RBR_THR_DLL_W<'a> { + w: &'a mut W, +} +impl<'a> RBR_THR_DLL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] + #[inline(always)] + pub fn rbr_thr_dll(&self) -> RBR_THR_DLL_R { + RBR_THR_DLL_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] + #[inline(always)] + pub fn rbr_thr_dll(&mut self) -> RBR_THR_DLL_W { + RBR_THR_DLL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Receive Buffer Register/Transmit Holding Register/Divisor Latch Low\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_rbr_thr_dll_reg](index.html) module"] +pub struct UART_RBR_THR_DLL_REG_SPEC; +impl crate::RegisterSpec for UART_RBR_THR_DLL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_rbr_thr_dll_reg::R](R) reader structure"] +impl crate::Readable for UART_RBR_THR_DLL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_rbr_thr_dll_reg::W](W) writer structure"] +impl crate::Writable for UART_RBR_THR_DLL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_RBR_THR_DLL_REG to value 0"] +impl crate::Resettable for UART_RBR_THR_DLL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_rfl_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_rfl_reg.rs new file mode 100644 index 0000000..cffcca6 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_rfl_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART_RFL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_RFL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_RECEIVE_FIFO_LEVEL` reader - Receive FIFO Level. This is indicates the number of data entries in the receive FIFO."] +pub struct UART_RECEIVE_FIFO_LEVEL_R(crate::FieldReader); +impl UART_RECEIVE_FIFO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_RECEIVE_FIFO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RECEIVE_FIFO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:4 - Receive FIFO Level. This is indicates the number of data entries in the receive FIFO."] + #[inline(always)] + pub fn uart_receive_fifo_level(&self) -> UART_RECEIVE_FIFO_LEVEL_R { + UART_RECEIVE_FIFO_LEVEL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Receive FIFO Level\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_rfl_reg](index.html) module"] +pub struct UART_RFL_REG_SPEC; +impl crate::RegisterSpec for UART_RFL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_rfl_reg::R](R) reader structure"] +impl crate::Readable for UART_RFL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_rfl_reg::W](W) writer structure"] +impl crate::Writable for UART_RFL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_RFL_REG to value 0"] +impl crate::Resettable for UART_RFL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_sbcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_sbcr_reg.rs new file mode 100644 index 0000000..d331d0b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_sbcr_reg.rs @@ -0,0 +1,117 @@ +#[doc = "Register `UART_SBCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SBCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_BREAK_CONTROL` reader - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] +pub struct UART_SHADOW_BREAK_CONTROL_R(crate::FieldReader); +impl UART_SHADOW_BREAK_CONTROL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_SHADOW_BREAK_CONTROL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_BREAK_CONTROL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_BREAK_CONTROL` writer - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] +pub struct UART_SHADOW_BREAK_CONTROL_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_BREAK_CONTROL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] + #[inline(always)] + pub fn uart_shadow_break_control(&self) -> UART_SHADOW_BREAK_CONTROL_R { + UART_SHADOW_BREAK_CONTROL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] + #[inline(always)] + pub fn uart_shadow_break_control(&mut self) -> UART_SHADOW_BREAK_CONTROL_W { + UART_SHADOW_BREAK_CONTROL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Break Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_sbcr_reg](index.html) module"] +pub struct UART_SBCR_REG_SPEC; +impl crate::RegisterSpec for UART_SBCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_sbcr_reg::R](R) reader structure"] +impl crate::Readable for UART_SBCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_sbcr_reg::W](W) writer structure"] +impl crate::Writable for UART_SBCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SBCR_REG to value 0"] +impl crate::Resettable for UART_SBCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_scr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_scr_reg.rs new file mode 100644 index 0000000..f3cc027 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_scr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART_SCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SCRATCH_PAD` reader - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] +pub struct UART_SCRATCH_PAD_R(crate::FieldReader); +impl UART_SCRATCH_PAD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_SCRATCH_PAD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SCRATCH_PAD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SCRATCH_PAD` writer - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] +pub struct UART_SCRATCH_PAD_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SCRATCH_PAD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] + #[inline(always)] + pub fn uart_scratch_pad(&self) -> UART_SCRATCH_PAD_R { + UART_SCRATCH_PAD_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] + #[inline(always)] + pub fn uart_scratch_pad(&mut self) -> UART_SCRATCH_PAD_W { + UART_SCRATCH_PAD_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Scratchpad Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_scr_reg](index.html) module"] +pub struct UART_SCR_REG_SPEC; +impl crate::RegisterSpec for UART_SCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_scr_reg::R](R) reader structure"] +impl crate::Readable for UART_SCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_scr_reg::W](W) writer structure"] +impl crate::Writable for UART_SCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SCR_REG to value 0"] +impl crate::Resettable for UART_SCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_sdmam_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_sdmam_reg.rs new file mode 100644 index 0000000..0d9e02c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_sdmam_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `UART_SDMAM_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SDMAM_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_DMA_MODE` reader - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_SHADOW_DMA_MODE_R(crate::FieldReader); +impl UART_SHADOW_DMA_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_SHADOW_DMA_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_DMA_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_DMA_MODE` writer - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_SHADOW_DMA_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_DMA_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_shadow_dma_mode(&self) -> UART_SHADOW_DMA_MODE_R { + UART_SHADOW_DMA_MODE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_shadow_dma_mode(&mut self) -> UART_SHADOW_DMA_MODE_W { + UART_SHADOW_DMA_MODE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow DMA Mode\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_sdmam_reg](index.html) module"] +pub struct UART_SDMAM_REG_SPEC; +impl crate::RegisterSpec for UART_SDMAM_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_sdmam_reg::R](R) reader structure"] +impl crate::Readable for UART_SDMAM_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_sdmam_reg::W](W) writer structure"] +impl crate::Writable for UART_SDMAM_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SDMAM_REG to value 0"] +impl crate::Resettable for UART_SDMAM_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_sfe_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_sfe_reg.rs new file mode 100644 index 0000000..c8fcee8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_sfe_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `UART_SFE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SFE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_FIFO_ENABLE` reader - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] +pub struct UART_SHADOW_FIFO_ENABLE_R(crate::FieldReader); +impl UART_SHADOW_FIFO_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_SHADOW_FIFO_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_FIFO_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_FIFO_ENABLE` writer - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] +pub struct UART_SHADOW_FIFO_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_FIFO_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] + #[inline(always)] + pub fn uart_shadow_fifo_enable(&self) -> UART_SHADOW_FIFO_ENABLE_R { + UART_SHADOW_FIFO_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] + #[inline(always)] + pub fn uart_shadow_fifo_enable(&mut self) -> UART_SHADOW_FIFO_ENABLE_W { + UART_SHADOW_FIFO_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow FIFO Enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_sfe_reg](index.html) module"] +pub struct UART_SFE_REG_SPEC; +impl crate::RegisterSpec for UART_SFE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_sfe_reg::R](R) reader structure"] +impl crate::Readable for UART_SFE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_sfe_reg::W](W) writer structure"] +impl crate::Writable for UART_SFE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SFE_REG to value 0"] +impl crate::Resettable for UART_SFE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr0_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr0_reg.rs new file mode 100644 index 0000000..941f31a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr0_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr0_reg](index.html) module"] +pub struct UART_SRBR_STHR0_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR0_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr0_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr0_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR0_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr10_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr10_reg.rs new file mode 100644 index 0000000..24c07c3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr10_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR10_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR10_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr10_reg](index.html) module"] +pub struct UART_SRBR_STHR10_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR10_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr10_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR10_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr10_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR10_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR10_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR10_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr11_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr11_reg.rs new file mode 100644 index 0000000..4f2cb8f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr11_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR11_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR11_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr11_reg](index.html) module"] +pub struct UART_SRBR_STHR11_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR11_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr11_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR11_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr11_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR11_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR11_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR11_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr12_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr12_reg.rs new file mode 100644 index 0000000..0847666 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr12_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR12_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR12_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr12_reg](index.html) module"] +pub struct UART_SRBR_STHR12_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR12_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr12_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR12_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr12_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR12_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR12_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR12_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr13_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr13_reg.rs new file mode 100644 index 0000000..388f8f7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr13_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR13_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR13_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr13_reg](index.html) module"] +pub struct UART_SRBR_STHR13_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR13_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr13_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR13_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr13_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR13_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR13_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR13_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr14_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr14_reg.rs new file mode 100644 index 0000000..ad9ab50 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr14_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR14_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR14_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr14_reg](index.html) module"] +pub struct UART_SRBR_STHR14_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR14_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr14_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR14_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr14_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR14_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR14_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR14_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr15_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr15_reg.rs new file mode 100644 index 0000000..92cd7ae --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr15_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR15_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR15_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr15_reg](index.html) module"] +pub struct UART_SRBR_STHR15_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR15_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr15_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR15_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr15_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR15_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR15_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR15_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr1_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr1_reg.rs new file mode 100644 index 0000000..bd01a35 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr1_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr1_reg](index.html) module"] +pub struct UART_SRBR_STHR1_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR1_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr1_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr1_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR1_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr2_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr2_reg.rs new file mode 100644 index 0000000..63f606b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr2_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr2_reg](index.html) module"] +pub struct UART_SRBR_STHR2_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr2_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr2_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR2_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr3_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr3_reg.rs new file mode 100644 index 0000000..f1786f5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr3_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr3_reg](index.html) module"] +pub struct UART_SRBR_STHR3_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR3_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr3_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr3_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR3_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr4_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr4_reg.rs new file mode 100644 index 0000000..d8926a7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr4_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR4_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR4_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr4_reg](index.html) module"] +pub struct UART_SRBR_STHR4_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR4_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr4_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR4_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr4_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR4_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR4_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR4_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr5_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr5_reg.rs new file mode 100644 index 0000000..fb8da0a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr5_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR5_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR5_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr5_reg](index.html) module"] +pub struct UART_SRBR_STHR5_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR5_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr5_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR5_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr5_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR5_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR5_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR5_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr6_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr6_reg.rs new file mode 100644 index 0000000..2bbf473 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr6_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR6_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR6_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr6_reg](index.html) module"] +pub struct UART_SRBR_STHR6_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR6_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr6_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR6_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr6_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR6_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR6_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR6_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr7_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr7_reg.rs new file mode 100644 index 0000000..4fb5aef --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr7_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR7_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR7_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr7_reg](index.html) module"] +pub struct UART_SRBR_STHR7_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR7_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr7_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR7_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr7_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR7_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR7_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR7_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr8_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr8_reg.rs new file mode 100644 index 0000000..5abc34d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr8_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR8_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR8_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr8_reg](index.html) module"] +pub struct UART_SRBR_STHR8_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR8_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr8_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR8_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr8_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR8_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR8_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR8_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr9_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr9_reg.rs new file mode 100644 index 0000000..de8f05d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srbr_sthr9_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART_SRBR_STHR9_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRBR_STHR9_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srbr_sthr9_reg](index.html) module"] +pub struct UART_SRBR_STHR9_REG_SPEC; +impl crate::RegisterSpec for UART_SRBR_STHR9_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srbr_sthr9_reg::R](R) reader structure"] +impl crate::Readable for UART_SRBR_STHR9_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srbr_sthr9_reg::W](W) writer structure"] +impl crate::Writable for UART_SRBR_STHR9_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRBR_STHR9_REG to value 0"] +impl crate::Resettable for UART_SRBR_STHR9_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srr_reg.rs new file mode 100644 index 0000000..b2ac880 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srr_reg.rs @@ -0,0 +1,145 @@ +#[doc = "Register `UART_SRR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_XFR` writer - XMIT FIFO Reset. This is a shadow register for the XMIT FIFO Reset bit (FCR\\[2\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the transmit FIFO. This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] +pub struct UART_XFR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_XFR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `UART_RFR` writer - RCVR FIFO Reset. This is a shadow register for the RCVR FIFO Reset bit (FCR\\[1\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the receive FIFO This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] +pub struct UART_RFR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_RFR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `UART_UR` writer - UART Reset. This asynchronously resets the UART Ctrl and synchronously removes the reset assertion. For a two clock implementation both pclk and sclk domains are reset."] +pub struct UART_UR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_UR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl W { + #[doc = "Bit 2 - XMIT FIFO Reset. This is a shadow register for the XMIT FIFO Reset bit (FCR\\[2\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the transmit FIFO. This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_xfr(&mut self) -> UART_XFR_W { + UART_XFR_W { w: self } + } + #[doc = "Bit 1 - RCVR FIFO Reset. This is a shadow register for the RCVR FIFO Reset bit (FCR\\[1\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the receive FIFO This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_rfr(&mut self) -> UART_RFR_W { + UART_RFR_W { w: self } + } + #[doc = "Bit 0 - UART Reset. This asynchronously resets the UART Ctrl and synchronously removes the reset assertion. For a two clock implementation both pclk and sclk domains are reset."] + #[inline(always)] + pub fn uart_ur(&mut self) -> UART_UR_W { + UART_UR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Software Reset Register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srr_reg](index.html) module"] +pub struct UART_SRR_REG_SPEC; +impl crate::RegisterSpec for UART_SRR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srr_reg::R](R) reader structure"] +impl crate::Readable for UART_SRR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srr_reg::W](W) writer structure"] +impl crate::Writable for UART_SRR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRR_REG to value 0"] +impl crate::Resettable for UART_SRR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srt_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srt_reg.rs new file mode 100644 index 0000000..11129b5 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART_SRT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_RCVR_TRIGGER` reader - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] +pub struct UART_SHADOW_RCVR_TRIGGER_R(crate::FieldReader); +impl UART_SHADOW_RCVR_TRIGGER_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_SHADOW_RCVR_TRIGGER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_RCVR_TRIGGER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_RCVR_TRIGGER` writer - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] +pub struct UART_SHADOW_RCVR_TRIGGER_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_RCVR_TRIGGER_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bits 0:1 - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_shadow_rcvr_trigger(&self) -> UART_SHADOW_RCVR_TRIGGER_R { + UART_SHADOW_RCVR_TRIGGER_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 0:1 - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_shadow_rcvr_trigger(&mut self) -> UART_SHADOW_RCVR_TRIGGER_W { + UART_SHADOW_RCVR_TRIGGER_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow RCVR Trigger\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srt_reg](index.html) module"] +pub struct UART_SRT_REG_SPEC; +impl crate::RegisterSpec for UART_SRT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srt_reg::R](R) reader structure"] +impl crate::Readable for UART_SRT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srt_reg::W](W) writer structure"] +impl crate::Writable for UART_SRT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRT_REG to value 0"] +impl crate::Resettable for UART_SRT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_srts_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_srts_reg.rs new file mode 100644 index 0000000..b95e38b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_srts_reg.rs @@ -0,0 +1,133 @@ +#[doc = "Register `UART_SRTS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_SRTS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_REQUEST_TO_SEND` reader - Shadow Request to Send. This is a shadow register for the RTS bit (MCR\\[1\\]), this can be used to remove the burden of having to performing a read-modify-write on the MCR. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART Ctrl is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] += 0), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high. In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] += 1) and FIFOs enable (FCR\\[0\\] += 1), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). Note that in Loopback mode (MCR\\[4\\] += 1), the rts_n output is held inactive-high while the value of this location is internally looped back to an input."] +pub struct UART_SHADOW_REQUEST_TO_SEND_R(crate::FieldReader); +impl UART_SHADOW_REQUEST_TO_SEND_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_SHADOW_REQUEST_TO_SEND_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_REQUEST_TO_SEND_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_REQUEST_TO_SEND` writer - Shadow Request to Send. This is a shadow register for the RTS bit (MCR\\[1\\]), this can be used to remove the burden of having to performing a read-modify-write on the MCR. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART Ctrl is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] += 0), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high. In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] += 1) and FIFOs enable (FCR\\[0\\] += 1), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). Note that in Loopback mode (MCR\\[4\\] += 1), the rts_n output is held inactive-high while the value of this location is internally looped back to an input."] +pub struct UART_SHADOW_REQUEST_TO_SEND_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_REQUEST_TO_SEND_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Shadow Request to Send. This is a shadow register for the RTS bit (MCR\\[1\\]), this can be used to remove the burden of having to performing a read-modify-write on the MCR. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART Ctrl is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] += 0), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high. In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] += 1) and FIFOs enable (FCR\\[0\\] += 1), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). Note that in Loopback mode (MCR\\[4\\] += 1), the rts_n output is held inactive-high while the value of this location is internally looped back to an input."] + #[inline(always)] + pub fn uart_shadow_request_to_send(&self) -> UART_SHADOW_REQUEST_TO_SEND_R { + UART_SHADOW_REQUEST_TO_SEND_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Shadow Request to Send. This is a shadow register for the RTS bit (MCR\\[1\\]), this can be used to remove the burden of having to performing a read-modify-write on the MCR. This is used to directly control the Request to Send (rts_n) output. The Request To Send (rts_n) output is used to inform the modem or data set that the UART Ctrl is ready to exchange data. When Auto RTS Flow Control is not enabled (MCR\\[5\\] += 0), the rts_n signal is set low by programming MCR\\[1\\] +(RTS) to a high. In Auto Flow Control, AFCE_MODE == Enabled and active (MCR\\[5\\] += 1) and FIFOs enable (FCR\\[0\\] += 1), the rts_n output is controlled in the same way, but is also gated with the receiver FIFO threshold trigger (rts_n is inactive high when above the threshold). Note that in Loopback mode (MCR\\[4\\] += 1), the rts_n output is held inactive-high while the value of this location is internally looped back to an input."] + #[inline(always)] + pub fn uart_shadow_request_to_send(&mut self) -> UART_SHADOW_REQUEST_TO_SEND_W { + UART_SHADOW_REQUEST_TO_SEND_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Request to Send\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_srts_reg](index.html) module"] +pub struct UART_SRTS_REG_SPEC; +impl crate::RegisterSpec for UART_SRTS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_srts_reg::R](R) reader structure"] +impl crate::Readable for UART_SRTS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_srts_reg::W](W) writer structure"] +impl crate::Writable for UART_SRTS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_SRTS_REG to value 0"] +impl crate::Resettable for UART_SRTS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_stet_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_stet_reg.rs new file mode 100644 index 0000000..bcc04c9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_stet_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART_STET_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_STET_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_TX_EMPTY_TRIGGER` reader - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] +pub struct UART_SHADOW_TX_EMPTY_TRIGGER_R(crate::FieldReader); +impl UART_SHADOW_TX_EMPTY_TRIGGER_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_SHADOW_TX_EMPTY_TRIGGER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_TX_EMPTY_TRIGGER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_TX_EMPTY_TRIGGER` writer - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] +pub struct UART_SHADOW_TX_EMPTY_TRIGGER_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_TX_EMPTY_TRIGGER_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bits 0:1 - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] + #[inline(always)] + pub fn uart_shadow_tx_empty_trigger(&self) -> UART_SHADOW_TX_EMPTY_TRIGGER_R { + UART_SHADOW_TX_EMPTY_TRIGGER_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 0:1 - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] + #[inline(always)] + pub fn uart_shadow_tx_empty_trigger(&mut self) -> UART_SHADOW_TX_EMPTY_TRIGGER_W { + UART_SHADOW_TX_EMPTY_TRIGGER_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow TX Empty Trigger\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_stet_reg](index.html) module"] +pub struct UART_STET_REG_SPEC; +impl crate::RegisterSpec for UART_STET_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_stet_reg::R](R) reader structure"] +impl crate::Readable for UART_STET_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_stet_reg::W](W) writer structure"] +impl crate::Writable for UART_STET_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_STET_REG to value 0"] +impl crate::Resettable for UART_STET_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_tfl_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_tfl_reg.rs new file mode 100644 index 0000000..b6105ab --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_tfl_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART_TFL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_TFL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_TRANSMIT_FIFO_LEVEL` reader - Transmit FIFO Level. This is indicates the number of data entries in the transmit FIFO."] +pub struct UART_TRANSMIT_FIFO_LEVEL_R(crate::FieldReader); +impl UART_TRANSMIT_FIFO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_TRANSMIT_FIFO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TRANSMIT_FIFO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:4 - Transmit FIFO Level. This is indicates the number of data entries in the transmit FIFO."] + #[inline(always)] + pub fn uart_transmit_fifo_level(&self) -> UART_TRANSMIT_FIFO_LEVEL_R { + UART_TRANSMIT_FIFO_LEVEL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Transmit FIFO Level\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_tfl_reg](index.html) module"] +pub struct UART_TFL_REG_SPEC; +impl crate::RegisterSpec for UART_TFL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_tfl_reg::R](R) reader structure"] +impl crate::Readable for UART_TFL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_tfl_reg::W](W) writer structure"] +impl crate::Writable for UART_TFL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_TFL_REG to value 0"] +impl crate::Resettable for UART_TFL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_ucv_high_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_ucv_high_reg.rs new file mode 100644 index 0000000..616eacb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_ucv_high_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART_UCV_HIGH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_UCV_HIGH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UCV` reader - Component Version"] +pub struct UCV_R(crate::FieldReader); +impl UCV_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + UCV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UCV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Version"] + #[inline(always)] + pub fn ucv(&self) -> UCV_R { + UCV_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Version\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_ucv_high_reg](index.html) module"] +pub struct UART_UCV_HIGH_REG_SPEC; +impl crate::RegisterSpec for UART_UCV_HIGH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_ucv_high_reg::R](R) reader structure"] +impl crate::Readable for UART_UCV_HIGH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_ucv_high_reg::W](W) writer structure"] +impl crate::Writable for UART_UCV_HIGH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_UCV_HIGH_REG to value 0x3331"] +impl crate::Resettable for UART_UCV_HIGH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x3331 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_ucv_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_ucv_reg.rs new file mode 100644 index 0000000..509f5c4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_ucv_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART_UCV_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_UCV_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UCV` reader - Component Version"] +pub struct UCV_R(crate::FieldReader); +impl UCV_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + UCV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UCV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Version"] + #[inline(always)] + pub fn ucv(&self) -> UCV_R { + UCV_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Version\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_ucv_reg](index.html) module"] +pub struct UART_UCV_REG_SPEC; +impl crate::RegisterSpec for UART_UCV_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_ucv_reg::R](R) reader structure"] +impl crate::Readable for UART_UCV_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_ucv_reg::W](W) writer structure"] +impl crate::Writable for UART_UCV_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_UCV_REG to value 0x352a"] +impl crate::Resettable for UART_UCV_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x352a + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart/uart_usr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart/uart_usr_reg.rs new file mode 100644 index 0000000..28b5f1b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart/uart_usr_reg.rs @@ -0,0 +1,166 @@ +#[doc = "Register `UART_USR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART_USR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_RFF` reader - Receive FIFO Full. This is used to indicate that the receive FIFO is completely full. 0 = Receive FIFO not full 1 = Receive FIFO Full This bit is cleared when the RX FIFO is no longer full."] +pub struct UART_RFF_R(crate::FieldReader); +impl UART_RFF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_RFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_RFNE` reader - Receive FIFO Not Empty. This is used to indicate that the receive FIFO contains one or more entries. 0 = Receive FIFO is empty 1 = Receive FIFO is not empty This bit is cleared when the RX FIFO is empty."] +pub struct UART_RFNE_R(crate::FieldReader); +impl UART_RFNE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_RFNE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RFNE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_TFE` reader - Transmit FIFO Empty. This is used to indicate that the transmit FIFO is completely empty. 0 = Transmit FIFO is not empty 1 = Transmit FIFO is empty This bit is cleared when the TX FIFO is no longer empty."] +pub struct UART_TFE_R(crate::FieldReader); +impl UART_TFE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_TFE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TFE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_TFNF` reader - Transmit FIFO Not Full. This is used to indicate that the transmit FIFO in not full. 0 = Transmit FIFO is full 1 = Transmit FIFO is not full This bit is cleared when the TX FIFO is full."] +pub struct UART_TFNF_R(crate::FieldReader); +impl UART_TFNF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_TFNF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TFNF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_BUSY` reader - UART Busy. This indicates that a serial transfer is in progress, when cleared indicates that the DW_apb_uart is idle or inactive. 0 - DW_apb_uart is idle or inactive 1 - DW_apb_uart is busy (actively transferring data) Note that it is possible for the UART Busy bit to be cleared even though a new character may have been sent from another device. That is, if the DW_apb_uart has no data in the THR and RBR and there is no transmission in progress and a start bit of a new character has just reached the DW_apb_uart. This is due to the fact that a valid start is not seen until the middle of the bit period and this duration is dependent on the baud divisor that has been programmed. If a second system clock has been implemented (CLOCK_MODE == Enabled) the assertion of this bit will also be delayed by several cycles of the slower clock."] +pub struct UART_BUSY_R(crate::FieldReader); +impl UART_BUSY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_BUSY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_BUSY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 4 - Receive FIFO Full. This is used to indicate that the receive FIFO is completely full. 0 = Receive FIFO not full 1 = Receive FIFO Full This bit is cleared when the RX FIFO is no longer full."] + #[inline(always)] + pub fn uart_rff(&self) -> UART_RFF_R { + UART_RFF_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Receive FIFO Not Empty. This is used to indicate that the receive FIFO contains one or more entries. 0 = Receive FIFO is empty 1 = Receive FIFO is not empty This bit is cleared when the RX FIFO is empty."] + #[inline(always)] + pub fn uart_rfne(&self) -> UART_RFNE_R { + UART_RFNE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Transmit FIFO Empty. This is used to indicate that the transmit FIFO is completely empty. 0 = Transmit FIFO is not empty 1 = Transmit FIFO is empty This bit is cleared when the TX FIFO is no longer empty."] + #[inline(always)] + pub fn uart_tfe(&self) -> UART_TFE_R { + UART_TFE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Transmit FIFO Not Full. This is used to indicate that the transmit FIFO in not full. 0 = Transmit FIFO is full 1 = Transmit FIFO is not full This bit is cleared when the TX FIFO is full."] + #[inline(always)] + pub fn uart_tfnf(&self) -> UART_TFNF_R { + UART_TFNF_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - UART Busy. This indicates that a serial transfer is in progress, when cleared indicates that the DW_apb_uart is idle or inactive. 0 - DW_apb_uart is idle or inactive 1 - DW_apb_uart is busy (actively transferring data) Note that it is possible for the UART Busy bit to be cleared even though a new character may have been sent from another device. That is, if the DW_apb_uart has no data in the THR and RBR and there is no transmission in progress and a start bit of a new character has just reached the DW_apb_uart. This is due to the fact that a valid start is not seen until the middle of the bit period and this duration is dependent on the baud divisor that has been programmed. If a second system clock has been implemented (CLOCK_MODE == Enabled) the assertion of this bit will also be delayed by several cycles of the slower clock."] + #[inline(always)] + pub fn uart_busy(&self) -> UART_BUSY_R { + UART_BUSY_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "UART Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart_usr_reg](index.html) module"] +pub struct UART_USR_REG_SPEC; +impl crate::RegisterSpec for UART_USR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart_usr_reg::R](R) reader structure"] +impl crate::Readable for UART_USR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart_usr_reg::W](W) writer structure"] +impl crate::Writable for UART_USR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART_USR_REG to value 0x06"] +impl crate::Resettable for UART_USR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x06 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2.rs b/bitbox02-bt/vendor/da14531/src/uart2.rs new file mode 100644 index 0000000..9a162f2 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2.rs @@ -0,0 +1,280 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Receive Buffer Register/Transmit Holding Register/Divisor Latch Low"] + pub uart2_rbr_thr_dll_reg: crate::Reg, + _reserved1: [u8; 0x02], + #[doc = "0x04 - Interrupt Enable Register/Divisor Latch High"] + pub uart2_ier_dlh_reg: crate::Reg, + _reserved2: [u8; 0x02], + #[doc = "0x08 - Interrupt Identification Register/FIFO Control Register"] + pub uart2_iir_fcr_reg: crate::Reg, + _reserved3: [u8; 0x02], + #[doc = "0x0c - Line Control Register"] + pub uart2_lcr_reg: crate::Reg, + _reserved4: [u8; 0x02], + #[doc = "0x10 - Modem Control Register"] + pub uart2_mcr_reg: crate::Reg, + _reserved5: [u8; 0x02], + #[doc = "0x14 - Line Status Register"] + pub uart2_lsr_reg: crate::Reg, + _reserved6: [u8; 0x06], + #[doc = "0x1c - Scratchpad Register"] + pub uart2_scr_reg: crate::Reg, + _reserved7: [u8; 0x12], + #[doc = "0x30 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr0_reg: crate::Reg, + _reserved8: [u8; 0x02], + #[doc = "0x34 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr1_reg: crate::Reg, + _reserved9: [u8; 0x02], + #[doc = "0x38 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr2_reg: crate::Reg, + _reserved10: [u8; 0x02], + #[doc = "0x3c - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr3_reg: crate::Reg, + _reserved11: [u8; 0x02], + #[doc = "0x40 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr4_reg: crate::Reg, + _reserved12: [u8; 0x02], + #[doc = "0x44 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr5_reg: crate::Reg, + _reserved13: [u8; 0x02], + #[doc = "0x48 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr6_reg: crate::Reg, + _reserved14: [u8; 0x02], + #[doc = "0x4c - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr7_reg: crate::Reg, + _reserved15: [u8; 0x02], + #[doc = "0x50 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr8_reg: crate::Reg, + _reserved16: [u8; 0x02], + #[doc = "0x54 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr9_reg: crate::Reg, + _reserved17: [u8; 0x02], + #[doc = "0x58 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr10_reg: crate::Reg, + _reserved18: [u8; 0x02], + #[doc = "0x5c - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr11_reg: crate::Reg, + _reserved19: [u8; 0x02], + #[doc = "0x60 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr12_reg: crate::Reg, + _reserved20: [u8; 0x02], + #[doc = "0x64 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr13_reg: crate::Reg, + _reserved21: [u8; 0x02], + #[doc = "0x68 - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr14_reg: crate::Reg, + _reserved22: [u8; 0x02], + #[doc = "0x6c - Shadow Receive/Transmit Buffer Register"] + pub uart2_srbr_sthr15_reg: crate::Reg, + _reserved23: [u8; 0x02], + #[doc = "0x70 - FIFO Access Register"] + pub uart2_far_reg: crate::Reg, + _reserved24: [u8; 0x0a], + #[doc = "0x7c - UART Status Register"] + pub uart2_usr_reg: crate::Reg, + _reserved25: [u8; 0x02], + #[doc = "0x80 - Transmit FIFO Level"] + pub uart2_tfl_reg: crate::Reg, + _reserved26: [u8; 0x02], + #[doc = "0x84 - Receive FIFO Level"] + pub uart2_rfl_reg: crate::Reg, + _reserved27: [u8; 0x02], + #[doc = "0x88 - Software Reset Register."] + pub uart2_srr_reg: crate::Reg, + _reserved28: [u8; 0x06], + #[doc = "0x90 - Shadow Break Control Register"] + pub uart2_sbcr_reg: crate::Reg, + _reserved29: [u8; 0x02], + #[doc = "0x94 - Shadow DMA Mode"] + pub uart2_sdmam_reg: crate::Reg, + _reserved30: [u8; 0x02], + #[doc = "0x98 - Shadow FIFO Enable"] + pub uart2_sfe_reg: crate::Reg, + _reserved31: [u8; 0x02], + #[doc = "0x9c - Shadow RCVR Trigger"] + pub uart2_srt_reg: crate::Reg, + _reserved32: [u8; 0x02], + #[doc = "0xa0 - Shadow TX Empty Trigger"] + pub uart2_stet_reg: crate::Reg, + _reserved33: [u8; 0x02], + #[doc = "0xa4 - Halt TX"] + pub uart2_htx_reg: crate::Reg, + _reserved34: [u8; 0x02], + #[doc = "0xa8 - DMA Software Acknowledge"] + pub uart2_dmasa_reg: crate::Reg, + _reserved35: [u8; 0x16], + #[doc = "0xc0 - Divisor Latch Fraction Register"] + pub uart2_dlf_reg: crate::Reg, + _reserved36: [u8; 0x36], + #[doc = "0xf8 - Component Version"] + pub uart2_ucv_reg: crate::Reg, + #[doc = "0xfa - Component Version"] + pub uart2_ucv_high_reg: crate::Reg, + #[doc = "0xfc - Component Type Register"] + pub uart2_ctr_reg: crate::Reg, + #[doc = "0xfe - Component Type Register"] + pub uart2_ctr_high_reg: crate::Reg, +} +#[doc = "UART2_CTR_HIGH_REG register accessor: an alias for `Reg`"] +pub type UART2_CTR_HIGH_REG = crate::Reg; +#[doc = "Component Type Register"] +pub mod uart2_ctr_high_reg; +#[doc = "UART2_CTR_REG register accessor: an alias for `Reg`"] +pub type UART2_CTR_REG = crate::Reg; +#[doc = "Component Type Register"] +pub mod uart2_ctr_reg; +#[doc = "UART2_DLF_REG register accessor: an alias for `Reg`"] +pub type UART2_DLF_REG = crate::Reg; +#[doc = "Divisor Latch Fraction Register"] +pub mod uart2_dlf_reg; +#[doc = "UART2_DMASA_REG register accessor: an alias for `Reg`"] +pub type UART2_DMASA_REG = crate::Reg; +#[doc = "DMA Software Acknowledge"] +pub mod uart2_dmasa_reg; +#[doc = "UART2_FAR_REG register accessor: an alias for `Reg`"] +pub type UART2_FAR_REG = crate::Reg; +#[doc = "FIFO Access Register"] +pub mod uart2_far_reg; +#[doc = "UART2_HTX_REG register accessor: an alias for `Reg`"] +pub type UART2_HTX_REG = crate::Reg; +#[doc = "Halt TX"] +pub mod uart2_htx_reg; +#[doc = "UART2_IER_DLH_REG register accessor: an alias for `Reg`"] +pub type UART2_IER_DLH_REG = crate::Reg; +#[doc = "Interrupt Enable Register/Divisor Latch High"] +pub mod uart2_ier_dlh_reg; +#[doc = "UART2_IIR_FCR_REG register accessor: an alias for `Reg`"] +pub type UART2_IIR_FCR_REG = crate::Reg; +#[doc = "Interrupt Identification Register/FIFO Control Register"] +pub mod uart2_iir_fcr_reg; +#[doc = "UART2_LCR_REG register accessor: an alias for `Reg`"] +pub type UART2_LCR_REG = crate::Reg; +#[doc = "Line Control Register"] +pub mod uart2_lcr_reg; +#[doc = "UART2_LSR_REG register accessor: an alias for `Reg`"] +pub type UART2_LSR_REG = crate::Reg; +#[doc = "Line Status Register"] +pub mod uart2_lsr_reg; +#[doc = "UART2_MCR_REG register accessor: an alias for `Reg`"] +pub type UART2_MCR_REG = crate::Reg; +#[doc = "Modem Control Register"] +pub mod uart2_mcr_reg; +#[doc = "UART2_RBR_THR_DLL_REG register accessor: an alias for `Reg`"] +pub type UART2_RBR_THR_DLL_REG = crate::Reg; +#[doc = "Receive Buffer Register/Transmit Holding Register/Divisor Latch Low"] +pub mod uart2_rbr_thr_dll_reg; +#[doc = "UART2_RFL_REG register accessor: an alias for `Reg`"] +pub type UART2_RFL_REG = crate::Reg; +#[doc = "Receive FIFO Level"] +pub mod uart2_rfl_reg; +#[doc = "UART2_SBCR_REG register accessor: an alias for `Reg`"] +pub type UART2_SBCR_REG = crate::Reg; +#[doc = "Shadow Break Control Register"] +pub mod uart2_sbcr_reg; +#[doc = "UART2_SCR_REG register accessor: an alias for `Reg`"] +pub type UART2_SCR_REG = crate::Reg; +#[doc = "Scratchpad Register"] +pub mod uart2_scr_reg; +#[doc = "UART2_SDMAM_REG register accessor: an alias for `Reg`"] +pub type UART2_SDMAM_REG = crate::Reg; +#[doc = "Shadow DMA Mode"] +pub mod uart2_sdmam_reg; +#[doc = "UART2_SFE_REG register accessor: an alias for `Reg`"] +pub type UART2_SFE_REG = crate::Reg; +#[doc = "Shadow FIFO Enable"] +pub mod uart2_sfe_reg; +#[doc = "UART2_SRBR_STHR0_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR0_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr0_reg; +#[doc = "UART2_SRBR_STHR10_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR10_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr10_reg; +#[doc = "UART2_SRBR_STHR11_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR11_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr11_reg; +#[doc = "UART2_SRBR_STHR12_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR12_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr12_reg; +#[doc = "UART2_SRBR_STHR13_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR13_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr13_reg; +#[doc = "UART2_SRBR_STHR14_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR14_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr14_reg; +#[doc = "UART2_SRBR_STHR15_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR15_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr15_reg; +#[doc = "UART2_SRBR_STHR1_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR1_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr1_reg; +#[doc = "UART2_SRBR_STHR2_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR2_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr2_reg; +#[doc = "UART2_SRBR_STHR3_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR3_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr3_reg; +#[doc = "UART2_SRBR_STHR4_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR4_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr4_reg; +#[doc = "UART2_SRBR_STHR5_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR5_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr5_reg; +#[doc = "UART2_SRBR_STHR6_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR6_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr6_reg; +#[doc = "UART2_SRBR_STHR7_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR7_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr7_reg; +#[doc = "UART2_SRBR_STHR8_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR8_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr8_reg; +#[doc = "UART2_SRBR_STHR9_REG register accessor: an alias for `Reg`"] +pub type UART2_SRBR_STHR9_REG = crate::Reg; +#[doc = "Shadow Receive/Transmit Buffer Register"] +pub mod uart2_srbr_sthr9_reg; +#[doc = "UART2_SRR_REG register accessor: an alias for `Reg`"] +pub type UART2_SRR_REG = crate::Reg; +#[doc = "Software Reset Register."] +pub mod uart2_srr_reg; +#[doc = "UART2_SRT_REG register accessor: an alias for `Reg`"] +pub type UART2_SRT_REG = crate::Reg; +#[doc = "Shadow RCVR Trigger"] +pub mod uart2_srt_reg; +#[doc = "UART2_STET_REG register accessor: an alias for `Reg`"] +pub type UART2_STET_REG = crate::Reg; +#[doc = "Shadow TX Empty Trigger"] +pub mod uart2_stet_reg; +#[doc = "UART2_TFL_REG register accessor: an alias for `Reg`"] +pub type UART2_TFL_REG = crate::Reg; +#[doc = "Transmit FIFO Level"] +pub mod uart2_tfl_reg; +#[doc = "UART2_UCV_HIGH_REG register accessor: an alias for `Reg`"] +pub type UART2_UCV_HIGH_REG = crate::Reg; +#[doc = "Component Version"] +pub mod uart2_ucv_high_reg; +#[doc = "UART2_UCV_REG register accessor: an alias for `Reg`"] +pub type UART2_UCV_REG = crate::Reg; +#[doc = "Component Version"] +pub mod uart2_ucv_reg; +#[doc = "UART2_USR_REG register accessor: an alias for `Reg`"] +pub type UART2_USR_REG = crate::Reg; +#[doc = "UART Status Register"] +pub mod uart2_usr_reg; diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_high_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_high_reg.rs new file mode 100644 index 0000000..fe511ab --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_high_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART2_CTR_HIGH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_CTR_HIGH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CTR` reader - Component Type Register"] +pub struct CTR_R(crate::FieldReader); +impl CTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Type Register"] + #[inline(always)] + pub fn ctr(&self) -> CTR_R { + CTR_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Type Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_ctr_high_reg](index.html) module"] +pub struct UART2_CTR_HIGH_REG_SPEC; +impl crate::RegisterSpec for UART2_CTR_HIGH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_ctr_high_reg::R](R) reader structure"] +impl crate::Readable for UART2_CTR_HIGH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_ctr_high_reg::W](W) writer structure"] +impl crate::Writable for UART2_CTR_HIGH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_CTR_HIGH_REG to value 0x4457"] +impl crate::Resettable for UART2_CTR_HIGH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x4457 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_reg.rs new file mode 100644 index 0000000..5fe3b0b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ctr_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART2_CTR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_CTR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `CTR` reader - Component Type Register"] +pub struct CTR_R(crate::FieldReader); +impl CTR_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + CTR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for CTR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Type Register"] + #[inline(always)] + pub fn ctr(&self) -> CTR_R { + CTR_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Type Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_ctr_reg](index.html) module"] +pub struct UART2_CTR_REG_SPEC; +impl crate::RegisterSpec for UART2_CTR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_ctr_reg::R](R) reader structure"] +impl crate::Readable for UART2_CTR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_ctr_reg::W](W) writer structure"] +impl crate::Writable for UART2_CTR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_CTR_REG to value 0x0110"] +impl crate::Resettable for UART2_CTR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x0110 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_dlf_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_dlf_reg.rs new file mode 100644 index 0000000..8888e1f --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_dlf_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART2_DLF_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_DLF_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_DLF` reader - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] +pub struct UART_DLF_R(crate::FieldReader); +impl UART_DLF_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_DLF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DLF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DLF` writer - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] +pub struct UART_DLF_W<'a> { + w: &'a mut W, +} +impl<'a> UART_DLF_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0f) | (value as u16 & 0x0f); + self.w + } +} +impl R { + #[doc = "Bits 0:3 - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] + #[inline(always)] + pub fn uart_dlf(&self) -> UART_DLF_R { + UART_DLF_R::new((self.bits & 0x0f) as u8) + } +} +impl W { + #[doc = "Bits 0:3 - The fractional value is added to integer value set by DLH, DLL. Fractional value is equal UART_DLF/16"] + #[inline(always)] + pub fn uart_dlf(&mut self) -> UART_DLF_W { + UART_DLF_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Divisor Latch Fraction Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_dlf_reg](index.html) module"] +pub struct UART2_DLF_REG_SPEC; +impl crate::RegisterSpec for UART2_DLF_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_dlf_reg::R](R) reader structure"] +impl crate::Readable for UART2_DLF_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_dlf_reg::W](W) writer structure"] +impl crate::Writable for UART2_DLF_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_DLF_REG to value 0"] +impl crate::Resettable for UART2_DLF_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_dmasa_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_dmasa_reg.rs new file mode 100644 index 0000000..00687f1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_dmasa_reg.rs @@ -0,0 +1,91 @@ +#[doc = "Register `UART2_DMASA_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_DMASA_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `DMASA` writer - This register is use to perform DMA software acknowledge if a transfer needs to be terminated due to an error condition. For example, if the DMA disables the channel, then the DW_apb_uart should clear its request. This will cause the TX request, TX single, RX request and RX single signals to de-assert. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct DMASA_W<'a> { + w: &'a mut W, +} +impl<'a> DMASA_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl W { + #[doc = "Bit 0 - This register is use to perform DMA software acknowledge if a transfer needs to be terminated due to an error condition. For example, if the DMA disables the channel, then the DW_apb_uart should clear its request. This will cause the TX request, TX single, RX request and RX single signals to de-assert. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn dmasa(&mut self) -> DMASA_W { + DMASA_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "DMA Software Acknowledge\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_dmasa_reg](index.html) module"] +pub struct UART2_DMASA_REG_SPEC; +impl crate::RegisterSpec for UART2_DMASA_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_dmasa_reg::R](R) reader structure"] +impl crate::Readable for UART2_DMASA_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_dmasa_reg::W](W) writer structure"] +impl crate::Writable for UART2_DMASA_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_DMASA_REG to value 0"] +impl crate::Resettable for UART2_DMASA_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_far_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_far_reg.rs new file mode 100644 index 0000000..8fedb8a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_far_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART2_FAR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_FAR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_FAR` reader - Description: Writes will have no effect when FIFO_ACCESS == No, always readable. This register is use to enable a FIFO access mode for testing, so that the receive FIFO can be written by the master and the transmit FIFO can be read by the master when FIFO's are implemented and enabled. When FIFO's are not implemented or not enabled it allows the RBR to be written by the master and the THR to be read by the master. 0 = FIFO access mode disabled 1 = FIFO access mode enabled Note, that when the FIFO access mode is enabled/disabled, the control portion of the receive FIFO and transmit FIFO is reset and the FIFO's are treated as empty."] +pub struct UART_FAR_R(crate::FieldReader); +impl UART_FAR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_FAR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_FAR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 0 - Description: Writes will have no effect when FIFO_ACCESS == No, always readable. This register is use to enable a FIFO access mode for testing, so that the receive FIFO can be written by the master and the transmit FIFO can be read by the master when FIFO's are implemented and enabled. When FIFO's are not implemented or not enabled it allows the RBR to be written by the master and the THR to be read by the master. 0 = FIFO access mode disabled 1 = FIFO access mode enabled Note, that when the FIFO access mode is enabled/disabled, the control portion of the receive FIFO and transmit FIFO is reset and the FIFO's are treated as empty."] + #[inline(always)] + pub fn uart_far(&self) -> UART_FAR_R { + UART_FAR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "FIFO Access Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_far_reg](index.html) module"] +pub struct UART2_FAR_REG_SPEC; +impl crate::RegisterSpec for UART2_FAR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_far_reg::R](R) reader structure"] +impl crate::Readable for UART2_FAR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_far_reg::W](W) writer structure"] +impl crate::Writable for UART2_FAR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_FAR_REG to value 0"] +impl crate::Resettable for UART2_FAR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_htx_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_htx_reg.rs new file mode 100644 index 0000000..0dc3fee --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_htx_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `UART2_HTX_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_HTX_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_HALT_TX` reader - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] +pub struct UART_HALT_TX_R(crate::FieldReader); +impl UART_HALT_TX_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_HALT_TX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_HALT_TX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_HALT_TX` writer - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] +pub struct UART_HALT_TX_W<'a> { + w: &'a mut W, +} +impl<'a> UART_HALT_TX_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] + #[inline(always)] + pub fn uart_halt_tx(&self) -> UART_HALT_TX_R { + UART_HALT_TX_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - This register is use to halt transmissions for testing, so that the transmit FIFO can be filled by the master when FIFOs are implemented and enabled. 0 = Halt TX disabled 1 = Halt TX enabled Note, if FIFOs are implemented and not enabled, the setting of the halt TX register has no effect on operation."] + #[inline(always)] + pub fn uart_halt_tx(&mut self) -> UART_HALT_TX_W { + UART_HALT_TX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Halt TX\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_htx_reg](index.html) module"] +pub struct UART2_HTX_REG_SPEC; +impl crate::RegisterSpec for UART2_HTX_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_htx_reg::R](R) reader structure"] +impl crate::Readable for UART2_HTX_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_htx_reg::W](W) writer structure"] +impl crate::Writable for UART2_HTX_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_HTX_REG to value 0"] +impl crate::Resettable for UART2_HTX_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_ier_dlh_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ier_dlh_reg.rs new file mode 100644 index 0000000..1102e0d --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ier_dlh_reg.rs @@ -0,0 +1,338 @@ +#[doc = "Register `UART2_IER_DLH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_IER_DLH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `PTIME_dlh7` reader - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct PTIME_DLH7_R(crate::FieldReader); +impl PTIME_DLH7_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + PTIME_DLH7_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for PTIME_DLH7_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `PTIME_dlh7` writer - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct PTIME_DLH7_W<'a> { + w: &'a mut W, +} +impl<'a> PTIME_DLH7_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `dlh6_4` reader - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] +pub struct DLH6_4_R(crate::FieldReader); +impl DLH6_4_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + DLH6_4_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for DLH6_4_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `dlh6_4` writer - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] +pub struct DLH6_4_W<'a> { + w: &'a mut W, +} +impl<'a> DLH6_4_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u16 & 7) << 4); + self.w + } +} +#[doc = "Field `EDSSI_dlh3` reader - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct EDSSI_DLH3_R(crate::FieldReader); +impl EDSSI_DLH3_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + EDSSI_DLH3_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EDSSI_DLH3_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EDSSI_dlh3` writer - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct EDSSI_DLH3_W<'a> { + w: &'a mut W, +} +impl<'a> EDSSI_DLH3_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `ELSI_dhl2` reader - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ELSI_DHL2_R(crate::FieldReader); +impl ELSI_DHL2_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ELSI_DHL2_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ELSI_DHL2_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ELSI_dhl2` writer - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ELSI_DHL2_W<'a> { + w: &'a mut W, +} +impl<'a> ELSI_DHL2_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `ETBEI_dlh1` reader - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ETBEI_DLH1_R(crate::FieldReader); +impl ETBEI_DLH1_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ETBEI_DLH1_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ETBEI_DLH1_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ETBEI_dlh1` writer - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ETBEI_DLH1_W<'a> { + w: &'a mut W, +} +impl<'a> ETBEI_DLH1_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `ERBFI_dlh0` reader - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ERBFI_DLH0_R(crate::FieldReader); +impl ERBFI_DLH0_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + ERBFI_DLH0_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for ERBFI_DLH0_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `ERBFI_dlh0` writer - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] +pub struct ERBFI_DLH0_W<'a> { + w: &'a mut W, +} +impl<'a> ERBFI_DLH0_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 7 - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn ptime_dlh7(&self) -> PTIME_DLH7_R { + PTIME_DLH7_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bits 4:6 - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn dlh6_4(&self) -> DLH6_4_R { + DLH6_4_R::new(((self.bits >> 4) & 7) as u8) + } + #[doc = "Bit 3 - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn edssi_dlh3(&self) -> EDSSI_DLH3_R { + EDSSI_DLH3_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn elsi_dhl2(&self) -> ELSI_DHL2_R { + ELSI_DHL2_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn etbei_dlh1(&self) -> ETBEI_DLH1_R { + ETBEI_DLH1_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn erbfi_dlh0(&self) -> ERBFI_DLH0_R { + ERBFI_DLH0_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 7 - Interrupt Enable Register: PTIME, Programmable THRE Interrupt Mode Enable. This is used to enable/disable the generation of THRE Interrupt. 0 = disabled 1 = enabled. Divisor Latch (High): DLH7, Bit 7 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn ptime_dlh7(&mut self) -> PTIME_DLH7_W { + PTIME_DLH7_W { w: self } + } + #[doc = "Bits 4:6 - Divisor Latch (High): DLH6 to DLH4, Bits 6 to 4 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set, otherwise, this field is reserved. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn dlh6_4(&mut self) -> DLH6_4_W { + DLH6_4_W { w: self } + } + #[doc = "Bit 3 - Interrupt Enable Register: EDSSI, Enable Modem Status Interrupt. This is used to enable/disable the generation of Modem Status Interrupt. This is the fourth highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH3, Bit 3 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn edssi_dlh3(&mut self) -> EDSSI_DLH3_W { + EDSSI_DLH3_W { w: self } + } + #[doc = "Bit 2 - Interrupt Enable Register: ELSI, Enable Receiver Line Status Interrupt. This is used to enable/disable the generation of Receiver Line Status Interrupt. This is the highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH2, Bit 2 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn elsi_dhl2(&mut self) -> ELSI_DHL2_W { + ELSI_DHL2_W { w: self } + } + #[doc = "Bit 1 - Interrupt Enable Register: ETBEI, Enable Transmit Holding Register Empty Interrupt. This is used to enable/disable the generation of Transmitter Holding Register Empty Interrupt. This is the third highest priority interrupt. 0 = disabled 1 = enabled Divisor Latch (High): DLH1, Bit 1 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn etbei_dlh1(&mut self) -> ETBEI_DLH1_W { + ETBEI_DLH1_W { w: self } + } + #[doc = "Bit 0 - Interrupt Enable Register: ERBFI, Enable Received Data Available Interrupt. This is used to enable/disable the generation of Received Data Available Interrupt and the Character Timeout Interrupt (if in FIFO mode and FIFO's enabled). These are the second highest priority interrupts. 0 = disabled 1 = enabled Divisor Latch (High): DLH0, Bit 0 of the upper part of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may be accessed only when the DLAB bit (LCR\\[7\\]) is set. See register UART_RBR_THR_DLL_REG."] + #[inline(always)] + pub fn erbfi_dlh0(&mut self) -> ERBFI_DLH0_W { + ERBFI_DLH0_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt Enable Register/Divisor Latch High\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_ier_dlh_reg](index.html) module"] +pub struct UART2_IER_DLH_REG_SPEC; +impl crate::RegisterSpec for UART2_IER_DLH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_ier_dlh_reg::R](R) reader structure"] +impl crate::Readable for UART2_IER_DLH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_ier_dlh_reg::W](W) writer structure"] +impl crate::Writable for UART2_IER_DLH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_IER_DLH_REG to value 0"] +impl crate::Resettable for UART2_IER_DLH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_iir_fcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_iir_fcr_reg.rs new file mode 100644 index 0000000..7aa9920 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_iir_fcr_reg.rs @@ -0,0 +1,308 @@ +#[doc = "Register `UART2_IIR_FCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_IIR_FCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_FIFOSE_RT` reader - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] +pub struct UART_FIFOSE_RT_R(crate::FieldReader); +impl UART_FIFOSE_RT_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_FIFOSE_RT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_FIFOSE_RT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_FIFOSE_RT` writer - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] +pub struct UART_FIFOSE_RT_W<'a> { + w: &'a mut W, +} +impl<'a> UART_FIFOSE_RT_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 6)) | ((value as u16 & 3) << 6); + self.w + } +} +#[doc = "Field `UART_TET` writer - On read reserved On Write TX Empty Trigger (or TET): This is used to select the empty threshold level at which the THRE Interrupts will be generated when the mode is active. It also determines when the dma_tx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO 1/4 full 11 = FIFO 1/2 full"] +pub struct UART_TET_W<'a> { + w: &'a mut W, +} +impl<'a> UART_TET_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(3 << 4)) | ((value as u16 & 3) << 4); + self.w + } +} +#[doc = "Field `UART_IID3_DMAM` reader - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_IID3_DMAM_R(crate::FieldReader); +impl UART_IID3_DMAM_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID3_DMAM_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID3_DMAM_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID3_DMAM` writer - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_IID3_DMAM_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID3_DMAM_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `UART_IID2_XFIFOR` reader - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID2_XFIFOR_R(crate::FieldReader); +impl UART_IID2_XFIFOR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID2_XFIFOR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID2_XFIFOR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID2_XFIFOR` writer - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID2_XFIFOR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID2_XFIFOR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `UART_IID1_RFIFOE` reader - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID1_RFIFOE_R(crate::FieldReader); +impl UART_IID1_RFIFOE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID1_RFIFOE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID1_RFIFOE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID1_RFIFOE` writer - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] +pub struct UART_IID1_RFIFOE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID1_RFIFOE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `UART_IID0_FIFOE` reader - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] +pub struct UART_IID0_FIFOE_R(crate::FieldReader); +impl UART_IID0_FIFOE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_IID0_FIFOE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_IID0_FIFOE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_IID0_FIFOE` writer - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] +pub struct UART_IID0_FIFOE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_IID0_FIFOE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bits 6:7 - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_fifose_rt(&self) -> UART_FIFOSE_RT_R { + UART_FIFOSE_RT_R::new(((self.bits >> 6) & 3) as u8) + } + #[doc = "Bit 3 - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_iid3_dmam(&self) -> UART_IID3_DMAM_R { + UART_IID3_DMAM_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid2_xfifor(&self) -> UART_IID2_XFIFOR_R { + UART_IID2_XFIFOR_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid1_rfifoe(&self) -> UART_IID1_RFIFOE_R { + UART_IID1_RFIFOE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] + #[inline(always)] + pub fn uart_iid0_fifoe(&self) -> UART_IID0_FIFOE_R { + UART_IID0_FIFOE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bits 6:7 - On read FIFO's Enabled (or FIFOSE): This is used to indicate whether the FIFO's are enabled or disabled. 00 = disabled. 11 = enabled. On write RCVR Trigger (or RT):. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt will be generated. In auto flow control mode it is used to determine when the rts_n signal will be de-asserted. It also determines when the dma_rx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO 1/4 full 10 = FIFO 1/2 full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_fifose_rt(&mut self) -> UART_FIFOSE_RT_W { + UART_FIFOSE_RT_W { w: self } + } + #[doc = "Bits 4:5 - On read reserved On Write TX Empty Trigger (or TET): This is used to select the empty threshold level at which the THRE Interrupts will be generated when the mode is active. It also determines when the dma_tx_req_n signal will be asserted when in certain modes of operation. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO 1/4 full 11 = FIFO 1/2 full"] + #[inline(always)] + pub fn uart_tet(&mut self) -> UART_TET_W { + UART_TET_W { w: self } + } + #[doc = "Bit 3 - On Read (Bit3) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write DMA Mode (or DMAM): This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_iid3_dmam(&mut self) -> UART_IID3_DMAM_W { + UART_IID3_DMAM_W { w: self } + } + #[doc = "Bit 2 - On Read (Bit2) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write XMIT FIFO Reset (or XFIFOR): This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid2_xfifor(&mut self) -> UART_IID2_XFIFOR_W { + UART_IID2_XFIFOR_W { w: self } + } + #[doc = "Bit 1 - On Read (Bit1) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write RCVR FIFO Reset (or RFIFOR): This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing' and it is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_iid1_rfifoe(&mut self) -> UART_IID1_RFIFOE_W { + UART_IID1_RFIFOE_W { w: self } + } + #[doc = "Bit 0 - On Read (Bit0) Interrupt ID (or IID): This indicates the highest priority pending interrupt which can be one of the following types: 0001 = no interrupt pending. 0010 = THR empty. 0100 = received data available. 0110 = receiver line status. 0111 = busy detect. 1100 = character timeout. On Write FIFO Enable (or FIFOE): This enables/disables the transmit (XMIT) and receive (RCVR) FIFO's. Whenever the value of this bit is changed both the XMIT and RCVR controller portion of FIFO's will be reset"] + #[inline(always)] + pub fn uart_iid0_fifoe(&mut self) -> UART_IID0_FIFOE_W { + UART_IID0_FIFOE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Interrupt Identification Register/FIFO Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_iir_fcr_reg](index.html) module"] +pub struct UART2_IIR_FCR_REG_SPEC; +impl crate::RegisterSpec for UART2_IIR_FCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_iir_fcr_reg::R](R) reader structure"] +impl crate::Readable for UART2_IIR_FCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_iir_fcr_reg::W](W) writer structure"] +impl crate::Writable for UART2_IIR_FCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_IIR_FCR_REG to value 0x01"] +impl crate::Resettable for UART2_IIR_FCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x01 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_lcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_lcr_reg.rs new file mode 100644 index 0000000..932a09e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_lcr_reg.rs @@ -0,0 +1,366 @@ +#[doc = "Register `UART2_LCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_LCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_DLAB` reader - Divisor Latch Access Bit.Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] +pub struct UART_DLAB_R(crate::FieldReader); +impl UART_DLAB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_DLAB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DLAB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DLAB` writer - Divisor Latch Access Bit.Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] +pub struct UART_DLAB_W<'a> { + w: &'a mut W, +} +impl<'a> UART_DLAB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `UART_BC` reader - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] +pub struct UART_BC_R(crate::FieldReader); +impl UART_BC_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_BC_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_BC_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_BC` writer - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] +pub struct UART_BC_W<'a> { + w: &'a mut W, +} +impl<'a> UART_BC_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `UART_EPS` reader - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] +pub struct UART_EPS_R(crate::FieldReader); +impl UART_EPS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_EPS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_EPS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_EPS` writer - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] +pub struct UART_EPS_W<'a> { + w: &'a mut W, +} +impl<'a> UART_EPS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +#[doc = "Field `UART_PEN` reader - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] +pub struct UART_PEN_R(crate::FieldReader); +impl UART_PEN_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_PEN_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_PEN_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_PEN` writer - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] +pub struct UART_PEN_W<'a> { + w: &'a mut W, +} +impl<'a> UART_PEN_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `UART_STOP` reader - Number of stop bits. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] +pub struct UART_STOP_R(crate::FieldReader); +impl UART_STOP_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_STOP_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_STOP_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_STOP` writer - Number of stop bits. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] +pub struct UART_STOP_W<'a> { + w: &'a mut W, +} +impl<'a> UART_STOP_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `UART_DLS` reader - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] +pub struct UART_DLS_R(crate::FieldReader); +impl UART_DLS_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_DLS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DLS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DLS` writer - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] +pub struct UART_DLS_W<'a> { + w: &'a mut W, +} +impl<'a> UART_DLS_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bit 7 - Divisor Latch Access Bit.Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] + #[inline(always)] + pub fn uart_dlab(&self) -> UART_DLAB_R { + UART_DLAB_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] + #[inline(always)] + pub fn uart_bc(&self) -> UART_BC_R { + UART_BC_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 4 - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] + #[inline(always)] + pub fn uart_eps(&self) -> UART_EPS_R { + UART_EPS_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] + #[inline(always)] + pub fn uart_pen(&self) -> UART_PEN_R { + UART_PEN_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Number of stop bits. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] + #[inline(always)] + pub fn uart_stop(&self) -> UART_STOP_R { + UART_STOP_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bits 0:1 - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] + #[inline(always)] + pub fn uart_dls(&self) -> UART_DLS_R { + UART_DLS_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bit 7 - Divisor Latch Access Bit.Writeable only when UART is not busy (USR\\[0\\] +is zero). This bit is used to enable reading and writing of the Divisor Latch register (DLL and DLH) to set the baud rate of the UART. This bit must be cleared after initial baud rate setup in order to access other registers."] + #[inline(always)] + pub fn uart_dlab(&mut self) -> UART_DLAB_W { + UART_DLAB_W { w: self } + } + #[doc = "Bit 6 - Break Control Bit. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If active (MCR\\[6\\] +set to one) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver and the sir_out_n line is forced low."] + #[inline(always)] + pub fn uart_bc(&mut self) -> UART_BC_W { + UART_BC_W { w: self } + } + #[doc = "Bit 4 - Even Parity Select. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select between even and odd parity, when parity is enabled (PEN set to one). If set to one, an even number of logic 1s is transmitted or checked. If set to zero, an odd number of logic 1s is transmitted or checked."] + #[inline(always)] + pub fn uart_eps(&mut self) -> UART_EPS_W { + UART_EPS_W { w: self } + } + #[doc = "Bit 3 - Parity Enable. Writeable only when UART is not busy (USR\\[0\\] +is zero) This bit is used to enable and disable parity generation and detection in transmitted and received serial character respectively. 0 = parity disabled 1 = parity enabled"] + #[inline(always)] + pub fn uart_pen(&mut self) -> UART_PEN_W { + UART_PEN_W { w: self } + } + #[doc = "Bit 2 - Number of stop bits. Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of stop bits per character that the peripheral transmits and receives. If set to zero, one stop bit is transmitted in the serial data. If set to one and the data bits are set to 5 (LCR\\[1:0\\] +set to zero) one and a half stop bits is transmitted. Otherwise, two stop bits are transmitted. Note that regardless of the number of stop bits selected, the receiver checks only the first stop bit. 0 = 1 stop bit 1 = 1.5 stop bits when DLS (LCR\\[1:0\\]) is zero, else 2 stop bit"] + #[inline(always)] + pub fn uart_stop(&mut self) -> UART_STOP_W { + UART_STOP_W { w: self } + } + #[doc = "Bits 0:1 - Data Length Select.Writeable only when UART is not busy (USR\\[0\\] +is zero). This is used to select the number of data bits per character that the peripheral transmits and receives. The number of bit that may be selected areas follows: 00 = 5 bits 01 = 6 bits 10 = 7 bits 11 = 8 bits"] + #[inline(always)] + pub fn uart_dls(&mut self) -> UART_DLS_W { + UART_DLS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Line Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_lcr_reg](index.html) module"] +pub struct UART2_LCR_REG_SPEC; +impl crate::RegisterSpec for UART2_LCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_lcr_reg::R](R) reader structure"] +impl crate::Readable for UART2_LCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_lcr_reg::W](W) writer structure"] +impl crate::Writable for UART2_LCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_LCR_REG to value 0"] +impl crate::Resettable for UART2_LCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_lsr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_lsr_reg.rs new file mode 100644 index 0000000..a66844a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_lsr_reg.rs @@ -0,0 +1,238 @@ +#[doc = "Register `UART2_LSR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_LSR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_RFE` reader - Receiver FIFO Error bit. This bit is only relevant when FIFOs are enabled (FCR\\[0\\] +set to one). This is used to indicate if there is at least one parity error, framing error, or break indication in the FIFO. 0 = no error in RX FIFO 1 = error in RX FIFO This bit is cleared when the LSR is read and the character with the error is at the top of the receiver FIFO and there are no subsequent errors in the FIFO."] +pub struct UART_RFE_R(crate::FieldReader); +impl UART_RFE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_RFE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RFE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_TEMT` reader - Transmitter Empty bit. If FIFOs enabled (FCR\\[0\\] +set to one), this bit is set whenever the Transmitter Shift Register and the FIFO are both empty. If FIFOs are disabled, this bit is set whenever the Transmitter Holding Register(THR) and the Transmitter Shift Register are both empty."] +pub struct UART_TEMT_R(crate::FieldReader); +impl UART_TEMT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_TEMT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TEMT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_THRE` reader - Transmit Holding Register Empty bit. If THRE mode is disabled (IER\\[7\\] +set to zero) and regardless of FIFO's being implemented/enabled or not, this bit indicates that the THR or TX FIFO is empty. This bit is set whenever data is transferred from the THR or TX FIFO to the transmitter shift register and no new data has been written to the THR or TX FIFO. This also causes a THRE Interrupt to occur, if the THRE Interrupt is enabled. If both modes are active (IER\\[7\\] +set to one and FCR\\[0\\] +set to one respectively), the functionality is switched to indicate the transmitter FIFO is full, and no longer controls THRE interrupts, which are then controlled by the FCR\\[5:4\\] +threshold setting."] +pub struct UART_THRE_R(crate::FieldReader); +impl UART_THRE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_THRE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_THRE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_BI` reader - Break Interrupt bit. This is used to indicate the detection of a break sequence on the serial input data. If in UART mode (SIR_MODE == Disabled), it is set whenever the serial input, sin, is held in a logic '0' state for longer than the sum of start time + data bits + parity + stop bits. If in infrared mode (SIR_MODE == Enabled), it is set whenever the serial input, sir_in, is continuously pulsed to logic '0' for longer than the sum of start time + data bits + parity + stop bits. A break condition on serial input causes one and only one character, consisting of all zeros, to be received by the UART. In the FIFO mode, the character associated with the break condition is carried through the FIFO and is revealed when the character is at the top of the FIFO. Reading the LSR clears the BI bit. In the non-FIFO mode, the BI indication occurs immediately and persists until the LSR is read."] +pub struct UART_BI_R(crate::FieldReader); +impl UART_BI_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_BI_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_BI_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_FE` reader - Framing Error bit. This is used to indicate the occurrence of a framing error in the receiver. A framing error occurs when the receiver does not detect a valid STOP bit in the received data. In the FIFO mode, since the framing error is associated with a character received, it is revealed when the character with the framing error is at the top of the FIFO. When a framing error occurs, the UART tries to resynchronize. It does this by assuming that the error was due to the start bit of the next character and then continues receiving the other bit i.e. data, and/or parity and stop. It should be noted that the Framing Error (FE) bit (LSR\\[3\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no framing error 1 = framing error Reading the LSR clears the FE bit."] +pub struct UART_FE_R(crate::FieldReader); +impl UART_FE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_FE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_FE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_PE` reader - Parity Error bit. This is used to indicate the occurrence of a parity error in the receiver if the Parity Enable (PEN) bit (LCR\\[3\\]) is set. In the FIFO mode, since the parity error is associated with a character received, it is revealed when the character with the parity error arrives at the top of the FIFO. It should be noted that the Parity Error (PE) bit (LSR\\[2\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no parity error 1 = parity error Reading the LSR clears the PE bit."] +pub struct UART_PE_R(crate::FieldReader); +impl UART_PE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_PE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_PE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_OE` reader - Overrun error bit. This is used to indicate the occurrence of an overrun error. This occurs if a new data character was received before the previous data was read. In the non-FIFO mode, the OE bit is set when a new character arrives in the receiver before the previous character was read from the RBR. When this happens, the data in the RBR is overwritten. In the FIFO mode, an overrun error occurs when the FIFO is full and a new character arrives at the receiver. The data in the FIFO is retained and the data in the receive shift register is lost. 0 = no overrun error 1 = overrun error Reading the LSR clears the OE bit."] +pub struct UART_OE_R(crate::FieldReader); +impl UART_OE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_OE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_OE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_DR` reader - Data Ready bit. This is used to indicate that the receiver contains at least one character in the RBR or the receiver FIFO. 0 = no data ready 1 = data ready This bit is cleared when the RBR is read in non-FIFO mode, or when the receiver FIFO is empty, in FIFO mode."] +pub struct UART_DR_R(crate::FieldReader); +impl UART_DR_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_DR_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_DR_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 7 - Receiver FIFO Error bit. This bit is only relevant when FIFOs are enabled (FCR\\[0\\] +set to one). This is used to indicate if there is at least one parity error, framing error, or break indication in the FIFO. 0 = no error in RX FIFO 1 = error in RX FIFO This bit is cleared when the LSR is read and the character with the error is at the top of the receiver FIFO and there are no subsequent errors in the FIFO."] + #[inline(always)] + pub fn uart_rfe(&self) -> UART_RFE_R { + UART_RFE_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - Transmitter Empty bit. If FIFOs enabled (FCR\\[0\\] +set to one), this bit is set whenever the Transmitter Shift Register and the FIFO are both empty. If FIFOs are disabled, this bit is set whenever the Transmitter Holding Register(THR) and the Transmitter Shift Register are both empty."] + #[inline(always)] + pub fn uart_temt(&self) -> UART_TEMT_R { + UART_TEMT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bit 5 - Transmit Holding Register Empty bit. If THRE mode is disabled (IER\\[7\\] +set to zero) and regardless of FIFO's being implemented/enabled or not, this bit indicates that the THR or TX FIFO is empty. This bit is set whenever data is transferred from the THR or TX FIFO to the transmitter shift register and no new data has been written to the THR or TX FIFO. This also causes a THRE Interrupt to occur, if the THRE Interrupt is enabled. If both modes are active (IER\\[7\\] +set to one and FCR\\[0\\] +set to one respectively), the functionality is switched to indicate the transmitter FIFO is full, and no longer controls THRE interrupts, which are then controlled by the FCR\\[5:4\\] +threshold setting."] + #[inline(always)] + pub fn uart_thre(&self) -> UART_THRE_R { + UART_THRE_R::new(((self.bits >> 5) & 1) != 0) + } + #[doc = "Bit 4 - Break Interrupt bit. This is used to indicate the detection of a break sequence on the serial input data. If in UART mode (SIR_MODE == Disabled), it is set whenever the serial input, sin, is held in a logic '0' state for longer than the sum of start time + data bits + parity + stop bits. If in infrared mode (SIR_MODE == Enabled), it is set whenever the serial input, sir_in, is continuously pulsed to logic '0' for longer than the sum of start time + data bits + parity + stop bits. A break condition on serial input causes one and only one character, consisting of all zeros, to be received by the UART. In the FIFO mode, the character associated with the break condition is carried through the FIFO and is revealed when the character is at the top of the FIFO. Reading the LSR clears the BI bit. In the non-FIFO mode, the BI indication occurs immediately and persists until the LSR is read."] + #[inline(always)] + pub fn uart_bi(&self) -> UART_BI_R { + UART_BI_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Framing Error bit. This is used to indicate the occurrence of a framing error in the receiver. A framing error occurs when the receiver does not detect a valid STOP bit in the received data. In the FIFO mode, since the framing error is associated with a character received, it is revealed when the character with the framing error is at the top of the FIFO. When a framing error occurs, the UART tries to resynchronize. It does this by assuming that the error was due to the start bit of the next character and then continues receiving the other bit i.e. data, and/or parity and stop. It should be noted that the Framing Error (FE) bit (LSR\\[3\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no framing error 1 = framing error Reading the LSR clears the FE bit."] + #[inline(always)] + pub fn uart_fe(&self) -> UART_FE_R { + UART_FE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Parity Error bit. This is used to indicate the occurrence of a parity error in the receiver if the Parity Enable (PEN) bit (LCR\\[3\\]) is set. In the FIFO mode, since the parity error is associated with a character received, it is revealed when the character with the parity error arrives at the top of the FIFO. It should be noted that the Parity Error (PE) bit (LSR\\[2\\]) is set if a break interrupt has occurred, as indicated by Break Interrupt (BI) bit (LSR\\[4\\]). 0 = no parity error 1 = parity error Reading the LSR clears the PE bit."] + #[inline(always)] + pub fn uart_pe(&self) -> UART_PE_R { + UART_PE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Overrun error bit. This is used to indicate the occurrence of an overrun error. This occurs if a new data character was received before the previous data was read. In the non-FIFO mode, the OE bit is set when a new character arrives in the receiver before the previous character was read from the RBR. When this happens, the data in the RBR is overwritten. In the FIFO mode, an overrun error occurs when the FIFO is full and a new character arrives at the receiver. The data in the FIFO is retained and the data in the receive shift register is lost. 0 = no overrun error 1 = overrun error Reading the LSR clears the OE bit."] + #[inline(always)] + pub fn uart_oe(&self) -> UART_OE_R { + UART_OE_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Data Ready bit. This is used to indicate that the receiver contains at least one character in the RBR or the receiver FIFO. 0 = no data ready 1 = data ready This bit is cleared when the RBR is read in non-FIFO mode, or when the receiver FIFO is empty, in FIFO mode."] + #[inline(always)] + pub fn uart_dr(&self) -> UART_DR_R { + UART_DR_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Line Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_lsr_reg](index.html) module"] +pub struct UART2_LSR_REG_SPEC; +impl crate::RegisterSpec for UART2_LSR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_lsr_reg::R](R) reader structure"] +impl crate::Readable for UART2_LSR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_lsr_reg::W](W) writer structure"] +impl crate::Writable for UART2_LSR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_LSR_REG to value 0x60"] +impl crate::Resettable for UART2_LSR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x60 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_mcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_mcr_reg.rs new file mode 100644 index 0000000..8ca14d8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_mcr_reg.rs @@ -0,0 +1,121 @@ +#[doc = "Register `UART2_MCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_MCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_LB` reader - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] +pub struct UART_LB_R(crate::FieldReader); +impl UART_LB_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_LB_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_LB_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_LB` writer - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] +pub struct UART_LB_W<'a> { + w: &'a mut W, +} +impl<'a> UART_LB_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 4)) | ((value as u16 & 1) << 4); + self.w + } +} +impl R { + #[doc = "Bit 4 - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] + #[inline(always)] + pub fn uart_lb(&self) -> UART_LB_R { + UART_LB_R::new(((self.bits >> 4) & 1) != 0) + } +} +impl W { + #[doc = "Bit 4 - LoopBack Bit. This is used to put the UART into a diagnostic mode for test purposes. If operating in UART mode (SIR_MODE not active, MCR\\[6\\] +set to zero), data on the sout line is held high, while serial data output is looped back to the sin line, internally. In this mode all the interrupts are fully functional. Also, in loopback mode, the modem control inputs (dsr_n, cts_n, ri_n, dcd_n) are disconnected and the modem control outputs (dtr_n, rts_n, out1_n, out2_n) are looped back to the inputs, internally. If operating in infrared mode (SIR_MODE active, MCR\\[6\\] +set to one), data on the sir_out_n line is held low, while serial data output is inverted and looped back to the sir_in line."] + #[inline(always)] + pub fn uart_lb(&mut self) -> UART_LB_W { + UART_LB_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Modem Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_mcr_reg](index.html) module"] +pub struct UART2_MCR_REG_SPEC; +impl crate::RegisterSpec for UART2_MCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_mcr_reg::R](R) reader structure"] +impl crate::Readable for UART2_MCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_mcr_reg::W](W) writer structure"] +impl crate::Writable for UART2_MCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_MCR_REG to value 0"] +impl crate::Resettable for UART2_MCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_rbr_thr_dll_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_rbr_thr_dll_reg.rs new file mode 100644 index 0000000..4e078fd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_rbr_thr_dll_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_RBR_THR_DLL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_RBR_THR_DLL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `RBR_THR_DLL` reader - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] +pub struct RBR_THR_DLL_R(crate::FieldReader); +impl RBR_THR_DLL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + RBR_THR_DLL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for RBR_THR_DLL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `RBR_THR_DLL` writer - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] +pub struct RBR_THR_DLL_W<'a> { + w: &'a mut W, +} +impl<'a> RBR_THR_DLL_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] + #[inline(always)] + pub fn rbr_thr_dll(&self) -> RBR_THR_DLL_R { + RBR_THR_DLL_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Receive Buffer Register: (RBR). This register contains the data byte received on the serial input port (sin) in UART mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Transmit Holding Register: (THR) This register contains data to be transmitted on the serial output port (sout) in UART mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, 16 number of characters of data may be written to the THR before the FIFO is full. Any attempt to write data when the FIFO is full results in the write data being lost. Divisor Latch (Low): (DLL) This register makes up the lower 8-bits of a 16-bit, read/write, Divisor Latch register that contains the baud rate divisor for the UART. This register may only be accessed when the DLAB bit (LCR\\[7\\]) is set. The output baud rate is equal to the serial clock (sclk) frequency divided by sixteen times the value of the baud rate divisor, as follows: baud rate = (serial clock freq) / (16 * divisor) Note that with the Divisor Latch Registers (DLL and DLH) set to zero, the baud clock is disabled and no serial communications will occur. Also, once the Divisor Latch is set, at least 8 clock cycles of the slowest UART clock should be allowed to pass before transmitting or receiving data. For the Divisor Latch (High) bits, see register UART_IER_DLH_REG."] + #[inline(always)] + pub fn rbr_thr_dll(&mut self) -> RBR_THR_DLL_W { + RBR_THR_DLL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Receive Buffer Register/Transmit Holding Register/Divisor Latch Low\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_rbr_thr_dll_reg](index.html) module"] +pub struct UART2_RBR_THR_DLL_REG_SPEC; +impl crate::RegisterSpec for UART2_RBR_THR_DLL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_rbr_thr_dll_reg::R](R) reader structure"] +impl crate::Readable for UART2_RBR_THR_DLL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_rbr_thr_dll_reg::W](W) writer structure"] +impl crate::Writable for UART2_RBR_THR_DLL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_RBR_THR_DLL_REG to value 0"] +impl crate::Resettable for UART2_RBR_THR_DLL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_rfl_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_rfl_reg.rs new file mode 100644 index 0000000..d0322cd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_rfl_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART2_RFL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_RFL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_RECEIVE_FIFO_LEVEL` reader - Receive FIFO Level. This is indicates the number of data entries in the receive FIFO."] +pub struct UART_RECEIVE_FIFO_LEVEL_R(crate::FieldReader); +impl UART_RECEIVE_FIFO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_RECEIVE_FIFO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RECEIVE_FIFO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:4 - Receive FIFO Level. This is indicates the number of data entries in the receive FIFO."] + #[inline(always)] + pub fn uart_receive_fifo_level(&self) -> UART_RECEIVE_FIFO_LEVEL_R { + UART_RECEIVE_FIFO_LEVEL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Receive FIFO Level\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_rfl_reg](index.html) module"] +pub struct UART2_RFL_REG_SPEC; +impl crate::RegisterSpec for UART2_RFL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_rfl_reg::R](R) reader structure"] +impl crate::Readable for UART2_RFL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_rfl_reg::W](W) writer structure"] +impl crate::Writable for UART2_RFL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_RFL_REG to value 0"] +impl crate::Resettable for UART2_RFL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_sbcr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_sbcr_reg.rs new file mode 100644 index 0000000..b55fe30 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_sbcr_reg.rs @@ -0,0 +1,117 @@ +#[doc = "Register `UART2_SBCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SBCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_BREAK_CONTROL` reader - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] +pub struct UART_SHADOW_BREAK_CONTROL_R(crate::FieldReader); +impl UART_SHADOW_BREAK_CONTROL_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_SHADOW_BREAK_CONTROL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_BREAK_CONTROL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_BREAK_CONTROL` writer - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] +pub struct UART_SHADOW_BREAK_CONTROL_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_BREAK_CONTROL_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] + #[inline(always)] + pub fn uart_shadow_break_control(&self) -> UART_SHADOW_BREAK_CONTROL_R { + UART_SHADOW_BREAK_CONTROL_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Shadow Break Control Bit. This is a shadow register for the Break bit (LCR\\[6\\]), this can be used to remove the burden of having to performing a read modify write on the LCR. This is used to cause a break condition to be transmitted to the receiving device. If set to one the serial output is forced to the spacing (logic 0) state. When not in Loopback Mode, as determined by MCR\\[4\\], the sout line is forced low until the Break bit is cleared. If SIR_MODE active (MCR\\[6\\] += 1) the sir_out_n line is continuously pulsed. When in Loopback Mode, the break condition is internally looped back to the receiver."] + #[inline(always)] + pub fn uart_shadow_break_control(&mut self) -> UART_SHADOW_BREAK_CONTROL_W { + UART_SHADOW_BREAK_CONTROL_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Break Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_sbcr_reg](index.html) module"] +pub struct UART2_SBCR_REG_SPEC; +impl crate::RegisterSpec for UART2_SBCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_sbcr_reg::R](R) reader structure"] +impl crate::Readable for UART2_SBCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_sbcr_reg::W](W) writer structure"] +impl crate::Writable for UART2_SBCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SBCR_REG to value 0"] +impl crate::Resettable for UART2_SBCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_scr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_scr_reg.rs new file mode 100644 index 0000000..df9eb49 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_scr_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART2_SCR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SCR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SCRATCH_PAD` reader - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] +pub struct UART_SCRATCH_PAD_R(crate::FieldReader); +impl UART_SCRATCH_PAD_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_SCRATCH_PAD_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SCRATCH_PAD_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SCRATCH_PAD` writer - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] +pub struct UART_SCRATCH_PAD_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SCRATCH_PAD_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] + #[inline(always)] + pub fn uart_scratch_pad(&self) -> UART_SCRATCH_PAD_R { + UART_SCRATCH_PAD_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - This register is for programmers to use as a temporary storage space. It has no defined purpose in the UART Ctrl."] + #[inline(always)] + pub fn uart_scratch_pad(&mut self) -> UART_SCRATCH_PAD_W { + UART_SCRATCH_PAD_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Scratchpad Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_scr_reg](index.html) module"] +pub struct UART2_SCR_REG_SPEC; +impl crate::RegisterSpec for UART2_SCR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_scr_reg::R](R) reader structure"] +impl crate::Readable for UART2_SCR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_scr_reg::W](W) writer structure"] +impl crate::Writable for UART2_SCR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SCR_REG to value 0"] +impl crate::Resettable for UART2_SCR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_sdmam_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_sdmam_reg.rs new file mode 100644 index 0000000..edc57fe --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_sdmam_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `UART2_SDMAM_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SDMAM_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_DMA_MODE` reader - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_SHADOW_DMA_MODE_R(crate::FieldReader); +impl UART_SHADOW_DMA_MODE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_SHADOW_DMA_MODE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_DMA_MODE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_DMA_MODE` writer - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] +pub struct UART_SHADOW_DMA_MODE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_DMA_MODE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_shadow_dma_mode(&self) -> UART_SHADOW_DMA_MODE_R { + UART_SHADOW_DMA_MODE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Shadow DMA Mode. This is a shadow register for the DMA mode bit (FCR\\[3\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the DMA Mode bit gets updated. This determines the DMA signalling mode used for the dma_tx_req_n and dma_rx_req_n output signals. 0 = mode 0 1 = mode 1"] + #[inline(always)] + pub fn uart_shadow_dma_mode(&mut self) -> UART_SHADOW_DMA_MODE_W { + UART_SHADOW_DMA_MODE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow DMA Mode\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_sdmam_reg](index.html) module"] +pub struct UART2_SDMAM_REG_SPEC; +impl crate::RegisterSpec for UART2_SDMAM_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_sdmam_reg::R](R) reader structure"] +impl crate::Readable for UART2_SDMAM_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_sdmam_reg::W](W) writer structure"] +impl crate::Writable for UART2_SDMAM_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SDMAM_REG to value 0"] +impl crate::Resettable for UART2_SDMAM_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_sfe_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_sfe_reg.rs new file mode 100644 index 0000000..997f917 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_sfe_reg.rs @@ -0,0 +1,113 @@ +#[doc = "Register `UART2_SFE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SFE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_FIFO_ENABLE` reader - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] +pub struct UART_SHADOW_FIFO_ENABLE_R(crate::FieldReader); +impl UART_SHADOW_FIFO_ENABLE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_SHADOW_FIFO_ENABLE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_FIFO_ENABLE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_FIFO_ENABLE` writer - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] +pub struct UART_SHADOW_FIFO_ENABLE_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_FIFO_ENABLE_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 0 - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] + #[inline(always)] + pub fn uart_shadow_fifo_enable(&self) -> UART_SHADOW_FIFO_ENABLE_R { + UART_SHADOW_FIFO_ENABLE_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 0 - Shadow FIFO Enable. This is a shadow register for the FIFO enable bit (FCR\\[0\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the FIFO enable bit gets updated.This enables/disables the transmit (XMIT) and receive (RCVR) FIFOs. If this bit is set to zero (disabled) after being enabled then both the XMIT and RCVR controller portion of FIFOs are reset."] + #[inline(always)] + pub fn uart_shadow_fifo_enable(&mut self) -> UART_SHADOW_FIFO_ENABLE_W { + UART_SHADOW_FIFO_ENABLE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow FIFO Enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_sfe_reg](index.html) module"] +pub struct UART2_SFE_REG_SPEC; +impl crate::RegisterSpec for UART2_SFE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_sfe_reg::R](R) reader structure"] +impl crate::Readable for UART2_SFE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_sfe_reg::W](W) writer structure"] +impl crate::Writable for UART2_SFE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SFE_REG to value 0"] +impl crate::Resettable for UART2_SFE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr0_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr0_reg.rs new file mode 100644 index 0000000..71c5e8b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr0_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR0_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR0_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr0_reg](index.html) module"] +pub struct UART2_SRBR_STHR0_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR0_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr0_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR0_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr0_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR0_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR0_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR0_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr10_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr10_reg.rs new file mode 100644 index 0000000..20958d7 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr10_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR10_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR10_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr10_reg](index.html) module"] +pub struct UART2_SRBR_STHR10_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR10_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr10_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR10_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr10_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR10_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR10_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR10_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr11_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr11_reg.rs new file mode 100644 index 0000000..28c37f1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr11_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR11_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR11_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr11_reg](index.html) module"] +pub struct UART2_SRBR_STHR11_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR11_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr11_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR11_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr11_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR11_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR11_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR11_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr12_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr12_reg.rs new file mode 100644 index 0000000..135b231 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr12_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR12_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR12_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr12_reg](index.html) module"] +pub struct UART2_SRBR_STHR12_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR12_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr12_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR12_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr12_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR12_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR12_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR12_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr13_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr13_reg.rs new file mode 100644 index 0000000..ec240ff --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr13_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR13_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR13_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr13_reg](index.html) module"] +pub struct UART2_SRBR_STHR13_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR13_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr13_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR13_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr13_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR13_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR13_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR13_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr14_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr14_reg.rs new file mode 100644 index 0000000..689ffeb --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr14_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR14_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR14_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr14_reg](index.html) module"] +pub struct UART2_SRBR_STHR14_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR14_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr14_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR14_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr14_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR14_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR14_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR14_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr15_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr15_reg.rs new file mode 100644 index 0000000..a25b8a3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr15_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR15_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR15_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr15_reg](index.html) module"] +pub struct UART2_SRBR_STHR15_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR15_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr15_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR15_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr15_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR15_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR15_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR15_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr1_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr1_reg.rs new file mode 100644 index 0000000..09640ac --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr1_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR1_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR1_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr1_reg](index.html) module"] +pub struct UART2_SRBR_STHR1_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR1_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr1_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR1_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr1_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR1_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR1_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR1_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr2_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr2_reg.rs new file mode 100644 index 0000000..6af188c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr2_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR2_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR2_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr2_reg](index.html) module"] +pub struct UART2_SRBR_STHR2_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR2_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr2_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR2_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr2_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR2_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR2_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR2_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr3_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr3_reg.rs new file mode 100644 index 0000000..8b77dd8 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr3_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR3_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR3_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr3_reg](index.html) module"] +pub struct UART2_SRBR_STHR3_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR3_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr3_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR3_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr3_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR3_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR3_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR3_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr4_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr4_reg.rs new file mode 100644 index 0000000..dee2dad --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr4_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR4_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR4_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr4_reg](index.html) module"] +pub struct UART2_SRBR_STHR4_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR4_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr4_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR4_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr4_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR4_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR4_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR4_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr5_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr5_reg.rs new file mode 100644 index 0000000..d4e8c56 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr5_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR5_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR5_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr5_reg](index.html) module"] +pub struct UART2_SRBR_STHR5_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR5_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr5_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR5_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr5_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR5_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR5_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR5_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr6_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr6_reg.rs new file mode 100644 index 0000000..e55bb78 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr6_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR6_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR6_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr6_reg](index.html) module"] +pub struct UART2_SRBR_STHR6_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR6_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr6_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR6_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr6_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR6_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR6_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR6_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr7_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr7_reg.rs new file mode 100644 index 0000000..33f6277 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr7_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR7_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR7_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr7_reg](index.html) module"] +pub struct UART2_SRBR_STHR7_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR7_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr7_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR7_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr7_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR7_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR7_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR7_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr8_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr8_reg.rs new file mode 100644 index 0000000..90e31a4 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr8_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR8_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR8_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr8_reg](index.html) module"] +pub struct UART2_SRBR_STHR8_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR8_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr8_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR8_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr8_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR8_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR8_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR8_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr9_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr9_reg.rs new file mode 100644 index 0000000..69a71aa --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srbr_sthr9_reg.rs @@ -0,0 +1,119 @@ +#[doc = "Register `UART2_SRBR_STHR9_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRBR_STHR9_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `SRBR_STHRx` reader - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_R(crate::FieldReader); +impl SRBR_STHRX_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + SRBR_STHRX_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for SRBR_STHRX_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `SRBR_STHRx` writer - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] +pub struct SRBR_STHRX_W<'a> { + w: &'a mut W, +} +impl<'a> SRBR_STHRX_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&self) -> SRBR_STHRX_R { + SRBR_STHRX_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Shadow Receive Buffer Register x: This is a shadow register for the RBR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains the data byte received on the serial input port (sin) in UART mode or the serial infrared input (sir_in) in infrared mode. The data in this register is valid only if the Data Ready (DR) bit in the Line status Register (LSR) is set. If FIFOs are disabled (FCR\\[0\\] +set to zero), the data in the RBR must be read before the next data arrives, otherwise it will be overwritten, resulting in an overrun error. If FIFOs are enabled (FCR\\[0\\] +set to one), this register accesses the head of the receive FIFO. If the receive FIFO is full and this register is not read before the next data character arrives, then the data already in the FIFO will be preserved but any incoming data will be lost. An overrun error will also occur. Shadow Transmit Holding Register 0: This is a shadow register for the THR and has been allocated sixteen 32-bit locations so as to accommodate burst accesses from the master. This register contains data to be transmitted on the serial output port (sout) in UART mode or the serial infrared output (sir_out_n) in infrared mode. Data should only be written to the THR when the THR Empty (THRE) bit (LSR\\[5\\]) is set. If FIFO's are disabled (FCR\\[0\\] +set to zero) and THRE is set, writing a single character to the THR clears the THRE. Any additional writes to the THR before the THRE is set again causes the THR data to be overwritten. If FIFO's are enabled (FCR\\[0\\] +set to one) and THRE is set, x number of characters of data may be written to the THR before the FIFO is full. The number x (default=16) is determined by the value of FIFO Depth that you set during configuration. Any attempt to write data when the FIFO is full results in the write data being lost."] + #[inline(always)] + pub fn srbr_sthrx(&mut self) -> SRBR_STHRX_W { + SRBR_STHRX_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow Receive/Transmit Buffer Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srbr_sthr9_reg](index.html) module"] +pub struct UART2_SRBR_STHR9_REG_SPEC; +impl crate::RegisterSpec for UART2_SRBR_STHR9_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srbr_sthr9_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRBR_STHR9_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srbr_sthr9_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRBR_STHR9_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRBR_STHR9_REG to value 0"] +impl crate::Resettable for UART2_SRBR_STHR9_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srr_reg.rs new file mode 100644 index 0000000..2d5d6ee --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srr_reg.rs @@ -0,0 +1,145 @@ +#[doc = "Register `UART2_SRR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_XFR` writer - XMIT FIFO Reset. This is a shadow register for the XMIT FIFO Reset bit (FCR\\[2\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the transmit FIFO. This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] +pub struct UART_XFR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_XFR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `UART_RFR` writer - RCVR FIFO Reset. This is a shadow register for the RCVR FIFO Reset bit (FCR\\[1\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the receive FIFO This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] +pub struct UART_RFR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_RFR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `UART_UR` writer - UART Reset. This asynchronously resets the UART Ctrl and synchronously removes the reset assertion. For a two clock implementation both pclk and sclk domains are reset."] +pub struct UART_UR_W<'a> { + w: &'a mut W, +} +impl<'a> UART_UR_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl W { + #[doc = "Bit 2 - XMIT FIFO Reset. This is a shadow register for the XMIT FIFO Reset bit (FCR\\[2\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the transmit FIFO. This resets the control portion of the transmit FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_xfr(&mut self) -> UART_XFR_W { + UART_XFR_W { w: self } + } + #[doc = "Bit 1 - RCVR FIFO Reset. This is a shadow register for the RCVR FIFO Reset bit (FCR\\[1\\]). This can be used to remove the burden on software having to store previously written FCR values (which are pretty static) just to reset the receive FIFO This resets the control portion of the receive FIFO and treats the FIFO as empty. Note that this bit is 'self-clearing'. It is not necessary to clear this bit."] + #[inline(always)] + pub fn uart_rfr(&mut self) -> UART_RFR_W { + UART_RFR_W { w: self } + } + #[doc = "Bit 0 - UART Reset. This asynchronously resets the UART Ctrl and synchronously removes the reset assertion. For a two clock implementation both pclk and sclk domains are reset."] + #[inline(always)] + pub fn uart_ur(&mut self) -> UART_UR_W { + UART_UR_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Software Reset Register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srr_reg](index.html) module"] +pub struct UART2_SRR_REG_SPEC; +impl crate::RegisterSpec for UART2_SRR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srr_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srr_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRR_REG to value 0"] +impl crate::Resettable for UART2_SRR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_srt_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srt_reg.rs new file mode 100644 index 0000000..9df4725 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_srt_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART2_SRT_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_SRT_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_RCVR_TRIGGER` reader - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] +pub struct UART_SHADOW_RCVR_TRIGGER_R(crate::FieldReader); +impl UART_SHADOW_RCVR_TRIGGER_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_SHADOW_RCVR_TRIGGER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_RCVR_TRIGGER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_RCVR_TRIGGER` writer - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] +pub struct UART_SHADOW_RCVR_TRIGGER_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_RCVR_TRIGGER_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bits 0:1 - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_shadow_rcvr_trigger(&self) -> UART_SHADOW_RCVR_TRIGGER_R { + UART_SHADOW_RCVR_TRIGGER_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 0:1 - Shadow RCVR Trigger. This is a shadow register for the RCVR trigger bits (FCR\\[7:6\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the RCVR trigger bit gets updated. This is used to select the trigger level in the receiver FIFO at which the Received Data Available Interrupt is generated. It also determines when the dma_rx_req_n signal is asserted when DMA Mode (FCR\\[3\\]) = 1. The following trigger levels are supported: 00 = 1 character in the FIFO 01 = FIFO ¼ full 10 = FIFO ½ full 11 = FIFO 2 less than full"] + #[inline(always)] + pub fn uart_shadow_rcvr_trigger(&mut self) -> UART_SHADOW_RCVR_TRIGGER_W { + UART_SHADOW_RCVR_TRIGGER_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow RCVR Trigger\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_srt_reg](index.html) module"] +pub struct UART2_SRT_REG_SPEC; +impl crate::RegisterSpec for UART2_SRT_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_srt_reg::R](R) reader structure"] +impl crate::Readable for UART2_SRT_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_srt_reg::W](W) writer structure"] +impl crate::Writable for UART2_SRT_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_SRT_REG to value 0"] +impl crate::Resettable for UART2_SRT_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_stet_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_stet_reg.rs new file mode 100644 index 0000000..2484e99 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_stet_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `UART2_STET_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_STET_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_SHADOW_TX_EMPTY_TRIGGER` reader - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] +pub struct UART_SHADOW_TX_EMPTY_TRIGGER_R(crate::FieldReader); +impl UART_SHADOW_TX_EMPTY_TRIGGER_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_SHADOW_TX_EMPTY_TRIGGER_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_SHADOW_TX_EMPTY_TRIGGER_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_SHADOW_TX_EMPTY_TRIGGER` writer - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] +pub struct UART_SHADOW_TX_EMPTY_TRIGGER_W<'a> { + w: &'a mut W, +} +impl<'a> UART_SHADOW_TX_EMPTY_TRIGGER_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !3) | (value as u16 & 3); + self.w + } +} +impl R { + #[doc = "Bits 0:1 - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] + #[inline(always)] + pub fn uart_shadow_tx_empty_trigger(&self) -> UART_SHADOW_TX_EMPTY_TRIGGER_R { + UART_SHADOW_TX_EMPTY_TRIGGER_R::new((self.bits & 3) as u8) + } +} +impl W { + #[doc = "Bits 0:1 - Shadow TX Empty Trigger. This is a shadow register for the TX empty trigger bits (FCR\\[5:4\\]). This can be used to remove the burden of having to store the previously written value to the FCR in memory and having to mask this value so that only the TX empty trigger bit gets updated. This is used to select the empty threshold level at which the THRE Interrupts are generated when the mode is active. The following trigger levels are supported: 00 = FIFO empty 01 = 2 characters in the FIFO 10 = FIFO ¼ full 11 = FIFO ½ full"] + #[inline(always)] + pub fn uart_shadow_tx_empty_trigger(&mut self) -> UART_SHADOW_TX_EMPTY_TRIGGER_W { + UART_SHADOW_TX_EMPTY_TRIGGER_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Shadow TX Empty Trigger\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_stet_reg](index.html) module"] +pub struct UART2_STET_REG_SPEC; +impl crate::RegisterSpec for UART2_STET_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_stet_reg::R](R) reader structure"] +impl crate::Readable for UART2_STET_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_stet_reg::W](W) writer structure"] +impl crate::Writable for UART2_STET_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_STET_REG to value 0"] +impl crate::Resettable for UART2_STET_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_tfl_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_tfl_reg.rs new file mode 100644 index 0000000..c0bd310 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_tfl_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART2_TFL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_TFL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_TRANSMIT_FIFO_LEVEL` reader - Transmit FIFO Level. This is indicates the number of data entries in the transmit FIFO."] +pub struct UART_TRANSMIT_FIFO_LEVEL_R(crate::FieldReader); +impl UART_TRANSMIT_FIFO_LEVEL_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + UART_TRANSMIT_FIFO_LEVEL_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TRANSMIT_FIFO_LEVEL_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:4 - Transmit FIFO Level. This is indicates the number of data entries in the transmit FIFO."] + #[inline(always)] + pub fn uart_transmit_fifo_level(&self) -> UART_TRANSMIT_FIFO_LEVEL_R { + UART_TRANSMIT_FIFO_LEVEL_R::new((self.bits & 0x1f) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Transmit FIFO Level\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_tfl_reg](index.html) module"] +pub struct UART2_TFL_REG_SPEC; +impl crate::RegisterSpec for UART2_TFL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_tfl_reg::R](R) reader structure"] +impl crate::Readable for UART2_TFL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_tfl_reg::W](W) writer structure"] +impl crate::Writable for UART2_TFL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_TFL_REG to value 0"] +impl crate::Resettable for UART2_TFL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_high_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_high_reg.rs new file mode 100644 index 0000000..d54ce68 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_high_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART2_UCV_HIGH_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_UCV_HIGH_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UCV` reader - Component Version"] +pub struct UCV_R(crate::FieldReader); +impl UCV_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + UCV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UCV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Version"] + #[inline(always)] + pub fn ucv(&self) -> UCV_R { + UCV_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Version\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_ucv_high_reg](index.html) module"] +pub struct UART2_UCV_HIGH_REG_SPEC; +impl crate::RegisterSpec for UART2_UCV_HIGH_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_ucv_high_reg::R](R) reader structure"] +impl crate::Readable for UART2_UCV_HIGH_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_ucv_high_reg::W](W) writer structure"] +impl crate::Writable for UART2_UCV_HIGH_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_UCV_HIGH_REG to value 0x3331"] +impl crate::Resettable for UART2_UCV_HIGH_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x3331 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_reg.rs new file mode 100644 index 0000000..4cd9480 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_ucv_reg.rs @@ -0,0 +1,86 @@ +#[doc = "Register `UART2_UCV_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_UCV_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UCV` reader - Component Version"] +pub struct UCV_R(crate::FieldReader); +impl UCV_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + UCV_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UCV_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 0:15 - Component Version"] + #[inline(always)] + pub fn ucv(&self) -> UCV_R { + UCV_R::new(self.bits) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Component Version\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_ucv_reg](index.html) module"] +pub struct UART2_UCV_REG_SPEC; +impl crate::RegisterSpec for UART2_UCV_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_ucv_reg::R](R) reader structure"] +impl crate::Readable for UART2_UCV_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_ucv_reg::W](W) writer structure"] +impl crate::Writable for UART2_UCV_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_UCV_REG to value 0x352a"] +impl crate::Resettable for UART2_UCV_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x352a + } +} diff --git a/bitbox02-bt/vendor/da14531/src/uart2/uart2_usr_reg.rs b/bitbox02-bt/vendor/da14531/src/uart2/uart2_usr_reg.rs new file mode 100644 index 0000000..83ccf90 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/uart2/uart2_usr_reg.rs @@ -0,0 +1,166 @@ +#[doc = "Register `UART2_USR_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `UART2_USR_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `UART_RFF` reader - Receive FIFO Full. This is used to indicate that the receive FIFO is completely full. 0 = Receive FIFO not full 1 = Receive FIFO Full This bit is cleared when the RX FIFO is no longer full."] +pub struct UART_RFF_R(crate::FieldReader); +impl UART_RFF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_RFF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RFF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_RFNE` reader - Receive FIFO Not Empty. This is used to indicate that the receive FIFO contains one or more entries. 0 = Receive FIFO is empty 1 = Receive FIFO is not empty This bit is cleared when the RX FIFO is empty."] +pub struct UART_RFNE_R(crate::FieldReader); +impl UART_RFNE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_RFNE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_RFNE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_TFE` reader - Transmit FIFO Empty. This is used to indicate that the transmit FIFO is completely empty. 0 = Transmit FIFO is not empty 1 = Transmit FIFO is empty This bit is cleared when the TX FIFO is no longer empty."] +pub struct UART_TFE_R(crate::FieldReader); +impl UART_TFE_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_TFE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TFE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_TFNF` reader - Transmit FIFO Not Full. This is used to indicate that the transmit FIFO in not full. 0 = Transmit FIFO is full 1 = Transmit FIFO is not full This bit is cleared when the TX FIFO is full."] +pub struct UART_TFNF_R(crate::FieldReader); +impl UART_TFNF_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_TFNF_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_TFNF_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `UART_BUSY` reader - UART Busy. This indicates that a serial transfer is in progress, when cleared indicates that the DW_apb_uart is idle or inactive. 0 - DW_apb_uart is idle or inactive 1 - DW_apb_uart is busy (actively transferring data) Note that it is possible for the UART Busy bit to be cleared even though a new character may have been sent from another device. That is, if the DW_apb_uart has no data in the THR and RBR and there is no transmission in progress and a start bit of a new character has just reached the DW_apb_uart. This is due to the fact that a valid start is not seen until the middle of the bit period and this duration is dependent on the baud divisor that has been programmed. If a second system clock has been implemented (CLOCK_MODE == Enabled) the assertion of this bit will also be delayed by several cycles of the slower clock."] +pub struct UART_BUSY_R(crate::FieldReader); +impl UART_BUSY_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + UART_BUSY_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for UART_BUSY_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bit 4 - Receive FIFO Full. This is used to indicate that the receive FIFO is completely full. 0 = Receive FIFO not full 1 = Receive FIFO Full This bit is cleared when the RX FIFO is no longer full."] + #[inline(always)] + pub fn uart_rff(&self) -> UART_RFF_R { + UART_RFF_R::new(((self.bits >> 4) & 1) != 0) + } + #[doc = "Bit 3 - Receive FIFO Not Empty. This is used to indicate that the receive FIFO contains one or more entries. 0 = Receive FIFO is empty 1 = Receive FIFO is not empty This bit is cleared when the RX FIFO is empty."] + #[inline(always)] + pub fn uart_rfne(&self) -> UART_RFNE_R { + UART_RFNE_R::new(((self.bits >> 3) & 1) != 0) + } + #[doc = "Bit 2 - Transmit FIFO Empty. This is used to indicate that the transmit FIFO is completely empty. 0 = Transmit FIFO is not empty 1 = Transmit FIFO is empty This bit is cleared when the TX FIFO is no longer empty."] + #[inline(always)] + pub fn uart_tfe(&self) -> UART_TFE_R { + UART_TFE_R::new(((self.bits >> 2) & 1) != 0) + } + #[doc = "Bit 1 - Transmit FIFO Not Full. This is used to indicate that the transmit FIFO in not full. 0 = Transmit FIFO is full 1 = Transmit FIFO is not full This bit is cleared when the TX FIFO is full."] + #[inline(always)] + pub fn uart_tfnf(&self) -> UART_TFNF_R { + UART_TFNF_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - UART Busy. This indicates that a serial transfer is in progress, when cleared indicates that the DW_apb_uart is idle or inactive. 0 - DW_apb_uart is idle or inactive 1 - DW_apb_uart is busy (actively transferring data) Note that it is possible for the UART Busy bit to be cleared even though a new character may have been sent from another device. That is, if the DW_apb_uart has no data in the THR and RBR and there is no transmission in progress and a start bit of a new character has just reached the DW_apb_uart. This is due to the fact that a valid start is not seen until the middle of the bit period and this duration is dependent on the baud divisor that has been programmed. If a second system clock has been implemented (CLOCK_MODE == Enabled) the assertion of this bit will also be delayed by several cycles of the slower clock."] + #[inline(always)] + pub fn uart_busy(&self) -> UART_BUSY_R { + UART_BUSY_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "UART Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [uart2_usr_reg](index.html) module"] +pub struct UART2_USR_REG_SPEC; +impl crate::RegisterSpec for UART2_USR_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [uart2_usr_reg::R](R) reader structure"] +impl crate::Readable for UART2_USR_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [uart2_usr_reg::W](W) writer structure"] +impl crate::Writable for UART2_USR_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets UART2_USR_REG to value 0x06"] +impl crate::Resettable for UART2_USR_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0x06 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup.rs b/bitbox02-bt/vendor/da14531/src/wkup.rs new file mode 100644 index 0000000..c30eafd --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup.rs @@ -0,0 +1,52 @@ +#[doc = r"Register block"] +#[repr(C)] +pub struct RegisterBlock { + #[doc = "0x00 - Control register for the wakeup counter"] + pub wkup_ctrl_reg: crate::Reg, + #[doc = "0x02 - Number of events before wakeup interrupt"] + pub wkup_compare_reg: crate::Reg, + #[doc = "0x04 - Reset wakeup interrupt"] + pub wkup_irq_status_reg: crate::Reg, + #[doc = "0x06 - Actual number of events of the wakeup counter"] + pub wkup_counter_reg: crate::Reg, + #[doc = "0x08 - Select which inputs from P0 port can trigger wkup counter"] + pub wkup_select_gpio_reg: crate::Reg, + #[doc = "0x0a - Select which inputs from P1 port can trigger wkup counter"] + pub wkup2_select_gpio_reg: crate::Reg, + #[doc = "0x0c - Select the sensitivity polarity for each P0 input"] + pub wkup_pol_gpio_reg: crate::Reg, + #[doc = "0x0e - Select the sensitivity polarity for each P1 input"] + pub wkup2_pol_gpio_reg: crate::Reg, +} +#[doc = "WKUP2_POL_GPIO_REG register accessor: an alias for `Reg`"] +pub type WKUP2_POL_GPIO_REG = crate::Reg; +#[doc = "Select the sensitivity polarity for each P1 input"] +pub mod wkup2_pol_gpio_reg; +#[doc = "WKUP2_SELECT_GPIO_REG register accessor: an alias for `Reg`"] +pub type WKUP2_SELECT_GPIO_REG = crate::Reg; +#[doc = "Select which inputs from P1 port can trigger wkup counter"] +pub mod wkup2_select_gpio_reg; +#[doc = "WKUP_COMPARE_REG register accessor: an alias for `Reg`"] +pub type WKUP_COMPARE_REG = crate::Reg; +#[doc = "Number of events before wakeup interrupt"] +pub mod wkup_compare_reg; +#[doc = "WKUP_COUNTER_REG register accessor: an alias for `Reg`"] +pub type WKUP_COUNTER_REG = crate::Reg; +#[doc = "Actual number of events of the wakeup counter"] +pub mod wkup_counter_reg; +#[doc = "WKUP_CTRL_REG register accessor: an alias for `Reg`"] +pub type WKUP_CTRL_REG = crate::Reg; +#[doc = "Control register for the wakeup counter"] +pub mod wkup_ctrl_reg; +#[doc = "WKUP_IRQ_STATUS_REG register accessor: an alias for `Reg`"] +pub type WKUP_IRQ_STATUS_REG = crate::Reg; +#[doc = "Reset wakeup interrupt"] +pub mod wkup_irq_status_reg; +#[doc = "WKUP_POL_GPIO_REG register accessor: an alias for `Reg`"] +pub type WKUP_POL_GPIO_REG = crate::Reg; +#[doc = "Select the sensitivity polarity for each P0 input"] +pub mod wkup_pol_gpio_reg; +#[doc = "WKUP_SELECT_GPIO_REG register accessor: an alias for `Reg`"] +pub type WKUP_SELECT_GPIO_REG = crate::Reg; +#[doc = "Select which inputs from P0 port can trigger wkup counter"] +pub mod wkup_select_gpio_reg; diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup2_pol_gpio_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup2_pol_gpio_reg.rs new file mode 100644 index 0000000..2434ff3 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup2_pol_gpio_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `WKUP2_POL_GPIO_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP2_POL_GPIO_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WKUP2_POL_GPIO` reader - 0 = the enabled input P0x increments the event2 counter if that input goes high 1 = the enabled input P0x increments the event2 counter if that input goes low"] +pub struct WKUP2_POL_GPIO_R(crate::FieldReader); +impl WKUP2_POL_GPIO_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + WKUP2_POL_GPIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP2_POL_GPIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP2_POL_GPIO` writer - 0 = the enabled input P0x increments the event2 counter if that input goes high 1 = the enabled input P0x increments the event2 counter if that input goes low"] +pub struct WKUP2_POL_GPIO_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP2_POL_GPIO_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl R { + #[doc = "Bits 0:11 - 0 = the enabled input P0x increments the event2 counter if that input goes high 1 = the enabled input P0x increments the event2 counter if that input goes low"] + #[inline(always)] + pub fn wkup2_pol_gpio(&self) -> WKUP2_POL_GPIO_R { + WKUP2_POL_GPIO_R::new((self.bits & 0x0fff) as u16) + } +} +impl W { + #[doc = "Bits 0:11 - 0 = the enabled input P0x increments the event2 counter if that input goes high 1 = the enabled input P0x increments the event2 counter if that input goes low"] + #[inline(always)] + pub fn wkup2_pol_gpio(&mut self) -> WKUP2_POL_GPIO_W { + WKUP2_POL_GPIO_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Select the sensitivity polarity for each P1 input\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup2_pol_gpio_reg](index.html) module"] +pub struct WKUP2_POL_GPIO_REG_SPEC; +impl crate::RegisterSpec for WKUP2_POL_GPIO_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup2_pol_gpio_reg::R](R) reader structure"] +impl crate::Readable for WKUP2_POL_GPIO_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup2_pol_gpio_reg::W](W) writer structure"] +impl crate::Writable for WKUP2_POL_GPIO_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP2_POL_GPIO_REG to value 0"] +impl crate::Resettable for WKUP2_POL_GPIO_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup2_select_gpio_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup2_select_gpio_reg.rs new file mode 100644 index 0000000..c2c9d3a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup2_select_gpio_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `WKUP2_SELECT_GPIO_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP2_SELECT_GPIO_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WKUP2_SELECT_GPIO` reader - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] +pub struct WKUP2_SELECT_GPIO_R(crate::FieldReader); +impl WKUP2_SELECT_GPIO_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + WKUP2_SELECT_GPIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP2_SELECT_GPIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP2_SELECT_GPIO` writer - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] +pub struct WKUP2_SELECT_GPIO_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP2_SELECT_GPIO_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl R { + #[doc = "Bits 0:11 - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] + #[inline(always)] + pub fn wkup2_select_gpio(&self) -> WKUP2_SELECT_GPIO_R { + WKUP2_SELECT_GPIO_R::new((self.bits & 0x0fff) as u16) + } +} +impl W { + #[doc = "Bits 0:11 - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] + #[inline(always)] + pub fn wkup2_select_gpio(&mut self) -> WKUP2_SELECT_GPIO_W { + WKUP2_SELECT_GPIO_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Select which inputs from P1 port can trigger wkup counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup2_select_gpio_reg](index.html) module"] +pub struct WKUP2_SELECT_GPIO_REG_SPEC; +impl crate::RegisterSpec for WKUP2_SELECT_GPIO_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup2_select_gpio_reg::R](R) reader structure"] +impl crate::Readable for WKUP2_SELECT_GPIO_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup2_select_gpio_reg::W](W) writer structure"] +impl crate::Writable for WKUP2_SELECT_GPIO_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP2_SELECT_GPIO_REG to value 0"] +impl crate::Resettable for WKUP2_SELECT_GPIO_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup_compare_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup_compare_reg.rs new file mode 100644 index 0000000..e57d0b1 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup_compare_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `WKUP_COMPARE_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP_COMPARE_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WKUP_COMPARE` reader - Defines the number of events -1 that have to be counted before the wakeup interrupt will be given. value 0 means one event."] +pub struct WKUP_COMPARE_R(crate::FieldReader); +impl WKUP_COMPARE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WKUP_COMPARE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP_COMPARE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP_COMPARE` writer - Defines the number of events -1 that have to be counted before the wakeup interrupt will be given. value 0 means one event."] +pub struct WKUP_COMPARE_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_COMPARE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff); + self.w + } +} +impl R { + #[doc = "Bits 0:7 - Defines the number of events -1 that have to be counted before the wakeup interrupt will be given. value 0 means one event."] + #[inline(always)] + pub fn wkup_compare(&self) -> WKUP_COMPARE_R { + WKUP_COMPARE_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Bits 0:7 - Defines the number of events -1 that have to be counted before the wakeup interrupt will be given. value 0 means one event."] + #[inline(always)] + pub fn wkup_compare(&mut self) -> WKUP_COMPARE_W { + WKUP_COMPARE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Number of events before wakeup interrupt\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup_compare_reg](index.html) module"] +pub struct WKUP_COMPARE_REG_SPEC; +impl crate::RegisterSpec for WKUP_COMPARE_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup_compare_reg::R](R) reader structure"] +impl crate::Readable for WKUP_COMPARE_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup_compare_reg::W](W) writer structure"] +impl crate::Writable for WKUP_COMPARE_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP_COMPARE_REG to value 0"] +impl crate::Resettable for WKUP_COMPARE_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup_counter_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup_counter_reg.rs new file mode 100644 index 0000000..91893c9 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup_counter_reg.rs @@ -0,0 +1,106 @@ +#[doc = "Register `WKUP_COUNTER_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP_COUNTER_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `EVENT2_VALUE` reader - This value represents the number of events that have been counted so far. It will be reset by resetting the interrupt."] +pub struct EVENT2_VALUE_R(crate::FieldReader); +impl EVENT2_VALUE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + EVENT2_VALUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENT2_VALUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `EVENT_VALUE` reader - This value represents the number of events that have been counted so far. It will be reset by resetting the interrupt."] +pub struct EVENT_VALUE_R(crate::FieldReader); +impl EVENT_VALUE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + EVENT_VALUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for EVENT_VALUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl R { + #[doc = "Bits 8:15 - This value represents the number of events that have been counted so far. It will be reset by resetting the interrupt."] + #[inline(always)] + pub fn event2_value(&self) -> EVENT2_VALUE_R { + EVENT2_VALUE_R::new(((self.bits >> 8) & 0xff) as u8) + } + #[doc = "Bits 0:7 - This value represents the number of events that have been counted so far. It will be reset by resetting the interrupt."] + #[inline(always)] + pub fn event_value(&self) -> EVENT_VALUE_R { + EVENT_VALUE_R::new((self.bits & 0xff) as u8) + } +} +impl W { + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Actual number of events of the wakeup counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup_counter_reg](index.html) module"] +pub struct WKUP_COUNTER_REG_SPEC; +impl crate::RegisterSpec for WKUP_COUNTER_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup_counter_reg::R](R) reader structure"] +impl crate::Readable for WKUP_COUNTER_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup_counter_reg::W](W) writer structure"] +impl crate::Writable for WKUP_COUNTER_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP_COUNTER_REG to value 0"] +impl crate::Resettable for WKUP_COUNTER_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup_ctrl_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup_ctrl_reg.rs new file mode 100644 index 0000000..3a5ab7c --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup_ctrl_reg.rs @@ -0,0 +1,244 @@ +#[doc = "Register `WKUP_CTRL_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP_CTRL_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WKUP2_ENABLE_IRQ` reader - 0 = no interrupt will be generated 1 = if the event counter2 reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] +pub struct WKUP2_ENABLE_IRQ_R(crate::FieldReader); +impl WKUP2_ENABLE_IRQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WKUP2_ENABLE_IRQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP2_ENABLE_IRQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP2_ENABLE_IRQ` writer - 0 = no interrupt will be generated 1 = if the event counter2 reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] +pub struct WKUP2_ENABLE_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP2_ENABLE_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 8)) | ((value as u16 & 1) << 8); + self.w + } +} +#[doc = "Field `WKUP_ENABLE_IRQ` reader - 0 = no interrupt will be generated 1 = if the event counter reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] +pub struct WKUP_ENABLE_IRQ_R(crate::FieldReader); +impl WKUP_ENABLE_IRQ_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WKUP_ENABLE_IRQ_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP_ENABLE_IRQ_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP_ENABLE_IRQ` writer - 0 = no interrupt will be generated 1 = if the event counter reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] +pub struct WKUP_ENABLE_IRQ_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_ENABLE_IRQ_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 7)) | ((value as u16 & 1) << 7); + self.w + } +} +#[doc = "Field `WKUP_SFT_KEYHIT` reader - 0 = no effect 1 = emulate key hit. The event counter and counter2 will increment by 1 (after debouncing if enabled). First make this bit 0 before any new key hit can be sensed."] +pub struct WKUP_SFT_KEYHIT_R(crate::FieldReader); +impl WKUP_SFT_KEYHIT_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WKUP_SFT_KEYHIT_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP_SFT_KEYHIT_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP_SFT_KEYHIT` writer - 0 = no effect 1 = emulate key hit. The event counter and counter2 will increment by 1 (after debouncing if enabled). First make this bit 0 before any new key hit can be sensed."] +pub struct WKUP_SFT_KEYHIT_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_SFT_KEYHIT_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 6)) | ((value as u16 & 1) << 6); + self.w + } +} +#[doc = "Field `WKUP_DEB_VALUE` reader - Keyboard debounce time (N*1 ms with N = 1 to 63). 0x0: no debouncing 0x1 to 0x3F: 1 ms to 63 ms debounce time"] +pub struct WKUP_DEB_VALUE_R(crate::FieldReader); +impl WKUP_DEB_VALUE_R { + #[inline(always)] + pub(crate) fn new(bits: u8) -> Self { + WKUP_DEB_VALUE_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP_DEB_VALUE_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP_DEB_VALUE` writer - Keyboard debounce time (N*1 ms with N = 1 to 63). 0x0: no debouncing 0x1 to 0x3F: 1 ms to 63 ms debounce time"] +pub struct WKUP_DEB_VALUE_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_DEB_VALUE_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !0x3f) | (value as u16 & 0x3f); + self.w + } +} +impl R { + #[doc = "Bit 8 - 0 = no interrupt will be generated 1 = if the event counter2 reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] + #[inline(always)] + pub fn wkup2_enable_irq(&self) -> WKUP2_ENABLE_IRQ_R { + WKUP2_ENABLE_IRQ_R::new(((self.bits >> 8) & 1) != 0) + } + #[doc = "Bit 7 - 0 = no interrupt will be generated 1 = if the event counter reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] + #[inline(always)] + pub fn wkup_enable_irq(&self) -> WKUP_ENABLE_IRQ_R { + WKUP_ENABLE_IRQ_R::new(((self.bits >> 7) & 1) != 0) + } + #[doc = "Bit 6 - 0 = no effect 1 = emulate key hit. The event counter and counter2 will increment by 1 (after debouncing if enabled). First make this bit 0 before any new key hit can be sensed."] + #[inline(always)] + pub fn wkup_sft_keyhit(&self) -> WKUP_SFT_KEYHIT_R { + WKUP_SFT_KEYHIT_R::new(((self.bits >> 6) & 1) != 0) + } + #[doc = "Bits 0:5 - Keyboard debounce time (N*1 ms with N = 1 to 63). 0x0: no debouncing 0x1 to 0x3F: 1 ms to 63 ms debounce time"] + #[inline(always)] + pub fn wkup_deb_value(&self) -> WKUP_DEB_VALUE_R { + WKUP_DEB_VALUE_R::new((self.bits & 0x3f) as u8) + } +} +impl W { + #[doc = "Bit 8 - 0 = no interrupt will be generated 1 = if the event counter2 reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] + #[inline(always)] + pub fn wkup2_enable_irq(&mut self) -> WKUP2_ENABLE_IRQ_W { + WKUP2_ENABLE_IRQ_W { w: self } + } + #[doc = "Bit 7 - 0 = no interrupt will be generated 1 = if the event counter reaches the value set by WKUP_COMPARE_REG an IRQ will be generated"] + #[inline(always)] + pub fn wkup_enable_irq(&mut self) -> WKUP_ENABLE_IRQ_W { + WKUP_ENABLE_IRQ_W { w: self } + } + #[doc = "Bit 6 - 0 = no effect 1 = emulate key hit. The event counter and counter2 will increment by 1 (after debouncing if enabled). First make this bit 0 before any new key hit can be sensed."] + #[inline(always)] + pub fn wkup_sft_keyhit(&mut self) -> WKUP_SFT_KEYHIT_W { + WKUP_SFT_KEYHIT_W { w: self } + } + #[doc = "Bits 0:5 - Keyboard debounce time (N*1 ms with N = 1 to 63). 0x0: no debouncing 0x1 to 0x3F: 1 ms to 63 ms debounce time"] + #[inline(always)] + pub fn wkup_deb_value(&mut self) -> WKUP_DEB_VALUE_W { + WKUP_DEB_VALUE_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Control register for the wakeup counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup_ctrl_reg](index.html) module"] +pub struct WKUP_CTRL_REG_SPEC; +impl crate::RegisterSpec for WKUP_CTRL_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup_ctrl_reg::R](R) reader structure"] +impl crate::Readable for WKUP_CTRL_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup_ctrl_reg::W](W) writer structure"] +impl crate::Writable for WKUP_CTRL_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP_CTRL_REG to value 0"] +impl crate::Resettable for WKUP_CTRL_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup_irq_status_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup_irq_status_reg.rs new file mode 100644 index 0000000..d30178a --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup_irq_status_reg.rs @@ -0,0 +1,214 @@ +#[doc = "Register `WKUP_IRQ_STATUS_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP_IRQ_STATUS_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WKUP2_CNTR_RST` writer - writing 1 will reset the event2 counter"] +pub struct WKUP2_CNTR_RST_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP2_CNTR_RST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 3)) | ((value as u16 & 1) << 3); + self.w + } +} +#[doc = "Field `WKUP_CNTR_RST` writer - writing 1 will reset the event counter"] +pub struct WKUP_CNTR_RST_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_CNTR_RST_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 2)) | ((value as u16 & 1) << 2); + self.w + } +} +#[doc = "Field `WKUP2_IRQ_STATUS` reader - Gives 1 when there is a wkup2 pending IRQ. Writing 1 will reset the interrupt."] +pub struct WKUP2_IRQ_STATUS_R(crate::FieldReader); +impl WKUP2_IRQ_STATUS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WKUP2_IRQ_STATUS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP2_IRQ_STATUS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP2_IRQ_STATUS` writer - Gives 1 when there is a wkup2 pending IRQ. Writing 1 will reset the interrupt."] +pub struct WKUP2_IRQ_STATUS_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP2_IRQ_STATUS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !(1 << 1)) | ((value as u16 & 1) << 1); + self.w + } +} +#[doc = "Field `WKUP_IRQ_STATUS` reader - Gives 1 when there is a wkup pending IRQ. Writing 1 will reset the interrupt."] +pub struct WKUP_IRQ_STATUS_R(crate::FieldReader); +impl WKUP_IRQ_STATUS_R { + #[inline(always)] + pub(crate) fn new(bits: bool) -> Self { + WKUP_IRQ_STATUS_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP_IRQ_STATUS_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP_IRQ_STATUS` writer - Gives 1 when there is a wkup pending IRQ. Writing 1 will reset the interrupt."] +pub struct WKUP_IRQ_STATUS_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_IRQ_STATUS_W<'a> { + #[doc = r"Sets the field bit"] + #[inline(always)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits = (self.w.bits & !1) | (value as u16 & 1); + self.w + } +} +impl R { + #[doc = "Bit 1 - Gives 1 when there is a wkup2 pending IRQ. Writing 1 will reset the interrupt."] + #[inline(always)] + pub fn wkup2_irq_status(&self) -> WKUP2_IRQ_STATUS_R { + WKUP2_IRQ_STATUS_R::new(((self.bits >> 1) & 1) != 0) + } + #[doc = "Bit 0 - Gives 1 when there is a wkup pending IRQ. Writing 1 will reset the interrupt."] + #[inline(always)] + pub fn wkup_irq_status(&self) -> WKUP_IRQ_STATUS_R { + WKUP_IRQ_STATUS_R::new((self.bits & 1) != 0) + } +} +impl W { + #[doc = "Bit 3 - writing 1 will reset the event2 counter"] + #[inline(always)] + pub fn wkup2_cntr_rst(&mut self) -> WKUP2_CNTR_RST_W { + WKUP2_CNTR_RST_W { w: self } + } + #[doc = "Bit 2 - writing 1 will reset the event counter"] + #[inline(always)] + pub fn wkup_cntr_rst(&mut self) -> WKUP_CNTR_RST_W { + WKUP_CNTR_RST_W { w: self } + } + #[doc = "Bit 1 - Gives 1 when there is a wkup2 pending IRQ. Writing 1 will reset the interrupt."] + #[inline(always)] + pub fn wkup2_irq_status(&mut self) -> WKUP2_IRQ_STATUS_W { + WKUP2_IRQ_STATUS_W { w: self } + } + #[doc = "Bit 0 - Gives 1 when there is a wkup pending IRQ. Writing 1 will reset the interrupt."] + #[inline(always)] + pub fn wkup_irq_status(&mut self) -> WKUP_IRQ_STATUS_W { + WKUP_IRQ_STATUS_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Reset wakeup interrupt\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup_irq_status_reg](index.html) module"] +pub struct WKUP_IRQ_STATUS_REG_SPEC; +impl crate::RegisterSpec for WKUP_IRQ_STATUS_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup_irq_status_reg::R](R) reader structure"] +impl crate::Readable for WKUP_IRQ_STATUS_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup_irq_status_reg::W](W) writer structure"] +impl crate::Writable for WKUP_IRQ_STATUS_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP_IRQ_STATUS_REG to value 0"] +impl crate::Resettable for WKUP_IRQ_STATUS_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup_pol_gpio_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup_pol_gpio_reg.rs new file mode 100644 index 0000000..8942789 --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup_pol_gpio_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `WKUP_POL_GPIO_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP_POL_GPIO_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WKUP_POL_GPIO` reader - 0 = the enabled input P0x increments the event counter if that input goes high 1 = the enabled input P0x increments the event counter if that input goes low"] +pub struct WKUP_POL_GPIO_R(crate::FieldReader); +impl WKUP_POL_GPIO_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + WKUP_POL_GPIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP_POL_GPIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP_POL_GPIO` writer - 0 = the enabled input P0x increments the event counter if that input goes high 1 = the enabled input P0x increments the event counter if that input goes low"] +pub struct WKUP_POL_GPIO_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_POL_GPIO_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl R { + #[doc = "Bits 0:11 - 0 = the enabled input P0x increments the event counter if that input goes high 1 = the enabled input P0x increments the event counter if that input goes low"] + #[inline(always)] + pub fn wkup_pol_gpio(&self) -> WKUP_POL_GPIO_R { + WKUP_POL_GPIO_R::new((self.bits & 0x0fff) as u16) + } +} +impl W { + #[doc = "Bits 0:11 - 0 = the enabled input P0x increments the event counter if that input goes high 1 = the enabled input P0x increments the event counter if that input goes low"] + #[inline(always)] + pub fn wkup_pol_gpio(&mut self) -> WKUP_POL_GPIO_W { + WKUP_POL_GPIO_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Select the sensitivity polarity for each P0 input\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup_pol_gpio_reg](index.html) module"] +pub struct WKUP_POL_GPIO_REG_SPEC; +impl crate::RegisterSpec for WKUP_POL_GPIO_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup_pol_gpio_reg::R](R) reader structure"] +impl crate::Readable for WKUP_POL_GPIO_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup_pol_gpio_reg::W](W) writer structure"] +impl crate::Writable for WKUP_POL_GPIO_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP_POL_GPIO_REG to value 0"] +impl crate::Resettable for WKUP_POL_GPIO_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/src/wkup/wkup_select_gpio_reg.rs b/bitbox02-bt/vendor/da14531/src/wkup/wkup_select_gpio_reg.rs new file mode 100644 index 0000000..8ae8f8b --- /dev/null +++ b/bitbox02-bt/vendor/da14531/src/wkup/wkup_select_gpio_reg.rs @@ -0,0 +1,103 @@ +#[doc = "Register `WKUP_SELECT_GPIO_REG` reader"] +pub struct R(crate::R); +impl core::ops::Deref for R { + type Target = crate::R; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl From> for R { + #[inline(always)] + fn from(reader: crate::R) -> Self { + R(reader) + } +} +#[doc = "Register `WKUP_SELECT_GPIO_REG` writer"] +pub struct W(crate::W); +impl core::ops::Deref for W { + type Target = crate::W; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl core::ops::DerefMut for W { + #[inline(always)] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} +impl From> for W { + #[inline(always)] + fn from(writer: crate::W) -> Self { + W(writer) + } +} +#[doc = "Field `WKUP_SELECT_GPIO` reader - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] +pub struct WKUP_SELECT_GPIO_R(crate::FieldReader); +impl WKUP_SELECT_GPIO_R { + #[inline(always)] + pub(crate) fn new(bits: u16) -> Self { + WKUP_SELECT_GPIO_R(crate::FieldReader::new(bits)) + } +} +impl core::ops::Deref for WKUP_SELECT_GPIO_R { + type Target = crate::FieldReader; + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[doc = "Field `WKUP_SELECT_GPIO` writer - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] +pub struct WKUP_SELECT_GPIO_W<'a> { + w: &'a mut W, +} +impl<'a> WKUP_SELECT_GPIO_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !0x0fff) | (value as u16 & 0x0fff); + self.w + } +} +impl R { + #[doc = "Bits 0:11 - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] + #[inline(always)] + pub fn wkup_select_gpio(&self) -> WKUP_SELECT_GPIO_R { + WKUP_SELECT_GPIO_R::new((self.bits & 0x0fff) as u16) + } +} +impl W { + #[doc = "Bits 0:11 - 0 = input P0x is not enabled for wakeup event counter 1 = input P0x is enabled for wakeup event counter"] + #[inline(always)] + pub fn wkup_select_gpio(&mut self) -> WKUP_SELECT_GPIO_W { + WKUP_SELECT_GPIO_W { w: self } + } + #[doc = "Writes raw bits to the register."] + #[inline(always)] + pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { + self.0.bits(bits); + self + } +} +#[doc = "Select which inputs from P0 port can trigger wkup counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wkup_select_gpio_reg](index.html) module"] +pub struct WKUP_SELECT_GPIO_REG_SPEC; +impl crate::RegisterSpec for WKUP_SELECT_GPIO_REG_SPEC { + type Ux = u16; +} +#[doc = "`read()` method returns [wkup_select_gpio_reg::R](R) reader structure"] +impl crate::Readable for WKUP_SELECT_GPIO_REG_SPEC { + type Reader = R; +} +#[doc = "`write(|w| ..)` method takes [wkup_select_gpio_reg::W](W) writer structure"] +impl crate::Writable for WKUP_SELECT_GPIO_REG_SPEC { + type Writer = W; +} +#[doc = "`reset()` method sets WKUP_SELECT_GPIO_REG to value 0"] +impl crate::Resettable for WKUP_SELECT_GPIO_REG_SPEC { + #[inline(always)] + fn reset_value() -> Self::Ux { + 0 + } +} diff --git a/bitbox02-bt/vendor/da14531/update.sh b/bitbox02-bt/vendor/da14531/update.sh new file mode 100755 index 0000000..560cb6e --- /dev/null +++ b/bitbox02-bt/vendor/da14531/update.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +mkdir -p tmp + +pushd tmp + +svd2rust -i ../DA14531.svd +form -i lib.rs -o src/ +scp -r src ../ + +popd + +rm -rf tmp + +cargo fmt \ No newline at end of file diff --git a/bitbox02-bt/vendor/embedded-hal/.cargo-checksum.json b/bitbox02-bt/vendor/embedded-hal/.cargo-checksum.json new file mode 100644 index 0000000..34c6ce4 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"77ffedb0fed8fc0ca01187ff0e49ac5789de197cf9395873bcf8fe7dad4a07af","CODE_OF_CONDUCT.md":"8e25e95078b1a582086587adf8e1d907d43aacee6a072b8630d54a6289e5e0b9","Cargo.toml":"f38086e8578b2292f3c519060d723d6142e59930d72d12cdb1bbc5aaed09bf3c","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"520bc4942f199aad3dfe939c475d67ffbddfea482e41fc4fcad8829b71affc99","README.md":"629413fa55785448460269d379312aed6618869606a1c761d86aad32eb76c2cc","src/adc.rs":"bfa0ae49cef222ec2b04178ce1d6dc8db4fbc8acebf1a82657de4b1447ecf313","src/blocking/can.rs":"4db197e3f8d77967a7bac0beca9605063a1c6abbc5cc03d9b74fc09fbf36ba42","src/blocking/delay.rs":"a483acfe72b033f8e18273bf744c237a8de803cbbaf820aeb2ce32458ac3b684","src/blocking/i2c.rs":"966589f5f9d3102bb1e88150a503967b51cd81dda7527c803c03a10e4aa2ffa8","src/blocking/mod.rs":"02bbd31f9e68bb7fa10977c6934b9ae046138fbd6f5ebe6c5dfac6fa3332a63a","src/blocking/rng.rs":"eed57d8770235cc2454452fd5b86948a2143bdb5220b0e14fc36003f4223b7c9","src/blocking/serial.rs":"1587824b545e6e781efafc8720f1a3c19f0e9a7cab3ad0cd96cc99f5e84f8667","src/blocking/spi.rs":"ddb233a3bcf8a20b8da0d95c0cb2bdcbefd729a93b8a568a879680b026e00e19","src/can/id.rs":"691582de769af2c893cdceab783ad0b28b984de7466c419cbe17efd9f60f2e51","src/can/mod.rs":"b82b04a537415180918c2de36af9f5d7e8ecc76091bec5fc6f7208a14bfaae89","src/can/nb.rs":"6c4325d38b6aebbaa7293286482ab9645337b8236e054bed8835456f2aa32019","src/digital/mod.rs":"08f5144d2bcf8d4cdde1995b3617f5da14309926f66f4e9568100d7794da1b91","src/digital/v1.rs":"afd83c7e86c4957adf682e2280f7ac14a94dc8cdd43d70cc8890c2d8cf06be51","src/digital/v1_compat.rs":"192ec293c4e7f6bfbf9f65f3b3b1e2b47190761cc9e2e5ea230e0d5e7d69d4f3","src/digital/v2.rs":"89fa6a89cdbbb68f498fb7a2d87842b5b4391a978c7205ff1a0479983223c9f9","src/digital/v2_compat.rs":"bae546f4583eeedafa3e5c7e93f8fa5a56716e05a0ff3f5cc5aaf4a461e17adf","src/fmt.rs":"e0e657a52545f5099f2f0d49625b1448d1d566ece2c5badd8611e40f4afd7aba","src/lib.rs":"f9abd6a03322386af8099bc790bf247ab246351e965d6fab9650f433ec2f6584","src/prelude.rs":"d72d971fa63105e0ef6a0278fdecd4eb97f7fc47520455575c3165ef33ddb29d","src/serial.rs":"73f2e98712e12cc06ffd47d4c797ef8709ff56ebbad0db2e726aea1bf2ae383b","src/spi.rs":"f925b243fd86d7768a63605e8d3f035174be25df002c4abeedf4cd4c00b91594","src/timer.rs":"6c8e09a566375cfa90f7dd619544e84205dcaba8a87afa61ee447d57104b78ad","src/watchdog.rs":"e507438a87ee8a2a4162f717cc0472deecc8a29385b15a2c8ecc44e602d96e9a"},"package":"35949884794ad573cf46071e41c9b60efb0cb311e3ca01f7af807af1debc66ff"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/embedded-hal/CHANGELOG.md b/bitbox02-bt/vendor/embedded-hal/CHANGELOG.md new file mode 100644 index 0000000..7fc2bbe --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/CHANGELOG.md @@ -0,0 +1,143 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.2.7] - 2022-02-09 + +### Added + +- Backport CAN interface from the upcoming 1.0 release. + +## [v0.2.6] - 2021-08-03 + +### Added + +Backported non-breaking changes from the upcoming 1.0 release: + +- `Transactional` SPI interface for executing groups of SPI transactions. +- `Transactional` I2C interface for executing groups of I2C transactions. +- 10-bit addressing mode for I2C traits. +- `set_state` method for `OutputPin` using an input `PinState` value. +- `IoPin` trait for pins that can change between being inputs or outputs + dynamically. + + +## [v0.2.5] - 2021-04-28 + +### Changed + +- Updated `nb` dependency to version `0.1.3` to ensure compatibility with `nb` version `1.0`. + + +## [v0.2.4] - 2020-06-17 + +### Changed + +- Fix for `dyn` traits in fmt.rs +- Remove `#![deny(warnings)]`, now imposed y CI +- Updates stm32f30x from 0.6.0 to 0.8.0 +- Fix the input pin v2->v1 compatibility shim constructor, where `OldInputPin::new` + was incorrectly implemented for `v1::OutputPin` values. + + +## [v0.2.3] - 2019-05-09 + +### Added +- A new version of the digital `OutputPin`, `StatefulOutputPin`, `ToggleableOutputPin` + and `InputPin` traits has been added under `digital::v2`. These traits are now + fallible and their methods now return a `Result` type as setting an output pin + and reading an input pin could potentially fail. + See [here](https://github.com/rust-embedded/embedded-hal/issues/95) for more info. +- Compatibility shims between `digital::v1` and `digital::v2` traits allowing v1 traits + to be implicitly promoted to v2, and for v2 traits to be explicitly cast to v1 wrappers. + +### Changed +- The current versions of the `OutputPin`, `StatefulOutputPin`, `ToggleableOutputPin` + and `InputPin` traits have been marked as deprecated. Please use the new versions + included in `digital::v2`. + See [here](https://github.com/rust-embedded/embedded-hal/issues/95) for more info. + + +## [v0.2.2] - 2018-11-03 + +### Added + +- Added the Rust Code of Conduct to this repository +- The first ADC-related trait. This is a simple trait for one-shot conversions. +- Iterator-based blocking write and write+read traits have been added to I2C and SPI. +- New helper constants for SPI modes. +- A new trait for a cancellable countdown. +- New traits for watchdog timer management, including startup, feeding, and stopping. + +### Changed +- Updated docs to clarify I2C address bit widths and expectations. + + +## [v0.2.1] - 2018-05-14 + +### Changed + +- Auto-generated documentation (docs.rs) now includes the unproven traits. + +## [v0.2.0] - 2018-05-12 + +### Added + +- A `ToggeableOutputPin` trait has been added. This trait contains a single method: `toggle` that + can be used to toggle the state of a push-pull pin. + +### Changed + +- [breaking-change] The signature of `CountDown.wait` changed; it now returns `nb::Result<(), + Void>`. Where [`Void`] is the stable alternative to the never type, `!`, provided by the stable + [`void`] crate. Implementations of the `CountDown` trait will have to be updated to use the new + signature. With this change this crate compiles on the stable and beta channels. + +[`Void`]: https://docs.rs/void/1.0.2/void/enum.Void.html +[`void`]: https://crates.io/crates/void + +- [breaking-change] the `OutputPin.is_{low,high}` methods have been moved into its own trait + `StatefulOutputPin` and renamed to `is_set_{low,high}`. + +- It has been clarified in the documentation that `OutputPin` must be implemented for push-pull + output pins (and e.g. not for open drain output pins). + +## [v0.1.3] - 2018-05-14 + +### Changed + +- Re-export most / unchanged traits from embedded-hal v0.2.x to allow inter-operation between HAL + implementations and drivers that are using different minor versions. + +## [v0.1.2] - 2018-02-14 + +### Added + +- Unproven `blocking::serial::*` traits + +## [v0.1.1] - 2018-02-06 + +### Added + +- Unproven `digital::InputPin` trait + +## v0.1.0 - 2018-01-16 + +Initial release + +[Unreleased]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.7...v0.2.x +[v0.2.7]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.6...v0.2.7 +[v0.2.6]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.5...v0.2.6 +[v0.2.5]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.4...v0.2.5 +[v0.2.4]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.3...v0.2.4 +[v0.2.3]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.2...v0.2.3 +[v0.2.2]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.1...v0.2.2 +[v0.2.1]: https://github.com/rust-embedded/embedded-hal/compare/v0.2.0...v0.2.1 +[v0.2.0]: https://github.com/rust-embedded/embedded-hal/compare/v0.1.2...v0.2.0 +[v0.1.2]: https://github.com/rust-embedded/embedded-hal/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/rust-embedded/embedded-hal/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/embedded-hal/CODE_OF_CONDUCT.md b/bitbox02-bt/vendor/embedded-hal/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..bcefc6a --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/CODE_OF_CONDUCT.md @@ -0,0 +1,37 @@ +# The Rust Code of Conduct + +## Conduct + +**Contact**: [HAL team][team] + +* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. +* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. +* Please be kind and courteous. There's no need to be mean or rude. +* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. +* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. +* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. +* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [HAL team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. +* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. + +## Moderation + +These are the policies for upholding our community's standards of conduct. + +1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) +2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. +3. Moderators will first respond to such remarks with a warning. +4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off. +5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded. +6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology. +7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed. +8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others. + +In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. + +And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. + +The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org). + +*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* + +[team]: https://github.com/rust-embedded/wg#the-hal-team diff --git a/bitbox02-bt/vendor/embedded-hal/Cargo.toml b/bitbox02-bt/vendor/embedded-hal/Cargo.toml new file mode 100644 index 0000000..94c6948 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/Cargo.toml @@ -0,0 +1,38 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "embedded-hal" +version = "0.2.7" +authors = ["The Embedded HAL Team ", "Jorge Aparicio ", "Jonathan 'theJPster' Pallant "] +description = " A Hardware Abstraction Layer (HAL) for embedded systems " +documentation = "https://docs.rs/embedded-hal" +readme = "README.md" +keywords = ["hal", "IO"] +categories = ["asynchronous", "embedded", "hardware-support", "no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-embedded/embedded-hal" +[package.metadata.docs.rs] +features = ["unproven"] +[dependencies.nb] +version = "0.1.3" + +[dependencies.void] +version = "1.0.2" +default-features = false +[dev-dependencies.futures] +version = "0.1.17" + +[dev-dependencies.stm32f30x] +version = "0.8.0" + +[features] +unproven = ["nb/unstable"] diff --git a/bitbox02-bt/vendor/embedded-hal/LICENSE-APACHE b/bitbox02-bt/vendor/embedded-hal/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/embedded-hal/LICENSE-MIT b/bitbox02-bt/vendor/embedded-hal/LICENSE-MIT new file mode 100644 index 0000000..52cb453 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017-2018 Jorge Aparicio + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/embedded-hal/README.md b/bitbox02-bt/vendor/embedded-hal/README.md new file mode 100644 index 0000000..66d9a33 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/README.md @@ -0,0 +1,86 @@ +# `embedded-hal` + +> A Hardware Abstraction Layer (HAL) for embedded systems + +This project is developed and maintained by the [HAL team][team]. + +## [API reference] + +[API reference]: https://docs.rs/embedded-hal + +## How-to: add a new trait + +This is the suggested approach to adding a new trait to `embedded-hal` + +### Discussion + +Ideally, before proposing a new trait, or set of traits, you should create an issue where the use +cases and requirements of the trait(s) are discussed. + +These issues will be labeled as `discussion`s in the issue tracker. + +### Proposing a trait + +Once there's consensus on the requirements of the trait(s) a new issue, or a PR, with a proposal +should be opened. The proposal should include the actual trait definitions as well as a link to the +issue with previous discussion, if there was one. + +If the proposal includes more than one alternative then there should be further discussion to try to +single out the best alternative. + +These issues / PRs will be labeled as `proposal`s in the issue tracker. + +### Testing period + +If there are no objections to the proposal the new trait(s) will land behind the "unproven" Cargo +feature and an issue about the new trait(s) will be created. If the proposal includes several +alternatives and a single one couldn't be chosen as the best then each alternative will land behind +a different Cargo feature, e.g. "alt1" or "alt2". + +The traits will undergo a testing period before they move into the set of proven traits. During +this period users are encouraged to try to implement the unproven traits for their platforms and to +build drivers on top of them. Problems implementing the trait(s) as well as successful +implementations should be reported on the corresponding issue. + +To leave the unproven state at least *two* implementations of the trait(s) for different platforms +(ideally, the two platforms should be from different vendors) and *one* generic driver built on top +of the trait(s), or alternatively one demo program that exercises the trait (via generic function / +trait object), *should* be demonstrated. If, instead, reports indicate that the proposed trait(s) +can't be implemented for a certain platform then the trait(s) will be removed and we'll go back to +the drawing board. + +Issues used to track unproven APIs will be labeled as `unproven-api`s in the issue tracker and they +may also include the labels `needs-impl` and `needs-driver` to signal what's required for them to +move to the set of proven traits. + +## Implementations and drivers + +For a list of `embedded-hal` implementations and driver crates check the [awesome-embedded-rust] +list. + +[awesome-embedded-rust]: https://github.com/rust-embedded/awesome-embedded-rust#driver-crates + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +## Code of Conduct + +Contribution to this crate is organized under the terms of the [Rust Code of +Conduct][CoC], the maintainer of this crate, the [HAL team][team], promises +to intervene to uphold that code of conduct. + +[CoC]: CODE_OF_CONDUCT.md +[team]: https://github.com/rust-embedded/wg#the-hal-team diff --git a/bitbox02-bt/vendor/embedded-hal/src/adc.rs b/bitbox02-bt/vendor/embedded-hal/src/adc.rs new file mode 100644 index 0000000..cb7d736 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/adc.rs @@ -0,0 +1,98 @@ +//! Analog-digital conversion traits + +#[cfg(feature = "unproven")] +use nb; + +/// A marker trait to identify MCU pins that can be used as inputs to an ADC channel. +/// +/// This marker trait denotes an object, i.e. a GPIO pin, that is ready for use as an input to the +/// ADC. As ADCs channels can be supplied by multiple pins, this trait defines the relationship +/// between the physical interface and the ADC sampling buffer. +/// +/// ``` +/// # use std::marker::PhantomData; +/// # use embedded_hal::adc::Channel; +/// +/// struct Adc1; // Example ADC with single bank of 8 channels +/// struct Gpio1Pin1(PhantomData); +/// struct Analog(()); // marker type to denote a pin in "analog" mode +/// +/// // GPIO 1 pin 1 can supply an ADC channel when it is configured in Analog mode +/// impl Channel for Gpio1Pin1 { +/// type ID = u8; // ADC channels are identified numerically +/// +/// fn channel() -> u8 { 7_u8 } // GPIO pin 1 is connected to ADC channel 7 +/// } +/// +/// struct Adc2; // ADC with two banks of 16 channels +/// struct Gpio2PinA(PhantomData); +/// struct AltFun(()); // marker type to denote some alternate function mode for the pin +/// +/// // GPIO 2 pin A can supply an ADC channel when it's configured in some alternate function mode +/// impl Channel for Gpio2PinA { +/// type ID = (u8, u8); // ADC channels are identified by bank number and channel number +/// +/// fn channel() -> (u8, u8) { (0, 3) } // bank 0 channel 3 +/// } +/// ``` +#[cfg(feature = "unproven")] +pub trait Channel { + /// Channel ID type + /// + /// A type used to identify this ADC channel. For example, if the ADC has eight channels, this + /// might be a `u8`. If the ADC has multiple banks of channels, it could be a tuple, like + /// `(u8: bank_id, u8: channel_id)`. + type ID; + + /// Get the specific ID that identifies this channel, for example `0_u8` for the first ADC + /// channel, if Self::ID is u8. + fn channel() -> Self::ID; + + // `channel` is a function due to [this reported + // issue](https://github.com/rust-lang/rust/issues/54973). Something about blanket impls + // combined with `type ID; const CHANNEL: Self::ID;` causes problems. + //const CHANNEL: Self::ID; +} + +/// ADCs that sample on single channels per request, and do so at the time of the request. +/// +/// This trait is the interface to an ADC that is configured to read a specific channel at the time +/// of the request (in contrast to continuous asynchronous sampling). +/// +/// ``` +/// use embedded_hal::adc::{Channel, OneShot}; +/// +/// struct MyAdc; // 10-bit ADC, with 5 channels +/// # impl MyAdc { +/// # pub fn power_up(&mut self) {} +/// # pub fn power_down(&mut self) {} +/// # pub fn do_conversion(&mut self, chan: u8) -> u16 { 0xAA55_u16 } +/// # } +/// +/// impl OneShot for MyAdc +/// where +/// WORD: From, +/// PIN: Channel, +/// { +/// type Error = (); +/// +/// fn read(&mut self, _pin: &mut PIN) -> nb::Result { +/// let chan = 1 << PIN::channel(); +/// self.power_up(); +/// let result = self.do_conversion(chan); +/// self.power_down(); +/// Ok(result.into()) +/// } +/// } +/// ``` +#[cfg(feature = "unproven")] +pub trait OneShot> { + /// Error type returned by ADC methods + type Error; + + /// Request that the ADC begin a conversion on the specified pin + /// + /// This method takes a `Pin` reference, as it is expected that the ADC will be able to sample + /// whatever channel underlies the pin. + fn read(&mut self, pin: &mut Pin) -> nb::Result; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/blocking/can.rs b/bitbox02-bt/vendor/embedded-hal/src/blocking/can.rs new file mode 100644 index 0000000..b13885a --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/blocking/can.rs @@ -0,0 +1,17 @@ +//! Blocking CAN API + +/// A blocking CAN interface that is able to transmit and receive frames. +pub trait Can { + /// Associated frame type. + type Frame: crate::can::Frame; + + /// Associated error type. + type Error: crate::can::Error; + + /// Puts a frame in the transmit buffer. Blocks until space is available in + /// the transmit buffer. + fn transmit(&mut self, frame: &Self::Frame) -> Result<(), Self::Error>; + + /// Blocks until a frame was received or an error occured. + fn receive(&mut self) -> Result; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/blocking/delay.rs b/bitbox02-bt/vendor/embedded-hal/src/blocking/delay.rs new file mode 100644 index 0000000..177c29c --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/blocking/delay.rs @@ -0,0 +1,26 @@ +//! Delays +//! +//! # What's the difference between these traits and the `timer::CountDown` trait? +//! +//! The `Timer` trait provides a *non-blocking* timer abstraction and it's meant to be used to build +//! higher level abstractions like I/O operations with timeouts. OTOH, these delays traits only +//! provide *blocking* functionality. Note that you can also use the `timer::CountDown` trait to +//! implement blocking delays. + +/// Millisecond delay +/// +/// `UXX` denotes the range type of the delay time. `UXX` can be `u8`, `u16`, etc. A single type can +/// implement this trait for different types of `UXX`. +pub trait DelayMs { + /// Pauses execution for `ms` milliseconds + fn delay_ms(&mut self, ms: UXX); +} + +/// Microsecond delay +/// +/// `UXX` denotes the range type of the delay time. `UXX` can be `u8`, `u16`, etc. A single type can +/// implement this trait for different types of `UXX`. +pub trait DelayUs { + /// Pauses execution for `us` microseconds + fn delay_us(&mut self, us: UXX); +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/blocking/i2c.rs b/bitbox02-bt/vendor/embedded-hal/src/blocking/i2c.rs new file mode 100644 index 0000000..60bb153 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/blocking/i2c.rs @@ -0,0 +1,297 @@ +//! Blocking I2C API +//! +//! This API supports 7-bit and 10-bit addresses. Traits feature an `AddressMode` +//! marker type parameter. Two implementation of the `AddressMode` exist: +//! `SevenBitAddress` and `TenBitAddress`. +//! +//! Through this marker types it is possible to implement each address mode for +//! the traits independently in `embedded-hal` implementations and device drivers +//! can depend only on the mode that they support. +//! +//! Additionally, the I2C 10-bit address mode has been developed to be fully +//! backwards compatible with the 7-bit address mode. This allows for a +//! software-emulated 10-bit addressing implementation if the address mode +//! is not supported by the hardware. +//! +//! Since 7-bit addressing is the mode of the majority of I2C devices, +//! `SevenBitAddress` has been set as default mode and thus can be omitted if desired. +//! +//! ## Examples +//! +//! ### `embedded-hal` implementation for an MCU +//! Here is an example of an embedded-hal implementation of the `Write` trait +//! for both modes: +//! ``` +//! # use embedded_hal::blocking::i2c::{SevenBitAddress, TenBitAddress, Write}; +//! /// I2C0 hardware peripheral which supports both 7-bit and 10-bit addressing. +//! pub struct I2c0; +//! +//! impl Write for I2c0 +//! { +//! # type Error = (); +//! # +//! fn write(&mut self, addr: u8, output: &[u8]) -> Result<(), Self::Error> { +//! // ... +//! # Ok(()) +//! } +//! } +//! +//! impl Write for I2c0 +//! { +//! # type Error = (); +//! # +//! fn write(&mut self, addr: u16, output: &[u8]) -> Result<(), Self::Error> { +//! // ... +//! # Ok(()) +//! } +//! } +//! ``` +//! +//! ### Device driver compatible only with 7-bit addresses +//! +//! For demonstration purposes the address mode parameter has been omitted in this example. +//! +//! ``` +//! # use embedded_hal::blocking::i2c::WriteRead; +//! const ADDR: u8 = 0x15; +//! # const TEMP_REGISTER: u8 = 0x1; +//! pub struct TemperatureSensorDriver { +//! i2c: I2C, +//! } +//! +//! impl TemperatureSensorDriver +//! where +//! I2C: WriteRead, +//! { +//! pub fn read_temperature(&mut self) -> Result { +//! let mut temp = [0]; +//! self.i2c +//! .write_read(ADDR, &[TEMP_REGISTER], &mut temp) +//! .and(Ok(temp[0])) +//! } +//! } +//! ``` +//! +//! ### Device driver compatible only with 10-bit addresses +//! +//! ``` +//! # use embedded_hal::blocking::i2c::{TenBitAddress, WriteRead}; +//! const ADDR: u16 = 0x158; +//! # const TEMP_REGISTER: u8 = 0x1; +//! pub struct TemperatureSensorDriver { +//! i2c: I2C, +//! } +//! +//! impl TemperatureSensorDriver +//! where +//! I2C: WriteRead, +//! { +//! pub fn read_temperature(&mut self) -> Result { +//! let mut temp = [0]; +//! self.i2c +//! .write_read(ADDR, &[TEMP_REGISTER], &mut temp) +//! .and(Ok(temp[0])) +//! } +//! } +//! ``` + +use crate::private; + +impl private::Sealed for SevenBitAddress {} +impl private::Sealed for TenBitAddress {} + +/// Address mode (7-bit / 10-bit) +/// +/// Note: This trait is sealed and should not be implemented outside of this crate. +pub trait AddressMode: private::Sealed {} + +/// 7-bit address mode type +pub type SevenBitAddress = u8; + +/// 10-bit address mode type +pub type TenBitAddress = u16; + +impl AddressMode for SevenBitAddress {} + +impl AddressMode for TenBitAddress {} + +/// Blocking read +pub trait Read { + /// Error type + type Error; + + /// Reads enough bytes from slave with `address` to fill `buffer` + /// + /// # I2C Events (contract) + /// + /// ``` text + /// Master: ST SAD+R MAK MAK ... NMAK SP + /// Slave: SAK B0 B1 ... BN + /// ``` + /// + /// Where + /// + /// - `ST` = start condition + /// - `SAD+R` = slave address followed by bit 1 to indicate reading + /// - `SAK` = slave acknowledge + /// - `Bi` = ith byte of data + /// - `MAK` = master acknowledge + /// - `NMAK` = master no acknowledge + /// - `SP` = stop condition + fn read(&mut self, address: A, buffer: &mut [u8]) -> Result<(), Self::Error>; +} + +/// Blocking write +pub trait Write { + /// Error type + type Error; + + /// Writes bytes to slave with address `address` + /// + /// # I2C Events (contract) + /// + /// ``` text + /// Master: ST SAD+W B0 B1 ... BN SP + /// Slave: SAK SAK SAK ... SAK + /// ``` + /// + /// Where + /// + /// - `ST` = start condition + /// - `SAD+W` = slave address followed by bit 0 to indicate writing + /// - `SAK` = slave acknowledge + /// - `Bi` = ith byte of data + /// - `SP` = stop condition + fn write(&mut self, address: A, bytes: &[u8]) -> Result<(), Self::Error>; +} + +/// Blocking write (iterator version) +pub trait WriteIter { + /// Error type + type Error; + + /// Writes bytes to slave with address `address` + /// + /// # I2C Events (contract) + /// + /// Same as `Write` + fn write(&mut self, address: A, bytes: B) -> Result<(), Self::Error> + where + B: IntoIterator; +} + +/// Blocking write + read +pub trait WriteRead { + /// Error type + type Error; + + /// Writes bytes to slave with address `address` and then reads enough bytes to fill `buffer` *in a + /// single transaction* + /// + /// # I2C Events (contract) + /// + /// ``` text + /// Master: ST SAD+W O0 O1 ... OM SR SAD+R MAK MAK ... NMAK SP + /// Slave: SAK SAK SAK ... SAK SAK I0 I1 ... IN + /// ``` + /// + /// Where + /// + /// - `ST` = start condition + /// - `SAD+W` = slave address followed by bit 0 to indicate writing + /// - `SAK` = slave acknowledge + /// - `Oi` = ith outgoing byte of data + /// - `SR` = repeated start condition + /// - `SAD+R` = slave address followed by bit 1 to indicate reading + /// - `Ii` = ith incoming byte of data + /// - `MAK` = master acknowledge + /// - `NMAK` = master no acknowledge + /// - `SP` = stop condition + fn write_read( + &mut self, + address: A, + bytes: &[u8], + buffer: &mut [u8], + ) -> Result<(), Self::Error>; +} + +/// Blocking write (iterator version) + read +pub trait WriteIterRead { + /// Error type + type Error; + + /// Writes bytes to slave with address `address` and then reads enough bytes to fill `buffer` *in a + /// single transaction* + /// + /// # I2C Events (contract) + /// + /// Same as the `WriteRead` trait + fn write_iter_read( + &mut self, + address: A, + bytes: B, + buffer: &mut [u8], + ) -> Result<(), Self::Error> + where + B: IntoIterator; +} + +/// Transactional I2C operation. +/// +/// Several operations can be combined as part of a transaction. +#[derive(Debug, PartialEq)] +pub enum Operation<'a> { + /// Read data into the provided buffer + Read(&'a mut [u8]), + /// Write data from the provided buffer + Write(&'a [u8]), +} + +/// Transactional I2C interface. +/// +/// This allows combining operations within an I2C transaction. +pub trait Transactional { + /// Error type + type Error; + + /// Execute the provided operations on the I2C bus. + /// + /// Transaction contract: + /// - Before executing the first operation an ST is sent automatically. This is followed by SAD+R/W as appropriate. + /// - Data from adjacent operations of the same type are sent after each other without an SP or SR. + /// - Between adjacent operations of a different type an SR and SAD+R/W is sent. + /// - After executing the last operation an SP is sent automatically. + /// - If the last operation is a `Read` the master does not send an acknowledge for the last byte. + /// + /// - `ST` = start condition + /// - `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0 to indicate writing + /// - `SR` = repeated start condition + /// - `SP` = stop condition + fn exec<'a>(&mut self, address: A, operations: &mut [Operation<'a>]) + -> Result<(), Self::Error>; +} + +/// Transactional I2C interface (iterator version). +/// +/// This allows combining operation within an I2C transaction. +pub trait TransactionalIter { + /// Error type + type Error; + + /// Execute the provided operations on the I2C bus (iterator version). + /// + /// Transaction contract: + /// - Before executing the first operation an ST is sent automatically. This is followed by SAD+R/W as appropriate. + /// - Data from adjacent operations of the same type are sent after each other without an SP or SR. + /// - Between adjacent operations of a different type an SR and SAD+R/W is sent. + /// - After executing the last operation an SP is sent automatically. + /// - If the last operation is a `Read` the master does not send an acknowledge for the last byte. + /// + /// - `ST` = start condition + /// - `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0 to indicate writing + /// - `SR` = repeated start condition + /// - `SP` = stop condition + fn exec_iter<'a, O>(&mut self, address: A, operations: O) -> Result<(), Self::Error> + where + O: IntoIterator>; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/blocking/mod.rs b/bitbox02-bt/vendor/embedded-hal/src/blocking/mod.rs new file mode 100644 index 0000000..e3c1328 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/blocking/mod.rs @@ -0,0 +1,12 @@ +//! Blocking API +//! +//! In some cases it's possible to implement these blocking traits on top of one of the core HAL +//! traits. To save boilerplate when that's the case a `Default` marker trait may be provided. +//! Implementing that marker trait will opt in your type into a blanket implementation. + +pub mod can; +pub mod delay; +pub mod i2c; +pub mod rng; +pub mod serial; +pub mod spi; diff --git a/bitbox02-bt/vendor/embedded-hal/src/blocking/rng.rs b/bitbox02-bt/vendor/embedded-hal/src/blocking/rng.rs new file mode 100644 index 0000000..cd8a543 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/blocking/rng.rs @@ -0,0 +1,19 @@ +//! Blocking hardware random number generator + +/// Blocking read +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +#[cfg(feature = "unproven")] +pub trait Read { + /// Error type + type Error; + + /// Reads enough bytes from hardware random number generator to fill `buffer` + /// + /// If any error is encountered then this function immediately returns. The contents of buf are + /// unspecified in this case. + /// + /// If this function returns an error, it is unspecified how many bytes it has read, but it + /// will never read more than would be necessary to completely fill the buffer. + fn read(&mut self, buffer: &mut [u8]) -> Result<(), Self::Error>; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/blocking/serial.rs b/bitbox02-bt/vendor/embedded-hal/src/blocking/serial.rs new file mode 100644 index 0000000..6b7c352 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/blocking/serial.rs @@ -0,0 +1,54 @@ +//! Blocking serial API + +/// Write half of a serial interface (blocking variant) +pub trait Write { + /// The type of error that can occur when writing + type Error; + + /// Writes a slice, blocking until everything has been written + /// + /// An implementation can choose to buffer the write, returning `Ok(())` + /// after the complete slice has been written to a buffer, but before all + /// words have been sent via the serial interface. To make sure that + /// everything has been sent, call [`bflush`] after this function returns. + /// + /// [`bflush`]: #tymethod.bflush + fn bwrite_all(&mut self, buffer: &[Word]) -> Result<(), Self::Error>; + + /// Block until the serial interface has sent all buffered words + fn bflush(&mut self) -> Result<(), Self::Error>; +} + +/// Blocking serial write +pub mod write { + /// Marker trait to opt into default blocking write implementation + /// + /// Implementers of [`serial::Write`] can implement this marker trait + /// for their type. Doing so will automatically provide the default + /// implementation of [`blocking::serial::Write`] for the type. + /// + /// [`serial::Write`]: ../../serial/trait.Write.html + /// [`blocking::serial::Write`]: ../trait.Write.html + pub trait Default: ::serial::Write {} + + impl ::blocking::serial::Write for S + where + S: Default, + Word: Clone, + { + type Error = S::Error; + + fn bwrite_all(&mut self, buffer: &[Word]) -> Result<(), Self::Error> { + for word in buffer { + block!(self.write(word.clone()))?; + } + + Ok(()) + } + + fn bflush(&mut self) -> Result<(), Self::Error> { + block!(self.flush())?; + Ok(()) + } + } +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/blocking/spi.rs b/bitbox02-bt/vendor/embedded-hal/src/blocking/spi.rs new file mode 100644 index 0000000..76623e2 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/blocking/spi.rs @@ -0,0 +1,127 @@ +//! Blocking SPI API + +/// Blocking transfer +pub trait Transfer { + /// Error type + type Error; + + /// Sends `words` to the slave. Returns the `words` received from the slave + fn transfer<'w>(&mut self, words: &'w mut [W]) -> Result<&'w [W], Self::Error>; +} + +/// Blocking write +pub trait Write { + /// Error type + type Error; + + /// Sends `words` to the slave, ignoring all the incoming words + fn write(&mut self, words: &[W]) -> Result<(), Self::Error>; +} + +/// Blocking write (iterator version) +#[cfg(feature = "unproven")] +pub trait WriteIter { + /// Error type + type Error; + + /// Sends `words` to the slave, ignoring all the incoming words + fn write_iter(&mut self, words: WI) -> Result<(), Self::Error> + where + WI: IntoIterator; +} + +/// Blocking transfer +pub mod transfer { + /// Default implementation of `blocking::spi::Transfer` for implementers of + /// `spi::FullDuplex` + pub trait Default: ::spi::FullDuplex {} + + impl ::blocking::spi::Transfer for S + where + S: Default, + W: Clone, + { + type Error = S::Error; + + fn transfer<'w>(&mut self, words: &'w mut [W]) -> Result<&'w [W], S::Error> { + for word in words.iter_mut() { + block!(self.send(word.clone()))?; + *word = block!(self.read())?; + } + + Ok(words) + } + } +} + +/// Blocking write +pub mod write { + /// Default implementation of `blocking::spi::Write` for implementers of `spi::FullDuplex` + pub trait Default: ::spi::FullDuplex {} + + impl ::blocking::spi::Write for S + where + S: Default, + W: Clone, + { + type Error = S::Error; + + fn write(&mut self, words: &[W]) -> Result<(), S::Error> { + for word in words { + block!(self.send(word.clone()))?; + block!(self.read())?; + } + + Ok(()) + } + } +} + +/// Blocking write (iterator version) +#[cfg(feature = "unproven")] +pub mod write_iter { + /// Default implementation of `blocking::spi::WriteIter` for implementers of + /// `spi::FullDuplex` + pub trait Default: ::spi::FullDuplex {} + + impl ::blocking::spi::WriteIter for S + where + S: Default, + W: Clone, + { + type Error = S::Error; + + fn write_iter(&mut self, words: WI) -> Result<(), S::Error> + where + WI: IntoIterator, + { + for word in words.into_iter() { + block!(self.send(word.clone()))?; + block!(self.read())?; + } + + Ok(()) + } + } +} + +/// Operation for transactional SPI trait +/// +/// This allows composition of SPI operations into a single bus transaction +#[derive(Debug, PartialEq)] +pub enum Operation<'a, W: 'static> { + /// Write data from the provided buffer, discarding read data + Write(&'a [W]), + /// Write data out while reading data into the provided buffer + Transfer(&'a mut [W]), +} + +/// Transactional trait allows multiple actions to be executed +/// as part of a single SPI transaction +pub trait Transactional { + /// Associated error type + type Error; + + /// Execute the provided transactions + fn exec<'a>(&mut self, operations: &mut [Operation<'a, W>]) -> Result<(), Self::Error>; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/can/id.rs b/bitbox02-bt/vendor/embedded-hal/src/can/id.rs new file mode 100644 index 0000000..811baa5 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/can/id.rs @@ -0,0 +1,160 @@ +//! CAN Identifiers. + +/// Standard 11-bit CAN Identifier (`0..=0x7FF`). +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct StandardId(u16); + +impl StandardId { + /// CAN ID `0`, the highest priority. + pub const ZERO: Self = StandardId(0); + + /// CAN ID `0x7FF`, the lowest priority. + pub const MAX: Self = StandardId(0x7FF); + + /// Tries to create a `StandardId` from a raw 16-bit integer. + /// + /// This will return `None` if `raw` is out of range of an 11-bit integer (`> 0x7FF`). + #[inline] + pub fn new(raw: u16) -> Option { + if raw <= 0x7FF { + Some(StandardId(raw)) + } else { + None + } + } + + /// Creates a new `StandardId` without checking if it is inside the valid range. + /// + /// # Safety + /// Using this method can create an invalid ID and is thus marked as unsafe. + #[inline] + pub const unsafe fn new_unchecked(raw: u16) -> Self { + StandardId(raw) + } + + /// Returns this CAN Identifier as a raw 16-bit integer. + #[inline] + pub fn as_raw(&self) -> u16 { + self.0 + } +} + +/// Extended 29-bit CAN Identifier (`0..=1FFF_FFFF`). +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct ExtendedId(u32); + +impl ExtendedId { + /// CAN ID `0`, the highest priority. + pub const ZERO: Self = ExtendedId(0); + + /// CAN ID `0x1FFFFFFF`, the lowest priority. + pub const MAX: Self = ExtendedId(0x1FFF_FFFF); + + /// Tries to create a `ExtendedId` from a raw 32-bit integer. + /// + /// This will return `None` if `raw` is out of range of an 29-bit integer (`> 0x1FFF_FFFF`). + #[inline] + pub fn new(raw: u32) -> Option { + if raw <= 0x1FFF_FFFF { + Some(ExtendedId(raw)) + } else { + None + } + } + + /// Creates a new `ExtendedId` without checking if it is inside the valid range. + /// + /// # Safety + /// Using this method can create an invalid ID and is thus marked as unsafe. + #[inline] + pub const unsafe fn new_unchecked(raw: u32) -> Self { + ExtendedId(raw) + } + + /// Returns this CAN Identifier as a raw 32-bit integer. + #[inline] + pub fn as_raw(&self) -> u32 { + self.0 + } + + /// Returns the Base ID part of this extended identifier. + pub fn standard_id(&self) -> StandardId { + // ID-28 to ID-18 + StandardId((self.0 >> 18) as u16) + } +} + +/// A CAN Identifier (standard or extended). +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum Id { + /// Standard 11-bit Identifier (`0..=0x7FF`). + Standard(StandardId), + + /// Extended 29-bit Identifier (`0..=0x1FFF_FFFF`). + Extended(ExtendedId), +} + +impl From for Id { + #[inline] + fn from(id: StandardId) -> Self { + Id::Standard(id) + } +} + +impl From for Id { + #[inline] + fn from(id: ExtendedId) -> Self { + Id::Extended(id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn standard_id_new() { + assert_eq!( + StandardId::new(StandardId::MAX.as_raw()), + Some(StandardId::MAX) + ); + } + + #[test] + fn standard_id_new_out_of_range() { + assert_eq!(StandardId::new(StandardId::MAX.as_raw() + 1), None); + } + + #[test] + fn standard_id_new_unchecked_out_of_range() { + let id = StandardId::MAX.as_raw() + 1; + assert_eq!(unsafe { StandardId::new_unchecked(id) }, StandardId(id)); + } + + #[test] + fn extended_id_new() { + assert_eq!( + ExtendedId::new(ExtendedId::MAX.as_raw()), + Some(ExtendedId::MAX) + ); + } + + #[test] + fn extended_id_new_out_of_range() { + assert_eq!(ExtendedId::new(ExtendedId::MAX.as_raw() + 1), None); + } + + #[test] + fn extended_id_new_unchecked_out_of_range() { + let id = ExtendedId::MAX.as_raw() + 1; + assert_eq!(unsafe { ExtendedId::new_unchecked(id) }, ExtendedId(id)); + } + + #[test] + fn get_standard_id_from_extended_id() { + assert_eq!( + Some(ExtendedId::MAX.standard_id()), + StandardId::new((ExtendedId::MAX.0 >> 18) as u16) + ); + } +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/can/mod.rs b/bitbox02-bt/vendor/embedded-hal/src/can/mod.rs new file mode 100644 index 0000000..c12e40a --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/can/mod.rs @@ -0,0 +1,123 @@ +//! Controller Area Network + +pub mod nb; + +mod id; + +pub use self::id::*; +pub use self::nb::*; + +/// A CAN2.0 Frame +pub trait Frame: Sized { + /// Creates a new frame. + /// + /// This will return `None` if the data slice is too long. + fn new(id: impl Into, data: &[u8]) -> Option; + + /// Creates a new remote frame (RTR bit set). + /// + /// This will return `None` if the data length code (DLC) is not valid. + fn new_remote(id: impl Into, dlc: usize) -> Option; + + /// Returns true if this frame is a extended frame. + fn is_extended(&self) -> bool; + + /// Returns true if this frame is a standard frame. + fn is_standard(&self) -> bool { + !self.is_extended() + } + + /// Returns true if this frame is a remote frame. + fn is_remote_frame(&self) -> bool; + + /// Returns true if this frame is a data frame. + fn is_data_frame(&self) -> bool { + !self.is_remote_frame() + } + + /// Returns the frame identifier. + fn id(&self) -> Id; + + /// Returns the data length code (DLC) which is in the range 0..8. + /// + /// For data frames the DLC value always matches the length of the data. + /// Remote frames do not carry any data, yet the DLC can be greater than 0. + fn dlc(&self) -> usize; + + /// Returns the frame data (0..8 bytes in length). + fn data(&self) -> &[u8]; +} + +/// CAN error +pub trait Error: core::fmt::Debug { + /// Convert error to a generic CAN error kind + /// + /// By using this method, CAN errors freely defined by HAL implementations + /// can be converted to a set of generic serial errors upon which generic + /// code can act. + fn kind(&self) -> ErrorKind; +} + +/// CAN error kind +/// +/// This represents a common set of CAN operation errors. HAL implementations are +/// free to define more specific or additional error types. However, by providing +/// a mapping to these common CAN errors, generic code can still react to them. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub enum ErrorKind { + /// The peripheral receive buffer was overrun. + Overrun, + + // MAC sublayer errors + /// A bit error is detected at that bit time when the bit value that is + /// monitored differs from the bit value sent. + Bit, + + /// A stuff error is detected at the bit time of the sixth consecutive + /// equal bit level in a frame field that shall be coded by the method + /// of bit stuffing. + Stuff, + + /// Calculated CRC sequence does not equal the received one. + Crc, + + /// A form error shall be detected when a fixed-form bit field contains + /// one or more illegal bits. + Form, + + /// An ACK error shall be detected by a transmitter whenever it does not + /// monitor a dominant bit during the ACK slot. + Acknowledge, + + /// A different error occurred. The original error may contain more information. + Other, +} + +impl Error for ErrorKind { + fn kind(&self) -> ErrorKind { + *self + } +} + +impl core::fmt::Display for ErrorKind { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + ErrorKind::Overrun => write!(f, "The peripheral receive buffer was overrun"), + ErrorKind::Bit => write!( + f, + "Bit value that is monitored differs from the bit value sent" + ), + ErrorKind::Stuff => write!(f, "Sixth consecutive equal bits detected"), + ErrorKind::Crc => write!(f, "Calculated CRC sequence does not equal the received one"), + ErrorKind::Form => write!( + f, + "A fixed-form bit field contains one or more illegal bits" + ), + ErrorKind::Acknowledge => write!(f, "Transmitted frame was not acknowledged"), + ErrorKind::Other => write!( + f, + "A different error occurred. The original error may contain more information" + ), + } + } +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/can/nb.rs b/bitbox02-bt/vendor/embedded-hal/src/can/nb.rs new file mode 100644 index 0000000..2ab6050 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/can/nb.rs @@ -0,0 +1,28 @@ +//! Non-blocking CAN API + +/// A CAN interface that is able to transmit and receive frames. +pub trait Can { + /// Associated frame type. + type Frame: crate::can::Frame; + + /// Associated error type. + type Error: crate::can::Error; + + /// Puts a frame in the transmit buffer to be sent on the bus. + /// + /// If the transmit buffer is full, this function will try to replace a pending + /// lower priority frame and return the frame that was replaced. + /// Returns `Err(WouldBlock)` if the transmit buffer is full and no frame can be + /// replaced. + /// + /// # Notes for implementers + /// + /// * Frames of equal identifier shall be transmited in FIFO fashion when more + /// than one transmit buffer is available. + /// * When replacing pending frames make sure the frame is not in the process of + /// being send to the bus. + fn transmit(&mut self, frame: &Self::Frame) -> nb::Result, Self::Error>; + + /// Returns a received frame if available. + fn receive(&mut self) -> nb::Result; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/digital/mod.rs b/bitbox02-bt/vendor/embedded-hal/src/digital/mod.rs new file mode 100644 index 0000000..5e1848f --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/digital/mod.rs @@ -0,0 +1,27 @@ +//! Digital I/O +//! +//! +//! + +// Deprecated / infallible traits +#[deprecated( + since = "0.2.2", + note = "Deprecated because the methods cannot return errors. \ + Users should use the traits in digital::v2." +)] +pub mod v1; + +// New / fallible traits +pub mod v2; + +// v2 -> v1 compatibility wrappers +// These require explicit casts from v2 -> v1 +pub mod v1_compat; + +// v1 -> v2 compatibility shims +// These are implicit over v1 implementations +pub mod v2_compat; + +// Re-export old traits so this isn't a breaking change +#[allow(deprecated)] +pub use self::v1::*; diff --git a/bitbox02-bt/vendor/embedded-hal/src/digital/v1.rs b/bitbox02-bt/vendor/embedded-hal/src/digital/v1.rs new file mode 100644 index 0000000..d7bbfac --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/digital/v1.rs @@ -0,0 +1,145 @@ +//! Digital I/O +//! +//! The traits in this module are now deprecated. Please use the new versions included +//! in `digital::v2`. + +#![allow(deprecated)] + +/// Single digital push-pull output pin +/// +/// *This version of the trait is now deprecated. Please use the new `OutputPin` trait in +/// `digital::v2::OutputPin`*. + +pub trait OutputPin { + /// Drives the pin low + /// + /// *NOTE* the actual electrical state of the pin may not actually be low, e.g. due to external + /// electrical sources + fn set_low(&mut self); + + /// Drives the pin high + /// + /// *NOTE* the actual electrical state of the pin may not actually be high, e.g. due to external + /// electrical sources + fn set_high(&mut self); +} + +/// Push-pull output pin that can read its output state +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +/// +/// *This version of the trait is now deprecated. Please use the new `StatefulOutputPin` trait in +/// `digital::v2::StatefulOutputPin`*. +#[cfg(feature = "unproven")] +pub trait StatefulOutputPin { + /// Is the pin in drive high mode? + /// + /// *NOTE* this does *not* read the electrical state of the pin + fn is_set_high(&self) -> bool; + + /// Is the pin in drive low mode? + /// + /// *NOTE* this does *not* read the electrical state of the pin + fn is_set_low(&self) -> bool; +} + +/// Output pin that can be toggled +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +/// +/// *This version of the trait is now deprecated. Please use the new `ToggleableOutputPin` +/// trait in `digital::v2::ToggleableOutputPin`*. +/// +/// See [toggleable](toggleable) to use a software implementation if +/// both [OutputPin](trait.OutputPin.html) and +/// [StatefulOutputPin](trait.StatefulOutputPin.html) are +/// implemented. Otherwise, implement this using hardware mechanisms. +#[cfg(feature = "unproven")] +pub trait ToggleableOutputPin { + /// Toggle pin output. + fn toggle(&mut self); +} + +/// If you can read **and** write the output state, a pin is +/// toggleable by software. +/// +/// *This version of the module is now deprecated. Please use the new `toggleable` module in +/// `digital::v2::toggleable`*. +/// +/// ``` +/// use embedded_hal::digital::{OutputPin, StatefulOutputPin, ToggleableOutputPin}; +/// use embedded_hal::digital::toggleable; +/// +/// /// A virtual output pin that exists purely in software +/// struct MyPin { +/// state: bool +/// } +/// +/// impl OutputPin for MyPin { +/// fn set_low(&mut self) { +/// self.state = false; +/// } +/// fn set_high(&mut self) { +/// self.state = true; +/// } +/// } +/// +/// impl StatefulOutputPin for MyPin { +/// fn is_set_low(&self) -> bool { +/// !self.state +/// } +/// fn is_set_high(&self) -> bool { +/// self.state +/// } +/// } +/// +/// /// Opt-in to the software implementation. +/// impl toggleable::Default for MyPin {} +/// +/// let mut pin = MyPin { state: false }; +/// pin.toggle(); +/// assert!(pin.is_set_high()); +/// pin.toggle(); +/// assert!(pin.is_set_low()); +/// ``` +#[cfg(feature = "unproven")] +pub mod toggleable { + #[allow(deprecated)] + use super::{OutputPin, StatefulOutputPin, ToggleableOutputPin}; + + /// Software-driven `toggle()` implementation. + /// + /// *This trait is available if embedded-hal is built with the `"unproven"` feature.* + #[allow(deprecated)] + pub trait Default: OutputPin + StatefulOutputPin {} + + #[allow(deprecated)] + impl

ToggleableOutputPin for P + where + P: Default, + { + /// Toggle pin output + fn toggle(&mut self) { + if self.is_set_low() { + self.set_high(); + } else { + self.set_low(); + } + } + } +} + +/// Single digital input pin +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +/// +/// *This version of the trait is now deprecated. Please use the new `InputPin` trait in +/// `digital::v2::InputPin`*. +#[cfg(feature = "unproven")] +pub trait InputPin { + /// Is the input pin high? + fn is_high(&self) -> bool; + + /// Is the input pin low? + fn is_low(&self) -> bool; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/digital/v1_compat.rs b/bitbox02-bt/vendor/embedded-hal/src/digital/v1_compat.rs new file mode 100644 index 0000000..83a9ffc --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/digital/v1_compat.rs @@ -0,0 +1,298 @@ +//! v1 compatibility wrappers +//! +//! This module provides wrappers to support use of v2 implementations with +//! v1 consumers. v2 traits must be explicitly cast to the v1 version using +//! `.into()`, and will panic on internal errors +//! +//! ``` +//! extern crate embedded_hal; +//! use embedded_hal::digital::{v1, v2, v1_compat::OldOutputPin}; +//! +//! struct NewOutputPinImpl {} +//! +//! impl v2::OutputPin for NewOutputPinImpl { +//! type Error = (); +//! fn set_low(&mut self) -> Result<(), Self::Error> { Ok(()) } +//! fn set_high(&mut self) -> Result<(), Self::Error>{ Ok(()) } +//! } +//! +//! struct OldOutputPinConsumer { +//! _pin: T, +//! } +//! +//! impl OldOutputPinConsumer +//! where T: v1::OutputPin { +//! pub fn new(pin: T) -> OldOutputPinConsumer { +//! OldOutputPinConsumer{ _pin: pin } +//! } +//! } +//! +//! fn main() { +//! let pin = NewOutputPinImpl{}; +//! let _consumer: OldOutputPinConsumer> = OldOutputPinConsumer::new(pin.into()); +//! } +//! ``` +//! + +#[allow(deprecated)] +use super::v1; +use super::v2; + +/// Wrapper to allow fallible `v2::OutputPin` traits to be converted to `v1::OutputPin` traits +pub struct OldOutputPin { + pin: T, +} + +impl OldOutputPin +where + T: v2::OutputPin, + E: core::fmt::Debug, +{ + /// Create a new OldOutputPin wrapper around a `v2::OutputPin` + pub fn new(pin: T) -> Self { + Self { pin } + } + + /// Fetch a reference to the inner `v2::OutputPin` impl + #[cfg(test)] + fn inner(&self) -> &T { + &self.pin + } +} + +impl From for OldOutputPin +where + T: v2::OutputPin, + E: core::fmt::Debug, +{ + fn from(pin: T) -> Self { + OldOutputPin { pin } + } +} + +/// Implementation of `v1::OutputPin` trait for fallible `v2::OutputPin` output pins +/// where errors will panic. +#[allow(deprecated)] +impl v1::OutputPin for OldOutputPin +where + T: v2::OutputPin, + E: core::fmt::Debug, +{ + fn set_low(&mut self) { + self.pin.set_low().unwrap() + } + + fn set_high(&mut self) { + self.pin.set_high().unwrap() + } +} + +/// Implementation of `v1::StatefulOutputPin` trait for `v2::StatefulOutputPin` fallible pins +/// where errors will panic. +#[cfg(feature = "unproven")] +#[allow(deprecated)] +impl v1::StatefulOutputPin for OldOutputPin +where + T: v2::StatefulOutputPin, + E: core::fmt::Debug, +{ + fn is_set_low(&self) -> bool { + self.pin.is_set_low().unwrap() + } + + fn is_set_high(&self) -> bool { + self.pin.is_set_high().unwrap() + } +} + +/// Wrapper to allow fallible `v2::InputPin` traits to be converted to `v1::InputPin` traits +/// where errors will panic. +#[cfg(feature = "unproven")] +pub struct OldInputPin { + pin: T, +} + +#[cfg(feature = "unproven")] +impl OldInputPin +where + T: v2::InputPin, + E: core::fmt::Debug, +{ + /// Create an `OldInputPin` wrapper around a `v2::InputPin`. + pub fn new(pin: T) -> Self { + Self { pin } + } +} + +#[cfg(feature = "unproven")] +impl From for OldInputPin +where + T: v2::InputPin, + E: core::fmt::Debug, +{ + fn from(pin: T) -> Self { + OldInputPin { pin } + } +} + +/// Implementation of `v1::InputPin` trait for `v2::InputPin` fallible pins +/// where errors will panic. +#[cfg(feature = "unproven")] +#[allow(deprecated)] +impl v1::InputPin for OldInputPin +where + T: v2::InputPin, + E: core::fmt::Debug, +{ + fn is_low(&self) -> bool { + self.pin.is_low().unwrap() + } + + fn is_high(&self) -> bool { + self.pin.is_high().unwrap() + } +} + +#[cfg(test)] +#[allow(deprecated)] +mod tests { + use super::*; + + #[allow(deprecated)] + use crate::digital::v1; + use crate::digital::v2; + + use crate::digital::v1::OutputPin; + + #[derive(Clone)] + struct NewOutputPinImpl { + state: bool, + res: Result<(), ()>, + } + + impl v2::OutputPin for NewOutputPinImpl { + type Error = (); + + fn set_low(&mut self) -> Result<(), Self::Error> { + self.state = false; + self.res + } + fn set_high(&mut self) -> Result<(), Self::Error> { + self.state = true; + self.res + } + } + + #[allow(deprecated)] + struct OldOutputPinConsumer { + _pin: T, + } + + #[allow(deprecated)] + impl OldOutputPinConsumer + where + T: v1::OutputPin, + { + pub fn new(pin: T) -> OldOutputPinConsumer { + OldOutputPinConsumer { _pin: pin } + } + } + + #[test] + fn v1_v2_output_explicit() { + let i = NewOutputPinImpl { + state: false, + res: Ok(()), + }; + let _c: OldOutputPinConsumer> = OldOutputPinConsumer::new(i.into()); + } + + #[test] + fn v1_v2_output_state() { + let mut o: OldOutputPin<_> = NewOutputPinImpl { + state: false, + res: Ok(()), + } + .into(); + + o.set_high(); + assert_eq!(o.inner().state, true); + + o.set_low(); + assert_eq!(o.inner().state, false); + } + + #[test] + #[should_panic] + fn v1_v2_output_panic() { + let mut o: OldOutputPin<_> = NewOutputPinImpl { + state: false, + res: Err(()), + } + .into(); + + o.set_high(); + } + + #[cfg(feature = "unproven")] + use crate::digital::v1::InputPin; + + #[cfg(feature = "unproven")] + struct NewInputPinImpl { + state: Result, + } + + #[cfg(feature = "unproven")] + impl v2::InputPin for NewInputPinImpl { + type Error = (); + + fn is_low(&self) -> Result { + self.state.map(|v| v == false) + } + fn is_high(&self) -> Result { + self.state.map(|v| v == true) + } + } + + #[cfg(feature = "unproven")] + #[allow(deprecated)] + struct OldInputPinConsumer { + _pin: T, + } + + #[cfg(feature = "unproven")] + #[allow(deprecated)] + impl OldInputPinConsumer + where + T: v1::InputPin, + { + pub fn new(pin: T) -> OldInputPinConsumer { + OldInputPinConsumer { _pin: pin } + } + } + + #[cfg(feature = "unproven")] + #[test] + fn v1_v2_input_explicit() { + let i = NewInputPinImpl { state: Ok(false) }; + let _c: OldInputPinConsumer> = OldInputPinConsumer::new(i.into()); + } + + #[cfg(feature = "unproven")] + #[test] + fn v1_v2_input_state() { + let i: OldInputPin<_> = NewInputPinImpl { state: Ok(false) }.into(); + + assert_eq!(i.is_low(), true); + assert_eq!(i.is_high(), false); + } + + #[cfg(feature = "unproven")] + #[test] + #[should_panic] + fn v1_v2_input_panic() { + let i: OldInputPin<_> = NewInputPinImpl { state: Err(()) }.into(); + + i.is_low(); + } +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/digital/v2.rs b/bitbox02-bt/vendor/embedded-hal/src/digital/v2.rs new file mode 100644 index 0000000..81fd67c --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/digital/v2.rs @@ -0,0 +1,216 @@ +//! Digital I/O +//! +//! Version 2 / fallible traits. Infallible implementations should set Error to `!`. + +use core::{convert::From, ops::Not}; + +/// Digital output pin state +/// +/// Conversion from `bool` and logical negation are also implemented +/// for this type. +/// ```rust +/// # use embedded_hal::digital::v2::PinState; +/// let state = PinState::from(false); +/// assert_eq!(state, PinState::Low); +/// assert_eq!(!state, PinState::High); +/// ``` +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum PinState { + /// Low pin state + Low, + /// High pin state + High, +} + +impl From for PinState { + fn from(value: bool) -> Self { + match value { + false => PinState::Low, + true => PinState::High, + } + } +} + +impl Not for PinState { + type Output = PinState; + + fn not(self) -> Self::Output { + match self { + PinState::High => PinState::Low, + PinState::Low => PinState::High, + } + } +} + +/// Single digital push-pull output pin +pub trait OutputPin { + /// Error type + type Error; + + /// Drives the pin low + /// + /// *NOTE* the actual electrical state of the pin may not actually be low, e.g. due to external + /// electrical sources + fn set_low(&mut self) -> Result<(), Self::Error>; + + /// Drives the pin high + /// + /// *NOTE* the actual electrical state of the pin may not actually be high, e.g. due to external + /// electrical sources + fn set_high(&mut self) -> Result<(), Self::Error>; + + /// Drives the pin high or low depending on the provided value + /// + /// *NOTE* the actual electrical state of the pin may not actually be high or low, e.g. due to external + /// electrical sources + fn set_state(&mut self, state: PinState) -> Result<(), Self::Error> { + match state { + PinState::Low => self.set_low(), + PinState::High => self.set_high(), + } + } +} + +/// Push-pull output pin that can read its output state +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +#[cfg(feature = "unproven")] +pub trait StatefulOutputPin: OutputPin { + /// Is the pin in drive high mode? + /// + /// *NOTE* this does *not* read the electrical state of the pin + fn is_set_high(&self) -> Result; + + /// Is the pin in drive low mode? + /// + /// *NOTE* this does *not* read the electrical state of the pin + fn is_set_low(&self) -> Result; +} + +/// Output pin that can be toggled +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +/// +/// See [toggleable](toggleable) to use a software implementation if +/// both [OutputPin](trait.OutputPin.html) and +/// [StatefulOutputPin](trait.StatefulOutputPin.html) are +/// implemented. Otherwise, implement this using hardware mechanisms. +#[cfg(feature = "unproven")] +pub trait ToggleableOutputPin { + /// Error type + type Error; + + /// Toggle pin output. + fn toggle(&mut self) -> Result<(), Self::Error>; +} + +/// If you can read **and** write the output state, a pin is +/// toggleable by software. +/// +/// ``` +/// use embedded_hal::digital::v2::{OutputPin, StatefulOutputPin, ToggleableOutputPin}; +/// use embedded_hal::digital::v2::toggleable; +/// +/// /// A virtual output pin that exists purely in software +/// struct MyPin { +/// state: bool +/// } +/// +/// impl OutputPin for MyPin { +/// type Error = void::Void; +/// +/// fn set_low(&mut self) -> Result<(), Self::Error> { +/// self.state = false; +/// Ok(()) +/// } +/// fn set_high(&mut self) -> Result<(), Self::Error> { +/// self.state = true; +/// Ok(()) +/// } +/// } +/// +/// impl StatefulOutputPin for MyPin { +/// fn is_set_low(&self) -> Result { +/// Ok(!self.state) +/// } +/// fn is_set_high(&self) -> Result { +/// Ok(self.state) +/// } +/// } +/// +/// /// Opt-in to the software implementation. +/// impl toggleable::Default for MyPin {} +/// +/// let mut pin = MyPin { state: false }; +/// pin.toggle().unwrap(); +/// assert!(pin.is_set_high().unwrap()); +/// pin.toggle().unwrap(); +/// assert!(pin.is_set_low().unwrap()); +/// ``` +#[cfg(feature = "unproven")] +pub mod toggleable { + use super::{OutputPin, StatefulOutputPin, ToggleableOutputPin}; + + /// Software-driven `toggle()` implementation. + /// + /// *This trait is available if embedded-hal is built with the `"unproven"` feature.* + pub trait Default: OutputPin + StatefulOutputPin {} + + impl

ToggleableOutputPin for P + where + P: Default, + { + type Error = P::Error; + + /// Toggle pin output + fn toggle(&mut self) -> Result<(), Self::Error> { + if self.is_set_low()? { + self.set_high() + } else { + self.set_low() + } + } + } +} + +/// Single digital input pin +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +#[cfg(feature = "unproven")] +pub trait InputPin { + /// Error type + type Error; + + /// Is the input pin high? + fn is_high(&self) -> Result; + + /// Is the input pin low? + fn is_low(&self) -> Result; +} + +/// Single pin that can switch from input to output mode, and vice-versa. +/// +/// Example use (assumes the `Error` type is the same for the `IoPin`, +/// `InputPin`, and `OutputPin`): +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +#[cfg(feature = "unproven")] +pub trait IoPin +where + TInput: InputPin + IoPin, + TOutput: OutputPin + IoPin, +{ + /// Error type. + type Error; + + /// Tries to convert this pin to input mode. + /// + /// If the pin is already in input mode, this method should succeed. + fn into_input_pin(self) -> Result; + + /// Tries to convert this pin to output mode with the given initial state. + /// + /// If the pin is already in the requested state, this method should + /// succeed. + fn into_output_pin(self, state: PinState) -> Result; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/digital/v2_compat.rs b/bitbox02-bt/vendor/embedded-hal/src/digital/v2_compat.rs new file mode 100644 index 0000000..929f413 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/digital/v2_compat.rs @@ -0,0 +1,234 @@ +//! v2 compatibility shims +//! +//! This module adds implicit forward support to v1 digital traits, +//! allowing v1 implementations to be directly used with v2 consumers. +//! +//! ``` +//! extern crate embedded_hal; +//! use embedded_hal::digital::{v1, v2}; +//! +//! struct OldOutputPinImpl { } +//! +//! impl v1::OutputPin for OldOutputPinImpl { +//! fn set_low(&mut self) { } +//! fn set_high(&mut self) { } +//! } +//! +//! struct NewOutputPinConsumer { +//! _pin: T, +//! } +//! +//! impl NewOutputPinConsumer +//! where T: v2::OutputPin { +//! pub fn new(pin: T) -> NewOutputPinConsumer { +//! NewOutputPinConsumer{ _pin: pin } +//! } +//! } +//! +//! fn main() { +//! let pin = OldOutputPinImpl{}; +//! let _consumer = NewOutputPinConsumer::new(pin); +//! } +//! ``` +//! + +#[allow(deprecated)] +use super::v1; +use super::v2; + +/// Implementation of fallible `v2::OutputPin` for `v1::OutputPin` traits +#[allow(deprecated)] +impl v2::OutputPin for T +where + T: v1::OutputPin, +{ + // TODO: update to ! when never_type is stabilized + type Error = (); + + fn set_low(&mut self) -> Result<(), Self::Error> { + Ok(self.set_low()) + } + + fn set_high(&mut self) -> Result<(), Self::Error> { + Ok(self.set_high()) + } +} + +/// Implementation of fallible `v2::StatefulOutputPin` for `v1::StatefulOutputPin` digital traits +#[cfg(feature = "unproven")] +#[allow(deprecated)] +impl v2::StatefulOutputPin for T +where + T: v1::StatefulOutputPin + v1::OutputPin, +{ + fn is_set_low(&self) -> Result { + Ok(self.is_set_low()) + } + + fn is_set_high(&self) -> Result { + Ok(self.is_set_high()) + } +} + +#[cfg(feature = "unproven")] +#[allow(deprecated)] +impl v2::toggleable::Default for T where T: v1::toggleable::Default {} + +/// Implementation of fallible `v2::InputPin` for `v1::InputPin` digital traits +#[cfg(feature = "unproven")] +#[allow(deprecated)] +impl v2::InputPin for T +where + T: v1::InputPin, +{ + // TODO: update to ! when never_type is stabilized + type Error = (); + + fn is_low(&self) -> Result { + Ok(self.is_low()) + } + + fn is_high(&self) -> Result { + Ok(self.is_high()) + } +} + +#[cfg(test)] +mod tests { + + #[allow(deprecated)] + use crate::digital::v1; + use crate::digital::v2; + + #[allow(deprecated)] + struct OldOutputPinImpl { + state: bool, + } + + #[allow(deprecated)] + impl v1::OutputPin for OldOutputPinImpl { + fn set_low(&mut self) { + self.state = false; + } + fn set_high(&mut self) { + self.state = true; + } + } + + #[allow(deprecated)] + #[cfg(feature = "unproven")] + impl v1::StatefulOutputPin for OldOutputPinImpl { + fn is_set_low(&self) -> bool { + self.state == false + } + + fn is_set_high(&self) -> bool { + self.state == true + } + } + + #[allow(deprecated)] + #[cfg(feature = "unproven")] + impl v1::toggleable::Default for OldOutputPinImpl {} + + struct NewOutputPinConsumer { + _pin: T, + } + + impl NewOutputPinConsumer + where + T: v2::OutputPin, + { + pub fn new(pin: T) -> NewOutputPinConsumer { + NewOutputPinConsumer { _pin: pin } + } + } + + #[cfg(feature = "unproven")] + struct NewToggleablePinConsumer { + _pin: T, + } + + #[cfg(feature = "unproven")] + impl NewToggleablePinConsumer + where + T: v2::ToggleableOutputPin, + { + pub fn new(pin: T) -> NewToggleablePinConsumer { + NewToggleablePinConsumer { _pin: pin } + } + } + + #[test] + #[cfg(feature = "unproven")] + fn v2_v1_toggleable_implicit() { + let i = OldOutputPinImpl { state: false }; + let _c = NewToggleablePinConsumer::new(i); + } + + #[test] + fn v2_v1_output_implicit() { + let i = OldOutputPinImpl { state: false }; + let _c = NewOutputPinConsumer::new(i); + } + + #[test] + fn v2_v1_output_state() { + let mut o = OldOutputPinImpl { state: false }; + + v2::OutputPin::set_high(&mut o).unwrap(); + assert_eq!(o.state, true); + + v2::OutputPin::set_low(&mut o).unwrap(); + assert_eq!(o.state, false); + } + + #[cfg(feature = "unproven")] + #[allow(deprecated)] + struct OldInputPinImpl { + state: bool, + } + + #[cfg(feature = "unproven")] + #[allow(deprecated)] + impl v1::InputPin for OldInputPinImpl { + fn is_low(&self) -> bool { + !self.state + } + fn is_high(&self) -> bool { + self.state + } + } + + #[cfg(feature = "unproven")] + struct NewInputPinConsumer { + _pin: T, + } + + #[cfg(feature = "unproven")] + impl NewInputPinConsumer + where + T: v2::InputPin, + { + pub fn new(pin: T) -> NewInputPinConsumer { + NewInputPinConsumer { _pin: pin } + } + } + + #[cfg(feature = "unproven")] + #[test] + #[cfg(feature = "unproven")] + fn v2_v1_input_implicit() { + let i = OldInputPinImpl { state: false }; + let _c = NewInputPinConsumer::new(i); + } + + #[cfg(feature = "unproven")] + #[test] + fn v2_v1_input_state() { + let mut i = OldInputPinImpl { state: false }; + + assert_eq!(v2::InputPin::is_high(&mut i).unwrap(), false); + assert_eq!(v2::InputPin::is_low(&mut i).unwrap(), true); + } +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/fmt.rs b/bitbox02-bt/vendor/embedded-hal/src/fmt.rs new file mode 100644 index 0000000..33041a8 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/fmt.rs @@ -0,0 +1,18 @@ +//! Implementation of `core::fmt::Write` for the HAL's `serial::Write`. +//! +//! TODO write example of usage +use core::fmt::{Result, Write}; + +impl Write for dyn (::serial::Write) +where + Word: From, +{ + fn write_str(&mut self, s: &str) -> Result { + let _ = s + .as_bytes() + .into_iter() + .map(|c| block!(self.write(Word::from(*c)))) + .last(); + Ok(()) + } +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/lib.rs b/bitbox02-bt/vendor/embedded-hal/src/lib.rs new file mode 100644 index 0000000..f0289b2 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/lib.rs @@ -0,0 +1,999 @@ +//! A Hardware Abstraction Layer (HAL) for embedded systems +//! +//! **NOTE** This HAL is still is active development. Expect the traits presented here to be +//! tweaked, split or be replaced wholesale before being stabilized, i.e. before hitting the 1.0.0 +//! release. That being said there's a part of the HAL that's currently considered unproven and is +//! hidden behind an "unproven" Cargo feature. This API is even more volatile and it's exempt from +//! semver rules: it can change in a non-backward compatible fashion or even disappear in between +//! patch releases. +//! +//! # Design goals +//! +//! The HAL +//! +//! - Must *erase* device specific details. Neither register, register blocks or magic values should +//! appear in the API. +//! +//! - Must be generic *within* a device and *across* devices. The API to use a serial interface must +//! be the same regardless of whether the implementation uses the USART1 or UART4 peripheral of a +//! device or the UART0 peripheral of another device. +//! +//! - Where possible must *not* be tied to a specific asynchronous model. The API should be usable +//! in blocking mode, with the `futures` model, with an async/await model or with a callback model. +//! (cf. the [`nb`] crate) +//! +//! - Must be minimal, and thus easy to implement and zero cost, yet highly composable. People that +//! want higher level abstraction should *prefer to use this HAL* rather than *re-implement* +//! register manipulation code. +//! +//! - Serve as a foundation for building an ecosystem of platform agnostic drivers. Here driver +//! means a library crate that lets a target platform interface an external device like a digital +//! sensor or a wireless transceiver. The advantage of this system is that by writing the driver as +//! a generic library on top of `embedded-hal` driver authors can support any number of target +//! platforms (e.g. Cortex-M microcontrollers, AVR microcontrollers, embedded Linux, etc.). The +//! advantage for application developers is that by adopting `embedded-hal` they can unlock all +//! these drivers for their platform. +//! +//! # Out of scope +//! +//! - Initialization and configuration stuff like "ensure this serial interface and that SPI +//! interface are not using the same pins". The HAL will focus on *doing I/O*. +//! +//! # Reference implementation +//! +//! The [`stm32f30x-hal`] crate contains a reference implementation of this HAL. +//! +//! [`stm32f30x-hal`]: https://crates.io/crates/stm32f30x-hal/0.1.0 +//! +//! # Platform agnostic drivers +//! +//! You can find platform agnostic drivers built on top of `embedded-hal` on crates.io by [searching +//! for the *embedded-hal* keyword](https://crates.io/keywords/embedded-hal). +//! +//! If you writing a platform agnostic driver yourself you are highly encouraged to [add the +//! embedded-hal keyword](https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata) +//! to your crate before publishing it! +//! +//! # Detailed design +//! +//! ## Traits +//! +//! The HAL is specified as traits to allow generic programming. These traits make use of the +//! [`nb`][] crate (*please go read that crate documentation before continuing*) to abstract over +//! the asynchronous model and to also provide a blocking operation mode. +//! +//! [`nb`]: https://crates.io/crates/nb +//! +//! Here's how a HAL trait may look like: +//! +//! ``` +//! extern crate nb; +//! +//! /// A serial interface +//! pub trait Serial { +//! /// Error type associated to this serial interface +//! type Error; +//! +//! /// Reads a single byte +//! fn read(&mut self) -> nb::Result; +//! +//! /// Writes a single byte +//! fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error>; +//! } +//! ``` +//! +//! The `nb::Result` enum is used to add a [`WouldBlock`] variant to the errors +//! of the serial interface. As explained in the documentation of the `nb` crate this single API, +//! when paired with the macros in the `nb` crate, can operate in a blocking manner, or in a +//! non-blocking manner compatible with `futures` and with the `await!` operator. +//! +//! [`WouldBlock`]: https://docs.rs/nb/0.1.0/nb/enum.Error.html +//! +//! Some traits, like the one shown below, may expose possibly blocking APIs that can't fail. In +//! those cases `nb::Result<_, Void>` is used. +//! +//! ``` +//! extern crate nb; +//! extern crate void; +//! +//! use void::Void; +//! +//! /// A count down timer +//! pub trait CountDown { +//! // .. +//! +//! /// "waits" until the count down is over +//! fn wait(&mut self) -> nb::Result<(), Void>; +//! } +//! +//! # fn main() {} +//! ``` +//! +//! ## Suggested implementation +//! +//! The HAL traits should be implemented for device crates generated via [`svd2rust`] to maximize +//! code reuse. +//! +//! [`svd2rust`]: https://crates.io/crates/svd2rust +//! +//! Shown below is an implementation of some of the HAL traits for the [`stm32f30x`] crate. This +//! single implementation will work for *any* microcontroller in the STM32F30x family. +//! +//! [`stm32f30x`]: https://crates.io/crates/stm32f30x +//! +//! ``` +//! // crate: stm32f30x-hal +//! // An implementation of the `embedded-hal` traits for STM32F30x microcontrollers +//! +//! extern crate embedded_hal as hal; +//! extern crate nb; +//! +//! // device crate +//! extern crate stm32f30x; +//! +//! use stm32f30x::USART1; +//! +//! /// A serial interface +//! // NOTE generic over the USART peripheral +//! pub struct Serial { usart: USART } +//! +//! // convenience type alias +//! pub type Serial1 = Serial; +//! +//! /// Serial interface error +//! pub enum Error { +//! /// Buffer overrun +//! Overrun, +//! // omitted: other error variants +//! } +//! +//! impl hal::serial::Read for Serial { +//! type Error = Error; +//! +//! fn read(&mut self) -> nb::Result { +//! // read the status register +//! let isr = self.usart.isr.read(); +//! +//! if isr.ore().bit_is_set() { +//! // Error: Buffer overrun +//! Err(nb::Error::Other(Error::Overrun)) +//! } +//! // omitted: checks for other errors +//! else if isr.rxne().bit_is_set() { +//! // Data available: read the data register +//! Ok(self.usart.rdr.read().bits() as u8) +//! } else { +//! // No data available yet +//! Err(nb::Error::WouldBlock) +//! } +//! } +//! } +//! +//! impl hal::serial::Write for Serial { +//! type Error = Error; +//! +//! fn write(&mut self, byte: u8) -> nb::Result<(), Error> { +//! // Similar to the `read` implementation +//! # Ok(()) +//! } +//! +//! fn flush(&mut self) -> nb::Result<(), Error> { +//! // Similar to the `read` implementation +//! # Ok(()) +//! } +//! } +//! +//! # fn main() {} +//! ``` +//! +//! ## Intended usage +//! +//! Thanks to the [`nb`] crate the HAL API can be used in a blocking manner, +//! with `futures` or with the `await` operator using the [`block!`], +//! [`try_nb!`] and [`await!`] macros respectively. +//! +//! [`block!`]: https://docs.rs/nb/0.1.0/nb/macro.block.html +//! [`try_nb!`]: https://docs.rs/nb/0.1.0/nb/index.html#how-to-use-this-crate +//! [`await!`]: https://docs.rs/nb/0.1.0/nb/index.html#how-to-use-this-crate +//! +//! ### Blocking mode +//! +//! An example of sending a string over the serial interface in a blocking +//! fashion: +//! +//! ``` +//! extern crate embedded_hal; +//! #[macro_use(block)] +//! extern crate nb; +//! +//! use stm32f30x_hal::Serial1; +//! use embedded_hal::serial::Write; +//! +//! # fn main() { +//! let mut serial: Serial1 = { +//! // .. +//! # Serial1 +//! }; +//! +//! for byte in b"Hello, world!" { +//! // NOTE `block!` blocks until `serial.write()` completes and returns +//! // `Result<(), Error>` +//! block!(serial.write(*byte)).unwrap(); +//! } +//! # } +//! +//! # mod stm32f30x_hal { +//! # extern crate void; +//! # use self::void::Void; +//! # pub struct Serial1; +//! # impl Serial1 { +//! # pub fn write(&mut self, _: u8) -> ::nb::Result<(), Void> { +//! # Ok(()) +//! # } +//! # } +//! # } +//! ``` +//! +//! ### `futures` +//! +//! An example of running two tasks concurrently. First task: blink an LED every +//! second. Second task: loop back data over the serial interface. +//! +//! ``` +//! extern crate embedded_hal as hal; +//! extern crate futures; +//! extern crate void; +//! +//! #[macro_use(try_nb)] +//! extern crate nb; +//! +//! use hal::prelude::*; +//! use futures::{ +//! future, +//! Async, +//! Future, +//! }; +//! use futures::future::Loop; +//! use stm32f30x_hal::{Led, Serial1, Timer6}; +//! use void::Void; +//! +//! /// `futures` version of `CountDown.wait` +//! /// +//! /// This returns a future that must be polled to completion +//! fn wait(mut timer: T) -> impl Future +//! where +//! T: hal::timer::CountDown, +//! { +//! let mut timer = Some(timer); +//! future::poll_fn(move || { +//! try_nb!(timer.as_mut().unwrap().wait()); +//! +//! Ok(Async::Ready(timer.take().unwrap())) +//! }) +//! } +//! +//! /// `futures` version of `Serial.read` +//! /// +//! /// This returns a future that must be polled to completion +//! fn read(mut serial: S) -> impl Future +//! where +//! S: hal::serial::Read, +//! { +//! let mut serial = Some(serial); +//! future::poll_fn(move || { +//! let byte = try_nb!(serial.as_mut().unwrap().read()); +//! +//! Ok(Async::Ready((serial.take().unwrap(), byte))) +//! }) +//! } +//! +//! /// `futures` version of `Serial.write` +//! /// +//! /// This returns a future that must be polled to completion +//! fn write(mut serial: S, byte: u8) -> impl Future +//! where +//! S: hal::serial::Write, +//! { +//! let mut serial = Some(serial); +//! future::poll_fn(move || { +//! try_nb!(serial.as_mut().unwrap().write(byte)); +//! +//! Ok(Async::Ready(serial.take().unwrap())) +//! }) +//! } +//! +//! fn main() { +//! // HAL implementers +//! let timer: Timer6 = { +//! // .. +//! # Timer6 +//! }; +//! let serial: Serial1 = { +//! // .. +//! # Serial1 +//! }; +//! let led: Led = { +//! // .. +//! # Led +//! }; +//! +//! // Tasks +//! let mut blinky = future::loop_fn::<_, (), _, _>( +//! (led, timer, true), +//! |(mut led, mut timer, state)| { +//! wait(timer).map(move |timer| { +//! if state { +//! led.on(); +//! } else { +//! led.off(); +//! } +//! +//! Loop::Continue((led, timer, !state)) +//! }) +//! }); +//! +//! let mut loopback = future::loop_fn::<_, (), _, _>(serial, |mut serial| { +//! read(serial).and_then(|(serial, byte)| { +//! write(serial, byte) +//! }).map(|serial| { +//! Loop::Continue(serial) +//! }) +//! }); +//! +//! // Event loop +//! loop { +//! blinky.poll().unwrap(); // NOTE(unwrap) E = Void +//! loopback.poll().unwrap(); +//! # break; +//! } +//! } +//! +//! # mod stm32f30x_hal { +//! # extern crate void; +//! # use self::void::Void; +//! # pub struct Timer6; +//! # impl ::hal::timer::CountDown for Timer6 { +//! # type Time = (); +//! # +//! # fn start(&mut self, _: T) where T: Into<()> {} +//! # fn wait(&mut self) -> ::nb::Result<(), Void> { Err(::nb::Error::WouldBlock) } +//! # } +//! # +//! # pub struct Serial1; +//! # impl ::hal::serial::Read for Serial1 { +//! # type Error = Void; +//! # fn read(&mut self) -> ::nb::Result { Err(::nb::Error::WouldBlock) } +//! # } +//! # impl ::hal::serial::Write for Serial1 { +//! # type Error = Void; +//! # fn flush(&mut self) -> ::nb::Result<(), Void> { Err(::nb::Error::WouldBlock) } +//! # fn write(&mut self, _: u8) -> ::nb::Result<(), Void> { Err(::nb::Error::WouldBlock) } +//! # } +//! # +//! # pub struct Led; +//! # impl Led { +//! # pub fn off(&mut self) {} +//! # pub fn on(&mut self) {} +//! # } +//! # } +//! ``` +//! +//! ### `await` +//! +//! Same example as above but using `await!` instead of `futures`. +//! +//! ``` +//! #![feature(generator_trait)] +//! #![feature(generators)] +//! +//! extern crate embedded_hal as hal; +//! +//! #[macro_use(await)] +//! extern crate nb; +//! +//! use std::ops::Generator; +//! use std::pin::Pin; +//! +//! use hal::prelude::*; +//! use stm32f30x_hal::{Led, Serial1, Timer6}; +//! +//! fn main() { +//! // HAL implementers +//! let mut timer: Timer6 = { +//! // .. +//! # Timer6 +//! }; +//! let mut serial: Serial1 = { +//! // .. +//! # Serial1 +//! }; +//! let mut led: Led = { +//! // .. +//! # Led +//! }; +//! +//! // Tasks +//! let mut blinky = (move || { +//! let mut state = false; +//! loop { +//! // `await!` means "suspend / yield here" instead of "block until +//! // completion" +//! await!(timer.wait()).unwrap(); // NOTE(unwrap) E = Void +//! +//! state = !state; +//! +//! if state { +//! led.on(); +//! } else { +//! led.off(); +//! } +//! } +//! }); +//! +//! let mut loopback = (move || { +//! loop { +//! let byte = await!(serial.read()).unwrap(); +//! await!(serial.write(byte)).unwrap(); +//! } +//! }); +//! +//! // Event loop +//! loop { +//! Pin::new(&mut blinky).resume(()); +//! Pin::new(&mut loopback).resume(()); +//! # break; +//! } +//! } +//! +//! # mod stm32f30x_hal { +//! # extern crate void; +//! # use self::void::Void; +//! # pub struct Serial1; +//! # impl Serial1 { +//! # pub fn read(&mut self) -> ::nb::Result { Err(::nb::Error::WouldBlock) } +//! # pub fn write(&mut self, _: u8) -> ::nb::Result<(), Void> { Err(::nb::Error::WouldBlock) } +//! # } +//! # pub struct Timer6; +//! # impl Timer6 { +//! # pub fn wait(&mut self) -> ::nb::Result<(), Void> { Err(::nb::Error::WouldBlock) } +//! # } +//! # pub struct Led; +//! # impl Led { +//! # pub fn off(&mut self) {} +//! # pub fn on(&mut self) {} +//! # } +//! # } +//! ``` +//! +//! ## Generic programming and higher level abstractions +//! +//! The core of the HAL has been kept minimal on purpose to encourage building **generic** higher +//! level abstractions on top of it. Some higher level abstractions that pick an asynchronous model +//! or that have blocking behavior and that are deemed useful to build other abstractions can be +//! found in the `blocking` module and, in the future, in the `futures` and `async` modules. +//! +//! Some examples: +//! +//! **NOTE** All the functions shown below could have been written as trait +//! methods with default implementation to allow specialization, but they have +//! been written as functions to keep things simple. +//! +//! - Write a whole buffer to a serial device in blocking a fashion. +//! +//! ``` +//! extern crate embedded_hal as hal; +//! #[macro_use(block)] +//! extern crate nb; +//! +//! use hal::prelude::*; +//! +//! fn write_all(serial: &mut S, buffer: &[u8]) -> Result<(), S::Error> +//! where +//! S: hal::serial::Write +//! { +//! for &byte in buffer { +//! block!(serial.write(byte))?; +//! } +//! +//! Ok(()) +//! } +//! +//! # fn main() {} +//! ``` +//! +//! - Blocking serial read with timeout +//! +//! ``` +//! extern crate embedded_hal as hal; +//! extern crate nb; +//! +//! use hal::prelude::*; +//! +//! enum Error { +//! /// Serial interface error +//! Serial(E), +//! TimedOut, +//! } +//! +//! fn read_with_timeout( +//! serial: &mut S, +//! timer: &mut T, +//! timeout: T::Time, +//! ) -> Result> +//! where +//! T: hal::timer::CountDown, +//! S: hal::serial::Read, +//! { +//! timer.start(timeout); +//! +//! loop { +//! match serial.read() { +//! // raise error +//! Err(nb::Error::Other(e)) => return Err(Error::Serial(e)), +//! Err(nb::Error::WouldBlock) => { +//! // no data available yet, check the timer below +//! }, +//! Ok(byte) => return Ok(byte), +//! } +//! +//! match timer.wait() { +//! Err(nb::Error::Other(e)) => { +//! // The error type specified by `timer.wait()` is `!`, which +//! // means no error can actually occur. The Rust compiler +//! // still forces us to provide this match arm, though. +//! unreachable!() +//! }, +//! // no timeout yet, try again +//! Err(nb::Error::WouldBlock) => continue, +//! Ok(()) => return Err(Error::TimedOut), +//! } +//! } +//! } +//! +//! # fn main() {} +//! ``` +//! +//! - Asynchronous SPI transfer +//! +//! ``` +//! #![feature(conservative_impl_trait)] +//! #![feature(generators)] +//! #![feature(generator_trait)] +//! +//! extern crate embedded_hal as hal; +//! #[macro_use(await)] +//! extern crate nb; +//! +//! use std::ops::Generator; +//! +//! /// Transfers a byte buffer of size N +//! /// +//! /// Returns the same byte buffer but filled with the data received from the +//! /// slave device +//! fn transfer( +//! mut spi: S, +//! mut buffer: [u8; 16], // NOTE this should be generic over the size of the array +//! ) -> impl Generator, Yield = ()> +//! where +//! S: hal::spi::FullDuplex, +//! { +//! move || { +//! let n = buffer.len(); +//! for i in 0..n { +//! await!(spi.send(buffer[i]))?; +//! buffer[i] = await!(spi.read())?; +//! } +//! +//! Ok((spi, buffer)) +//! } +//! } +//! +//! # fn main() {} +//! ``` +//! +//! - Buffered serial interface with periodic flushing in interrupt handler +//! +//! ``` +//! extern crate embedded_hal as hal; +//! extern crate nb; +//! extern crate void; +//! +//! use hal::prelude::*; +//! use void::Void; +//! +//! fn flush(serial: &mut S, cb: &mut CircularBuffer) +//! where +//! S: hal::serial::Write, +//! { +//! loop { +//! if let Some(byte) = cb.peek() { +//! match serial.write(*byte) { +//! Err(nb::Error::Other(_)) => unreachable!(), +//! Err(nb::Error::WouldBlock) => return, +//! Ok(()) => {}, // keep flushing data +//! } +//! } +//! +//! cb.pop(); +//! } +//! } +//! +//! // The stuff below could be in some other crate +//! +//! /// Global singleton +//! pub struct BufferedSerial1; +//! +//! // NOTE private +//! static BUFFER1: Mutex = { +//! // .. +//! # Mutex(CircularBuffer) +//! }; +//! static SERIAL1: Mutex = { +//! // .. +//! # Mutex(Serial1) +//! }; +//! +//! impl BufferedSerial1 { +//! pub fn write(&self, byte: u8) { +//! self.write_all(&[byte]) +//! } +//! +//! pub fn write_all(&self, bytes: &[u8]) { +//! let mut buffer = BUFFER1.lock(); +//! for byte in bytes { +//! buffer.push(*byte).expect("buffer overrun"); +//! } +//! // omitted: pend / enable interrupt_handler +//! } +//! } +//! +//! fn interrupt_handler() { +//! let mut serial = SERIAL1.lock(); +//! let mut buffer = BUFFER1.lock(); +//! +//! flush(&mut *serial, &mut buffer); +//! } +//! +//! # struct Mutex(T); +//! # impl Mutex { +//! # fn lock(&self) -> RefMut { unimplemented!() } +//! # } +//! # struct RefMut<'a, T>(&'a mut T) where T: 'a; +//! # impl<'a, T> ::std::ops::Deref for RefMut<'a, T> { +//! # type Target = T; +//! # fn deref(&self) -> &T { self.0 } +//! # } +//! # impl<'a, T> ::std::ops::DerefMut for RefMut<'a, T> { +//! # fn deref_mut(&mut self) -> &mut T { self.0 } +//! # } +//! # struct Serial1; +//! # impl ::hal::serial::Write for Serial1 { +//! # type Error = Void; +//! # fn write(&mut self, _: u8) -> nb::Result<(), Void> { Err(::nb::Error::WouldBlock) } +//! # fn flush(&mut self) -> nb::Result<(), Void> { Err(::nb::Error::WouldBlock) } +//! # } +//! # struct CircularBuffer; +//! # impl CircularBuffer { +//! # pub fn peek(&mut self) -> Option<&u8> { None } +//! # pub fn pop(&mut self) -> Option { None } +//! # pub fn push(&mut self, _: u8) -> Result<(), ()> { Ok(()) } +//! # } +//! +//! # fn main() {} +//! ``` + +#![deny(missing_docs)] +#![no_std] + +#[macro_use] +extern crate nb; +extern crate void; + +pub mod adc; +pub mod blocking; +pub mod can; +pub mod digital; +pub mod fmt; +pub mod prelude; +pub mod serial; +pub mod spi; +pub mod timer; +pub mod watchdog; + +/// Input capture +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +/// +/// # Examples +/// +/// You can use this interface to measure the period of (quasi) periodic signals +/// / events +/// +/// ``` +/// extern crate embedded_hal as hal; +/// #[macro_use(block)] +/// extern crate nb; +/// +/// use hal::prelude::*; +/// +/// fn main() { +/// let mut capture: Capture1 = { +/// // .. +/// # Capture1 +/// }; +/// +/// capture.set_resolution(1.ms()); +/// +/// let before = block!(capture.capture(Channel::_1)).unwrap(); +/// let after = block!(capture.capture(Channel::_1)).unwrap(); +/// +/// let period = after.wrapping_sub(before); +/// +/// println!("Period: {} ms", period); +/// } +/// +/// # extern crate void; +/// # use void::Void; +/// # struct MilliSeconds(u32); +/// # trait U32Ext { fn ms(self) -> MilliSeconds; } +/// # impl U32Ext for u32 { fn ms(self) -> MilliSeconds { MilliSeconds(self) } } +/// # struct Capture1; +/// # enum Channel { _1 } +/// # impl hal::Capture for Capture1 { +/// # type Capture = u16; +/// # type Channel = Channel; +/// # type Error = Void; +/// # type Time = MilliSeconds; +/// # fn capture(&mut self, _: Channel) -> ::nb::Result { Ok(0) } +/// # fn disable(&mut self, _: Channel) { unimplemented!() } +/// # fn enable(&mut self, _: Channel) { unimplemented!() } +/// # fn get_resolution(&self) -> MilliSeconds { unimplemented!() } +/// # fn set_resolution(&mut self, _: T) where T: Into {} +/// # } +/// ``` +#[cfg(feature = "unproven")] +// reason: pre-singletons API. With singletons a `CapturePin` (cf. `PwmPin`) trait seems more +// appropriate +pub trait Capture { + /// Enumeration of `Capture` errors + /// + /// Possible errors: + /// + /// - *overcapture*, the previous capture value was overwritten because it + /// was not read in a timely manner + type Error; + + /// Enumeration of channels that can be used with this `Capture` interface + /// + /// If your `Capture` interface has no channels you can use the type `()` + /// here + type Channel; + + /// A time unit that can be converted into a human time unit (e.g. seconds) + type Time; + + /// The type of the value returned by `capture` + type Capture; + + /// "Waits" for a transition in the capture `channel` and returns the value + /// of counter at that instant + /// + /// NOTE that you must multiply the returned value by the *resolution* of + /// this `Capture` interface to get a human time unit (e.g. seconds) + fn capture(&mut self, channel: Self::Channel) -> nb::Result; + + /// Disables a capture `channel` + fn disable(&mut self, channel: Self::Channel); + + /// Enables a capture `channel` + fn enable(&mut self, channel: Self::Channel); + + /// Returns the current resolution + fn get_resolution(&self) -> Self::Time; + + /// Sets the resolution of the capture timer + fn set_resolution(&mut self, resolution: R) + where + R: Into; +} + +/// Pulse Width Modulation +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +/// +/// # Examples +/// +/// Use this interface to control the power output of some actuator +/// +/// ``` +/// extern crate embedded_hal as hal; +/// +/// use hal::prelude::*; +/// +/// fn main() { +/// let mut pwm: Pwm1 = { +/// // .. +/// # Pwm1 +/// }; +/// +/// pwm.set_period(1.khz()); +/// +/// let max_duty = pwm.get_max_duty(); +/// +/// // brightest LED +/// pwm.set_duty(Channel::_1, max_duty); +/// +/// // dimmer LED +/// pwm.set_duty(Channel::_2, max_duty / 4); +/// } +/// +/// # struct KiloHertz(u32); +/// # trait U32Ext { fn khz(self) -> KiloHertz; } +/// # impl U32Ext for u32 { fn khz(self) -> KiloHertz { KiloHertz(self) } } +/// # enum Channel { _1, _2 } +/// # struct Pwm1; +/// # impl hal::Pwm for Pwm1 { +/// # type Channel = Channel; +/// # type Time = KiloHertz; +/// # type Duty = u16; +/// # fn disable(&mut self, _: Channel) { unimplemented!() } +/// # fn enable(&mut self, _: Channel) { unimplemented!() } +/// # fn get_duty(&self, _: Channel) -> u16 { unimplemented!() } +/// # fn get_max_duty(&self) -> u16 { 0 } +/// # fn set_duty(&mut self, _: Channel, _: u16) {} +/// # fn get_period(&self) -> KiloHertz { unimplemented!() } +/// # fn set_period(&mut self, _: T) where T: Into {} +/// # } +/// ``` +#[cfg(feature = "unproven")] +// reason: pre-singletons API. The `PwmPin` trait seems more useful because it models independent +// PWM channels. Here a certain number of channels are multiplexed in a single implementer. +pub trait Pwm { + /// Enumeration of channels that can be used with this `Pwm` interface + /// + /// If your `Pwm` interface has no channels you can use the type `()` + /// here + type Channel; + + /// A time unit that can be converted into a human time unit (e.g. seconds) + type Time; + + /// Type for the `duty` methods + /// + /// The implementer is free to choose a float / percentage representation + /// (e.g. `0.0 .. 1.0`) or an integer representation (e.g. `0 .. 65535`) + type Duty; + + /// Disables a PWM `channel` + fn disable(&mut self, channel: Self::Channel); + + /// Enables a PWM `channel` + fn enable(&mut self, channel: Self::Channel); + + /// Returns the current PWM period + fn get_period(&self) -> Self::Time; + + /// Returns the current duty cycle + fn get_duty(&self, channel: Self::Channel) -> Self::Duty; + + /// Returns the maximum duty cycle value + fn get_max_duty(&self) -> Self::Duty; + + /// Sets a new duty cycle + fn set_duty(&mut self, channel: Self::Channel, duty: Self::Duty); + + /// Sets a new PWM period + fn set_period

(&mut self, period: P) + where + P: Into; +} + +/// A single PWM channel / pin +/// +/// See `Pwm` for details +pub trait PwmPin { + /// Type for the `duty` methods + /// + /// The implementer is free to choose a float / percentage representation + /// (e.g. `0.0 .. 1.0`) or an integer representation (e.g. `0 .. 65535`) + type Duty; + + /// Disables a PWM `channel` + fn disable(&mut self); + + /// Enables a PWM `channel` + fn enable(&mut self); + + /// Returns the current duty cycle + fn get_duty(&self) -> Self::Duty; + + /// Returns the maximum duty cycle value + fn get_max_duty(&self) -> Self::Duty; + + /// Sets a new duty cycle + fn set_duty(&mut self, duty: Self::Duty); +} + +/// Quadrature encoder interface +/// +/// *This trait is available if embedded-hal is built with the `"unproven"` feature.* +/// +/// # Examples +/// +/// You can use this interface to measure the speed of a motor +/// +/// ``` +/// extern crate embedded_hal as hal; +/// #[macro_use(block)] +/// extern crate nb; +/// +/// use hal::prelude::*; +/// +/// fn main() { +/// let mut qei: Qei1 = { +/// // .. +/// # Qei1 +/// }; +/// let mut timer: Timer6 = { +/// // .. +/// # Timer6 +/// }; +/// +/// +/// let before = qei.count(); +/// timer.start(1.s()); +/// block!(timer.wait()); +/// let after = qei.count(); +/// +/// let speed = after.wrapping_sub(before); +/// println!("Speed: {} pulses per second", speed); +/// } +/// +/// # extern crate void; +/// # use void::Void; +/// # struct Seconds(u32); +/// # trait U32Ext { fn s(self) -> Seconds; } +/// # impl U32Ext for u32 { fn s(self) -> Seconds { Seconds(self) } } +/// # struct Qei1; +/// # impl hal::Qei for Qei1 { +/// # type Count = u16; +/// # fn count(&self) -> u16 { 0 } +/// # fn direction(&self) -> ::hal::Direction { unimplemented!() } +/// # } +/// # struct Timer6; +/// # impl hal::timer::CountDown for Timer6 { +/// # type Time = Seconds; +/// # fn start(&mut self, _: T) where T: Into {} +/// # fn wait(&mut self) -> ::nb::Result<(), Void> { Ok(()) } +/// # } +/// ``` +#[cfg(feature = "unproven")] +// reason: needs to be re-evaluated in the new singletons world. At the very least this needs a +// reference implementation +pub trait Qei { + /// The type of the value returned by `count` + type Count; + + /// Returns the current pulse count of the encoder + fn count(&self) -> Self::Count; + + /// Returns the count direction + fn direction(&self) -> Direction; +} + +/// Count direction +/// +/// *This enumeration is available if embedded-hal is built with the `"unproven"` feature.* +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg(feature = "unproven")] +// reason: part of the unproven `Qei` interface +pub enum Direction { + /// 3, 2, 1 + Downcounting, + /// 1, 2, 3 + Upcounting, +} + +mod private { + pub trait Sealed {} +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/prelude.rs b/bitbox02-bt/vendor/embedded-hal/src/prelude.rs new file mode 100644 index 0000000..4d17043 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/prelude.rs @@ -0,0 +1,44 @@ +//! The prelude is a collection of all the traits in this crate +//! +//! The traits have been renamed to avoid collisions with other items when +//! performing a glob import. + +#[cfg(feature = "unproven")] +pub use adc::OneShot as _embedded_hal_adc_OneShot; +pub use blocking::delay::DelayMs as _embedded_hal_blocking_delay_DelayMs; +pub use blocking::delay::DelayUs as _embedded_hal_blocking_delay_DelayUs; +pub use blocking::i2c::{ + Read as _embedded_hal_blocking_i2c_Read, Write as _embedded_hal_blocking_i2c_Write, + WriteRead as _embedded_hal_blocking_i2c_WriteRead, +}; +#[cfg(feature = "unproven")] +pub use blocking::rng::Read as _embedded_hal_blocking_rng_Read; +pub use blocking::serial::Write as _embedded_hal_blocking_serial_Write; +pub use blocking::spi::{ + Transfer as _embedded_hal_blocking_spi_Transfer, Write as _embedded_hal_blocking_spi_Write, +}; +#[allow(deprecated)] +#[cfg(feature = "unproven")] +pub use digital::InputPin as _embedded_hal_digital_InputPin; +#[allow(deprecated)] +pub use digital::OutputPin as _embedded_hal_digital_OutputPin; +#[cfg(feature = "unproven")] +#[allow(deprecated)] +pub use digital::ToggleableOutputPin as _embedded_hal_digital_ToggleableOutputPin; +pub use serial::Read as _embedded_hal_serial_Read; +pub use serial::Write as _embedded_hal_serial_Write; +pub use spi::FullDuplex as _embedded_hal_spi_FullDuplex; +pub use timer::CountDown as _embedded_hal_timer_CountDown; +#[cfg(feature = "unproven")] +pub use watchdog::Watchdog as _embedded_hal_watchdog_Watchdog; +#[cfg(feature = "unproven")] +pub use watchdog::WatchdogDisable as _embedded_hal_watchdog_WatchdogDisable; +#[cfg(feature = "unproven")] +pub use watchdog::WatchdogEnable as _embedded_hal_watchdog_WatchdogEnable; +#[cfg(feature = "unproven")] +pub use Capture as _embedded_hal_Capture; +#[cfg(feature = "unproven")] +pub use Pwm as _embedded_hal_Pwm; +pub use PwmPin as _embedded_hal_PwmPin; +#[cfg(feature = "unproven")] +pub use Qei as _embedded_hal_Qei; diff --git a/bitbox02-bt/vendor/embedded-hal/src/serial.rs b/bitbox02-bt/vendor/embedded-hal/src/serial.rs new file mode 100644 index 0000000..484bb29 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/serial.rs @@ -0,0 +1,27 @@ +//! Serial interface + +use nb; + +/// Read half of a serial interface +/// +/// Some serial interfaces support different data sizes (8 bits, 9 bits, etc.); +/// This can be encoded in this trait via the `Word` type parameter. +pub trait Read { + /// Read error + type Error; + + /// Reads a single word from the serial interface + fn read(&mut self) -> nb::Result; +} + +/// Write half of a serial interface +pub trait Write { + /// Write error + type Error; + + /// Writes a single word to the serial interface + fn write(&mut self, word: Word) -> nb::Result<(), Self::Error>; + + /// Ensures that none of the previously written words are still buffered + fn flush(&mut self) -> nb::Result<(), Self::Error>; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/spi.rs b/bitbox02-bt/vendor/embedded-hal/src/spi.rs new file mode 100644 index 0000000..20d8538 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/spi.rs @@ -0,0 +1,78 @@ +//! Serial Peripheral Interface + +use nb; + +/// Full duplex (master mode) +/// +/// # Notes +/// +/// - It's the task of the user of this interface to manage the slave select lines +/// +/// - Due to how full duplex SPI works each `read` call must be preceded by a `send` call. +/// +/// - Some SPIs can work with 8-bit *and* 16-bit words. You can overload this trait with different +/// `Word` types to allow operation in both modes. +pub trait FullDuplex { + /// An enumeration of SPI errors + type Error; + + /// Reads the word stored in the shift register + /// + /// **NOTE** A word must be sent to the slave before attempting to call this + /// method. + fn read(&mut self) -> nb::Result; + + /// Sends a word to the slave + fn send(&mut self, word: Word) -> nb::Result<(), Self::Error>; +} + +/// Clock polarity +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Polarity { + /// Clock signal low when idle + IdleLow, + /// Clock signal high when idle + IdleHigh, +} + +/// Clock phase +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Phase { + /// Data in "captured" on the first clock transition + CaptureOnFirstTransition, + /// Data in "captured" on the second clock transition + CaptureOnSecondTransition, +} + +/// SPI mode +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Mode { + /// Clock polarity + pub polarity: Polarity, + /// Clock phase + pub phase: Phase, +} + +/// Helper for CPOL = 0, CPHA = 0 +pub const MODE_0: Mode = Mode { + polarity: Polarity::IdleLow, + phase: Phase::CaptureOnFirstTransition, +}; + +/// Helper for CPOL = 0, CPHA = 1 +pub const MODE_1: Mode = Mode { + polarity: Polarity::IdleLow, + phase: Phase::CaptureOnSecondTransition, +}; + +/// Helper for CPOL = 1, CPHA = 0 +pub const MODE_2: Mode = Mode { + polarity: Polarity::IdleHigh, + phase: Phase::CaptureOnFirstTransition, +}; + +/// Helper for CPOL = 1, CPHA = 1 +pub const MODE_3: Mode = Mode { + polarity: Polarity::IdleHigh, + phase: Phase::CaptureOnSecondTransition, +}; diff --git a/bitbox02-bt/vendor/embedded-hal/src/timer.rs b/bitbox02-bt/vendor/embedded-hal/src/timer.rs new file mode 100644 index 0000000..08ba276 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/timer.rs @@ -0,0 +1,95 @@ +//! Timers + +use nb; +use void::Void; + +/// A count down timer +/// +/// # Contract +/// +/// - `self.start(count); block!(self.wait());` MUST block for AT LEAST the time specified by +/// `count`. +/// +/// *Note* that the implementer doesn't necessarily have to be a *downcounting* timer; it could also +/// be an *upcounting* timer as long as the above contract is upheld. +/// +/// # Examples +/// +/// You can use this timer to create delays +/// +/// ``` +/// extern crate embedded_hal as hal; +/// #[macro_use(block)] +/// extern crate nb; +/// +/// use hal::prelude::*; +/// +/// fn main() { +/// let mut led: Led = { +/// // .. +/// # Led +/// }; +/// let mut timer: Timer6 = { +/// // .. +/// # Timer6 +/// }; +/// +/// Led.on(); +/// timer.start(1.s()); +/// block!(timer.wait()); // blocks for 1 second +/// Led.off(); +/// } +/// +/// # extern crate void; +/// # use void::Void; +/// # struct Seconds(u32); +/// # trait U32Ext { fn s(self) -> Seconds; } +/// # impl U32Ext for u32 { fn s(self) -> Seconds { Seconds(self) } } +/// # struct Led; +/// # impl Led { +/// # pub fn off(&mut self) {} +/// # pub fn on(&mut self) {} +/// # } +/// # struct Timer6; +/// # impl hal::timer::CountDown for Timer6 { +/// # type Time = Seconds; +/// # fn start(&mut self, _: T) where T: Into {} +/// # fn wait(&mut self) -> ::nb::Result<(), Void> { Ok(()) } +/// # } +/// ``` +pub trait CountDown { + /// The unit of time used by this timer + type Time; + + /// Starts a new count down + fn start(&mut self, count: T) + where + T: Into; + + /// Non-blockingly "waits" until the count down finishes + /// + /// # Contract + /// + /// - If `Self: Periodic`, the timer will start a new count down right after the last one + /// finishes. + /// - Otherwise the behavior of calling `wait` after the last call returned `Ok` is UNSPECIFIED. + /// Implementers are suggested to panic on this scenario to signal a programmer error. + fn wait(&mut self) -> nb::Result<(), Void>; +} + +/// Marker trait that indicates that a timer is periodic +pub trait Periodic {} + +/// Trait for cancelable countdowns. +pub trait Cancel: CountDown { + /// Error returned when a countdown can't be canceled. + type Error; + + /// Tries to cancel this countdown. + /// + /// # Errors + /// + /// An error will be returned if the countdown has already been canceled or was never started. + /// An error is also returned if the countdown is not `Periodic` and has already expired. + fn cancel(&mut self) -> Result<(), Self::Error>; +} diff --git a/bitbox02-bt/vendor/embedded-hal/src/watchdog.rs b/bitbox02-bt/vendor/embedded-hal/src/watchdog.rs new file mode 100644 index 0000000..41e76f6 --- /dev/null +++ b/bitbox02-bt/vendor/embedded-hal/src/watchdog.rs @@ -0,0 +1,30 @@ +//! Traits for interactions with a processors watchdog timer. + +/// Feeds an existing watchdog to ensure the processor isn't reset. Sometimes +/// commonly referred to as "kicking" or "refreshing". +#[cfg(feature = "unproven")] +pub trait Watchdog { + /// Triggers the watchdog. This must be done once the watchdog is started + /// to prevent the processor being reset. + fn feed(&mut self); +} + +/// Enables A watchdog timer to reset the processor if software is frozen or +/// stalled. +#[cfg(feature = "unproven")] +pub trait WatchdogEnable { + /// Unit of time used by the watchdog + type Time; + /// Starts the watchdog with a given period, typically once this is done + /// the watchdog needs to be kicked periodically or the processor is reset. + fn start(&mut self, period: T) + where + T: Into; +} + +/// Disables a running watchdog timer so the processor won't be reset. +#[cfg(feature = "unproven")] +pub trait WatchdogDisable { + /// Disables the watchdog + fn disable(&mut self); +} diff --git a/bitbox02-bt/vendor/envsubst/.cargo-checksum.json b/bitbox02-bt/vendor/envsubst/.cargo-checksum.json new file mode 100644 index 0000000..f6dfa26 --- /dev/null +++ b/bitbox02-bt/vendor/envsubst/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYRIGHT":"8a75413f2036b7154353aa115327423031417b49473ccc2fe2dd6426a45a2197","Cargo.toml":"421a6ef1838dcda7a1cfe2f5b9af7736ad183c1c70ea1a552c947c8613e0a398","LICENSE-APACHE-2.0":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"cb5aedb296c5246d1f22e9099f925a65146f9f0d6b4eebba97fd27a6cdbbab2d","README.md":"6fc9eb03156baaeaf7a803f22ec828b7afa6bae57c6600d282e73ab6e6052748","src/lib.rs":"0a9ffccea02147b236cbc33c0236326d8f9637b1d3bcc68818a86019a9c70dce"},"package":"cf2f29f6ee674d1229e5715dfc7e24f14395a20d66949e36032de68b31542643"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/envsubst/COPYRIGHT b/bitbox02-bt/vendor/envsubst/COPYRIGHT new file mode 100644 index 0000000..d96cd50 --- /dev/null +++ b/bitbox02-bt/vendor/envsubst/COPYRIGHT @@ -0,0 +1,7 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: envsubst +Source: https://github.com/coreos/envsubst-rs + +Files: * +Copyright: 2019-2022, Project contributors +License: MIT or Apache-2.0 diff --git a/bitbox02-bt/vendor/envsubst/Cargo.toml b/bitbox02-bt/vendor/envsubst/Cargo.toml new file mode 100644 index 0000000..906cdf6 --- /dev/null +++ b/bitbox02-bt/vendor/envsubst/Cargo.toml @@ -0,0 +1,36 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "envsubst" +version = "0.2.1" +authors = ["Luca Bruno "] +exclude = [".gitignore"] +description = "Variables substitution" +readme = "README.md" +keywords = [ + "envsubst", + "varsubst", +] +license = "MIT/Apache-2.0" +repository = "https://github.com/coreos/envsubst-rs" + +[package.metadata.release] +sign-commit = true +publish = false +push = false +pre-release-commit-message = "cargo: envsubst release {{version}}" +post-release-commit-message = "cargo: development version bump" +tag-message = "envsubst {{version}}" + +[dependencies.thiserror] +version = "^1.0" diff --git a/bitbox02-bt/vendor/envsubst/LICENSE-APACHE-2.0 b/bitbox02-bt/vendor/envsubst/LICENSE-APACHE-2.0 new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/bitbox02-bt/vendor/envsubst/LICENSE-APACHE-2.0 @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/bitbox02-bt/vendor/envsubst/LICENSE-MIT b/bitbox02-bt/vendor/envsubst/LICENSE-MIT new file mode 100644 index 0000000..c9b44cb --- /dev/null +++ b/bitbox02-bt/vendor/envsubst/LICENSE-MIT @@ -0,0 +1,18 @@ +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/envsubst/README.md b/bitbox02-bt/vendor/envsubst/README.md new file mode 100644 index 0000000..5b0a141 --- /dev/null +++ b/bitbox02-bt/vendor/envsubst/README.md @@ -0,0 +1,25 @@ +# envsubst + +[![crates.io](https://img.shields.io/crates/v/envsubst.svg)](https://crates.io/crates/envsubst) +[![Documentation](https://docs.rs/envsubst/badge.svg)](https://docs.rs/envsubst) + +A simple Rust library for variables substitution. + +This library provide helper functions for string manipulation, +taking values from a context **env**ironment map and **subst**ituting +all matching placeholders. + +Its name and logic is similar to the [`envsubst`] GNU utility, but +this only supports braces-delimited variables (i.e. `${foo}`) and +takes replacement values from an explicit map of variables. + +[`envsubst`]: https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html + +## License + +Licensed under either of + + * MIT license - + * Apache License, Version 2.0 - + +at your option. diff --git a/bitbox02-bt/vendor/envsubst/src/lib.rs b/bitbox02-bt/vendor/envsubst/src/lib.rs new file mode 100644 index 0000000..7364de3 --- /dev/null +++ b/bitbox02-bt/vendor/envsubst/src/lib.rs @@ -0,0 +1,171 @@ +//! Variables substitution in string templates. +//! +//! This library provide helper functions for string manipulation, +//! taking values from a context **env**ironment map and **subst**ituting +//! all matching placeholders. +//! +//! Its name and logic is similar to the [`envsubst`] GNU utility, but +//! this only supports braces-delimited variables (i.e. `${foo}`) and +//! takes replacement values from an explicit map of variables. +//! +//! [`envsubst`]: https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html +//! +//! ## Example +//! +//! ```rust +//! let base_url = "${protocol}://${hostname}/${endpoint}"; +//! assert!(envsubst::is_templated(base_url)); +//! +//! let mut context = std::collections::HashMap::new(); +//! context.insert("protocol".to_string(), "https".to_string()); +//! context.insert("hostname".to_string(), "example.com".to_string()); +//! context.insert("endpoint".to_string(), "login".to_string()); +//! assert!(envsubst::validate_vars(&context).is_ok()); +//! +//! let final_url = envsubst::substitute(base_url, &context).unwrap(); +//! assert!(!envsubst::is_templated(&final_url)); +//! assert_eq!(final_url, "https://example.com/login"); +//! ``` + +#![allow(clippy::implicit_hasher)] + +use std::collections::HashMap; + +/// Library errors. +#[derive(thiserror::Error, Debug)] +#[error("envsubst error: {0}")] +pub struct Error(String); + +/// Substitute variables in a template string. +/// +/// Given an input string `template`, replace tokens of the form `${foo}` with +/// values provided in `variables`. +pub fn substitute(template: T, variables: &HashMap) -> Result +where + T: Into, +{ + let mut output = template.into(); + if variables.is_empty() { + return Ok(output); + } + + for (k, v) in variables { + validate(k, "key")?; + validate(v, "value")?; + + let from = format!("${{{}}}", k); + output = output.replace(&from, &v) + } + + Ok(output) +} + +/// Check whether input string contains templated variables. +pub fn is_templated(input: S) -> bool +where + S: AsRef, +{ + let start = input.as_ref().find("${"); + let end = input.as_ref().find('}'); + + match (start, end) { + (Some(s), Some(e)) => s < e, + _ => false, + } +} + +/// Validate variables for substitution. +/// +/// This check whether substitution variables are valid. In order to make +/// substitution deterministic, the following characters are not allowed +/// within variables names nor values: `$`, `{`, `}`. +pub fn validate_vars(variables: &HashMap) -> Result<(), Error> { + for (k, v) in variables { + validate(k, "key")?; + validate(v, "value")?; + } + Ok(()) +} + +/// Check whether `value` contains invalid characters. +fn validate(value: S, kind: &str) -> Result<(), Error> +where + S: AsRef, +{ + let forbidden = &["$", "{", "}"]; + for c in forbidden { + if value.as_ref().contains(c) { + let err_msg = format!( + "variable {} '{}' contains forbidden character '{}'", + kind, + value.as_ref(), + c + ); + return Err(Error(err_msg)); + }; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn basic_subst() { + let template = "foo ${VAR} bar"; + let mut env = HashMap::new(); + env.insert("VAR".to_string(), "var".to_string()); + + let out = substitute(template, &env).unwrap(); + let expected = "foo var bar"; + assert_eq!(out, expected); + } + + #[test] + fn template_check() { + let plain = "foo"; + assert!(!is_templated(plain)); + + let template = "foo ${VAR} bar"; + assert!(is_templated(template)); + + let starting = "foo${"; + assert!(!is_templated(starting)); + + let ending = "foo}"; + assert!(!is_templated(ending)); + } + + #[test] + fn basic_empty_vars() { + let template = "foo ${VAR} bar"; + let env = HashMap::new(); + + let out = substitute(template, &env).unwrap(); + assert_eq!(out, template); + } + + #[test] + fn dollar_bracket() { + let template = "foo ${ bar"; + let mut env = HashMap::new(); + env.insert("VAR".to_string(), "var".to_string()); + + let out = substitute(template, &env).unwrap(); + assert_eq!(out, template); + } + + #[test] + fn invalid_vars() { + let template = "foo ${VAR} bar"; + let mut env = HashMap::new(); + env.insert("${VAR}".to_string(), "var".to_string()); + + substitute(template, &env).unwrap_err(); + + let mut env = HashMap::new(); + env.insert("VAR".to_string(), "${VAR}".to_string()); + } +} diff --git a/bitbox02-bt/vendor/equivalent/.cargo-checksum.json b/bitbox02-bt/vendor/equivalent/.cargo-checksum.json new file mode 100644 index 0000000..18cb3e7 --- /dev/null +++ b/bitbox02-bt/vendor/equivalent/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"87d7f4d5b05a14966f11c5e40940ca2687a3ae8e751bb15d7f537ae95310ab7b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7365cc8878a1d7ce155a58c4ca09c3d7a6be413efa5334a80ea842912b669349","README.md":"bbcbb8419f9bb01a51d3d5e808fe35651d423014992a72be3e7acd518485f190","src/lib.rs":"1dd84363f561b30b1da713486c6b583900353e62c569d7ba1dd84eb2c04f1a14"},"package":"5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/equivalent/Cargo.toml b/bitbox02-bt/vendor/equivalent/Cargo.toml new file mode 100644 index 0000000..925d53e --- /dev/null +++ b/bitbox02-bt/vendor/equivalent/Cargo.toml @@ -0,0 +1,27 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +rust-version = "1.6" +name = "equivalent" +version = "1.0.1" +description = "Traits for key comparison in maps." +readme = "README.md" +keywords = [ + "hashmap", + "no_std", +] +categories = [ + "data-structures", + "no-std", +] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/cuviper/equivalent" diff --git a/bitbox02-bt/vendor/equivalent/LICENSE-APACHE b/bitbox02-bt/vendor/equivalent/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/equivalent/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/equivalent/LICENSE-MIT b/bitbox02-bt/vendor/equivalent/LICENSE-MIT new file mode 100644 index 0000000..5ac40da --- /dev/null +++ b/bitbox02-bt/vendor/equivalent/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016--2023 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/equivalent/README.md b/bitbox02-bt/vendor/equivalent/README.md new file mode 100644 index 0000000..8ff7e24 --- /dev/null +++ b/bitbox02-bt/vendor/equivalent/README.md @@ -0,0 +1,25 @@ +# Equivalent + +[![crates.io](https://img.shields.io/crates/v/equivalent.svg)](https://crates.io/crates/equivalent) +[![docs](https://docs.rs/equivalent/badge.svg)](https://docs.rs/equivalent) + +`Equivalent` and `Comparable` are Rust traits for key comparison in maps. + +These may be used in the implementation of maps where the lookup type `Q` +may be different than the stored key type `K`. + +* `Q: Equivalent` checks for equality, similar to the `HashMap` + constraint `K: Borrow, Q: Eq`. +* `Q: Comparable` checks the ordering, similar to the `BTreeMap` + constraint `K: Borrow, Q: Ord`. + +These traits are not used by the maps in the standard library, but they may +add more flexibility in third-party map implementations, especially in +situations where a strict `K: Borrow` relationship is not available. + +## License + +Equivalent is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). See [LICENSE-APACHE](LICENSE-APACHE) and +[LICENSE-MIT](LICENSE-MIT) for details. Opening a pull request is +assumed to signal agreement with these licensing terms. diff --git a/bitbox02-bt/vendor/equivalent/src/lib.rs b/bitbox02-bt/vendor/equivalent/src/lib.rs new file mode 100644 index 0000000..09ba58d --- /dev/null +++ b/bitbox02-bt/vendor/equivalent/src/lib.rs @@ -0,0 +1,113 @@ +//! [`Equivalent`] and [`Comparable`] are traits for key comparison in maps. +//! +//! These may be used in the implementation of maps where the lookup type `Q` +//! may be different than the stored key type `K`. +//! +//! * `Q: Equivalent` checks for equality, similar to the `HashMap` +//! constraint `K: Borrow, Q: Eq`. +//! * `Q: Comparable` checks the ordering, similar to the `BTreeMap` +//! constraint `K: Borrow, Q: Ord`. +//! +//! These traits are not used by the maps in the standard library, but they may +//! add more flexibility in third-party map implementations, especially in +//! situations where a strict `K: Borrow` relationship is not available. +//! +//! # Examples +//! +//! ``` +//! use equivalent::*; +//! use std::cmp::Ordering; +//! +//! pub struct Pair(pub A, pub B); +//! +//! impl<'a, A: ?Sized, B: ?Sized, C, D> Equivalent<(C, D)> for Pair<&'a A, &'a B> +//! where +//! A: Equivalent, +//! B: Equivalent, +//! { +//! fn equivalent(&self, key: &(C, D)) -> bool { +//! self.0.equivalent(&key.0) && self.1.equivalent(&key.1) +//! } +//! } +//! +//! impl<'a, A: ?Sized, B: ?Sized, C, D> Comparable<(C, D)> for Pair<&'a A, &'a B> +//! where +//! A: Comparable, +//! B: Comparable, +//! { +//! fn compare(&self, key: &(C, D)) -> Ordering { +//! match self.0.compare(&key.0) { +//! Ordering::Equal => self.1.compare(&key.1), +//! not_equal => not_equal, +//! } +//! } +//! } +//! +//! fn main() { +//! let key = (String::from("foo"), String::from("bar")); +//! let q1 = Pair("foo", "bar"); +//! let q2 = Pair("boo", "bar"); +//! let q3 = Pair("foo", "baz"); +//! +//! assert!(q1.equivalent(&key)); +//! assert!(!q2.equivalent(&key)); +//! assert!(!q3.equivalent(&key)); +//! +//! assert_eq!(q1.compare(&key), Ordering::Equal); +//! assert_eq!(q2.compare(&key), Ordering::Less); +//! assert_eq!(q3.compare(&key), Ordering::Greater); +//! } +//! ``` + +#![no_std] + +use core::borrow::Borrow; +use core::cmp::Ordering; + +/// Key equivalence trait. +/// +/// This trait allows hash table lookup to be customized. It has one blanket +/// implementation that uses the regular solution with `Borrow` and `Eq`, just +/// like `HashMap` does, so that you can pass `&str` to lookup into a map with +/// `String` keys and so on. +/// +/// # Contract +/// +/// The implementor **must** hash like `K`, if it is hashable. +pub trait Equivalent { + /// Compare self to `key` and return `true` if they are equal. + fn equivalent(&self, key: &K) -> bool; +} + +impl Equivalent for Q +where + Q: Eq, + K: Borrow, +{ + #[inline] + fn equivalent(&self, key: &K) -> bool { + PartialEq::eq(self, key.borrow()) + } +} + +/// Key ordering trait. +/// +/// This trait allows ordered map lookup to be customized. It has one blanket +/// implementation that uses the regular solution with `Borrow` and `Ord`, just +/// like `BTreeMap` does, so that you can pass `&str` to lookup into a map with +/// `String` keys and so on. +pub trait Comparable: Equivalent { + /// Compare self to `key` and return their ordering. + fn compare(&self, key: &K) -> Ordering; +} + +impl Comparable for Q +where + Q: Ord, + K: Borrow, +{ + #[inline] + fn compare(&self, key: &K) -> Ordering { + Ord::cmp(self, key.borrow()) + } +} diff --git a/bitbox02-bt/vendor/grounded/.cargo-checksum.json b/bitbox02-bt/vendor/grounded/.cargo-checksum.json new file mode 100644 index 0000000..12ccbca --- /dev/null +++ b/bitbox02-bt/vendor/grounded/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"75d048b8bbab714d8d5805256112796fdf5f7662cb11b8a88a4fac43711bf571","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"177540cad091a40e8071db310bc3b6115c4e329a92a234609b60c154b008a888","README.md":"34e8e5fa08d2735ad5dda6084c09978c3978e5886db0cdb370d4767080c39abb","src/alloc_single.rs":"40de300a511817397517ef61e1a7efcea5537756d032c1c1621dac9f44d3a1aa","src/const_init.rs":"ee73477ba827e16f67bd7e581da438eb64145ad907919e4f4508de7a27904800","src/lib.rs":"7cc59f73fe1f3aeb901f6f64fee6d6e1ff05f6c371f0ee3af3c1665bf59f96b9","src/uninit.rs":"fd67733928bf0102f04ee4e934973cf94c20238612803fdfc3aa38d5360e5155"},"package":"917d82402c7eb9755fdd87d52117701dae9e413a6abb309fac2a13af693b6080"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/grounded/Cargo.toml b/bitbox02-bt/vendor/grounded/Cargo.toml new file mode 100644 index 0000000..3917086 --- /dev/null +++ b/bitbox02-bt/vendor/grounded/Cargo.toml @@ -0,0 +1,37 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "grounded" +version = "0.2.0" +authors = ["James Munns "] +description = "A toolkit for managing unsafe statics" +documentation = "https://docs.rs/grounded/" +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/jamesmunns/grounded" + +[package.metadata.docs.rs] +features = ["cas"] +rustdoc-args = [ + "--cfg", + "doc_cfg", +] + +[dependencies.portable-atomic] +version = "1.3" +default-features = false + +[features] +cas = ["portable-atomic/require-cas"] +critical-section = ["portable-atomic/critical-section"] +default = [] diff --git a/bitbox02-bt/vendor/grounded/LICENSE-APACHE b/bitbox02-bt/vendor/grounded/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/grounded/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/grounded/LICENSE-MIT b/bitbox02-bt/vendor/grounded/LICENSE-MIT new file mode 100644 index 0000000..ee10cca --- /dev/null +++ b/bitbox02-bt/vendor/grounded/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2019 Anthony James Munns + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/grounded/README.md b/bitbox02-bt/vendor/grounded/README.md new file mode 100644 index 0000000..a63d92f --- /dev/null +++ b/bitbox02-bt/vendor/grounded/README.md @@ -0,0 +1,23 @@ +# Grounded + +Building blocks for handling potentially unsafe statics. + +This crate aims to provide useful and sound components that serve as building blocks for `static` datatypes that are common, and often necessary, in embedded systems. + +In some cases, fully safe methods and types will be provided. In other cases, "harm reduction" tools will be provided to make it easier to build sound abstractions and avoid undefined behavior. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/bitbox02-bt/vendor/grounded/src/alloc_single.rs b/bitbox02-bt/vendor/grounded/src/alloc_single.rs new file mode 100644 index 0000000..a9c690b --- /dev/null +++ b/bitbox02-bt/vendor/grounded/src/alloc_single.rs @@ -0,0 +1,166 @@ +//! Utilities for allocating a single item, using a box-like smart pointer + +use core::{ + ops::{Deref, DerefMut}, + sync::atomic::Ordering, +}; +use portable_atomic::AtomicBool; + +use crate::{const_init::ConstInit, uninit::GroundedCell}; + +/// AllocSingle is our one-element allocator pool +/// +/// If your type implements [ConstInit], consider using +/// [AllocSingle::alloc_const_val] instead of [AllocSingle::alloc] +/// to avoid unnecessary stack usage. +/// +/// This does require use of CAS atomics. You must enable the `cas` +/// feature, and if your target does not have native atomic CAS, you +/// must also enable the `critical-section` feature. +/// +/// ```rust +/// use grounded::alloc_single::AllocSingle; +/// +/// static SINGLE: AllocSingle<[u8; 256]> = AllocSingle::new(); +/// +/// // alloc a single item +/// let mut s1 = SINGLE.alloc([4; 256]).unwrap(); +/// s1.iter().for_each(|b| assert_eq!(*b, 4)); +/// +/// // we can't alloc while `s1` is still live +/// assert!(SINGLE.alloc([5; 256]).is_none()); +/// +/// // now drop it +/// drop(s1); +/// +/// // and we can alloc again +/// let mut s2 = SINGLE.alloc([7; 256]).unwrap(); +/// s2.iter().for_each(|b| assert_eq!(*b, 7)); +/// ``` +pub struct AllocSingle { + taken: AtomicBool, + storage: GroundedCell, +} + +impl AllocSingle { + /// Create a new, uninitalized, single-element allocation pool + pub const fn new() -> Self { + Self { + taken: AtomicBool::new(false), + storage: GroundedCell::uninit(), + } + } + + /// Attempts to allocate a single item. Returns None and + /// discards `t` if an allocation is already live. + #[inline] + pub fn alloc(&self, t: T) -> Option> { + // Set taken, and if it was already taken before, we can't + // allocate + if self.taken.swap(true, Ordering::AcqRel) { + // already taken + return None; + } + let new = SingleBox { single: self }; + // Initialize by moving t into the storage + unsafe { + new.as_ptr().write(t); + } + Some(new) + } +} + +impl AllocSingle { + /// Attempts to allocate a single item, using `ConstInit::VAL` as + /// the initializer. Returns None if the item is already allocated + pub fn alloc_const_val(&self) -> Option> { + // Set taken, and if it was already taken before, we can't + // allocate + if self.taken.swap(true, Ordering::AcqRel) { + // already taken + return None; + } + let new = SingleBox { single: self }; + // Initialize by writing t into the storage + unsafe { + new.as_ptr().write(T::VAL); + } + Some(new) + } +} + +pub struct SingleBox<'a, T> { + single: &'a AllocSingle, +} + +impl<'a, T> SingleBox<'a, T> { + fn as_ptr(&self) -> *mut T { + self.single.storage.get() + } +} + +impl<'a, T> Drop for SingleBox<'a, T> { + fn drop(&mut self) { + // When we drop the SingleBox, mark the AllocSingle as available again + unsafe { self.as_ptr().drop_in_place() } + self.single.taken.store(false, Ordering::Release); + } +} + +impl<'a, T> Deref for SingleBox<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*self.as_ptr() } + } +} + +impl<'a, T> DerefMut for SingleBox<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { &mut *self.as_ptr() } + } +} + +#[cfg(test)] +pub mod test { + use super::AllocSingle; + use crate::const_init::ConstInit; + use core::ops::Deref; + + #[derive(Debug)] + struct Demo([u8; 512]); + + impl ConstInit for Demo { + const VAL: Self = Demo([44u8; 512]); + } + + #[test] + fn smoke() { + static SINGLE: AllocSingle<[u8; 1024]> = AllocSingle::new(); + static SINGLE_DEMO: AllocSingle = AllocSingle::new(); + + { + let buf = [0xAF; 1024]; + let mut bx = SINGLE.alloc(buf).unwrap(); + println!("{:?}", bx.as_slice()); + bx.iter_mut().for_each(|b| *b = 123); + println!("{:?}", bx.as_slice()); + + // Second alloc fails + let buf2 = [0x01; 1024]; + assert!(SINGLE.alloc(buf2).is_none()); + } + + // bx is dropped because we left scope, which means we can + // alloc again + let buf3 = [0x42; 1024]; + let mut bx2 = SINGLE.alloc(buf3).unwrap(); + println!("{:?}", bx2.as_slice()); + bx2.iter_mut().for_each(|b| *b = 231); + println!("{:?}", bx2.as_slice()); + + // look ma no stack + let bx3 = SINGLE_DEMO.alloc_const_val().unwrap(); + println!("{:?}", bx3.deref()); + } +} diff --git a/bitbox02-bt/vendor/grounded/src/const_init.rs b/bitbox02-bt/vendor/grounded/src/const_init.rs new file mode 100644 index 0000000..8d8a2f6 --- /dev/null +++ b/bitbox02-bt/vendor/grounded/src/const_init.rs @@ -0,0 +1,50 @@ +//! Const Init +//! +//! A trait that is like `Default`, but const + +/// A trait that is like `Default`, but const +pub trait ConstInit { + /// The constant default value + const VAL: Self; +} + +// Here's some impls that roughly match the default +// value of these types + +macro_rules! impl_const_init_for { + ($(($tyname:ty, $val:expr),)+) => { + $( + impl ConstInit for $tyname { + const VAL: Self = $val; + } + )+ + }; +} + +impl_const_init_for! { + (u8, 0), + (u16, 0), + (u32, 0), + (u64, 0), + (u128, 0), + (i8, 0), + (i16, 0), + (i32, 0), + (i64, 0), + (i128, 0), + (f32, 0.0), + (f64, 0.0), + (bool, false), + ((), ()), +} + +impl ConstInit for [T; N] +where + T: ConstInit, +{ + const VAL: Self = [T::VAL; N]; +} + +impl ConstInit for Option { + const VAL: Self = None; +} diff --git a/bitbox02-bt/vendor/grounded/src/lib.rs b/bitbox02-bt/vendor/grounded/src/lib.rs new file mode 100644 index 0000000..1ced464 --- /dev/null +++ b/bitbox02-bt/vendor/grounded/src/lib.rs @@ -0,0 +1,8 @@ +#![cfg_attr(not(test), no_std)] +#![doc = include_str!("../README.md")] + +pub mod const_init; +pub mod uninit; + +#[cfg(feature = "cas")] +pub mod alloc_single; diff --git a/bitbox02-bt/vendor/grounded/src/uninit.rs b/bitbox02-bt/vendor/grounded/src/uninit.rs new file mode 100644 index 0000000..68965bf --- /dev/null +++ b/bitbox02-bt/vendor/grounded/src/uninit.rs @@ -0,0 +1,317 @@ +//! Helpers for dealing with statics that are (potentially) uninitialized at the +//! start of a program. + +use core::{cell::UnsafeCell, mem::MaybeUninit}; + +use crate::const_init::ConstInit; + +/// ## GroundedCell +/// +/// [GroundedCell] is a type that contains a single `T`. The contained T is wrapped +/// with: +/// +/// * An [UnsafeCell] - as synchronization *must* be provided by the wrapping user +/// * A [MaybeUninit] - as the contents will not be initialized at program start. +/// +/// This type is intended to be used as a building block for other types, such as +/// runtime initialized constants, data within uninitialized memory/linker sections, +/// or similar. +/// +/// This type may be used to provide inner mutability, when accessed through the +/// [GroundedCell::get()] interface. +/// +/// [GroundedCell] is also `#[repr(transparent)], as are `UnsafeCell` and `MaybeUninit`, +/// which means that it will have the same layout and alignment as `T`. +#[repr(transparent)] +pub struct GroundedCell { + inner: UnsafeCell>, +} + +unsafe impl Sync for GroundedCell {} + +impl GroundedCell { + /// Create a new GroundedCell with the cell initialized with + /// the value of [ConstInit::VAL]. + /// + /// ```rust + /// use grounded::uninit::GroundedCell; + /// + /// static EXAMPLE: GroundedCell<[u8; 1024]> = GroundedCell::const_init(); + /// ``` + pub const fn const_init() -> Self { + Self { + inner: UnsafeCell::new(MaybeUninit::new(T::VAL)), + } + } +} + +impl GroundedCell { + /// Create an uninitialized `GroundedCell`. + /// + /// ```rust + /// use grounded::uninit::GroundedCell; + /// + /// static EXAMPLE: GroundedCell = GroundedCell::uninit(); + /// ``` + pub const fn uninit() -> Self { + Self { + inner: UnsafeCell::new(MaybeUninit::uninit()), + } + } + + /// Obtain a mutable pointer to the contained T. + /// + /// No claims are made on the validity of the T (it may be invalid or uninitialized), + /// and the caller is required to guarantee synchronization of access, e.g. guaranteeing + /// that access is shared XOR mutable for the duration of any references created from this + /// pointer. + /// + /// ```rust + /// use grounded::uninit::GroundedCell; + /// static EXAMPLE: GroundedCell = GroundedCell::uninit(); + /// + /// let ptr: *mut u32 = EXAMPLE.get(); + /// assert_ne!(core::ptr::null_mut(), ptr); + /// ``` + pub fn get(&self) -> *mut T { + let mu_ptr: *mut MaybeUninit = self.inner.get(); + let t_ptr: *mut T = mu_ptr.cast::(); + t_ptr + } +} + +/// ## GroundedArrayCell +/// +/// [GroundedArrayCell] is a type that contains a contiguous array of `[T; N]`. +/// The contained [T; N] is wrapped with: +/// +/// * An [UnsafeCell] - as synchronization *must* be provided by the wrapping user +/// * A [MaybeUninit] - as the contents will not be initialized at program start. +/// +/// This type is intended to be used as a building block for other types, such as +/// runtime initialized constants, data within uninitialized memory/linker sections, +/// or similar. +/// +/// This type may be used to provide inner mutability, when accessed through the +/// [GroundedArrayCell::get_ptr_len()] interface. +/// +/// [GroundedArrayCell] is also `#[repr(transparent)], as are `UnsafeCell` and `MaybeUninit`, +/// which means that it will have the same layout and alignment as `[T; N]`. +#[repr(transparent)] +pub struct GroundedArrayCell { + inner: UnsafeCell>, +} + +unsafe impl Sync for GroundedArrayCell {} + +impl GroundedArrayCell { + /// Create a new GroundedArrayCell with all cells initialized with + /// the value of [ConstInit::VAL]. + /// + /// If your type's implementation of [ConstInit] happens to be all zeroes, like it + /// is for many integer and boolean primitives, it is likely your static will end + /// up in `.bss`. + /// + /// ```rust + /// use grounded::uninit::GroundedArrayCell; + /// + /// static EXAMPLE: GroundedArrayCell = GroundedArrayCell::const_init(); + /// ``` + pub const fn const_init() -> Self { + Self { + inner: UnsafeCell::new(MaybeUninit::new(<[T; N] as ConstInit>::VAL)), + } + } +} + +impl GroundedArrayCell { + /// Create an uninitialized `GroundedArrayCell`. + /// + /// ```rust + /// use grounded::uninit::GroundedArrayCell; + /// + /// static EXAMPLE: GroundedArrayCell = GroundedArrayCell::uninit(); + /// ``` + pub const fn uninit() -> Self { + Self { + inner: UnsafeCell::new(MaybeUninit::uninit()), + } + } + + /// Initialize each element from the provided value, if `T: Copy`. + /// + /// ## Safety + /// + /// The caller must ensure that no other access is made to the data contained within this + /// cell for the duration of this function + #[inline] + pub unsafe fn initialize_all_copied(&self, val: T) + where + T: Copy, + { + let (mut ptr, len) = self.get_ptr_len(); + let end = ptr.add(len); + while ptr != end { + ptr.write(val); + ptr = ptr.add(1); + } + } + + /// Initialize each item, using a provided closure on a per-element basis + /// + /// ## Safety + /// + /// The caller must ensure that no other access is made to the data contained within this + /// cell for the duration of this function + #[inline] + pub unsafe fn initialize_all_with T>(&self, mut f: F) { + let (mut ptr, len) = self.get_ptr_len(); + let end = ptr.add(len); + while ptr != end { + ptr.write(f()); + ptr = ptr.add(1); + } + } + + /// Obtain a mutable starting pointer to the contained [T; N]. + /// + /// No claims are made on the validity of the [T; N] (they may be partially or wholly + /// invalid or uninitialized), and the caller is required to guarantee synchronization of + /// access, e.g. guaranteeing that access is shared XOR mutable for the duration of any + /// references (including slices) created from this pointer. + /// + /// ```rust + /// use grounded::uninit::GroundedArrayCell; + /// static EXAMPLE: GroundedArrayCell = GroundedArrayCell::uninit(); + /// + /// let ptr: *mut u8 = EXAMPLE.as_mut_ptr(); + /// assert_ne!(core::ptr::null_mut(), ptr); + /// ``` + #[inline] + pub fn as_mut_ptr(&self) -> *mut T { + let mu_ptr: *mut MaybeUninit<[T; N]> = self.inner.get(); + let arr_ptr: *mut [T; N] = mu_ptr.cast::<[T; N]>(); + let t_ptr: *mut T = arr_ptr.cast::(); + t_ptr + } + + /// Obtain a mutable starting pointer and length to the contained [T; N]. + /// + /// No claims are made on the validity of the [T; N] (they may be partially or wholly + /// invalid or uninitialized), and the caller is required to guarantee synchronization of + /// access, e.g. guaranteeing that access is shared XOR mutable for the duration of any + /// references (including slices) created from this pointer. + /// + /// ```rust + /// use grounded::uninit::GroundedArrayCell; + /// static EXAMPLE: GroundedArrayCell = GroundedArrayCell::uninit(); + /// + /// let (ptr, len): (*mut u8, usize) = EXAMPLE.get_ptr_len(); + /// assert_ne!(core::ptr::null_mut(), ptr); + /// assert_eq!(len, 128); + /// ``` + /// + /// ## NOTE + /// + /// This method is suggested to only be used for actions such as initializing the entire + /// range. If you are building a data structure that provides partial access safely, such + /// as a channel, bip-buffer, or similar, consider using one of the following methods, which + /// can help avoid cases where strict provenance is invalidated by creation of an aliasing + /// slice: + /// + /// * For getting a single element: + /// * [Self::get_element_unchecked()] + /// * [Self::get_element_mut_unchecked()] + /// * For getting a subslice: + /// * [Self::get_subslice_unchecked()] + /// * [Self::get_subslice_mut_unchecked()] + #[inline] + pub fn get_ptr_len(&self) -> (*mut T, usize) { + (self.as_mut_ptr(), N) + } + + /// Obtain a reference to a single element, which can be thought of as `&data[offset]`. + /// + /// The reference is created **without** creating the entire slice this cell represents. + /// This is important, if a mutable reference of a disjoint region is currently live. + /// + /// ## Safety + /// + /// The caller **must** ensure all of the following: + /// + /// * The selected element has been initialized with a valid value prior to calling + /// this function + /// * No `&mut` slices or references may overlap the produced reference for the duration the reference is live + /// * No modifications (even via pointers) are made to to the element pointed to + /// while the reference is live + /// * `offset` is < N + #[inline] + pub unsafe fn get_element_unchecked(&self, offset: usize) -> &'_ T { + &*self.as_mut_ptr().add(offset) + } + + /// Obtain a mutable reference to a single element, which can be thought of as `&mut data[offset]`. + /// + /// The reference is created **without** creating the entire slice this cell represents. + /// This is important, if a mutable reference of a disjoint region is currently live. + /// + /// ## Safety + /// + /// The caller **must** ensure all of the following: + /// + /// * The selected element has been initialized with a valid value prior to calling + /// this function + /// * No slices or references of any kind may overlap the produced reference for the duration + /// the reference is live + /// * No modifications (even via pointers) are made to to the element pointed to + /// while the reference is live + /// * `offset` is < N + #[allow(clippy::mut_from_ref)] + #[inline] + pub unsafe fn get_element_mut_unchecked(&self, offset: usize) -> &mut T { + &mut *self.as_mut_ptr().add(offset) + } + + /// Obtain a subslice starting at `offset`, of length `len`, which + /// can be thought of as `&data[offset..][..len]`. + /// + /// The subslice is created **without** creating the entire slice this cell represents. + /// This is important, if a mutable reference of a disjoint region is currently live. + /// + /// ## Safety + /// + /// The caller **must** ensure all of the following: + /// + /// * All elements in this region have been initialized with a valid value prior to calling + /// this function + /// * No `&mut` slices may overlap the produced slice for the duration the slice is live + /// * No modifications (even via pointers) are made to data within the range of this slice + /// while the slice is live + /// * `offset` and `offset + len` are <= N + #[inline] + pub unsafe fn get_subslice_unchecked(&self, offset: usize, len: usize) -> &'_ [T] { + core::slice::from_raw_parts(self.as_mut_ptr().add(offset), len) + } + + /// Obtain a mutable subslice starting at `offset`, of length `len`, which + /// can be thought of as `&mut data[offset..][..len]`. + /// + /// The subslice is created **without** creating the entire slice this cell represents. + /// This is important, if ANY reference of a disjoint region is currently live. + /// + /// ## Safety + /// + /// The caller **must** ensure all of the following: + /// + /// * All elements in this region have been initialized with a valid value prior to calling + /// this function + /// * No ``&` or &mut` slices may overlap the produced slice for the duration the slice is live + /// * No modifications (even via pointers) are made to data within the range of this slice + /// while the slice is live + /// * `offset` and `offset + len` are <= N + #[allow(clippy::mut_from_ref)] + #[inline] + pub unsafe fn get_subslice_mut_unchecked(&self, offset: usize, len: usize) -> &'_ mut [T] { + core::slice::from_raw_parts_mut(self.as_mut_ptr().add(offset), len) + } +} diff --git a/bitbox02-bt/vendor/hashbrown/.cargo-checksum.json b/bitbox02-bt/vendor/hashbrown/.cargo-checksum.json new file mode 100644 index 0000000..a9431d0 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"93bef00f7260b84baa3c02bf965bad809424bd6d048c1dce5873dc61d14d653b","Cargo.toml":"4d14ada8580232a87fbc1117374e250324189f7c55b5b948f4cad976c34801a9","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"ff8f68cb076caf8cefe7a6430d4ac086ce6af2ca8ce2c4e5a2004d4552ef52a2","README.md":"c295e447a94b10d0868ae696ae38f3704764b68328ecd9b443b79cb23a9b95e8","benches/bench.rs":"9e5da01f699980543d9ec0035f2b92d44d8a5b3c83b8f58e355e17b5678792dd","benches/insert_unique_unchecked.rs":"dfe644035cad6ff13b280e3d72c9df2569491ecddc84f7c2502daf940814a63e","benches/set_ops.rs":"936cd15055c25d42aabc6bde738e3135da541520b40633c4fba940eb73e06f4d","clippy.toml":"7535949f908c6d9aea4f9a9f3a7625552c93fc29e963d059d40f4def9d77ea7b","src/external_trait_impls/borsh/hash_map.rs":"3bcf031c22271dcd706bbd4e97924128f1dab762eabf49c7c832dfd07641a653","src/external_trait_impls/borsh/mod.rs":"08125b7b7750054e3f941634cf5f051618375eef192a02e7c8a24a1c32021e8d","src/external_trait_impls/mod.rs":"cb94a509446c836542ac0a04decdd9c703c9f08b03cb74420136420b7bf13928","src/external_trait_impls/rayon/helpers.rs":"ba105bf0853ebc45157f22116ad0f55d3bdab75e721d8e7a677c7b912d0c0c6d","src/external_trait_impls/rayon/map.rs":"e1e08653c6c3d2f0586638ab7baf082c06fdc5551b5852b0f9e73aa9484b4955","src/external_trait_impls/rayon/mod.rs":"126edc882501dddd25e442d9236508b5b386eb8c0a9f5d654f2dd081086c1616","src/external_trait_impls/rayon/raw.rs":"04012fb2e99648819b4bc0044107ed3cb94013e242b7865075c5bd9ebf1b6865","src/external_trait_impls/rayon/set.rs":"7539348ff7bc6e3cce6b3c019d62dc401eea0138c578fef729c2593e8ead1cfa","src/external_trait_impls/rayon/table.rs":"aebd92261f44aef2e4c13a80a566e0308655396a3cc6f973d330d2f5ba26fc45","src/external_trait_impls/serde.rs":"6dbe104dee16b453b6b048b541c6e02c6d067d970dfafd243fc4360288b0168c","src/lib.rs":"3cb011393b5787f4eee320ec3f60ee31380692d7ba2a8539dca92194706a38f9","src/macros.rs":"98a26b908fc0fbe6a58d008a317e550013d615eb3cc17a5054a573c62c1d74cb","src/map.rs":"3291eb55c0bd625e106763b939ef69a90dc288e46aaa5e2cbb9a3b15a35db46e","src/raw/alloc.rs":"902f8588d0fdee3e5c3dc02410f41d4b38ac88843727387f929f3186b3a2d322","src/raw/bitmask.rs":"6bcd7d0f77121e87fc89dd1e512f48c101a62d6ef8ba10e435ea273a2a6a0c74","src/raw/generic.rs":"efc5e603be3e9a17935aef1836a38ce01c78a0093b2af0671548eb5459b37921","src/raw/mod.rs":"c94e7977d257386faf72a8405c2c82bda2c3a2be8163b0a048194871071cb8e9","src/raw/neon.rs":"9907d8ebc36fc3df562dde478ea9b72213fda65288a304718d8647f0029dc9ad","src/raw/sse2.rs":"39038e3344e49f4638e211bcdbf56565ac53e90dce56172cc3b526fea911c2af","src/raw_entry.rs":"41f54fabf968b6ba19a6fbb41372f7e86e1ccd221622591816fe48bcc3797369","src/rustc_entry.rs":"b0e6b20d93fa79edb2950ecdffc1431f43a6819a326fe08891cc7bfc6cd73bd2","src/scopeguard.rs":"1a246e08a63c06cd8ad934bd7da229421bf804f991ae93cd7e242da27ca6c601","src/set.rs":"8d31df77ea874f3e183e938bd4d30cc46be83bea697c58372440f81333e86ecc","src/table.rs":"7323b4123ccb4d0aca13b0fd5597f85cd71cb31376bebf7139eea519f4db8675","tests/equivalent_trait.rs":"84faa3fe9d67c375d03fec81f0f1412c47862477d42e84e7d235258236338d5b","tests/hasher.rs":"fd06130f011660743202904221f3f7487d8d143d8903c73cd3a76d079ebbe9fb","tests/rayon.rs":"39cb24ab45fce8087bb54948715c8b6973ebfba1a325292b5b3cd9aab50b5fd2","tests/serde.rs":"6bac8054db722dd049901b37a6e006535bac30f425eb5cd91af19b5bc1dfe78e","tests/set.rs":"9f8011c29d1059aadb54b6dd4623521d5178b4278b4a56021ef2cee4bbb19fd9"},"package":"1e087f84d4f86bf4b218b927129862374b72199ae7d8657835f1e89000eea4fb"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/hashbrown/CHANGELOG.md b/bitbox02-bt/vendor/hashbrown/CHANGELOG.md new file mode 100644 index 0000000..b7b49d3 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/CHANGELOG.md @@ -0,0 +1,571 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/) +and this project adheres to [Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [v0.15.0] - 2024-10-01 + +This update contains breaking changes that remove the `raw` API with the hope of +centralising on the `HashTable` API in the future. You can follow the discussion +and progress in #545 to discuss features you think should be added to this API +that were previously only possible on the `raw` API. + +### Added + +- Added `borsh` feature with `BorshSerialize` and `BorshDeserialize` impls. (#525) +- Added `Assign` impls for `HashSet` operators. (#529) +- Added `Default` impls for iterator types. (#542) +- Added `HashTable::iter_hash{,_mut}` methods. (#549) +- Added `Hash{Table,Map,Set}::allocation_size` methods. (#553) +- Implemented `Debug` and `FusedIterator` for all `HashTable` iterators. (#561) +- Specialized `Iterator::fold` for all `HashTable` iterators. (#561) + +### Changed + +- Changed `hash_set::VacantEntry::insert` to return `OccupiedEntry`. (#495) +- Improved`hash_set::Difference::size_hint` lower-bound. (#530) +- Improved `HashSet::is_disjoint` performance. (#531) +- `equivalent` feature is now enabled by default. (#532) +- `HashSet` operators now return a set with the same allocator. (#529) +- Changed the default hasher to foldhash. (#563) +- `ahash` feature has been renamed to `default-hasher`. (#533) +- Entry API has been reworked and several methods have been renamed. (#535) +- `Hash{Map,Set}::insert_unique_unchecked` is now unsafe. (#556) +- The signature of `get_many_mut` and related methods was changed. (#562) + +### Fixed + +* Fixed typos, stray backticks in docs. (#558, #560) + +### Removed + +- Raw entry API is now under `raw-entry` feature, to be eventually removed. (#534, #555) +- Raw table API has been made private and the `raw` feature is removed; + in the future, all code should be using the `HashTable` API instead. (#531, #546) +- `rykv` feature was removed; this is now provided by the `rykv` crate instead. (#554) +- `HashSet::get_or_insert_owned` was removed in favor of `get_or_insert_with`. (#555) + +## [v0.14.5] - 2024-04-28 + +### Fixed + +- Fixed index calculation in panic guard of `clone_from_impl`. (#511) + +## ~~[v0.14.4] - 2024-03-19~~ + +This release was _yanked_ due to a breaking change. + +## [v0.14.3] - 2023-11-26 + +### Added + +- Specialized `fold` implementation of iterators. (#480) + +### Fixed + +- Avoid using unstable `ptr::invalid_mut` on nightly. (#481) + +## [v0.14.2] - 2023-10-19 + +### Added + +- `HashTable` type which provides a low-level but safe API with explicit hashing. (#466) + +### Fixed + +- Disabled the use of NEON instructions on big-endian ARM. (#475) +- Disabled the use of NEON instructions on Miri. (#476) + +## [v0.14.1] - 2023-09-28 + +### Added + +- Allow serializing `HashMap`s that use a custom allocator. (#449) + +### Changed + +- Use the `Equivalent` trait from the `equivalent` crate. (#442) +- Slightly improved performance of table resizing. (#451) +- Relaxed MSRV to 1.63.0. (#457) +- Removed `Clone` requirement from custom allocators. (#468) + +### Fixed + +- Fixed custom allocators being leaked in some situations. (#439, #465) + +## [v0.14.0] - 2023-06-01 + +### Added + +- Support for `allocator-api2` crate + for interfacing with custom allocators on stable. (#417) +- Optimized implementation for ARM using NEON instructions. (#430) +- Support for rkyv serialization. (#432) +- `Equivalent` trait to look up values without `Borrow`. (#345) +- `Hash{Map,Set}::raw_table_mut` is added which returns a mutable reference. (#404) +- Fast path for `clear` on empty tables. (#428) + +### Changed + +- Optimized insertion to only perform a single lookup. (#277) +- `DrainFilter` (`drain_filter`) has been renamed to `ExtractIf` and no longer drops remaining + elements when the iterator is dropped. #(374) +- Bumped MSRV to 1.64.0. (#431) +- `{Map,Set}::raw_table` now returns an immutable reference. (#404) +- `VacantEntry` and `OccupiedEntry` now use the default hasher if none is + specified in generics. (#389) +- `RawTable::data_start` now returns a `NonNull` to match `RawTable::data_end`. (#387) +- `RawIter::{reflect_insert, reflect_remove}` are now unsafe. (#429) +- `RawTable::find_potential` is renamed to `find_or_find_insert_slot` and returns an `InsertSlot`. (#429) +- `RawTable::remove` now also returns an `InsertSlot`. (#429) +- `InsertSlot` can be used to insert an element with `RawTable::insert_in_slot`. (#429) +- `RawIterHash` no longer has a lifetime tied to that of the `RawTable`. (#427) +- The trait bounds of `HashSet::raw_table` have been relaxed to not require `Eq + Hash`. (#423) +- `EntryRef::and_replace_entry_with` and `OccupiedEntryRef::replace_entry_with` + were changed to give a `&K` instead of a `&Q` to the closure. + +### Removed + +- Support for `bumpalo` as an allocator with custom wrapper. + Use `allocator-api2` feature in `bumpalo` to use it as an allocator + for `hashbrown` collections. (#417) + +## [v0.13.2] - 2023-01-12 + +### Fixed + +- Added `#[inline(always)]` to `find_inner`. (#375) +- Fixed `RawTable::allocation_info` for empty tables. (#376) + +## [v0.13.1] - 2022-11-10 + +### Added + +- Added `Equivalent` trait to customize key lookups. (#350) +- Added support for 16-bit targets. (#368) +- Added `RawTable::allocation_info` which provides information about the memory + usage of a table. (#371) + +### Changed + +- Bumped MSRV to 1.61.0. +- Upgraded to `ahash` 0.8. (#357) +- Make `with_hasher_in` const. (#355) +- The following methods have been removed from the `RawTable` API in favor of + safer alternatives: + - `RawTable::erase_no_drop` => Use `RawTable::erase` or `RawTable::remove` instead. + - `Bucket::read` => Use `RawTable::remove` instead. + - `Bucket::drop` => Use `RawTable::erase` instead. + - `Bucket::write` => Use `Bucket::as_mut` instead. + +### Fixed + +- Ensure that `HashMap` allocations don't exceed `isize::MAX`. (#362) +- Fixed issue with field retagging in scopeguard. (#359) + +## [v0.12.3] - 2022-07-17 + +### Fixed + +- Fixed double-drop in `RawTable::clone_from`. (#348) + +## [v0.12.2] - 2022-07-09 + +### Added + +- Added `Entry` API for `HashSet`. (#342) +- Added `Extend<&'a (K, V)> for HashMap`. (#340) +- Added length-based short-circuiting for hash table iteration. (#338) +- Added a function to access the `RawTable` of a `HashMap`. (#335) + +### Changed + +- Edited `do_alloc` to reduce LLVM IR generated. (#341) + +## [v0.12.1] - 2022-05-02 + +### Fixed + +- Fixed underflow in `RawIterRange::size_hint`. (#325) +- Fixed the implementation of `Debug` for `ValuesMut` and `IntoValues`. (#325) + +## [v0.12.0] - 2022-01-17 + +### Added + +- Added `From<[T; N]>` and `From<[(K, V); N]>` for `HashSet` and `HashMap` respectively. (#297) +- Added an `allocator()` getter to HashMap and HashSet. (#257) +- Added `insert_unique_unchecked` to `HashMap` and `HashSet`. (#293) +- Added `into_keys` and `into_values` to HashMap. (#295) +- Implement `From` on `HashSet` and `HashMap`. (#298) +- Added `entry_ref` API to `HashMap`. (#201) + +### Changed + +- Bumped minimum Rust version to 1.56.1 and edition to 2021. +- Use u64 for the GroupWord on WebAssembly. (#271) +- Optimized `find`. (#279) +- Made rehashing and resizing less generic to reduce compilation time. (#282) +- Inlined small functions. (#283) +- Use `BuildHasher::hash_one` when `feature = "nightly"` is enabled. (#292) +- Relaxed the bounds on `Debug` for `HashSet`. (#296) +- Rename `get_each_mut` to `get_many_mut` and align API with the stdlib. (#291) +- Don't hash the key when searching in an empty table. (#305) + +### Fixed + +- Guard against allocations exceeding isize::MAX. (#268) +- Made `RawTable::insert_no_grow` unsafe. (#254) +- Inline `static_empty`. (#280) +- Fixed trait bounds on Send/Sync impls. (#303) + +## [v0.11.2] - 2021-03-25 + +### Fixed + +- Added missing allocator type parameter to `HashMap`'s and `HashSet`'s `Clone` impls. (#252) + +## [v0.11.1] - 2021-03-20 + +### Fixed + +- Added missing `pub` modifier to `BumpWrapper`. (#251) + +## [v0.11.0] - 2021-03-14 + +### Added +- Added safe `try_insert_no_grow` method to `RawTable`. (#229) +- Added support for `bumpalo` as an allocator without the `nightly` feature. (#231) +- Implemented `Default` for `RawTable`. (#237) +- Added new safe methods `RawTable::get_each_mut`, `HashMap::get_each_mut`, and + `HashMap::get_each_key_value_mut`. (#239) +- Added `From>` for `HashSet`. (#235) +- Added `try_insert` method to `HashMap`. (#247) + +### Changed +- The minimum Rust version has been bumped to 1.49.0. (#230) +- Significantly improved compilation times by reducing the amount of generated IR. (#205) + +### Removed +- We no longer re-export the unstable allocator items from the standard library, nor the stable shims approximating the same. (#227) +- Removed hasher specialization support from `aHash`, which was resulting in inconsistent hashes being generated for a key. (#248) + +### Fixed +- Fixed union length comparison. (#228) + +## ~~[v0.10.0] - 2021-01-16~~ + +This release was _yanked_ due to inconsistent hashes being generated with the `nightly` feature. (#248) + +### Changed +- Parametrized `RawTable`, `HashSet` and `HashMap` over an allocator. (#133) +- Improved branch prediction hints on stable. (#209) +- Optimized hashing of primitive types with AHash using specialization. (#207) +- Only instantiate `RawTable`'s reserve functions once per key-value. (#204) + +## [v0.9.1] - 2020-09-28 + +### Added +- Added safe methods to `RawTable` (#202): + - `get`: `find` and `as_ref` + - `get_mut`: `find` and `as_mut` + - `insert_entry`: `insert` and `as_mut` + - `remove_entry`: `find` and `remove` + - `erase_entry`: `find` and `erase` + +### Changed +- Removed `from_key_hashed_nocheck`'s `Q: Hash`. (#200) +- Made `RawTable::drain` safe. (#201) + +## [v0.9.0] - 2020-09-03 + +### Fixed +- `drain_filter` now removes and yields items that do match the predicate, + rather than items that don't. This is a **breaking change** to match the + behavior of the `drain_filter` methods in `std`. (#187) + +### Added +- Added `replace_entry_with` to `OccupiedEntry`, and `and_replace_entry_with` to `Entry`. (#190) +- Implemented `FusedIterator` and `size_hint` for `DrainFilter`. (#188) + +### Changed +- The minimum Rust version has been bumped to 1.36 (due to `crossbeam` dependency). (#193) +- Updated `ahash` dependency to 0.4. (#198) +- `HashMap::with_hasher` and `HashSet::with_hasher` are now `const fn`. (#195) +- Removed `T: Hash + Eq` and `S: BuildHasher` bounds on `HashSet::new`, + `with_capacity`, `with_hasher`, and `with_capacity_and_hasher`. (#185) + +## [v0.8.2] - 2020-08-08 + +### Changed +- Avoid closures to improve compile times. (#183) +- Do not iterate to drop if empty. (#182) + +## [v0.8.1] - 2020-07-16 + +### Added +- Added `erase` and `remove` to `RawTable`. (#171) +- Added `try_with_capacity` to `RawTable`. (#174) +- Added methods that allow re-using a `RawIter` for `RawDrain`, + `RawIntoIter`, and `RawParIter`. (#175) +- Added `reflect_remove` and `reflect_insert` to `RawIter`. (#175) +- Added a `drain_filter` function to `HashSet`. (#179) + +### Changed +- Deprecated `RawTable::erase_no_drop` in favor of `erase` and `remove`. (#176) +- `insert_no_grow` is now exposed under the `"raw"` feature. (#180) + +## [v0.8.0] - 2020-06-18 + +### Fixed +- Marked `RawTable::par_iter` as `unsafe`. (#157) + +### Changed +- Reduced the size of `HashMap`. (#159) +- No longer create tables with a capacity of 1 element. (#162) +- Removed `K: Eq + Hash` bounds on `retain`. (#163) +- Pulled in `HashMap` changes from rust-lang/rust (#164): + - `extend_one` support on nightly. + - `CollectionAllocErr` renamed to `TryReserveError`. + - Added `HashSet::get_or_insert_owned`. + - `Default` for `HashSet` no longer requires `T: Eq + Hash` and `S: BuildHasher`. + +## [v0.7.2] - 2020-04-27 + +### Added +- Added `or_insert_with_key` to `Entry`. (#152) + +### Fixed +- Partially reverted `Clone` optimization which was unsound. (#154) + +### Changed +- Disabled use of `const-random` by default, which prevented reproducible builds. (#155) +- Optimized `repeat` function. (#150) +- Use `NonNull` for buckets, which improves codegen for iterators. (#148) + +## [v0.7.1] - 2020-03-16 + +### Added +- Added `HashMap::get_key_value_mut`. (#145) + +### Changed +- Optimized `Clone` implementation. (#146) + +## [v0.7.0] - 2020-01-31 + +### Added +- Added a `drain_filter` function to `HashMap`. (#135) + +### Changed +- Updated `ahash` dependency to 0.3. (#141) +- Optimized set union and intersection. (#130) +- `raw_entry` can now be used without requiring `S: BuildHasher`. (#123) +- `RawTable::bucket_index` can now be used under the `raw` feature. (#128) + +## [v0.6.3] - 2019-10-31 + +### Added +- Added an `ahash-compile-time-rng` feature (enabled by default) which allows disabling the + `compile-time-rng` feature in `ahash` to work around a Cargo bug. (#125) + +## [v0.6.2] - 2019-10-23 + +### Added +- Added an `inline-more` feature (enabled by default) which allows choosing a tradeoff between + runtime performance and compilation time. (#119) + +## [v0.6.1] - 2019-10-04 + +### Added +- Added `Entry::insert` and `RawEntryMut::insert`. (#118) + +### Changed +- `Group::static_empty` was changed from a `const` to a `static` (#116). + +## [v0.6.0] - 2019-08-13 + +### Fixed +- Fixed AHash accidentally depending on `std`. (#110) + +### Changed +- The minimum Rust version has been bumped to 1.32 (due to `rand` dependency). + +## ~~[v0.5.1] - 2019-08-04~~ + +This release was _yanked_ due to a breaking change for users of `no-default-features`. + +### Added +- The experimental and unsafe `RawTable` API is available under the "raw" feature. (#108) +- Added entry-like methods for `HashSet`. (#98) + +### Changed +- Changed the default hasher from FxHash to AHash. (#97) +- `hashbrown` is now fully `no_std` on recent Rust versions (1.36+). (#96) + +### Fixed +- We now avoid growing the table during insertions when it wasn't necessary. (#106) +- `RawOccupiedEntryMut` now properly implements `Send` and `Sync`. (#100) +- Relaxed `lazy_static` version. (#92) + +## [v0.5.0] - 2019-06-12 + +### Fixed +- Resize with a more conservative amount of space after deletions. (#86) + +### Changed +- Exposed the Layout of the failed allocation in CollectionAllocErr::AllocErr. (#89) + +## [v0.4.0] - 2019-05-30 + +### Fixed +- Fixed `Send` trait bounds on `IterMut` not matching the libstd one. (#82) + +## [v0.3.1] - 2019-05-30 + +### Fixed +- Fixed incorrect use of slice in unsafe code. (#80) + +## [v0.3.0] - 2019-04-23 + +### Changed +- Changed shrink_to to not panic if min_capacity < capacity. (#67) + +### Fixed +- Worked around emscripten bug emscripten-core/emscripten-fastcomp#258. (#66) + +## [v0.2.2] - 2019-04-16 + +### Fixed +- Inlined non-nightly lowest_set_bit_nonzero. (#64) +- Fixed build on latest nightly. (#65) + +## [v0.2.1] - 2019-04-14 + +### Changed +- Use for_each in map Extend and FromIterator. (#58) +- Improved worst-case performance of HashSet.is_subset. (#61) + +### Fixed +- Removed incorrect debug_assert. (#60) + +## [v0.2.0] - 2019-03-31 + +### Changed +- The code has been updated to Rust 2018 edition. This means that the minimum + Rust version has been bumped to 1.31 (2018 edition). + +### Added +- Added `insert_with_hasher` to the raw_entry API to allow `K: !(Hash + Eq)`. (#54) +- Added support for using hashbrown as the hash table implementation in libstd. (#46) + +### Fixed +- Fixed cargo build with minimal-versions. (#45) +- Fixed `#[may_dangle]` attributes to match the libstd `HashMap`. (#46) +- ZST keys and values are now handled properly. (#46) + +## [v0.1.8] - 2019-01-14 + +### Added +- Rayon parallel iterator support (#37) +- `raw_entry` support (#31) +- `#[may_dangle]` on nightly (#31) +- `try_reserve` support (#31) + +### Fixed +- Fixed variance on `IterMut`. (#31) + +## [v0.1.7] - 2018-12-05 + +### Fixed +- Fixed non-SSE version of convert_special_to_empty_and_full_to_deleted. (#32) +- Fixed overflow in rehash_in_place. (#33) + +## [v0.1.6] - 2018-11-17 + +### Fixed +- Fixed compile error on nightly. (#29) + +## [v0.1.5] - 2018-11-08 + +### Fixed +- Fixed subtraction overflow in generic::Group::match_byte. (#28) + +## [v0.1.4] - 2018-11-04 + +### Fixed +- Fixed a bug in the `erase_no_drop` implementation. (#26) + +## [v0.1.3] - 2018-11-01 + +### Added +- Serde support. (#14) + +### Fixed +- Make the compiler inline functions more aggressively. (#20) + +## [v0.1.2] - 2018-10-31 + +### Fixed +- `clear` segfaults when called on an empty table. (#13) + +## [v0.1.1] - 2018-10-30 + +### Fixed +- `erase_no_drop` optimization not triggering in the SSE2 implementation. (#3) +- Missing `Send` and `Sync` for hash map and iterator types. (#7) +- Bug when inserting into a table smaller than the group width. (#5) + +## v0.1.0 - 2018-10-29 + +- Initial release + +[Unreleased]: https://github.com/rust-lang/hashbrown/compare/v0.15.0...HEAD +[v0.15.0]: https://github.com/rust-lang/hashbrown/compare/v0.14.5...v0.15.0 +[v0.14.5]: https://github.com/rust-lang/hashbrown/compare/v0.14.4...v0.14.5 +[v0.14.4]: https://github.com/rust-lang/hashbrown/compare/v0.14.3...v0.14.4 +[v0.14.3]: https://github.com/rust-lang/hashbrown/compare/v0.14.2...v0.14.3 +[v0.14.2]: https://github.com/rust-lang/hashbrown/compare/v0.14.1...v0.14.2 +[v0.14.1]: https://github.com/rust-lang/hashbrown/compare/v0.14.0...v0.14.1 +[v0.14.0]: https://github.com/rust-lang/hashbrown/compare/v0.13.2...v0.14.0 +[v0.13.2]: https://github.com/rust-lang/hashbrown/compare/v0.13.1...v0.13.2 +[v0.13.1]: https://github.com/rust-lang/hashbrown/compare/v0.12.3...v0.13.1 +[v0.12.3]: https://github.com/rust-lang/hashbrown/compare/v0.12.2...v0.12.3 +[v0.12.2]: https://github.com/rust-lang/hashbrown/compare/v0.12.1...v0.12.2 +[v0.12.1]: https://github.com/rust-lang/hashbrown/compare/v0.12.0...v0.12.1 +[v0.12.0]: https://github.com/rust-lang/hashbrown/compare/v0.11.2...v0.12.0 +[v0.11.2]: https://github.com/rust-lang/hashbrown/compare/v0.11.1...v0.11.2 +[v0.11.1]: https://github.com/rust-lang/hashbrown/compare/v0.11.0...v0.11.1 +[v0.11.0]: https://github.com/rust-lang/hashbrown/compare/v0.10.0...v0.11.0 +[v0.10.0]: https://github.com/rust-lang/hashbrown/compare/v0.9.1...v0.10.0 +[v0.9.1]: https://github.com/rust-lang/hashbrown/compare/v0.9.0...v0.9.1 +[v0.9.0]: https://github.com/rust-lang/hashbrown/compare/v0.8.2...v0.9.0 +[v0.8.2]: https://github.com/rust-lang/hashbrown/compare/v0.8.1...v0.8.2 +[v0.8.1]: https://github.com/rust-lang/hashbrown/compare/v0.8.0...v0.8.1 +[v0.8.0]: https://github.com/rust-lang/hashbrown/compare/v0.7.2...v0.8.0 +[v0.7.2]: https://github.com/rust-lang/hashbrown/compare/v0.7.1...v0.7.2 +[v0.7.1]: https://github.com/rust-lang/hashbrown/compare/v0.7.0...v0.7.1 +[v0.7.0]: https://github.com/rust-lang/hashbrown/compare/v0.6.3...v0.7.0 +[v0.6.3]: https://github.com/rust-lang/hashbrown/compare/v0.6.2...v0.6.3 +[v0.6.2]: https://github.com/rust-lang/hashbrown/compare/v0.6.1...v0.6.2 +[v0.6.1]: https://github.com/rust-lang/hashbrown/compare/v0.6.0...v0.6.1 +[v0.6.0]: https://github.com/rust-lang/hashbrown/compare/v0.5.1...v0.6.0 +[v0.5.1]: https://github.com/rust-lang/hashbrown/compare/v0.5.0...v0.5.1 +[v0.5.0]: https://github.com/rust-lang/hashbrown/compare/v0.4.0...v0.5.0 +[v0.4.0]: https://github.com/rust-lang/hashbrown/compare/v0.3.1...v0.4.0 +[v0.3.1]: https://github.com/rust-lang/hashbrown/compare/v0.3.0...v0.3.1 +[v0.3.0]: https://github.com/rust-lang/hashbrown/compare/v0.2.2...v0.3.0 +[v0.2.2]: https://github.com/rust-lang/hashbrown/compare/v0.2.1...v0.2.2 +[v0.2.1]: https://github.com/rust-lang/hashbrown/compare/v0.2.0...v0.2.1 +[v0.2.0]: https://github.com/rust-lang/hashbrown/compare/v0.1.8...v0.2.0 +[v0.1.8]: https://github.com/rust-lang/hashbrown/compare/v0.1.7...v0.1.8 +[v0.1.7]: https://github.com/rust-lang/hashbrown/compare/v0.1.6...v0.1.7 +[v0.1.6]: https://github.com/rust-lang/hashbrown/compare/v0.1.5...v0.1.6 +[v0.1.5]: https://github.com/rust-lang/hashbrown/compare/v0.1.4...v0.1.5 +[v0.1.4]: https://github.com/rust-lang/hashbrown/compare/v0.1.3...v0.1.4 +[v0.1.3]: https://github.com/rust-lang/hashbrown/compare/v0.1.2...v0.1.3 +[v0.1.2]: https://github.com/rust-lang/hashbrown/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/rust-lang/hashbrown/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/hashbrown/Cargo.toml b/bitbox02-bt/vendor/hashbrown/Cargo.toml new file mode 100644 index 0000000..b0960bf --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/Cargo.toml @@ -0,0 +1,178 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.63.0" +name = "hashbrown" +version = "0.15.0" +authors = ["Amanieu d'Antras "] +build = false +exclude = [ + ".github", + "/ci/*", +] +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A Rust port of Google's SwissTable hash map" +readme = "README.md" +keywords = [ + "hash", + "no_std", + "hashmap", + "swisstable", +] +categories = [ + "data-structures", + "no-std", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-lang/hashbrown" + +[package.metadata.docs.rs] +features = [ + "nightly", + "rayon", + "serde", + "raw-entry", +] +rustdoc-args = ["--generate-link-to-definition"] + +[lib] +name = "hashbrown" +path = "src/lib.rs" + +[[test]] +name = "equivalent_trait" +path = "tests/equivalent_trait.rs" + +[[test]] +name = "hasher" +path = "tests/hasher.rs" + +[[test]] +name = "rayon" +path = "tests/rayon.rs" + +[[test]] +name = "serde" +path = "tests/serde.rs" + +[[test]] +name = "set" +path = "tests/set.rs" + +[[bench]] +name = "bench" +path = "benches/bench.rs" + +[[bench]] +name = "insert_unique_unchecked" +path = "benches/insert_unique_unchecked.rs" + +[[bench]] +name = "set_ops" +path = "benches/set_ops.rs" + +[dependencies.alloc] +version = "1.0.0" +optional = true +package = "rustc-std-workspace-alloc" + +[dependencies.allocator-api2] +version = "0.2.9" +features = ["alloc"] +optional = true +default-features = false + +[dependencies.borsh] +version = "1.5.0" +features = ["derive"] +optional = true +default-features = false + +[dependencies.compiler_builtins] +version = "0.1.2" +optional = true + +[dependencies.core] +version = "1.0.0" +optional = true +package = "rustc-std-workspace-core" + +[dependencies.equivalent] +version = "1.0" +optional = true +default-features = false + +[dependencies.foldhash] +version = "0.1.2" +optional = true +default-features = false + +[dependencies.rayon] +version = "1.0" +optional = true + +[dependencies.serde] +version = "1.0.25" +optional = true +default-features = false + +[dev-dependencies.bumpalo] +version = "3.13.0" +features = ["allocator-api2"] + +[dev-dependencies.doc-comment] +version = "0.3.1" + +[dev-dependencies.fnv] +version = "1.0.7" + +[dev-dependencies.lazy_static] +version = "1.4" + +[dev-dependencies.rand] +version = "0.8.3" +features = ["small_rng"] + +[dev-dependencies.rayon] +version = "1.0" + +[dev-dependencies.serde_test] +version = "1.0" + +[features] +default = [ + "default-hasher", + "inline-more", + "allocator-api2", + "equivalent", + "raw-entry", +] +default-hasher = ["dep:foldhash"] +inline-more = [] +nightly = [ + "allocator-api2?/nightly", + "bumpalo/allocator_api", +] +raw-entry = [] +rustc-dep-of-std = [ + "nightly", + "core", + "compiler_builtins", + "alloc", + "rustc-internal-api", + "raw-entry", +] +rustc-internal-api = [] diff --git a/bitbox02-bt/vendor/hashbrown/LICENSE-APACHE b/bitbox02-bt/vendor/hashbrown/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/hashbrown/LICENSE-MIT b/bitbox02-bt/vendor/hashbrown/LICENSE-MIT new file mode 100644 index 0000000..5afc2a7 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Amanieu d'Antras + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/hashbrown/README.md b/bitbox02-bt/vendor/hashbrown/README.md new file mode 100644 index 0000000..6c30f8e --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/README.md @@ -0,0 +1,81 @@ +hashbrown +========= + +[![Build Status](https://github.com/rust-lang/hashbrown/actions/workflows/rust.yml/badge.svg)](https://github.com/rust-lang/hashbrown/actions) +[![Crates.io](https://img.shields.io/crates/v/hashbrown.svg)](https://crates.io/crates/hashbrown) +[![Documentation](https://docs.rs/hashbrown/badge.svg)](https://docs.rs/hashbrown) +[![Rust](https://img.shields.io/badge/rust-1.63.0%2B-blue.svg?maxAge=3600)](https://github.com/rust-lang/hashbrown) + +This crate is a Rust port of Google's high-performance [SwissTable] hash +map, adapted to make it a drop-in replacement for Rust's standard `HashMap` +and `HashSet` types. + +The original C++ version of SwissTable can be found [here], and this +[CppCon talk] gives an overview of how the algorithm works. + +Since Rust 1.36, this is now the `HashMap` implementation for the Rust standard +library. However you may still want to use this crate instead since it works +in environments without `std`, such as embedded systems and kernels. + +[SwissTable]: https://abseil.io/blog/20180927-swisstables +[here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h +[CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4 + +## [Change log](CHANGELOG.md) + +## Features + +- Drop-in replacement for the standard library `HashMap` and `HashSet` types. +- Uses [foldhash](https://github.com/orlp/foldhash) as the default hasher, which is much faster than SipHash. + However, foldhash does *not provide the same level of HashDoS resistance* as SipHash, so if that is important to you, you might want to consider using a different hasher. +- Around 2x faster than the previous standard library `HashMap`. +- Lower memory usage: only 1 byte of overhead per entry instead of 8. +- Compatible with `#[no_std]` (but requires a global allocator with the `alloc` crate). +- Empty hash maps do not allocate any memory. +- SIMD lookups to scan multiple hash entries in parallel. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +hashbrown = "0.14" +``` + +Then: + +```rust +use hashbrown::HashMap; + +let mut map = HashMap::new(); +map.insert(1, "one"); +``` +## Flags +This crate has the following Cargo features: + +- `nightly`: Enables nightly-only features including: `#[may_dangle]`. +- `serde`: Enables serde serialization support. +- `borsh`: Enables borsh serialization support. +- `rayon`: Enables rayon parallel iterator support. +- `equivalent`: Allows comparisons to be customized with the `Equivalent` trait. (enabled by default) +- `raw-entry`: Enables access to the deprecated `RawEntry` API. +- `inline-more`: Adds inline hints to most functions, improving run-time performance at the cost + of compilation time. (enabled by default) +- `default-hasher`: Compiles with foldhash as default hasher. (enabled by default) +- `allocator-api2`: Enables support for allocators that support `allocator-api2`. (enabled by default) + +## License + +Licensed under either of: + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/bitbox02-bt/vendor/hashbrown/benches/bench.rs b/bitbox02-bt/vendor/hashbrown/benches/bench.rs new file mode 100644 index 0000000..dd55159 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/benches/bench.rs @@ -0,0 +1,331 @@ +// This benchmark suite contains some benchmarks along a set of dimensions: +// Hasher: std default (SipHash) and crate default (foldhash). +// Int key distribution: low bit heavy, top bit heavy, and random. +// Task: basic functionality: insert, insert_erase, lookup, lookup_fail, iter +#![feature(test)] + +extern crate test; + +use test::{black_box, Bencher}; + +use hashbrown::DefaultHashBuilder; +use hashbrown::{HashMap, HashSet}; +use std::{ + collections::hash_map::RandomState, + sync::atomic::{self, AtomicUsize}, +}; + +const SIZE: usize = 1000; + +// The default hashmap when using this crate directly. +type FoldHashMap = HashMap; +// This uses the hashmap from this crate with the default hasher of the stdlib. +type StdHashMap = HashMap; + +// A random key iterator. +#[derive(Clone, Copy)] +struct RandomKeys { + state: usize, +} + +impl RandomKeys { + fn new() -> Self { + RandomKeys { state: 0 } + } +} + +impl Iterator for RandomKeys { + type Item = usize; + fn next(&mut self) -> Option { + // Add 1 then multiply by some 32 bit prime. + self.state = self.state.wrapping_add(1).wrapping_mul(3_787_392_781); + Some(self.state) + } +} + +// Just an arbitrary side effect to make the maps not shortcircuit to the non-dropping path +// when dropping maps/entries (most real world usages likely have drop in the key or value) +lazy_static::lazy_static! { + static ref SIDE_EFFECT: AtomicUsize = AtomicUsize::new(0); +} + +#[derive(Clone)] +struct DropType(usize); +impl Drop for DropType { + fn drop(&mut self) { + SIDE_EFFECT.fetch_add(self.0, atomic::Ordering::SeqCst); + } +} + +macro_rules! bench_suite { + ($bench_macro:ident, $bench_foldhash_serial:ident, $bench_std_serial:ident, + $bench_foldhash_highbits:ident, $bench_std_highbits:ident, + $bench_foldhash_random:ident, $bench_std_random:ident) => { + $bench_macro!($bench_foldhash_serial, FoldHashMap, 0..); + $bench_macro!($bench_std_serial, StdHashMap, 0..); + $bench_macro!( + $bench_foldhash_highbits, + FoldHashMap, + (0..).map(usize::swap_bytes) + ); + $bench_macro!( + $bench_std_highbits, + StdHashMap, + (0..).map(usize::swap_bytes) + ); + $bench_macro!($bench_foldhash_random, FoldHashMap, RandomKeys::new()); + $bench_macro!($bench_std_random, StdHashMap, RandomKeys::new()); + }; +} + +macro_rules! bench_insert { + ($name:ident, $maptype:ident, $keydist:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut m = $maptype::with_capacity_and_hasher(SIZE, Default::default()); + b.iter(|| { + m.clear(); + for i in ($keydist).take(SIZE) { + m.insert(i, (DropType(i), [i; 20])); + } + black_box(&mut m); + }); + eprintln!("{}", SIDE_EFFECT.load(atomic::Ordering::SeqCst)); + } + }; +} + +bench_suite!( + bench_insert, + insert_foldhash_serial, + insert_std_serial, + insert_foldhash_highbits, + insert_std_highbits, + insert_foldhash_random, + insert_std_random +); + +macro_rules! bench_grow_insert { + ($name:ident, $maptype:ident, $keydist:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + b.iter(|| { + let mut m = $maptype::default(); + for i in ($keydist).take(SIZE) { + m.insert(i, DropType(i)); + } + black_box(&mut m); + }) + } + }; +} + +bench_suite!( + bench_grow_insert, + grow_insert_foldhash_serial, + grow_insert_std_serial, + grow_insert_foldhash_highbits, + grow_insert_std_highbits, + grow_insert_foldhash_random, + grow_insert_std_random +); + +macro_rules! bench_insert_erase { + ($name:ident, $maptype:ident, $keydist:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut base = $maptype::default(); + for i in ($keydist).take(SIZE) { + base.insert(i, DropType(i)); + } + let skip = $keydist.skip(SIZE); + b.iter(|| { + let mut m = base.clone(); + let mut add_iter = skip.clone(); + let mut remove_iter = $keydist; + // While keeping the size constant, + // replace the first keydist with the second. + for (add, remove) in (&mut add_iter).zip(&mut remove_iter).take(SIZE) { + m.insert(add, DropType(add)); + black_box(m.remove(&remove)); + } + black_box(m); + }); + eprintln!("{}", SIDE_EFFECT.load(atomic::Ordering::SeqCst)); + } + }; +} + +bench_suite!( + bench_insert_erase, + insert_erase_foldhash_serial, + insert_erase_std_serial, + insert_erase_foldhash_highbits, + insert_erase_std_highbits, + insert_erase_foldhash_random, + insert_erase_std_random +); + +macro_rules! bench_lookup { + ($name:ident, $maptype:ident, $keydist:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut m = $maptype::default(); + for i in $keydist.take(SIZE) { + m.insert(i, DropType(i)); + } + + b.iter(|| { + for i in $keydist.take(SIZE) { + black_box(m.get(&i)); + } + }); + eprintln!("{}", SIDE_EFFECT.load(atomic::Ordering::SeqCst)); + } + }; +} + +bench_suite!( + bench_lookup, + lookup_foldhash_serial, + lookup_std_serial, + lookup_foldhash_highbits, + lookup_std_highbits, + lookup_foldhash_random, + lookup_std_random +); + +macro_rules! bench_lookup_fail { + ($name:ident, $maptype:ident, $keydist:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut m = $maptype::default(); + let mut iter = $keydist; + for i in (&mut iter).take(SIZE) { + m.insert(i, DropType(i)); + } + + b.iter(|| { + for i in (&mut iter).take(SIZE) { + black_box(m.get(&i)); + } + }) + } + }; +} + +bench_suite!( + bench_lookup_fail, + lookup_fail_foldhash_serial, + lookup_fail_std_serial, + lookup_fail_foldhash_highbits, + lookup_fail_std_highbits, + lookup_fail_foldhash_random, + lookup_fail_std_random +); + +macro_rules! bench_iter { + ($name:ident, $maptype:ident, $keydist:expr) => { + #[bench] + fn $name(b: &mut Bencher) { + let mut m = $maptype::default(); + for i in ($keydist).take(SIZE) { + m.insert(i, DropType(i)); + } + + b.iter(|| { + for i in &m { + black_box(i); + } + }) + } + }; +} + +bench_suite!( + bench_iter, + iter_foldhash_serial, + iter_std_serial, + iter_foldhash_highbits, + iter_std_highbits, + iter_foldhash_random, + iter_std_random +); + +#[bench] +fn clone_small(b: &mut Bencher) { + let mut m = HashMap::new(); + for i in 0..10 { + m.insert(i, DropType(i)); + } + + b.iter(|| { + black_box(m.clone()); + }) +} + +#[bench] +fn clone_from_small(b: &mut Bencher) { + let mut m = HashMap::new(); + let mut m2 = HashMap::new(); + for i in 0..10 { + m.insert(i, DropType(i)); + } + + b.iter(|| { + m2.clone_from(&m); + black_box(&mut m2); + }) +} + +#[bench] +fn clone_large(b: &mut Bencher) { + let mut m = HashMap::new(); + for i in 0..1000 { + m.insert(i, DropType(i)); + } + + b.iter(|| { + black_box(m.clone()); + }) +} + +#[bench] +fn clone_from_large(b: &mut Bencher) { + let mut m = HashMap::new(); + let mut m2 = HashMap::new(); + for i in 0..1000 { + m.insert(i, DropType(i)); + } + + b.iter(|| { + m2.clone_from(&m); + black_box(&mut m2); + }) +} + +#[bench] +fn rehash_in_place(b: &mut Bencher) { + b.iter(|| { + let mut set = HashSet::new(); + + // Each loop triggers one rehash + for _ in 0..10 { + for i in 0..223 { + set.insert(i); + } + + assert_eq!( + set.capacity(), + 224, + "The set must be at or close to capacity to trigger a re hashing" + ); + + for i in 100..1400 { + set.remove(&(i - 100)); + set.insert(i); + } + set.clear(); + } + }); +} diff --git a/bitbox02-bt/vendor/hashbrown/benches/insert_unique_unchecked.rs b/bitbox02-bt/vendor/hashbrown/benches/insert_unique_unchecked.rs new file mode 100644 index 0000000..cfd69cd --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/benches/insert_unique_unchecked.rs @@ -0,0 +1,34 @@ +//! Compare `insert` and `insert_unique_unchecked` operations performance. + +#![feature(test)] + +extern crate test; + +use hashbrown::HashMap; +use test::Bencher; + +#[bench] +fn insert(b: &mut Bencher) { + let keys: Vec = (0..1000).map(|i| format!("xxxx{}yyyy", i)).collect(); + b.iter(|| { + let mut m = HashMap::with_capacity(1000); + for k in &keys { + m.insert(k, k); + } + m + }); +} + +#[bench] +fn insert_unique_unchecked(b: &mut Bencher) { + let keys: Vec = (0..1000).map(|i| format!("xxxx{}yyyy", i)).collect(); + b.iter(|| { + let mut m = HashMap::with_capacity(1000); + for k in &keys { + unsafe { + m.insert_unique_unchecked(k, k); + } + } + m + }); +} diff --git a/bitbox02-bt/vendor/hashbrown/benches/set_ops.rs b/bitbox02-bt/vendor/hashbrown/benches/set_ops.rs new file mode 100644 index 0000000..3b2ab5f --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/benches/set_ops.rs @@ -0,0 +1,148 @@ +//! This file contains benchmarks for the ops traits implemented by HashSet. +//! Each test is intended to have a defined larger and smaller set, +//! but using a larger size for the "small" set works just as well. +//! +//! Each assigning test is done in the configuration that is faster. Cheating, I know. +//! The exception to this is Sub, because there the result differs. So I made two benchmarks for Sub. + +#![feature(test)] + +extern crate test; + +use hashbrown::HashSet; +use test::Bencher; + +/// The number of items to generate for the larger of the sets. +const LARGE_SET_SIZE: usize = 1000; + +/// The number of items to generate for the smaller of the sets. +const SMALL_SET_SIZE: usize = 100; + +/// The number of keys present in both sets. +const OVERLAP: usize = + [LARGE_SET_SIZE, SMALL_SET_SIZE][(LARGE_SET_SIZE < SMALL_SET_SIZE) as usize] / 2; + +/// Creates a set containing end - start unique string elements. +fn create_set(start: usize, end: usize) -> HashSet { + (start..end).map(|nr| format!("key{}", nr)).collect() +} + +#[bench] +fn set_ops_bit_or(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| &large_set | &small_set) +} + +#[bench] +fn set_ops_bit_and(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| &large_set & &small_set) +} + +#[bench] +fn set_ops_bit_xor(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| &large_set ^ &small_set) +} + +#[bench] +fn set_ops_sub_large_small(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| &large_set - &small_set) +} + +#[bench] +fn set_ops_sub_small_large(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| &small_set - &large_set) +} + +#[bench] +fn set_ops_bit_or_assign(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| { + let mut set = large_set.clone(); + set |= &small_set; + set + }); +} + +#[bench] +fn set_ops_bit_and_assign(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| { + let mut set = small_set.clone(); + set &= &large_set; + set + }); +} + +#[bench] +fn set_ops_bit_xor_assign(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| { + let mut set = large_set.clone(); + set ^= &small_set; + set + }); +} + +#[bench] +fn set_ops_sub_assign_large_small(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| { + let mut set = large_set.clone(); + set -= &small_set; + set + }); +} + +#[bench] +fn set_ops_sub_assign_small_large(b: &mut Bencher) { + let large_set = create_set(0, LARGE_SET_SIZE); + let small_set = create_set( + LARGE_SET_SIZE - OVERLAP, + LARGE_SET_SIZE + SMALL_SET_SIZE - OVERLAP, + ); + b.iter(|| { + let mut set = small_set.clone(); + set -= &large_set; + set + }); +} diff --git a/bitbox02-bt/vendor/hashbrown/clippy.toml b/bitbox02-bt/vendor/hashbrown/clippy.toml new file mode 100644 index 0000000..d98bf2c --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/clippy.toml @@ -0,0 +1 @@ +doc-valid-idents = [ "CppCon", "SwissTable", "SipHash", "HashDoS" ] diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/hash_map.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/hash_map.rs new file mode 100644 index 0000000..8991aff --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/hash_map.rs @@ -0,0 +1,78 @@ +use crate::HashMap; + +use borsh::{ + io::{Read, Result, Write}, + BorshDeserialize, BorshSerialize, +}; + +impl BorshSerialize for HashMap { + fn serialize(&self, writer: &mut W) -> Result<()> { + // assuming hash may have some seed, + // as borsh is supposed by default to be deterministic, need to write it down + // if allocator is compile time, than one can just impl wrapper with zero bytes serde of it + self.hash_builder.serialize(writer)?; + // considering A stateless + self.len().serialize(writer)?; + for kv in self.iter() { + kv.serialize(writer)?; + } + Ok(()) + } +} + +impl< + K: BorshDeserialize + core::hash::Hash + Eq, + V: BorshDeserialize, + S: BorshDeserialize + core::hash::BuildHasher, + > BorshDeserialize for HashMap +{ + fn deserialize_reader(reader: &mut R) -> Result { + let hash_builder = S::deserialize_reader(reader)?; + let len = usize::deserialize_reader(reader)?; + let mut map = HashMap::with_capacity_and_hasher(len, hash_builder); + for _ in 0..len { + let (k, v) = <(K, V)>::deserialize_reader(reader)?; + // can use raw api here to init from memory, so can do it other time + map.insert(k, v); + } + Ok(map) + } +} + +#[cfg(test)] +mod tests { + use borsh::{BorshDeserialize, BorshSerialize}; + use std::vec::Vec; + + #[derive(Default, BorshDeserialize, BorshSerialize, Clone)] + struct NoHash; + + impl core::hash::BuildHasher for NoHash { + type Hasher = NoHash; + fn build_hasher(&self) -> NoHash { + Self + } + } + + impl core::hash::Hasher for NoHash { + fn finish(&self) -> u64 { + 42 + } + + fn write(&mut self, _bytes: &[u8]) {} + } + + #[test] + fn encdec() { + let mut map = crate::HashMap::<_, _, NoHash>::default(); + map.insert(1, 2); + map.insert(3, 4); + let mut buf = Vec::new(); + map.serialize(&mut buf).unwrap(); + let original = map.clone(); + map = crate::HashMap::<_, _, NoHash>::deserialize_reader(&mut &buf[..]).unwrap(); + assert_eq!(original[&1], map[&1]); + assert_eq!(original[&3], map[&3]); + assert_eq!(original.len(), map.len()); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/mod.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/mod.rs new file mode 100644 index 0000000..841e4b1 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/borsh/mod.rs @@ -0,0 +1 @@ +mod hash_map; diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/mod.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/mod.rs new file mode 100644 index 0000000..bca8f97 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/mod.rs @@ -0,0 +1,6 @@ +#[cfg(feature = "borsh")] +mod borsh; +#[cfg(feature = "rayon")] +pub(crate) mod rayon; +#[cfg(feature = "serde")] +mod serde; diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/helpers.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/helpers.rs new file mode 100644 index 0000000..070b08c --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/helpers.rs @@ -0,0 +1,27 @@ +use alloc::collections::LinkedList; +use alloc::vec::Vec; + +use rayon::iter::{IntoParallelIterator, ParallelIterator}; + +/// Helper for collecting parallel iterators to an intermediary +#[allow(clippy::linkedlist)] // yes, we need linked list here for efficient appending! +pub(super) fn collect(iter: I) -> (LinkedList>, usize) { + let list = iter + .into_par_iter() + .fold(Vec::new, |mut vec, elem| { + vec.push(elem); + vec + }) + .map(|vec| { + let mut list = LinkedList::new(); + list.push_back(vec); + list + }) + .reduce(LinkedList::new, |mut list1, mut list2| { + list1.append(&mut list2); + list1 + }); + + let len = list.iter().map(Vec::len).sum(); + (list, len) +} diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/map.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/map.rs new file mode 100644 index 0000000..9623ca7 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/map.rs @@ -0,0 +1,721 @@ +//! Rayon extensions for `HashMap`. + +use super::raw::{RawIntoParIter, RawParDrain, RawParIter}; +use crate::hash_map::HashMap; +use crate::raw::{Allocator, Global}; +use core::fmt; +use core::hash::{BuildHasher, Hash}; +use core::marker::PhantomData; +use rayon::iter::plumbing::UnindexedConsumer; +use rayon::iter::{FromParallelIterator, IntoParallelIterator, ParallelExtend, ParallelIterator}; + +/// Parallel iterator over shared references to entries in a map. +/// +/// This iterator is created by the [`par_iter`] method on [`HashMap`] +/// (provided by the [`IntoParallelRefIterator`] trait). +/// See its documentation for more. +/// +/// [`par_iter`]: /hashbrown/struct.HashMap.html#method.par_iter +/// [`HashMap`]: /hashbrown/struct.HashMap.html +/// [`IntoParallelRefIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelRefIterator.html +pub struct ParIter<'a, K, V> { + inner: RawParIter<(K, V)>, + marker: PhantomData<(&'a K, &'a V)>, +} + +impl<'a, K: Sync, V: Sync> ParallelIterator for ParIter<'a, K, V> { + type Item = (&'a K, &'a V); + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner + .map(|x| unsafe { + let r = x.as_ref(); + (&r.0, &r.1) + }) + .drive_unindexed(consumer) + } +} + +impl Clone for ParIter<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +impl fmt::Debug for ParIter<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = unsafe { self.inner.iter() }.map(|x| unsafe { + let r = x.as_ref(); + (&r.0, &r.1) + }); + f.debug_list().entries(iter).finish() + } +} + +/// Parallel iterator over shared references to keys in a map. +/// +/// This iterator is created by the [`par_keys`] method on [`HashMap`]. +/// See its documentation for more. +/// +/// [`par_keys`]: /hashbrown/struct.HashMap.html#method.par_keys +/// [`HashMap`]: /hashbrown/struct.HashMap.html +pub struct ParKeys<'a, K, V> { + inner: RawParIter<(K, V)>, + marker: PhantomData<(&'a K, &'a V)>, +} + +impl<'a, K: Sync, V: Sync> ParallelIterator for ParKeys<'a, K, V> { + type Item = &'a K; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner + .map(|x| unsafe { &x.as_ref().0 }) + .drive_unindexed(consumer) + } +} + +impl Clone for ParKeys<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +impl fmt::Debug for ParKeys<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = unsafe { self.inner.iter() }.map(|x| unsafe { &x.as_ref().0 }); + f.debug_list().entries(iter).finish() + } +} + +/// Parallel iterator over shared references to values in a map. +/// +/// This iterator is created by the [`par_values`] method on [`HashMap`]. +/// See its documentation for more. +/// +/// [`par_values`]: /hashbrown/struct.HashMap.html#method.par_values +/// [`HashMap`]: /hashbrown/struct.HashMap.html +pub struct ParValues<'a, K, V> { + inner: RawParIter<(K, V)>, + marker: PhantomData<(&'a K, &'a V)>, +} + +impl<'a, K: Sync, V: Sync> ParallelIterator for ParValues<'a, K, V> { + type Item = &'a V; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner + .map(|x| unsafe { &x.as_ref().1 }) + .drive_unindexed(consumer) + } +} + +impl Clone for ParValues<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +impl fmt::Debug for ParValues<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = unsafe { self.inner.iter() }.map(|x| unsafe { &x.as_ref().1 }); + f.debug_list().entries(iter).finish() + } +} + +/// Parallel iterator over mutable references to entries in a map. +/// +/// This iterator is created by the [`par_iter_mut`] method on [`HashMap`] +/// (provided by the [`IntoParallelRefMutIterator`] trait). +/// See its documentation for more. +/// +/// [`par_iter_mut`]: /hashbrown/struct.HashMap.html#method.par_iter_mut +/// [`HashMap`]: /hashbrown/struct.HashMap.html +/// [`IntoParallelRefMutIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelRefMutIterator.html +pub struct ParIterMut<'a, K, V> { + inner: RawParIter<(K, V)>, + marker: PhantomData<(&'a K, &'a mut V)>, +} + +impl<'a, K: Sync, V: Send> ParallelIterator for ParIterMut<'a, K, V> { + type Item = (&'a K, &'a mut V); + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner + .map(|x| unsafe { + let r = x.as_mut(); + (&r.0, &mut r.1) + }) + .drive_unindexed(consumer) + } +} + +impl fmt::Debug for ParIterMut<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ParIter { + inner: self.inner.clone(), + marker: PhantomData, + } + .fmt(f) + } +} + +/// Parallel iterator over mutable references to values in a map. +/// +/// This iterator is created by the [`par_values_mut`] method on [`HashMap`]. +/// See its documentation for more. +/// +/// [`par_values_mut`]: /hashbrown/struct.HashMap.html#method.par_values_mut +/// [`HashMap`]: /hashbrown/struct.HashMap.html +pub struct ParValuesMut<'a, K, V> { + inner: RawParIter<(K, V)>, + marker: PhantomData<(&'a K, &'a mut V)>, +} + +impl<'a, K: Sync, V: Send> ParallelIterator for ParValuesMut<'a, K, V> { + type Item = &'a mut V; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner + .map(|x| unsafe { &mut x.as_mut().1 }) + .drive_unindexed(consumer) + } +} + +impl fmt::Debug for ParValuesMut<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ParValues { + inner: self.inner.clone(), + marker: PhantomData, + } + .fmt(f) + } +} + +/// Parallel iterator over entries of a consumed map. +/// +/// This iterator is created by the [`into_par_iter`] method on [`HashMap`] +/// (provided by the [`IntoParallelIterator`] trait). +/// See its documentation for more. +/// +/// [`into_par_iter`]: /hashbrown/struct.HashMap.html#method.into_par_iter +/// [`HashMap`]: /hashbrown/struct.HashMap.html +/// [`IntoParallelIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelIterator.html +pub struct IntoParIter { + inner: RawIntoParIter<(K, V), A>, +} + +impl ParallelIterator for IntoParIter { + type Item = (K, V); + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner.drive_unindexed(consumer) + } +} + +impl fmt::Debug for IntoParIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ParIter { + inner: unsafe { self.inner.par_iter() }, + marker: PhantomData, + } + .fmt(f) + } +} + +/// Parallel draining iterator over entries of a map. +/// +/// This iterator is created by the [`par_drain`] method on [`HashMap`]. +/// See its documentation for more. +/// +/// [`par_drain`]: /hashbrown/struct.HashMap.html#method.par_drain +/// [`HashMap`]: /hashbrown/struct.HashMap.html +pub struct ParDrain<'a, K, V, A: Allocator = Global> { + inner: RawParDrain<'a, (K, V), A>, +} + +impl ParallelIterator for ParDrain<'_, K, V, A> { + type Item = (K, V); + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner.drive_unindexed(consumer) + } +} + +impl fmt::Debug for ParDrain<'_, K, V, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ParIter { + inner: unsafe { self.inner.par_iter() }, + marker: PhantomData, + } + .fmt(f) + } +} + +impl HashMap { + /// Visits (potentially in parallel) immutably borrowed keys in an arbitrary order. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_keys(&self) -> ParKeys<'_, K, V> { + ParKeys { + inner: unsafe { self.table.par_iter() }, + marker: PhantomData, + } + } + + /// Visits (potentially in parallel) immutably borrowed values in an arbitrary order. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_values(&self) -> ParValues<'_, K, V> { + ParValues { + inner: unsafe { self.table.par_iter() }, + marker: PhantomData, + } + } +} + +impl HashMap { + /// Visits (potentially in parallel) mutably borrowed values in an arbitrary order. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_values_mut(&mut self) -> ParValuesMut<'_, K, V> { + ParValuesMut { + inner: unsafe { self.table.par_iter() }, + marker: PhantomData, + } + } + + /// Consumes (potentially in parallel) all values in an arbitrary order, + /// while preserving the map's allocated memory for reuse. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_drain(&mut self) -> ParDrain<'_, K, V, A> { + ParDrain { + inner: self.table.par_drain(), + } + } +} + +impl HashMap +where + K: Eq + Hash + Sync, + V: PartialEq + Sync, + S: BuildHasher + Sync, + A: Allocator + Sync, +{ + /// Returns `true` if the map is equal to another, + /// i.e. both maps contain the same keys mapped to the same values. + /// + /// This method runs in a potentially parallel fashion. + pub fn par_eq(&self, other: &Self) -> bool { + self.len() == other.len() + && self + .into_par_iter() + .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v)) + } +} + +impl IntoParallelIterator for HashMap { + type Item = (K, V); + type Iter = IntoParIter; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + inner: self.table.into_par_iter(), + } + } +} + +impl<'a, K: Sync, V: Sync, S, A: Allocator> IntoParallelIterator for &'a HashMap { + type Item = (&'a K, &'a V); + type Iter = ParIter<'a, K, V>; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + ParIter { + inner: unsafe { self.table.par_iter() }, + marker: PhantomData, + } + } +} + +impl<'a, K: Sync, V: Send, S, A: Allocator> IntoParallelIterator for &'a mut HashMap { + type Item = (&'a K, &'a mut V); + type Iter = ParIterMut<'a, K, V>; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + ParIterMut { + inner: unsafe { self.table.par_iter() }, + marker: PhantomData, + } + } +} + +/// Collect (key, value) pairs from a parallel iterator into a +/// hashmap. If multiple pairs correspond to the same key, then the +/// ones produced earlier in the parallel iterator will be +/// overwritten, just as with a sequential iterator. +impl FromParallelIterator<(K, V)> for HashMap +where + K: Eq + Hash + Send, + V: Send, + S: BuildHasher + Default, +{ + fn from_par_iter

(par_iter: P) -> Self + where + P: IntoParallelIterator, + { + let mut map = HashMap::default(); + map.par_extend(par_iter); + map + } +} + +/// Extend a hash map with items from a parallel iterator. +impl ParallelExtend<(K, V)> for HashMap +where + K: Eq + Hash + Send, + V: Send, + S: BuildHasher, + A: Allocator, +{ + fn par_extend(&mut self, par_iter: I) + where + I: IntoParallelIterator, + { + extend(self, par_iter); + } +} + +/// Extend a hash map with copied items from a parallel iterator. +impl<'a, K, V, S, A> ParallelExtend<(&'a K, &'a V)> for HashMap +where + K: Copy + Eq + Hash + Sync, + V: Copy + Sync, + S: BuildHasher, + A: Allocator, +{ + fn par_extend(&mut self, par_iter: I) + where + I: IntoParallelIterator, + { + extend(self, par_iter); + } +} + +// This is equal to the normal `HashMap` -- no custom advantage. +fn extend(map: &mut HashMap, par_iter: I) +where + K: Eq + Hash, + S: BuildHasher, + I: IntoParallelIterator, + A: Allocator, + HashMap: Extend, +{ + let (list, len) = super::helpers::collect(par_iter); + + // Keys may be already present or show multiple times in the iterator. + // Reserve the entire length if the map is empty. + // Otherwise reserve half the length (rounded up), so the map + // will only resize twice in the worst case. + let reserve = if map.is_empty() { len } else { (len + 1) / 2 }; + map.reserve(reserve); + for vec in list { + map.extend(vec); + } +} + +#[cfg(test)] +mod test_par_map { + use alloc::vec::Vec; + use core::hash::{Hash, Hasher}; + use core::sync::atomic::{AtomicUsize, Ordering}; + + use rayon::prelude::*; + + use crate::hash_map::HashMap; + + struct Droppable<'a> { + k: usize, + counter: &'a AtomicUsize, + } + + impl Droppable<'_> { + fn new(k: usize, counter: &AtomicUsize) -> Droppable<'_> { + counter.fetch_add(1, Ordering::Relaxed); + + Droppable { k, counter } + } + } + + impl Drop for Droppable<'_> { + fn drop(&mut self) { + self.counter.fetch_sub(1, Ordering::Relaxed); + } + } + + impl Clone for Droppable<'_> { + fn clone(&self) -> Self { + Droppable::new(self.k, self.counter) + } + } + + impl Hash for Droppable<'_> { + fn hash(&self, state: &mut H) + where + H: Hasher, + { + self.k.hash(state); + } + } + + impl PartialEq for Droppable<'_> { + fn eq(&self, other: &Self) -> bool { + self.k == other.k + } + } + + impl Eq for Droppable<'_> {} + + #[test] + fn test_into_iter_drops() { + let key = AtomicUsize::new(0); + let value = AtomicUsize::new(0); + + let hm = { + let mut hm = HashMap::new(); + + assert_eq!(key.load(Ordering::Relaxed), 0); + assert_eq!(value.load(Ordering::Relaxed), 0); + + for i in 0..100 { + let d1 = Droppable::new(i, &key); + let d2 = Droppable::new(i + 100, &value); + hm.insert(d1, d2); + } + + assert_eq!(key.load(Ordering::Relaxed), 100); + assert_eq!(value.load(Ordering::Relaxed), 100); + + hm + }; + + // By the way, ensure that cloning doesn't screw up the dropping. + drop(hm.clone()); + + assert_eq!(key.load(Ordering::Relaxed), 100); + assert_eq!(value.load(Ordering::Relaxed), 100); + + // Ensure that dropping the iterator does not leak anything. + drop(hm.clone().into_par_iter()); + + { + assert_eq!(key.load(Ordering::Relaxed), 100); + assert_eq!(value.load(Ordering::Relaxed), 100); + + // retain only half + let _v: Vec<_> = hm.into_par_iter().filter(|(key, _)| key.k < 50).collect(); + + assert_eq!(key.load(Ordering::Relaxed), 50); + assert_eq!(value.load(Ordering::Relaxed), 50); + }; + + assert_eq!(key.load(Ordering::Relaxed), 0); + assert_eq!(value.load(Ordering::Relaxed), 0); + } + + #[test] + fn test_drain_drops() { + let key = AtomicUsize::new(0); + let value = AtomicUsize::new(0); + + let mut hm = { + let mut hm = HashMap::new(); + + assert_eq!(key.load(Ordering::Relaxed), 0); + assert_eq!(value.load(Ordering::Relaxed), 0); + + for i in 0..100 { + let d1 = Droppable::new(i, &key); + let d2 = Droppable::new(i + 100, &value); + hm.insert(d1, d2); + } + + assert_eq!(key.load(Ordering::Relaxed), 100); + assert_eq!(value.load(Ordering::Relaxed), 100); + + hm + }; + + // By the way, ensure that cloning doesn't screw up the dropping. + drop(hm.clone()); + + assert_eq!(key.load(Ordering::Relaxed), 100); + assert_eq!(value.load(Ordering::Relaxed), 100); + + // Ensure that dropping the drain iterator does not leak anything. + drop(hm.clone().par_drain()); + + { + assert_eq!(key.load(Ordering::Relaxed), 100); + assert_eq!(value.load(Ordering::Relaxed), 100); + + // retain only half + let _v: Vec<_> = hm.drain().filter(|(key, _)| key.k < 50).collect(); + assert!(hm.is_empty()); + + assert_eq!(key.load(Ordering::Relaxed), 50); + assert_eq!(value.load(Ordering::Relaxed), 50); + }; + + assert_eq!(key.load(Ordering::Relaxed), 0); + assert_eq!(value.load(Ordering::Relaxed), 0); + } + + #[test] + fn test_empty_iter() { + let mut m: HashMap = HashMap::new(); + assert_eq!(m.par_drain().count(), 0); + assert_eq!(m.par_keys().count(), 0); + assert_eq!(m.par_values().count(), 0); + assert_eq!(m.par_values_mut().count(), 0); + assert_eq!(m.par_iter().count(), 0); + assert_eq!(m.par_iter_mut().count(), 0); + assert_eq!(m.len(), 0); + assert!(m.is_empty()); + assert_eq!(m.into_par_iter().count(), 0); + } + + #[test] + fn test_iterate() { + let mut m = HashMap::with_capacity(4); + for i in 0..32 { + assert!(m.insert(i, i * 2).is_none()); + } + assert_eq!(m.len(), 32); + + let observed = AtomicUsize::new(0); + + m.par_iter().for_each(|(k, v)| { + assert_eq!(*v, *k * 2); + observed.fetch_or(1 << *k, Ordering::Relaxed); + }); + assert_eq!(observed.into_inner(), 0xFFFF_FFFF); + } + + #[test] + fn test_keys() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = vec.into_par_iter().collect(); + let keys: Vec<_> = map.par_keys().cloned().collect(); + assert_eq!(keys.len(), 3); + assert!(keys.contains(&1)); + assert!(keys.contains(&2)); + assert!(keys.contains(&3)); + } + + #[test] + fn test_values() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = vec.into_par_iter().collect(); + let values: Vec<_> = map.par_values().cloned().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&'a')); + assert!(values.contains(&'b')); + assert!(values.contains(&'c')); + } + + #[test] + fn test_values_mut() { + let vec = vec![(1, 1), (2, 2), (3, 3)]; + let mut map: HashMap<_, _> = vec.into_par_iter().collect(); + map.par_values_mut().for_each(|value| *value *= 2); + let values: Vec<_> = map.par_values().cloned().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&2)); + assert!(values.contains(&4)); + assert!(values.contains(&6)); + } + + #[test] + fn test_eq() { + let mut m1 = HashMap::new(); + m1.insert(1, 2); + m1.insert(2, 3); + m1.insert(3, 4); + + let mut m2 = HashMap::new(); + m2.insert(1, 2); + m2.insert(2, 3); + + assert!(!m1.par_eq(&m2)); + + m2.insert(3, 4); + + assert!(m1.par_eq(&m2)); + } + + #[test] + fn test_from_iter() { + let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + + let map: HashMap<_, _> = xs.par_iter().cloned().collect(); + + for &(k, v) in &xs { + assert_eq!(map.get(&k), Some(&v)); + } + } + + #[test] + fn test_extend_ref() { + let mut a = HashMap::new(); + a.insert(1, "one"); + let mut b = HashMap::new(); + b.insert(2, "two"); + b.insert(3, "three"); + + a.par_extend(&b); + + assert_eq!(a.len(), 3); + assert_eq!(a[&1], "one"); + assert_eq!(a[&2], "two"); + assert_eq!(a[&3], "three"); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/mod.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/mod.rs new file mode 100644 index 0000000..61ca69b --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/mod.rs @@ -0,0 +1,5 @@ +mod helpers; +pub(crate) mod map; +pub(crate) mod raw; +pub(crate) mod set; +pub(crate) mod table; diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/raw.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/raw.rs new file mode 100644 index 0000000..612be47 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/raw.rs @@ -0,0 +1,230 @@ +use crate::raw::Bucket; +use crate::raw::{Allocator, Global, RawIter, RawIterRange, RawTable}; +use crate::scopeguard::guard; +use core::marker::PhantomData; +use core::mem; +use core::ptr::NonNull; +use rayon::iter::{ + plumbing::{self, Folder, UnindexedConsumer, UnindexedProducer}, + ParallelIterator, +}; + +/// Parallel iterator which returns a raw pointer to every full bucket in the table. +pub struct RawParIter { + iter: RawIterRange, +} + +impl RawParIter { + #[cfg_attr(feature = "inline-more", inline)] + pub(super) unsafe fn iter(&self) -> RawIterRange { + self.iter.clone() + } +} + +impl Clone for RawParIter { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + iter: self.iter.clone(), + } + } +} + +impl From> for RawParIter { + fn from(it: RawIter) -> Self { + RawParIter { iter: it.iter } + } +} + +impl ParallelIterator for RawParIter { + type Item = Bucket; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + let producer = ParIterProducer { iter: self.iter }; + plumbing::bridge_unindexed(producer, consumer) + } +} + +/// Producer which returns a `Bucket` for every element. +struct ParIterProducer { + iter: RawIterRange, +} + +impl UnindexedProducer for ParIterProducer { + type Item = Bucket; + + #[cfg_attr(feature = "inline-more", inline)] + fn split(self) -> (Self, Option) { + let (left, right) = self.iter.split(); + let left = ParIterProducer { iter: left }; + let right = right.map(|right| ParIterProducer { iter: right }); + (left, right) + } + + #[cfg_attr(feature = "inline-more", inline)] + fn fold_with(self, folder: F) -> F + where + F: Folder, + { + folder.consume_iter(self.iter) + } +} + +/// Parallel iterator which consumes a table and returns elements. +pub struct RawIntoParIter { + table: RawTable, +} + +impl RawIntoParIter { + #[cfg_attr(feature = "inline-more", inline)] + pub(super) unsafe fn par_iter(&self) -> RawParIter { + self.table.par_iter() + } +} + +impl ParallelIterator for RawIntoParIter { + type Item = T; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + let iter = unsafe { self.table.iter().iter }; + let _guard = guard(self.table.into_allocation(), |alloc| { + if let Some((ptr, layout, ref alloc)) = *alloc { + unsafe { + alloc.deallocate(ptr, layout); + } + } + }); + let producer = ParDrainProducer { iter }; + plumbing::bridge_unindexed(producer, consumer) + } +} + +/// Parallel iterator which consumes elements without freeing the table storage. +pub struct RawParDrain<'a, T, A: Allocator = Global> { + // We don't use a &'a mut RawTable because we want RawParDrain to be + // covariant over T. + table: NonNull>, + marker: PhantomData<&'a RawTable>, +} + +unsafe impl Send for RawParDrain<'_, T, A> {} + +impl RawParDrain<'_, T, A> { + #[cfg_attr(feature = "inline-more", inline)] + pub(super) unsafe fn par_iter(&self) -> RawParIter { + self.table.as_ref().par_iter() + } +} + +impl ParallelIterator for RawParDrain<'_, T, A> { + type Item = T; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + let _guard = guard(self.table, |table| unsafe { + table.as_mut().clear_no_drop(); + }); + let iter = unsafe { self.table.as_ref().iter().iter }; + mem::forget(self); + let producer = ParDrainProducer { iter }; + plumbing::bridge_unindexed(producer, consumer) + } +} + +impl Drop for RawParDrain<'_, T, A> { + fn drop(&mut self) { + // If drive_unindexed is not called then simply clear the table. + unsafe { + self.table.as_mut().clear(); + } + } +} + +/// Producer which will consume all elements in the range, even if it is dropped +/// halfway through. +struct ParDrainProducer { + iter: RawIterRange, +} + +impl UnindexedProducer for ParDrainProducer { + type Item = T; + + #[cfg_attr(feature = "inline-more", inline)] + fn split(self) -> (Self, Option) { + let (left, right) = self.iter.clone().split(); + mem::forget(self); + let left = ParDrainProducer { iter: left }; + let right = right.map(|right| ParDrainProducer { iter: right }); + (left, right) + } + + #[cfg_attr(feature = "inline-more", inline)] + fn fold_with(mut self, mut folder: F) -> F + where + F: Folder, + { + // Make sure to modify the iterator in-place so that any remaining + // elements are processed in our Drop impl. + for item in &mut self.iter { + folder = folder.consume(unsafe { item.read() }); + if folder.full() { + return folder; + } + } + + // If we processed all elements then we don't need to run the drop. + mem::forget(self); + folder + } +} + +impl Drop for ParDrainProducer { + #[cfg_attr(feature = "inline-more", inline)] + fn drop(&mut self) { + // Drop all remaining elements + if mem::needs_drop::() { + for item in &mut self.iter { + unsafe { + item.drop(); + } + } + } + } +} + +impl RawTable { + /// Returns a parallel iterator over the elements in a `RawTable`. + #[cfg_attr(feature = "inline-more", inline)] + pub unsafe fn par_iter(&self) -> RawParIter { + RawParIter { + iter: self.iter().iter, + } + } + + /// Returns a parallel iterator over the elements in a `RawTable`. + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_par_iter(self) -> RawIntoParIter { + RawIntoParIter { table: self } + } + + /// Returns a parallel iterator which consumes all elements of a `RawTable` + /// without freeing its memory allocation. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_drain(&mut self) -> RawParDrain<'_, T, A> { + RawParDrain { + table: NonNull::from(self), + marker: PhantomData, + } + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/set.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/set.rs new file mode 100644 index 0000000..3de98fc --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/set.rs @@ -0,0 +1,659 @@ +//! Rayon extensions for `HashSet`. + +use super::map; +use crate::hash_set::HashSet; +use crate::raw::{Allocator, Global}; +use core::hash::{BuildHasher, Hash}; +use rayon::iter::plumbing::UnindexedConsumer; +use rayon::iter::{FromParallelIterator, IntoParallelIterator, ParallelExtend, ParallelIterator}; + +/// Parallel iterator over elements of a consumed set. +/// +/// This iterator is created by the [`into_par_iter`] method on [`HashSet`] +/// (provided by the [`IntoParallelIterator`] trait). +/// See its documentation for more. +/// +/// [`into_par_iter`]: /hashbrown/struct.HashSet.html#method.into_par_iter +/// [`HashSet`]: /hashbrown/struct.HashSet.html +/// [`IntoParallelIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelIterator.html +pub struct IntoParIter { + inner: map::IntoParIter, +} + +impl ParallelIterator for IntoParIter { + type Item = T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner.map(|(k, _)| k).drive_unindexed(consumer) + } +} + +/// Parallel draining iterator over entries of a set. +/// +/// This iterator is created by the [`par_drain`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`par_drain`]: /hashbrown/struct.HashSet.html#method.par_drain +/// [`HashSet`]: /hashbrown/struct.HashSet.html +pub struct ParDrain<'a, T, A: Allocator = Global> { + inner: map::ParDrain<'a, T, (), A>, +} + +impl ParallelIterator for ParDrain<'_, T, A> { + type Item = T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner.map(|(k, _)| k).drive_unindexed(consumer) + } +} + +/// Parallel iterator over shared references to elements in a set. +/// +/// This iterator is created by the [`par_iter`] method on [`HashSet`] +/// (provided by the [`IntoParallelRefIterator`] trait). +/// See its documentation for more. +/// +/// [`par_iter`]: /hashbrown/struct.HashSet.html#method.par_iter +/// [`HashSet`]: /hashbrown/struct.HashSet.html +/// [`IntoParallelRefIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelRefIterator.html +pub struct ParIter<'a, T> { + inner: map::ParKeys<'a, T, ()>, +} + +impl<'a, T: Sync> ParallelIterator for ParIter<'a, T> { + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner.drive_unindexed(consumer) + } +} + +/// Parallel iterator over shared references to elements in the difference of +/// sets. +/// +/// This iterator is created by the [`par_difference`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`par_difference`]: /hashbrown/struct.HashSet.html#method.par_difference +/// [`HashSet`]: /hashbrown/struct.HashSet.html +pub struct ParDifference<'a, T, S, A: Allocator = Global> { + a: &'a HashSet, + b: &'a HashSet, +} + +impl<'a, T, S, A> ParallelIterator for ParDifference<'a, T, S, A> +where + T: Eq + Hash + Sync, + S: BuildHasher + Sync, + A: Allocator + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.a + .into_par_iter() + .filter(|&x| !self.b.contains(x)) + .drive_unindexed(consumer) + } +} + +/// Parallel iterator over shared references to elements in the symmetric +/// difference of sets. +/// +/// This iterator is created by the [`par_symmetric_difference`] method on +/// [`HashSet`]. +/// See its documentation for more. +/// +/// [`par_symmetric_difference`]: /hashbrown/struct.HashSet.html#method.par_symmetric_difference +/// [`HashSet`]: /hashbrown/struct.HashSet.html +pub struct ParSymmetricDifference<'a, T, S, A: Allocator = Global> { + a: &'a HashSet, + b: &'a HashSet, +} + +impl<'a, T, S, A> ParallelIterator for ParSymmetricDifference<'a, T, S, A> +where + T: Eq + Hash + Sync, + S: BuildHasher + Sync, + A: Allocator + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.a + .par_difference(self.b) + .chain(self.b.par_difference(self.a)) + .drive_unindexed(consumer) + } +} + +/// Parallel iterator over shared references to elements in the intersection of +/// sets. +/// +/// This iterator is created by the [`par_intersection`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`par_intersection`]: /hashbrown/struct.HashSet.html#method.par_intersection +/// [`HashSet`]: /hashbrown/struct.HashSet.html +pub struct ParIntersection<'a, T, S, A: Allocator = Global> { + a: &'a HashSet, + b: &'a HashSet, +} + +impl<'a, T, S, A> ParallelIterator for ParIntersection<'a, T, S, A> +where + T: Eq + Hash + Sync, + S: BuildHasher + Sync, + A: Allocator + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.a + .into_par_iter() + .filter(|&x| self.b.contains(x)) + .drive_unindexed(consumer) + } +} + +/// Parallel iterator over shared references to elements in the union of sets. +/// +/// This iterator is created by the [`par_union`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`par_union`]: /hashbrown/struct.HashSet.html#method.par_union +/// [`HashSet`]: /hashbrown/struct.HashSet.html +pub struct ParUnion<'a, T, S, A: Allocator = Global> { + a: &'a HashSet, + b: &'a HashSet, +} + +impl<'a, T, S, A> ParallelIterator for ParUnion<'a, T, S, A> +where + T: Eq + Hash + Sync, + S: BuildHasher + Sync, + A: Allocator + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + // We'll iterate one set in full, and only the remaining difference from the other. + // Use the smaller set for the difference in order to reduce hash lookups. + let (smaller, larger) = if self.a.len() <= self.b.len() { + (self.a, self.b) + } else { + (self.b, self.a) + }; + larger + .into_par_iter() + .chain(smaller.par_difference(larger)) + .drive_unindexed(consumer) + } +} + +impl HashSet +where + T: Eq + Hash + Sync, + S: BuildHasher + Sync, + A: Allocator + Sync, +{ + /// Visits (potentially in parallel) the values representing the union, + /// i.e. all the values in `self` or `other`, without duplicates. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_union<'a>(&'a self, other: &'a Self) -> ParUnion<'a, T, S, A> { + ParUnion { a: self, b: other } + } + + /// Visits (potentially in parallel) the values representing the difference, + /// i.e. the values that are in `self` but not in `other`. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_difference<'a>(&'a self, other: &'a Self) -> ParDifference<'a, T, S, A> { + ParDifference { a: self, b: other } + } + + /// Visits (potentially in parallel) the values representing the symmetric + /// difference, i.e. the values that are in `self` or in `other` but not in both. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_symmetric_difference<'a>( + &'a self, + other: &'a Self, + ) -> ParSymmetricDifference<'a, T, S, A> { + ParSymmetricDifference { a: self, b: other } + } + + /// Visits (potentially in parallel) the values representing the + /// intersection, i.e. the values that are both in `self` and `other`. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_intersection<'a>(&'a self, other: &'a Self) -> ParIntersection<'a, T, S, A> { + ParIntersection { a: self, b: other } + } + + /// Returns `true` if `self` has no elements in common with `other`. + /// This is equivalent to checking for an empty intersection. + /// + /// This method runs in a potentially parallel fashion. + pub fn par_is_disjoint(&self, other: &Self) -> bool { + self.into_par_iter().all(|x| !other.contains(x)) + } + + /// Returns `true` if the set is a subset of another, + /// i.e. `other` contains at least all the values in `self`. + /// + /// This method runs in a potentially parallel fashion. + pub fn par_is_subset(&self, other: &Self) -> bool { + if self.len() <= other.len() { + self.into_par_iter().all(|x| other.contains(x)) + } else { + false + } + } + + /// Returns `true` if the set is a superset of another, + /// i.e. `self` contains at least all the values in `other`. + /// + /// This method runs in a potentially parallel fashion. + pub fn par_is_superset(&self, other: &Self) -> bool { + other.par_is_subset(self) + } + + /// Returns `true` if the set is equal to another, + /// i.e. both sets contain the same values. + /// + /// This method runs in a potentially parallel fashion. + pub fn par_eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.par_is_subset(other) + } +} + +impl HashSet +where + T: Eq + Hash + Send, + A: Allocator + Send, +{ + /// Consumes (potentially in parallel) all values in an arbitrary order, + /// while preserving the set's allocated memory for reuse. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_drain(&mut self) -> ParDrain<'_, T, A> { + ParDrain { + inner: self.map.par_drain(), + } + } +} + +impl IntoParallelIterator for HashSet { + type Item = T; + type Iter = IntoParIter; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + inner: self.map.into_par_iter(), + } + } +} + +impl<'a, T: Sync, S, A: Allocator> IntoParallelIterator for &'a HashSet { + type Item = &'a T; + type Iter = ParIter<'a, T>; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + ParIter { + inner: self.map.par_keys(), + } + } +} + +/// Collect values from a parallel iterator into a hashset. +impl FromParallelIterator for HashSet +where + T: Eq + Hash + Send, + S: BuildHasher + Default, +{ + fn from_par_iter

(par_iter: P) -> Self + where + P: IntoParallelIterator, + { + let mut set = HashSet::default(); + set.par_extend(par_iter); + set + } +} + +/// Extend a hash set with items from a parallel iterator. +impl ParallelExtend for HashSet +where + T: Eq + Hash + Send, + S: BuildHasher, +{ + fn par_extend(&mut self, par_iter: I) + where + I: IntoParallelIterator, + { + extend(self, par_iter); + } +} + +/// Extend a hash set with copied items from a parallel iterator. +impl<'a, T, S> ParallelExtend<&'a T> for HashSet +where + T: 'a + Copy + Eq + Hash + Sync, + S: BuildHasher, +{ + fn par_extend(&mut self, par_iter: I) + where + I: IntoParallelIterator, + { + extend(self, par_iter); + } +} + +// This is equal to the normal `HashSet` -- no custom advantage. +fn extend(set: &mut HashSet, par_iter: I) +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, + I: IntoParallelIterator, + HashSet: Extend, +{ + let (list, len) = super::helpers::collect(par_iter); + + // Values may be already present or show multiple times in the iterator. + // Reserve the entire length if the set is empty. + // Otherwise reserve half the length (rounded up), so the set + // will only resize twice in the worst case. + let reserve = if set.is_empty() { len } else { (len + 1) / 2 }; + set.reserve(reserve); + for vec in list { + set.extend(vec); + } +} + +#[cfg(test)] +mod test_par_set { + use alloc::vec::Vec; + use core::sync::atomic::{AtomicUsize, Ordering}; + + use rayon::prelude::*; + + use crate::hash_set::HashSet; + + #[test] + fn test_disjoint() { + let mut xs = HashSet::new(); + let mut ys = HashSet::new(); + assert!(xs.par_is_disjoint(&ys)); + assert!(ys.par_is_disjoint(&xs)); + assert!(xs.insert(5)); + assert!(ys.insert(11)); + assert!(xs.par_is_disjoint(&ys)); + assert!(ys.par_is_disjoint(&xs)); + assert!(xs.insert(7)); + assert!(xs.insert(19)); + assert!(xs.insert(4)); + assert!(ys.insert(2)); + assert!(ys.insert(-11)); + assert!(xs.par_is_disjoint(&ys)); + assert!(ys.par_is_disjoint(&xs)); + assert!(ys.insert(7)); + assert!(!xs.par_is_disjoint(&ys)); + assert!(!ys.par_is_disjoint(&xs)); + } + + #[test] + fn test_subset_and_superset() { + let mut a = HashSet::new(); + assert!(a.insert(0)); + assert!(a.insert(5)); + assert!(a.insert(11)); + assert!(a.insert(7)); + + let mut b = HashSet::new(); + assert!(b.insert(0)); + assert!(b.insert(7)); + assert!(b.insert(19)); + assert!(b.insert(250)); + assert!(b.insert(11)); + assert!(b.insert(200)); + + assert!(!a.par_is_subset(&b)); + assert!(!a.par_is_superset(&b)); + assert!(!b.par_is_subset(&a)); + assert!(!b.par_is_superset(&a)); + + assert!(b.insert(5)); + + assert!(a.par_is_subset(&b)); + assert!(!a.par_is_superset(&b)); + assert!(!b.par_is_subset(&a)); + assert!(b.par_is_superset(&a)); + } + + #[test] + fn test_iterate() { + let mut a = HashSet::new(); + for i in 0..32 { + assert!(a.insert(i)); + } + let observed = AtomicUsize::new(0); + a.par_iter().for_each(|k| { + observed.fetch_or(1 << *k, Ordering::Relaxed); + }); + assert_eq!(observed.into_inner(), 0xFFFF_FFFF); + } + + #[test] + fn test_intersection() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(11)); + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(77)); + assert!(a.insert(103)); + assert!(a.insert(5)); + assert!(a.insert(-5)); + + assert!(b.insert(2)); + assert!(b.insert(11)); + assert!(b.insert(77)); + assert!(b.insert(-9)); + assert!(b.insert(-42)); + assert!(b.insert(5)); + assert!(b.insert(3)); + + let expected = [3, 5, 11, 77]; + let i = a + .par_intersection(&b) + .map(|x| { + assert!(expected.contains(x)); + 1 + }) + .sum::(); + assert_eq!(i, expected.len()); + } + + #[test] + fn test_difference() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(3)); + assert!(b.insert(9)); + + let expected = [1, 5, 11]; + let i = a + .par_difference(&b) + .map(|x| { + assert!(expected.contains(x)); + 1 + }) + .sum::(); + assert_eq!(i, expected.len()); + } + + #[test] + fn test_symmetric_difference() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(-2)); + assert!(b.insert(3)); + assert!(b.insert(9)); + assert!(b.insert(14)); + assert!(b.insert(22)); + + let expected = [-2, 1, 5, 11, 14, 22]; + let i = a + .par_symmetric_difference(&b) + .map(|x| { + assert!(expected.contains(x)); + 1 + }) + .sum::(); + assert_eq!(i, expected.len()); + } + + #[test] + fn test_union() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + assert!(a.insert(16)); + assert!(a.insert(19)); + assert!(a.insert(24)); + + assert!(b.insert(-2)); + assert!(b.insert(1)); + assert!(b.insert(5)); + assert!(b.insert(9)); + assert!(b.insert(13)); + assert!(b.insert(19)); + + let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]; + let i = a + .par_union(&b) + .map(|x| { + assert!(expected.contains(x)); + 1 + }) + .sum::(); + assert_eq!(i, expected.len()); + } + + #[test] + fn test_from_iter() { + let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + + let set: HashSet<_> = xs.par_iter().cloned().collect(); + + for x in &xs { + assert!(set.contains(x)); + } + } + + #[test] + fn test_move_iter() { + let hs = { + let mut hs = HashSet::new(); + + hs.insert('a'); + hs.insert('b'); + + hs + }; + + let v = hs.into_par_iter().collect::>(); + assert!(v == ['a', 'b'] || v == ['b', 'a']); + } + + #[test] + fn test_eq() { + // These constants once happened to expose a bug in insert(). + // I'm keeping them around to prevent a regression. + let mut s1 = HashSet::new(); + + s1.insert(1); + s1.insert(2); + s1.insert(3); + + let mut s2 = HashSet::new(); + + s2.insert(1); + s2.insert(2); + + assert!(!s1.par_eq(&s2)); + + s2.insert(3); + + assert!(s1.par_eq(&s2)); + } + + #[test] + fn test_extend_ref() { + let mut a = HashSet::new(); + a.insert(1); + + a.par_extend(&[2, 3, 4][..]); + + assert_eq!(a.len(), 4); + assert!(a.contains(&1)); + assert!(a.contains(&2)); + assert!(a.contains(&3)); + assert!(a.contains(&4)); + + let mut b = HashSet::new(); + b.insert(5); + b.insert(6); + + a.par_extend(&b); + + assert_eq!(a.len(), 6); + assert!(a.contains(&1)); + assert!(a.contains(&2)); + assert!(a.contains(&3)); + assert!(a.contains(&4)); + assert!(a.contains(&5)); + assert!(a.contains(&6)); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/table.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/table.rs new file mode 100644 index 0000000..cb04a03 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/rayon/table.rs @@ -0,0 +1,249 @@ +//! Rayon extensions for `HashTable`. + +use super::raw::{RawIntoParIter, RawParDrain, RawParIter}; +use crate::hash_table::HashTable; +use crate::raw::{Allocator, Global}; +use core::fmt; +use core::marker::PhantomData; +use rayon::iter::plumbing::UnindexedConsumer; +use rayon::iter::{IntoParallelIterator, ParallelIterator}; + +/// Parallel iterator over shared references to entries in a map. +/// +/// This iterator is created by the [`par_iter`] method on [`HashTable`] +/// (provided by the [`IntoParallelRefIterator`] trait). +/// See its documentation for more. +/// +/// [`par_iter`]: /hashbrown/struct.HashTable.html#method.par_iter +/// [`HashTable`]: /hashbrown/struct.HashTable.html +/// [`IntoParallelRefIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelRefIterator.html +pub struct ParIter<'a, T> { + inner: RawParIter, + marker: PhantomData<&'a T>, +} + +impl<'a, T: Sync> ParallelIterator for ParIter<'a, T> { + type Item = &'a T; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner + .map(|x| unsafe { x.as_ref() }) + .drive_unindexed(consumer) + } +} + +impl Clone for ParIter<'_, T> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +impl fmt::Debug for ParIter<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = unsafe { self.inner.iter() }.map(|x| unsafe { x.as_ref() }); + f.debug_list().entries(iter).finish() + } +} + +/// Parallel iterator over mutable references to entries in a map. +/// +/// This iterator is created by the [`par_iter_mut`] method on [`HashTable`] +/// (provided by the [`IntoParallelRefMutIterator`] trait). +/// See its documentation for more. +/// +/// [`par_iter_mut`]: /hashbrown/struct.HashTable.html#method.par_iter_mut +/// [`HashTable`]: /hashbrown/struct.HashTable.html +/// [`IntoParallelRefMutIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelRefMutIterator.html +pub struct ParIterMut<'a, T> { + inner: RawParIter, + marker: PhantomData<&'a mut T>, +} + +impl<'a, T: Send> ParallelIterator for ParIterMut<'a, T> { + type Item = &'a mut T; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner + .map(|x| unsafe { x.as_mut() }) + .drive_unindexed(consumer) + } +} + +impl fmt::Debug for ParIterMut<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ParIter { + inner: self.inner.clone(), + marker: PhantomData, + } + .fmt(f) + } +} + +/// Parallel iterator over entries of a consumed map. +/// +/// This iterator is created by the [`into_par_iter`] method on [`HashTable`] +/// (provided by the [`IntoParallelIterator`] trait). +/// See its documentation for more. +/// +/// [`into_par_iter`]: /hashbrown/struct.HashTable.html#method.into_par_iter +/// [`HashTable`]: /hashbrown/struct.HashTable.html +/// [`IntoParallelIterator`]: https://docs.rs/rayon/1.0/rayon/iter/trait.IntoParallelIterator.html +pub struct IntoParIter { + inner: RawIntoParIter, +} + +impl ParallelIterator for IntoParIter { + type Item = T; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner.drive_unindexed(consumer) + } +} + +impl fmt::Debug for IntoParIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ParIter { + inner: unsafe { self.inner.par_iter() }, + marker: PhantomData, + } + .fmt(f) + } +} + +/// Parallel draining iterator over entries of a map. +/// +/// This iterator is created by the [`par_drain`] method on [`HashTable`]. +/// See its documentation for more. +/// +/// [`par_drain`]: /hashbrown/struct.HashTable.html#method.par_drain +/// [`HashTable`]: /hashbrown/struct.HashTable.html +pub struct ParDrain<'a, T, A: Allocator = Global> { + inner: RawParDrain<'a, T, A>, +} + +impl ParallelIterator for ParDrain<'_, T, A> { + type Item = T; + + #[cfg_attr(feature = "inline-more", inline)] + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.inner.drive_unindexed(consumer) + } +} + +impl fmt::Debug for ParDrain<'_, T, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ParIter { + inner: unsafe { self.inner.par_iter() }, + marker: PhantomData, + } + .fmt(f) + } +} + +impl HashTable { + /// Consumes (potentially in parallel) all values in an arbitrary order, + /// while preserving the map's allocated memory for reuse. + #[cfg_attr(feature = "inline-more", inline)] + pub fn par_drain(&mut self) -> ParDrain<'_, T, A> { + ParDrain { + inner: self.raw.par_drain(), + } + } +} + +impl IntoParallelIterator for HashTable { + type Item = T; + type Iter = IntoParIter; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + inner: self.raw.into_par_iter(), + } + } +} + +impl<'a, T: Sync, A: Allocator> IntoParallelIterator for &'a HashTable { + type Item = &'a T; + type Iter = ParIter<'a, T>; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + ParIter { + inner: unsafe { self.raw.par_iter() }, + marker: PhantomData, + } + } +} + +impl<'a, T: Send, A: Allocator> IntoParallelIterator for &'a mut HashTable { + type Item = &'a mut T; + type Iter = ParIterMut<'a, T>; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_par_iter(self) -> Self::Iter { + ParIterMut { + inner: unsafe { self.raw.par_iter() }, + marker: PhantomData, + } + } +} + +#[cfg(test)] +mod test_par_table { + use alloc::vec::Vec; + use core::sync::atomic::{AtomicUsize, Ordering}; + + use rayon::prelude::*; + + use crate::{hash_map::make_hash, hash_table::HashTable, DefaultHashBuilder}; + + #[test] + fn test_iterate() { + let hasher = DefaultHashBuilder::default(); + let mut a = HashTable::new(); + for i in 0..32 { + a.insert_unique(make_hash(&hasher, &i), i, |x| make_hash(&hasher, x)); + } + let observed = AtomicUsize::new(0); + a.par_iter().for_each(|k| { + observed.fetch_or(1 << *k, Ordering::Relaxed); + }); + assert_eq!(observed.into_inner(), 0xFFFF_FFFF); + } + + #[test] + fn test_move_iter() { + let hasher = DefaultHashBuilder::default(); + let hs = { + let mut hs = HashTable::new(); + + hs.insert_unique(make_hash(&hasher, &'a'), 'a', |x| make_hash(&hasher, x)); + hs.insert_unique(make_hash(&hasher, &'b'), 'b', |x| make_hash(&hasher, x)); + + hs + }; + + let v = hs.into_par_iter().collect::>(); + assert!(v == ['a', 'b'] || v == ['b', 'a']); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/serde.rs b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/serde.rs new file mode 100644 index 0000000..0a76dbe --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/external_trait_impls/serde.rs @@ -0,0 +1,220 @@ +mod size_hint { + use core::cmp; + + /// This presumably exists to prevent denial of service attacks. + /// + /// Original discussion: https://github.com/serde-rs/serde/issues/1114. + #[cfg_attr(feature = "inline-more", inline)] + pub(super) fn cautious(hint: Option) -> usize { + cmp::min(hint.unwrap_or(0), 4096) + } +} + +mod map { + use crate::raw::Allocator; + use core::fmt; + use core::hash::{BuildHasher, Hash}; + use core::marker::PhantomData; + use serde::de::{Deserialize, Deserializer, MapAccess, Visitor}; + use serde::ser::{Serialize, Serializer}; + + use crate::hash_map::HashMap; + + use super::size_hint; + + impl Serialize for HashMap + where + K: Serialize + Eq + Hash, + V: Serialize, + H: BuildHasher, + A: Allocator, + { + #[cfg_attr(feature = "inline-more", inline)] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_map(self) + } + } + + impl<'de, K, V, S, A> Deserialize<'de> for HashMap + where + K: Deserialize<'de> + Eq + Hash, + V: Deserialize<'de>, + S: BuildHasher + Default, + A: Allocator + Default, + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct MapVisitor + where + A: Allocator, + { + marker: PhantomData>, + } + + impl<'de, K, V, S, A> Visitor<'de> for MapVisitor + where + K: Deserialize<'de> + Eq + Hash, + V: Deserialize<'de>, + S: BuildHasher + Default, + A: Allocator + Default, + { + type Value = HashMap; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a map") + } + + #[cfg_attr(feature = "inline-more", inline)] + fn visit_map(self, mut map: M) -> Result + where + M: MapAccess<'de>, + { + let mut values = HashMap::with_capacity_and_hasher_in( + size_hint::cautious(map.size_hint()), + S::default(), + A::default(), + ); + + while let Some((key, value)) = map.next_entry()? { + values.insert(key, value); + } + + Ok(values) + } + } + + let visitor = MapVisitor { + marker: PhantomData, + }; + deserializer.deserialize_map(visitor) + } + } +} + +mod set { + use crate::raw::Allocator; + use core::fmt; + use core::hash::{BuildHasher, Hash}; + use core::marker::PhantomData; + use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor}; + use serde::ser::{Serialize, Serializer}; + + use crate::hash_set::HashSet; + + use super::size_hint; + + impl Serialize for HashSet + where + T: Serialize + Eq + Hash, + H: BuildHasher, + A: Allocator, + { + #[cfg_attr(feature = "inline-more", inline)] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_seq(self) + } + } + + impl<'de, T, S, A> Deserialize<'de> for HashSet + where + T: Deserialize<'de> + Eq + Hash, + S: BuildHasher + Default, + A: Allocator + Default, + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct SeqVisitor + where + A: Allocator, + { + marker: PhantomData>, + } + + impl<'de, T, S, A> Visitor<'de> for SeqVisitor + where + T: Deserialize<'de> + Eq + Hash, + S: BuildHasher + Default, + A: Allocator + Default, + { + type Value = HashSet; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[cfg_attr(feature = "inline-more", inline)] + fn visit_seq(self, mut seq: M) -> Result + where + M: SeqAccess<'de>, + { + let mut values = HashSet::with_capacity_and_hasher_in( + size_hint::cautious(seq.size_hint()), + S::default(), + A::default(), + ); + + while let Some(value) = seq.next_element()? { + values.insert(value); + } + + Ok(values) + } + } + + let visitor = SeqVisitor { + marker: PhantomData, + }; + deserializer.deserialize_seq(visitor) + } + + #[allow(clippy::missing_errors_doc)] + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct SeqInPlaceVisitor<'a, T, S, A>(&'a mut HashSet) + where + A: Allocator; + + impl<'a, 'de, T, S, A> Visitor<'de> for SeqInPlaceVisitor<'a, T, S, A> + where + T: Deserialize<'de> + Eq + Hash, + S: BuildHasher + Default, + A: Allocator, + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[cfg_attr(feature = "inline-more", inline)] + fn visit_seq(self, mut seq: M) -> Result + where + M: SeqAccess<'de>, + { + self.0.clear(); + self.0.reserve(size_hint::cautious(seq.size_hint())); + + while let Some(value) = seq.next_element()? { + self.0.insert(value); + } + + Ok(()) + } + } + + deserializer.deserialize_seq(SeqInPlaceVisitor(place)) + } + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/lib.rs b/bitbox02-bt/vendor/hashbrown/src/lib.rs new file mode 100644 index 0000000..a637ccb --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/lib.rs @@ -0,0 +1,177 @@ +//! This crate is a Rust port of Google's high-performance [SwissTable] hash +//! map, adapted to make it a drop-in replacement for Rust's standard `HashMap` +//! and `HashSet` types. +//! +//! The original C++ version of [SwissTable] can be found [here], and this +//! [CppCon talk] gives an overview of how the algorithm works. +//! +//! [SwissTable]: https://abseil.io/blog/20180927-swisstables +//! [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h +//! [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4 + +#![no_std] +#![cfg_attr( + feature = "nightly", + feature( + test, + core_intrinsics, + dropck_eyepatch, + min_specialization, + extend_one, + allocator_api, + slice_ptr_get, + maybe_uninit_array_assume_init, + strict_provenance + ) +)] +#![allow( + clippy::doc_markdown, + clippy::module_name_repetitions, + clippy::must_use_candidate, + clippy::option_if_let_else, + clippy::redundant_else, + clippy::manual_map, + clippy::missing_safety_doc, + clippy::missing_errors_doc +)] +#![warn(missing_docs)] +#![warn(rust_2018_idioms)] +#![cfg_attr(feature = "nightly", warn(fuzzy_provenance_casts))] +#![cfg_attr(feature = "nightly", allow(internal_features))] + +/// Default hasher for [`HashMap`] and [`HashSet`]. +#[cfg(feature = "default-hasher")] +pub type DefaultHashBuilder = foldhash::fast::RandomState; + +/// Dummy default hasher for [`HashMap`] and [`HashSet`]. +#[cfg(not(feature = "default-hasher"))] +pub enum DefaultHashBuilder {} + +#[cfg(test)] +#[macro_use] +extern crate std; + +#[cfg_attr(test, macro_use)] +extern crate alloc; + +#[cfg(feature = "nightly")] +#[cfg(doctest)] +doc_comment::doctest!("../README.md"); + +#[macro_use] +mod macros; + +mod raw; + +mod external_trait_impls; +mod map; +#[cfg(feature = "raw-entry")] +mod raw_entry; +#[cfg(feature = "rustc-internal-api")] +mod rustc_entry; +mod scopeguard; +mod set; +mod table; + +pub mod hash_map { + //! A hash map implemented with quadratic probing and SIMD lookup. + pub use crate::map::*; + + #[cfg(feature = "rustc-internal-api")] + pub use crate::rustc_entry::*; + + #[cfg(feature = "rayon")] + /// [rayon]-based parallel iterator types for hash maps. + /// You will rarely need to interact with it directly unless you have need + /// to name one of the iterator types. + /// + /// [rayon]: https://docs.rs/rayon/1.0/rayon + pub mod rayon { + pub use crate::external_trait_impls::rayon::map::*; + } +} +pub mod hash_set { + //! A hash set implemented as a `HashMap` where the value is `()`. + pub use crate::set::*; + + #[cfg(feature = "rayon")] + /// [rayon]-based parallel iterator types for hash sets. + /// You will rarely need to interact with it directly unless you have need + /// to name one of the iterator types. + /// + /// [rayon]: https://docs.rs/rayon/1.0/rayon + pub mod rayon { + pub use crate::external_trait_impls::rayon::set::*; + } +} +pub mod hash_table { + //! A hash table implemented with quadratic probing and SIMD lookup. + pub use crate::table::*; + + #[cfg(feature = "rayon")] + /// [rayon]-based parallel iterator types for hash tables. + /// You will rarely need to interact with it directly unless you have need + /// to name one of the iterator types. + /// + /// [rayon]: https://docs.rs/rayon/1.0/rayon + pub mod rayon { + pub use crate::external_trait_impls::rayon::table::*; + } +} + +pub use crate::map::HashMap; +pub use crate::set::HashSet; +pub use crate::table::HashTable; + +#[cfg(feature = "equivalent")] +pub use equivalent::Equivalent; + +// This is only used as a fallback when building as part of `std`. +#[cfg(not(feature = "equivalent"))] +/// Key equivalence trait. +/// +/// This trait defines the function used to compare the input value with the +/// map keys (or set values) during a lookup operation such as [`HashMap::get`] +/// or [`HashSet::contains`]. +/// It is provided with a blanket implementation based on the +/// [`Borrow`](core::borrow::Borrow) trait. +/// +/// # Correctness +/// +/// Equivalent values must hash to the same value. +pub trait Equivalent { + /// Checks if this value is equivalent to the given key. + /// + /// Returns `true` if both values are equivalent, and `false` otherwise. + /// + /// # Correctness + /// + /// When this function returns `true`, both `self` and `key` must hash to + /// the same value. + fn equivalent(&self, key: &K) -> bool; +} + +#[cfg(not(feature = "equivalent"))] +impl Equivalent for Q +where + Q: Eq, + K: core::borrow::Borrow, +{ + fn equivalent(&self, key: &K) -> bool { + self == key.borrow() + } +} + +/// The error type for `try_reserve` methods. +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum TryReserveError { + /// Error due to the computed capacity exceeding the collection's maximum + /// (usually `isize::MAX` bytes). + CapacityOverflow, + + /// The memory allocator returned an error + AllocError { + /// The layout of the allocation request that failed. + layout: alloc::alloc::Layout, + }, +} diff --git a/bitbox02-bt/vendor/hashbrown/src/macros.rs b/bitbox02-bt/vendor/hashbrown/src/macros.rs new file mode 100644 index 0000000..eaba6be --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/macros.rs @@ -0,0 +1,70 @@ +// See the cfg-if crate. +#[allow(unused_macro_rules)] +macro_rules! cfg_if { + // match if/else chains with a final `else` + ($( + if #[cfg($($meta:meta),*)] { $($it:item)* } + ) else * else { + $($it2:item)* + }) => { + cfg_if! { + @__items + () ; + $( ( ($($meta),*) ($($it)*) ), )* + ( () ($($it2)*) ), + } + }; + + // match if/else chains lacking a final `else` + ( + if #[cfg($($i_met:meta),*)] { $($i_it:item)* } + $( + else if #[cfg($($e_met:meta),*)] { $($e_it:item)* } + )* + ) => { + cfg_if! { + @__items + () ; + ( ($($i_met),*) ($($i_it)*) ), + $( ( ($($e_met),*) ($($e_it)*) ), )* + ( () () ), + } + }; + + // Internal and recursive macro to emit all the items + // + // Collects all the negated cfgs in a list at the beginning and after the + // semicolon is all the remaining items + (@__items ($($not:meta,)*) ; ) => {}; + (@__items ($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => { + // Emit all items within one block, applying an appropriate #[cfg]. The + // #[cfg] will require all `$m` matchers specified and must also negate + // all previous matchers. + cfg_if! { @__apply cfg(all($($m,)* not(any($($not),*)))), $($it)* } + + // Recurse to emit all other items in `$rest`, and when we do so add all + // our `$m` matchers to the list of `$not` matchers as future emissions + // will have to negate everything we just matched as well. + cfg_if! { @__items ($($not,)* $($m,)*) ; $($rest)* } + }; + + // Internal macro to Apply a cfg attribute to a list of items + (@__apply $m:meta, $($it:item)*) => { + $(#[$m] $it)* + }; +} + +// Helper macro for specialization. This also helps avoid parse errors if the +// default fn syntax for specialization changes in the future. +#[cfg(feature = "nightly")] +macro_rules! default_fn { + (#[$($a:tt)*] $($tt:tt)*) => { + #[$($a)*] default $($tt)* + } +} +#[cfg(not(feature = "nightly"))] +macro_rules! default_fn { + ($($tt:tt)*) => { + $($tt)* + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/map.rs b/bitbox02-bt/vendor/hashbrown/src/map.rs new file mode 100644 index 0000000..03a9f19 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/map.rs @@ -0,0 +1,6510 @@ +use crate::raw::{ + Allocator, Bucket, Global, RawDrain, RawExtractIf, RawIntoIter, RawIter, RawTable, +}; +use crate::{DefaultHashBuilder, Equivalent, TryReserveError}; +use core::borrow::Borrow; +use core::fmt::{self, Debug}; +use core::hash::{BuildHasher, Hash}; +use core::iter::FusedIterator; +use core::marker::PhantomData; +use core::mem; +use core::ops::Index; + +#[cfg(feature = "raw-entry")] +pub use crate::raw_entry::*; + +/// A hash map implemented with quadratic probing and SIMD lookup. +/// +/// The default hashing algorithm is currently [`foldhash`], though this is +/// subject to change at any point in the future. This hash function is very +/// fast for all types of keys, but this algorithm will typically *not* protect +/// against attacks such as HashDoS. +/// +/// The hashing algorithm can be replaced on a per-`HashMap` basis using the +/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many +/// alternative algorithms are available on crates.io, such as the [`fnv`] crate. +/// +/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although +/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`. +/// If you implement these yourself, it is important that the following +/// property holds: +/// +/// ```text +/// k1 == k2 -> hash(k1) == hash(k2) +/// ``` +/// +/// In other words, if two keys are equal, their hashes must be equal. +/// +/// It is a logic error for a key to be modified in such a way that the key's +/// hash, as determined by the [`Hash`] trait, or its equality, as determined by +/// the [`Eq`] trait, changes while it is in the map. This is normally only +/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code. +/// +/// It is also a logic error for the [`Hash`] implementation of a key to panic. +/// This is generally only possible if the trait is implemented manually. If a +/// panic does occur then the contents of the `HashMap` may become corrupted and +/// some items may be dropped from the table. +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// // Type inference lets us omit an explicit type signature (which +/// // would be `HashMap` in this example). +/// let mut book_reviews = HashMap::new(); +/// +/// // Review some books. +/// book_reviews.insert( +/// "Adventures of Huckleberry Finn".to_string(), +/// "My favorite book.".to_string(), +/// ); +/// book_reviews.insert( +/// "Grimms' Fairy Tales".to_string(), +/// "Masterpiece.".to_string(), +/// ); +/// book_reviews.insert( +/// "Pride and Prejudice".to_string(), +/// "Very enjoyable.".to_string(), +/// ); +/// book_reviews.insert( +/// "The Adventures of Sherlock Holmes".to_string(), +/// "Eye lyked it alot.".to_string(), +/// ); +/// +/// // Check for a specific one. +/// // When collections store owned values (String), they can still be +/// // queried using references (&str). +/// if !book_reviews.contains_key("Les Misérables") { +/// println!("We've got {} reviews, but Les Misérables ain't one.", +/// book_reviews.len()); +/// } +/// +/// // oops, this review has a lot of spelling mistakes, let's delete it. +/// book_reviews.remove("The Adventures of Sherlock Holmes"); +/// +/// // Look up the values associated with some keys. +/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; +/// for &book in &to_find { +/// match book_reviews.get(book) { +/// Some(review) => println!("{}: {}", book, review), +/// None => println!("{} is unreviewed.", book) +/// } +/// } +/// +/// // Look up the value for a key (will panic if the key is not found). +/// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]); +/// +/// // Iterate over everything. +/// for (book, review) in &book_reviews { +/// println!("{}: \"{}\"", book, review); +/// } +/// ``` +/// +/// `HashMap` also implements an [`Entry API`](#method.entry), which allows +/// for more complex methods of getting, setting, updating and removing keys and +/// their values: +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// // type inference lets us omit an explicit type signature (which +/// // would be `HashMap<&str, u8>` in this example). +/// let mut player_stats = HashMap::new(); +/// +/// fn random_stat_buff() -> u8 { +/// // could actually return some random value here - let's just return +/// // some fixed value for now +/// 42 +/// } +/// +/// // insert a key only if it doesn't already exist +/// player_stats.entry("health").or_insert(100); +/// +/// // insert a key using a function that provides a new value only if it +/// // doesn't already exist +/// player_stats.entry("defence").or_insert_with(random_stat_buff); +/// +/// // update a key, guarding against the key possibly not being set +/// let stat = player_stats.entry("attack").or_insert(100); +/// *stat += random_stat_buff(); +/// ``` +/// +/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`]. +/// We must also derive [`PartialEq`]. +/// +/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html +/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html +/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html +/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html +/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html +/// [`default`]: #method.default +/// [`with_hasher`]: #method.with_hasher +/// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher +/// [`fnv`]: https://crates.io/crates/fnv +/// [`foldhash`]: https://crates.io/crates/foldhash +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// #[derive(Hash, Eq, PartialEq, Debug)] +/// struct Viking { +/// name: String, +/// country: String, +/// } +/// +/// impl Viking { +/// /// Creates a new Viking. +/// fn new(name: &str, country: &str) -> Viking { +/// Viking { name: name.to_string(), country: country.to_string() } +/// } +/// } +/// +/// // Use a HashMap to store the vikings' health points. +/// let mut vikings = HashMap::new(); +/// +/// vikings.insert(Viking::new("Einar", "Norway"), 25); +/// vikings.insert(Viking::new("Olaf", "Denmark"), 24); +/// vikings.insert(Viking::new("Harald", "Iceland"), 12); +/// +/// // Use derived implementation to print the status of the vikings. +/// for (viking, health) in &vikings { +/// println!("{:?} has {} hp", viking, health); +/// } +/// ``` +/// +/// A `HashMap` with fixed list of elements can be initialized from an array: +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)] +/// .into_iter().collect(); +/// // use the values stored in map +/// ``` +pub struct HashMap { + pub(crate) hash_builder: S, + pub(crate) table: RawTable<(K, V), A>, +} + +impl Clone for HashMap { + fn clone(&self) -> Self { + HashMap { + hash_builder: self.hash_builder.clone(), + table: self.table.clone(), + } + } + + fn clone_from(&mut self, source: &Self) { + self.table.clone_from(&source.table); + + // Update hash_builder only if we successfully cloned all elements. + self.hash_builder.clone_from(&source.hash_builder); + } +} + +/// Ensures that a single closure type across uses of this which, in turn prevents multiple +/// instances of any functions like `RawTable::reserve` from being generated +#[cfg_attr(feature = "inline-more", inline)] +pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ +where + Q: Hash, + S: BuildHasher, +{ + move |val| make_hash::(hash_builder, &val.0) +} + +/// Ensures that a single closure type across uses of this which, in turn prevents multiple +/// instances of any functions like `RawTable::reserve` from being generated +#[cfg_attr(feature = "inline-more", inline)] +pub(crate) fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ +where + Q: Equivalent + ?Sized, +{ + move |x| k.equivalent(&x.0) +} + +/// Ensures that a single closure type across uses of this which, in turn prevents multiple +/// instances of any functions like `RawTable::reserve` from being generated +#[cfg_attr(feature = "inline-more", inline)] +#[allow(dead_code)] +pub(crate) fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ +where + Q: Equivalent + ?Sized, +{ + move |x| k.equivalent(x) +} + +#[cfg(not(feature = "nightly"))] +#[cfg_attr(feature = "inline-more", inline)] +pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 +where + Q: Hash + ?Sized, + S: BuildHasher, +{ + use core::hash::Hasher; + let mut state = hash_builder.build_hasher(); + val.hash(&mut state); + state.finish() +} + +#[cfg(feature = "nightly")] +#[cfg_attr(feature = "inline-more", inline)] +pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 +where + Q: Hash + ?Sized, + S: BuildHasher, +{ + hash_builder.hash_one(val) +} + +#[cfg(feature = "default-hasher")] +impl HashMap { + /// Creates an empty `HashMap`. + /// + /// The hash map is initially created with a capacity of 0, so it will not allocate until it + /// is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`], for example with + /// [`with_hasher`](HashMap::with_hasher) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// let mut map: HashMap<&str, i32> = HashMap::new(); + /// assert_eq!(map.len(), 0); + /// assert_eq!(map.capacity(), 0); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn new() -> Self { + Self::default() + } + + /// Creates an empty `HashMap` with the specified capacity. + /// + /// The hash map will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash map will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`], for example with + /// [`with_capacity_and_hasher`](HashMap::with_capacity_and_hasher) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10); + /// assert_eq!(map.len(), 0); + /// assert!(map.capacity() >= 10); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity(capacity: usize) -> Self { + Self::with_capacity_and_hasher(capacity, DefaultHashBuilder::default()) + } +} + +#[cfg(feature = "default-hasher")] +impl HashMap { + /// Creates an empty `HashMap` using the given allocator. + /// + /// The hash map is initially created with a capacity of 0, so it will not allocate until it + /// is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`], for example with + /// [`with_hasher_in`](HashMap::with_hasher_in) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use bumpalo::Bump; + /// + /// let bump = Bump::new(); + /// let mut map = HashMap::new_in(&bump); + /// + /// // The created HashMap holds none elements + /// assert_eq!(map.len(), 0); + /// + /// // The created HashMap also doesn't allocate memory + /// assert_eq!(map.capacity(), 0); + /// + /// // Now we insert element inside created HashMap + /// map.insert("One", 1); + /// // We can see that the HashMap holds 1 element + /// assert_eq!(map.len(), 1); + /// // And it also allocates some capacity + /// assert!(map.capacity() > 1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn new_in(alloc: A) -> Self { + Self::with_hasher_in(DefaultHashBuilder::default(), alloc) + } + + /// Creates an empty `HashMap` with the specified capacity using the given allocator. + /// + /// The hash map will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash map will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`], for example with + /// [`with_capacity_and_hasher_in`](HashMap::with_capacity_and_hasher_in) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use bumpalo::Bump; + /// + /// let bump = Bump::new(); + /// let mut map = HashMap::with_capacity_in(5, &bump); + /// + /// // The created HashMap holds none elements + /// assert_eq!(map.len(), 0); + /// // But it can hold at least 5 elements without reallocating + /// let empty_map_capacity = map.capacity(); + /// assert!(empty_map_capacity >= 5); + /// + /// // Now we insert some 5 elements inside created HashMap + /// map.insert("One", 1); + /// map.insert("Two", 2); + /// map.insert("Three", 3); + /// map.insert("Four", 4); + /// map.insert("Five", 5); + /// + /// // We can see that the HashMap holds 5 elements + /// assert_eq!(map.len(), 5); + /// // But its capacity isn't changed + /// assert_eq!(map.capacity(), empty_map_capacity) + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { + Self::with_capacity_and_hasher_in(capacity, DefaultHashBuilder::default(), alloc) + } +} + +impl HashMap { + /// Creates an empty `HashMap` which will use the given hash builder to hash + /// keys. + /// + /// The hash map is initially created with a capacity of 0, so it will not + /// allocate until it is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`]. + /// + /// The `hash_builder` passed should implement the [`BuildHasher`] trait for + /// the `HashMap` to be useful, see its documentation for details. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut map = HashMap::with_hasher(s); + /// assert_eq!(map.len(), 0); + /// assert_eq!(map.capacity(), 0); + /// + /// map.insert(1, 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub const fn with_hasher(hash_builder: S) -> Self { + Self { + hash_builder, + table: RawTable::new(), + } + } + + /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` + /// to hash the keys. + /// + /// The hash map will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash map will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`]. + /// + /// The `hash_builder` passed should implement the [`BuildHasher`] trait for + /// the `HashMap` to be useful, see its documentation for details. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut map = HashMap::with_capacity_and_hasher(10, s); + /// assert_eq!(map.len(), 0); + /// assert!(map.capacity() >= 10); + /// + /// map.insert(1, 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self { + Self { + hash_builder, + table: RawTable::with_capacity(capacity), + } + } +} + +impl HashMap { + /// Returns a reference to the underlying allocator. + #[inline] + pub fn allocator(&self) -> &A { + self.table.allocator() + } + + /// Creates an empty `HashMap` which will use the given hash builder to hash + /// keys. It will be allocated with the given allocator. + /// + /// The hash map is initially created with a capacity of 0, so it will not allocate until it + /// is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`]. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut map = HashMap::with_hasher(s); + /// map.insert(1, 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub const fn with_hasher_in(hash_builder: S, alloc: A) -> Self { + Self { + hash_builder, + table: RawTable::new_in(alloc), + } + } + + /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` + /// to hash the keys. It will be allocated with the given allocator. + /// + /// The hash map will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash map will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashMap`]. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut map = HashMap::with_capacity_and_hasher(10, s); + /// map.insert(1, 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> Self { + Self { + hash_builder, + table: RawTable::with_capacity_in(capacity, alloc), + } + } + + /// Returns a reference to the map's [`BuildHasher`]. + /// + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::DefaultHashBuilder; + /// + /// let hasher = DefaultHashBuilder::default(); + /// let map: HashMap = HashMap::with_hasher(hasher); + /// let hasher: &DefaultHashBuilder = map.hasher(); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn hasher(&self) -> &S { + &self.hash_builder + } + + /// Returns the number of elements the map can hold without reallocating. + /// + /// This number is a lower bound; the `HashMap` might be able to hold + /// more, but is guaranteed to be able to hold at least this many. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// let map: HashMap = HashMap::with_capacity(100); + /// assert_eq!(map.len(), 0); + /// assert!(map.capacity() >= 100); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn capacity(&self) -> usize { + self.table.capacity() + } + + /// An iterator visiting all keys in arbitrary order. + /// The iterator element type is `&'a K`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert("a", 1); + /// map.insert("b", 2); + /// map.insert("c", 3); + /// assert_eq!(map.len(), 3); + /// let mut vec: Vec<&str> = Vec::new(); + /// + /// for key in map.keys() { + /// println!("{}", key); + /// vec.push(*key); + /// } + /// + /// // The `Keys` iterator produces keys in arbitrary order, so the + /// // keys must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, ["a", "b", "c"]); + /// + /// assert_eq!(map.len(), 3); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn keys(&self) -> Keys<'_, K, V> { + Keys { inner: self.iter() } + } + + /// An iterator visiting all values in arbitrary order. + /// The iterator element type is `&'a V`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert("a", 1); + /// map.insert("b", 2); + /// map.insert("c", 3); + /// assert_eq!(map.len(), 3); + /// let mut vec: Vec = Vec::new(); + /// + /// for val in map.values() { + /// println!("{}", val); + /// vec.push(*val); + /// } + /// + /// // The `Values` iterator produces values in arbitrary order, so the + /// // values must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [1, 2, 3]); + /// + /// assert_eq!(map.len(), 3); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn values(&self) -> Values<'_, K, V> { + Values { inner: self.iter() } + } + + /// An iterator visiting all values mutably in arbitrary order. + /// The iterator element type is `&'a mut V`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// + /// map.insert("a", 1); + /// map.insert("b", 2); + /// map.insert("c", 3); + /// + /// for val in map.values_mut() { + /// *val = *val + 10; + /// } + /// + /// assert_eq!(map.len(), 3); + /// let mut vec: Vec = Vec::new(); + /// + /// for val in map.values() { + /// println!("{}", val); + /// vec.push(*val); + /// } + /// + /// // The `Values` iterator produces values in arbitrary order, so the + /// // values must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [11, 12, 13]); + /// + /// assert_eq!(map.len(), 3); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> { + ValuesMut { + inner: self.iter_mut(), + } + } + + /// An iterator visiting all key-value pairs in arbitrary order. + /// The iterator element type is `(&'a K, &'a V)`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert("a", 1); + /// map.insert("b", 2); + /// map.insert("c", 3); + /// assert_eq!(map.len(), 3); + /// let mut vec: Vec<(&str, i32)> = Vec::new(); + /// + /// for (key, val) in map.iter() { + /// println!("key: {} val: {}", key, val); + /// vec.push((*key, *val)); + /// } + /// + /// // The `Iter` iterator produces items in arbitrary order, so the + /// // items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]); + /// + /// assert_eq!(map.len(), 3); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn iter(&self) -> Iter<'_, K, V> { + // Here we tie the lifetime of self to the iter. + unsafe { + Iter { + inner: self.table.iter(), + marker: PhantomData, + } + } + } + + /// An iterator visiting all key-value pairs in arbitrary order, + /// with mutable references to the values. + /// The iterator element type is `(&'a K, &'a mut V)`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert("a", 1); + /// map.insert("b", 2); + /// map.insert("c", 3); + /// + /// // Update all values + /// for (_, val) in map.iter_mut() { + /// *val *= 2; + /// } + /// + /// assert_eq!(map.len(), 3); + /// let mut vec: Vec<(&str, i32)> = Vec::new(); + /// + /// for (key, val) in &map { + /// println!("key: {} val: {}", key, val); + /// vec.push((*key, *val)); + /// } + /// + /// // The `Iter` iterator produces items in arbitrary order, so the + /// // items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]); + /// + /// assert_eq!(map.len(), 3); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { + // Here we tie the lifetime of self to the iter. + unsafe { + IterMut { + inner: self.table.iter(), + marker: PhantomData, + } + } + } + + #[cfg(test)] + #[cfg_attr(feature = "inline-more", inline)] + fn raw_capacity(&self) -> usize { + self.table.buckets() + } + + /// Returns the number of elements in the map. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut a = HashMap::new(); + /// assert_eq!(a.len(), 0); + /// a.insert(1, "a"); + /// assert_eq!(a.len(), 1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn len(&self) -> usize { + self.table.len() + } + + /// Returns `true` if the map contains no elements. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut a = HashMap::new(); + /// assert!(a.is_empty()); + /// a.insert(1, "a"); + /// assert!(!a.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Clears the map, returning all key-value pairs as an iterator. Keeps the + /// allocated memory for reuse. + /// + /// If the returned iterator is dropped before being fully consumed, it + /// drops the remaining key-value pairs. The returned iterator keeps a + /// mutable borrow on the vector to optimize its implementation. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut a = HashMap::new(); + /// a.insert(1, "a"); + /// a.insert(2, "b"); + /// let capacity_before_drain = a.capacity(); + /// + /// for (k, v) in a.drain().take(1) { + /// assert!(k == 1 || k == 2); + /// assert!(v == "a" || v == "b"); + /// } + /// + /// // As we can see, the map is empty and contains no element. + /// assert!(a.is_empty() && a.len() == 0); + /// // But map capacity is equal to old one. + /// assert_eq!(a.capacity(), capacity_before_drain); + /// + /// let mut a = HashMap::new(); + /// a.insert(1, "a"); + /// a.insert(2, "b"); + /// + /// { // Iterator is dropped without being consumed. + /// let d = a.drain(); + /// } + /// + /// // But the map is empty even if we do not use Drain iterator. + /// assert!(a.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn drain(&mut self) -> Drain<'_, K, V, A> { + Drain { + inner: self.table.drain(), + } + } + + /// Retains only the elements specified by the predicate. Keeps the + /// allocated memory for reuse. + /// + /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. + /// The elements are visited in unsorted (and unspecified) order. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = (0..8).map(|x|(x, x*10)).collect(); + /// assert_eq!(map.len(), 8); + /// + /// map.retain(|&k, _| k % 2 == 0); + /// + /// // We can see, that the number of elements inside map is changed. + /// assert_eq!(map.len(), 4); + /// + /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect(); + /// vec.sort_unstable(); + /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]); + /// ``` + pub fn retain(&mut self, mut f: F) + where + F: FnMut(&K, &mut V) -> bool, + { + // Here we only use `iter` as a temporary, preventing use-after-free + unsafe { + for item in self.table.iter() { + let &mut (ref key, ref mut value) = item.as_mut(); + if !f(key, value) { + self.table.erase(item); + } + } + } + } + + /// Drains elements which are true under the given predicate, + /// and returns an iterator over the removed items. + /// + /// In other words, move all pairs `(k, v)` such that `f(&k, &mut v)` returns `true` out + /// into another iterator. + /// + /// Note that `extract_if` lets you mutate every value in the filter closure, regardless of + /// whether you choose to keep or remove it. + /// + /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating + /// or the iteration short-circuits, then the remaining elements will be retained. + /// Use [`retain()`] with a negated predicate if you do not need the returned iterator. + /// + /// Keeps the allocated memory for reuse. + /// + /// [`retain()`]: HashMap::retain + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = (0..8).map(|x| (x, x)).collect(); + /// + /// let drained: HashMap = map.extract_if(|k, _v| k % 2 == 0).collect(); + /// + /// let mut evens = drained.keys().cloned().collect::>(); + /// let mut odds = map.keys().cloned().collect::>(); + /// evens.sort(); + /// odds.sort(); + /// + /// assert_eq!(evens, vec![0, 2, 4, 6]); + /// assert_eq!(odds, vec![1, 3, 5, 7]); + /// + /// let mut map: HashMap = (0..8).map(|x| (x, x)).collect(); + /// + /// { // Iterator is dropped without being consumed. + /// let d = map.extract_if(|k, _v| k % 2 != 0); + /// } + /// + /// // ExtractIf was not exhausted, therefore no elements were drained. + /// assert_eq!(map.len(), 8); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn extract_if(&mut self, f: F) -> ExtractIf<'_, K, V, F, A> + where + F: FnMut(&K, &mut V) -> bool, + { + ExtractIf { + f, + inner: RawExtractIf { + iter: unsafe { self.table.iter() }, + table: &mut self.table, + }, + } + } + + /// Clears the map, removing all key-value pairs. Keeps the allocated memory + /// for reuse. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut a = HashMap::new(); + /// a.insert(1, "a"); + /// let capacity_before_clear = a.capacity(); + /// + /// a.clear(); + /// + /// // Map is empty. + /// assert!(a.is_empty()); + /// // But map capacity is equal to old one. + /// assert_eq!(a.capacity(), capacity_before_clear); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn clear(&mut self) { + self.table.clear(); + } + + /// Creates a consuming iterator visiting all the keys in arbitrary order. + /// The map cannot be used after calling this. + /// The iterator element type is `K`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert("a", 1); + /// map.insert("b", 2); + /// map.insert("c", 3); + /// + /// let mut vec: Vec<&str> = map.into_keys().collect(); + /// + /// // The `IntoKeys` iterator produces keys in arbitrary order, so the + /// // keys must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, ["a", "b", "c"]); + /// ``` + #[inline] + pub fn into_keys(self) -> IntoKeys { + IntoKeys { + inner: self.into_iter(), + } + } + + /// Creates a consuming iterator visiting all the values in arbitrary order. + /// The map cannot be used after calling this. + /// The iterator element type is `V`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert("a", 1); + /// map.insert("b", 2); + /// map.insert("c", 3); + /// + /// let mut vec: Vec = map.into_values().collect(); + /// + /// // The `IntoValues` iterator produces values in arbitrary order, so + /// // the values must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [1, 2, 3]); + /// ``` + #[inline] + pub fn into_values(self) -> IntoValues { + IntoValues { + inner: self.into_iter(), + } + } +} + +impl HashMap +where + K: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the `HashMap`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program + /// in case of allocation error. Use [`try_reserve`](HashMap::try_reserve) instead + /// if you want to handle memory allocation failure. + /// + /// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html + /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// let mut map: HashMap<&str, i32> = HashMap::new(); + /// // Map is empty and doesn't allocate memory + /// assert_eq!(map.capacity(), 0); + /// + /// map.reserve(10); + /// + /// // And now map can hold at least 10 elements + /// assert!(map.capacity() >= 10); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn reserve(&mut self, additional: usize) { + self.table + .reserve(additional, make_hasher::<_, V, S>(&self.hash_builder)); + } + + /// Tries to reserve capacity for at least `additional` more elements to be inserted + /// in the given `HashMap`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, isize> = HashMap::new(); + /// // Map is empty and doesn't allocate memory + /// assert_eq!(map.capacity(), 0); + /// + /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?"); + /// + /// // And now map can hold at least 10 elements + /// assert!(map.capacity() >= 10); + /// ``` + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned: + /// ``` + /// # fn test() { + /// use hashbrown::HashMap; + /// use hashbrown::TryReserveError; + /// let mut map: HashMap = HashMap::new(); + /// + /// match map.try_reserve(usize::MAX) { + /// Err(error) => match error { + /// TryReserveError::CapacityOverflow => {} + /// _ => panic!("TryReserveError::AllocError ?"), + /// }, + /// _ => panic!(), + /// } + /// # } + /// # fn main() { + /// # #[cfg(not(miri))] + /// # test() + /// # } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.table + .try_reserve(additional, make_hasher::<_, V, S>(&self.hash_builder)) + } + + /// Shrinks the capacity of the map as much as possible. It will drop + /// down as much as possible while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::with_capacity(100); + /// map.insert(1, 2); + /// map.insert(3, 4); + /// assert!(map.capacity() >= 100); + /// map.shrink_to_fit(); + /// assert!(map.capacity() >= 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn shrink_to_fit(&mut self) { + self.table + .shrink_to(0, make_hasher::<_, V, S>(&self.hash_builder)); + } + + /// Shrinks the capacity of the map with a lower limit. It will drop + /// down no lower than the supplied limit while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// This function does nothing if the current capacity is smaller than the + /// supplied minimum capacity. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::with_capacity(100); + /// map.insert(1, 2); + /// map.insert(3, 4); + /// assert!(map.capacity() >= 100); + /// map.shrink_to(10); + /// assert!(map.capacity() >= 10); + /// map.shrink_to(0); + /// assert!(map.capacity() >= 2); + /// map.shrink_to(10); + /// assert!(map.capacity() >= 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.table + .shrink_to(min_capacity, make_hasher::<_, V, S>(&self.hash_builder)); + } + + /// Gets the given key's corresponding entry in the map for in-place manipulation. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut letters = HashMap::new(); + /// + /// for ch in "a short treatise on fungi".chars() { + /// let counter = letters.entry(ch).or_insert(0); + /// *counter += 1; + /// } + /// + /// assert_eq!(letters[&'s'], 2); + /// assert_eq!(letters[&'t'], 3); + /// assert_eq!(letters[&'u'], 1); + /// assert_eq!(letters.get(&'y'), None); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { + let hash = make_hash::(&self.hash_builder, &key); + if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { + Entry::Occupied(OccupiedEntry { + hash, + elem, + table: self, + }) + } else { + Entry::Vacant(VacantEntry { + hash, + key, + table: self, + }) + } + } + + /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut words: HashMap = HashMap::new(); + /// let source = ["poneyland", "horseyland", "poneyland", "poneyland"]; + /// for (i, &s) in source.iter().enumerate() { + /// let counter = words.entry_ref(s).or_insert(0); + /// *counter += 1; + /// } + /// + /// assert_eq!(words["poneyland"], 3); + /// assert_eq!(words["horseyland"], 1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn entry_ref<'a, 'b, Q>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A> + where + Q: Hash + Equivalent + ?Sized, + { + let hash = make_hash::(&self.hash_builder, key); + if let Some(elem) = self.table.find(hash, equivalent_key(key)) { + EntryRef::Occupied(OccupiedEntry { + hash, + elem, + table: self, + }) + } else { + EntryRef::Vacant(VacantEntryRef { + hash, + key, + table: self, + }) + } + } + + /// Returns a reference to the value corresponding to the key. + /// + /// The key may be any borrowed form of the map's key type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the key type. + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, "a"); + /// assert_eq!(map.get(&1), Some(&"a")); + /// assert_eq!(map.get(&2), None); + /// ``` + #[inline] + pub fn get(&self, k: &Q) -> Option<&V> + where + Q: Hash + Equivalent + ?Sized, + { + // Avoid `Option::map` because it bloats LLVM IR. + match self.get_inner(k) { + Some((_, v)) => Some(v), + None => None, + } + } + + /// Returns the key-value pair corresponding to the supplied key. + /// + /// The supplied key may be any borrowed form of the map's key type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the key type. + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, "a"); + /// assert_eq!(map.get_key_value(&1), Some((&1, &"a"))); + /// assert_eq!(map.get_key_value(&2), None); + /// ``` + #[inline] + pub fn get_key_value(&self, k: &Q) -> Option<(&K, &V)> + where + Q: Hash + Equivalent + ?Sized, + { + // Avoid `Option::map` because it bloats LLVM IR. + match self.get_inner(k) { + Some((key, value)) => Some((key, value)), + None => None, + } + } + + #[inline] + fn get_inner(&self, k: &Q) -> Option<&(K, V)> + where + Q: Hash + Equivalent + ?Sized, + { + if self.table.is_empty() { + None + } else { + let hash = make_hash::(&self.hash_builder, k); + self.table.get(hash, equivalent_key(k)) + } + } + + /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. + /// + /// The supplied key may be any borrowed form of the map's key type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the key type. + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, "a"); + /// let (k, v) = map.get_key_value_mut(&1).unwrap(); + /// assert_eq!(k, &1); + /// assert_eq!(v, &mut "a"); + /// *v = "b"; + /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b"))); + /// assert_eq!(map.get_key_value_mut(&2), None); + /// ``` + #[inline] + pub fn get_key_value_mut(&mut self, k: &Q) -> Option<(&K, &mut V)> + where + Q: Hash + Equivalent + ?Sized, + { + // Avoid `Option::map` because it bloats LLVM IR. + match self.get_inner_mut(k) { + Some(&mut (ref key, ref mut value)) => Some((key, value)), + None => None, + } + } + + /// Returns `true` if the map contains a value for the specified key. + /// + /// The key may be any borrowed form of the map's key type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the key type. + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, "a"); + /// assert_eq!(map.contains_key(&1), true); + /// assert_eq!(map.contains_key(&2), false); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn contains_key(&self, k: &Q) -> bool + where + Q: Hash + Equivalent + ?Sized, + { + self.get_inner(k).is_some() + } + + /// Returns a mutable reference to the value corresponding to the key. + /// + /// The key may be any borrowed form of the map's key type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the key type. + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, "a"); + /// if let Some(x) = map.get_mut(&1) { + /// *x = "b"; + /// } + /// assert_eq!(map[&1], "b"); + /// + /// assert_eq!(map.get_mut(&2), None); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> + where + Q: Hash + Equivalent + ?Sized, + { + // Avoid `Option::map` because it bloats LLVM IR. + match self.get_inner_mut(k) { + Some(&mut (_, ref mut v)) => Some(v), + None => None, + } + } + + #[inline] + fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> + where + Q: Hash + Equivalent + ?Sized, + { + if self.table.is_empty() { + None + } else { + let hash = make_hash::(&self.hash_builder, k); + self.table.get_mut(hash, equivalent_key(k)) + } + } + + /// Attempts to get mutable references to `N` values in the map at once. + /// + /// Returns an array of length `N` with the results of each query. For soundness, at most one + /// mutable reference will be returned to any value. `None` will be used if the key is missing. + /// + /// # Panics + /// + /// Panics if any keys are overlapping. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut libraries = HashMap::new(); + /// libraries.insert("Bodleian Library".to_string(), 1602); + /// libraries.insert("Athenæum".to_string(), 1807); + /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); + /// libraries.insert("Library of Congress".to_string(), 1800); + /// + /// // Get Athenæum and Bodleian Library + /// let [Some(a), Some(b)] = libraries.get_many_mut([ + /// "Athenæum", + /// "Bodleian Library", + /// ]) else { panic!() }; + /// + /// // Assert values of Athenæum and Library of Congress + /// let got = libraries.get_many_mut([ + /// "Athenæum", + /// "Library of Congress", + /// ]); + /// assert_eq!( + /// got, + /// [ + /// Some(&mut 1807), + /// Some(&mut 1800), + /// ], + /// ); + /// + /// // Missing keys result in None + /// let got = libraries.get_many_mut([ + /// "Athenæum", + /// "New York Public Library", + /// ]); + /// assert_eq!( + /// got, + /// [ + /// Some(&mut 1807), + /// None + /// ] + /// ); + /// ``` + /// + /// ```should_panic + /// use hashbrown::HashMap; + /// + /// let mut libraries = HashMap::new(); + /// libraries.insert("Athenæum".to_string(), 1807); + /// + /// // Duplicate keys panic! + /// let got = libraries.get_many_mut([ + /// "Athenæum", + /// "Athenæum", + /// ]); + /// ``` + pub fn get_many_mut(&mut self, ks: [&Q; N]) -> [Option<&'_ mut V>; N] + where + Q: Hash + Equivalent + ?Sized, + { + self.get_many_mut_inner(ks).map(|res| res.map(|(_, v)| v)) + } + + /// Attempts to get mutable references to `N` values in the map at once, without validating that + /// the values are unique. + /// + /// Returns an array of length `N` with the results of each query. `None` will be used if + /// the key is missing. + /// + /// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`). + /// + /// # Safety + /// + /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting + /// references are not used. + /// + /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut libraries = HashMap::new(); + /// libraries.insert("Bodleian Library".to_string(), 1602); + /// libraries.insert("Athenæum".to_string(), 1807); + /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); + /// libraries.insert("Library of Congress".to_string(), 1800); + /// + /// // SAFETY: The keys do not overlap. + /// let [Some(a), Some(b)] = (unsafe { libraries.get_many_unchecked_mut([ + /// "Athenæum", + /// "Bodleian Library", + /// ]) }) else { panic!() }; + /// + /// // SAFETY: The keys do not overlap. + /// let got = unsafe { libraries.get_many_unchecked_mut([ + /// "Athenæum", + /// "Library of Congress", + /// ]) }; + /// assert_eq!( + /// got, + /// [ + /// Some(&mut 1807), + /// Some(&mut 1800), + /// ], + /// ); + /// + /// // SAFETY: The keys do not overlap. + /// let got = unsafe { libraries.get_many_unchecked_mut([ + /// "Athenæum", + /// "New York Public Library", + /// ]) }; + /// // Missing keys result in None + /// assert_eq!(got, [Some(&mut 1807), None]); + /// ``` + pub unsafe fn get_many_unchecked_mut( + &mut self, + ks: [&Q; N], + ) -> [Option<&'_ mut V>; N] + where + Q: Hash + Equivalent + ?Sized, + { + self.get_many_unchecked_mut_inner(ks) + .map(|res| res.map(|(_, v)| v)) + } + + /// Attempts to get mutable references to `N` values in the map at once, with immutable + /// references to the corresponding keys. + /// + /// Returns an array of length `N` with the results of each query. For soundness, at most one + /// mutable reference will be returned to any value. `None` will be used if the key is missing. + /// + /// # Panics + /// + /// Panics if any keys are overlapping. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut libraries = HashMap::new(); + /// libraries.insert("Bodleian Library".to_string(), 1602); + /// libraries.insert("Athenæum".to_string(), 1807); + /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); + /// libraries.insert("Library of Congress".to_string(), 1800); + /// + /// let got = libraries.get_many_key_value_mut([ + /// "Bodleian Library", + /// "Herzogin-Anna-Amalia-Bibliothek", + /// ]); + /// assert_eq!( + /// got, + /// [ + /// Some((&"Bodleian Library".to_string(), &mut 1602)), + /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)), + /// ], + /// ); + /// // Missing keys result in None + /// let got = libraries.get_many_key_value_mut([ + /// "Bodleian Library", + /// "Gewandhaus", + /// ]); + /// assert_eq!(got, [Some((&"Bodleian Library".to_string(), &mut 1602)), None]); + /// ``` + /// + /// ```should_panic + /// use hashbrown::HashMap; + /// + /// let mut libraries = HashMap::new(); + /// libraries.insert("Bodleian Library".to_string(), 1602); + /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); + /// + /// // Duplicate keys result in panic! + /// let got = libraries.get_many_key_value_mut([ + /// "Bodleian Library", + /// "Herzogin-Anna-Amalia-Bibliothek", + /// "Herzogin-Anna-Amalia-Bibliothek", + /// ]); + /// ``` + pub fn get_many_key_value_mut( + &mut self, + ks: [&Q; N], + ) -> [Option<(&'_ K, &'_ mut V)>; N] + where + Q: Hash + Equivalent + ?Sized, + { + self.get_many_mut_inner(ks) + .map(|res| res.map(|(k, v)| (&*k, v))) + } + + /// Attempts to get mutable references to `N` values in the map at once, with immutable + /// references to the corresponding keys, without validating that the values are unique. + /// + /// Returns an array of length `N` with the results of each query. `None` will be returned if + /// any of the keys are missing. + /// + /// For a safe alternative see [`get_many_key_value_mut`](`HashMap::get_many_key_value_mut`). + /// + /// # Safety + /// + /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting + /// references are not used. + /// + /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut libraries = HashMap::new(); + /// libraries.insert("Bodleian Library".to_string(), 1602); + /// libraries.insert("Athenæum".to_string(), 1807); + /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); + /// libraries.insert("Library of Congress".to_string(), 1800); + /// + /// let got = libraries.get_many_key_value_mut([ + /// "Bodleian Library", + /// "Herzogin-Anna-Amalia-Bibliothek", + /// ]); + /// assert_eq!( + /// got, + /// [ + /// Some((&"Bodleian Library".to_string(), &mut 1602)), + /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)), + /// ], + /// ); + /// // Missing keys result in None + /// let got = libraries.get_many_key_value_mut([ + /// "Bodleian Library", + /// "Gewandhaus", + /// ]); + /// assert_eq!( + /// got, + /// [ + /// Some((&"Bodleian Library".to_string(), &mut 1602)), + /// None, + /// ], + /// ); + /// ``` + pub unsafe fn get_many_key_value_unchecked_mut( + &mut self, + ks: [&Q; N], + ) -> [Option<(&'_ K, &'_ mut V)>; N] + where + Q: Hash + Equivalent + ?Sized, + { + self.get_many_unchecked_mut_inner(ks) + .map(|res| res.map(|(k, v)| (&*k, v))) + } + + fn get_many_mut_inner(&mut self, ks: [&Q; N]) -> [Option<&'_ mut (K, V)>; N] + where + Q: Hash + Equivalent + ?Sized, + { + let hashes = self.build_hashes_inner(ks); + self.table + .get_many_mut(hashes, |i, (k, _)| ks[i].equivalent(k)) + } + + unsafe fn get_many_unchecked_mut_inner( + &mut self, + ks: [&Q; N], + ) -> [Option<&'_ mut (K, V)>; N] + where + Q: Hash + Equivalent + ?Sized, + { + let hashes = self.build_hashes_inner(ks); + self.table + .get_many_unchecked_mut(hashes, |i, (k, _)| ks[i].equivalent(k)) + } + + fn build_hashes_inner(&self, ks: [&Q; N]) -> [u64; N] + where + Q: Hash + Equivalent + ?Sized, + { + let mut hashes = [0_u64; N]; + for i in 0..N { + hashes[i] = make_hash::(&self.hash_builder, ks[i]); + } + hashes + } + + /// Inserts a key-value pair into the map. + /// + /// If the map did not have this key present, [`None`] is returned. + /// + /// If the map did have this key present, the value is updated, and the old + /// value is returned. The key is not updated, though; this matters for + /// types that can be `==` without being identical. See the [`std::collections`] + /// [module-level documentation] for more. + /// + /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None + /// [`std::collections`]: https://doc.rust-lang.org/std/collections/index.html + /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// assert_eq!(map.insert(37, "a"), None); + /// assert_eq!(map.is_empty(), false); + /// + /// map.insert(37, "b"); + /// assert_eq!(map.insert(37, "c"), Some("b")); + /// assert_eq!(map[&37], "c"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(&mut self, k: K, v: V) -> Option { + let hash = make_hash::(&self.hash_builder, &k); + match self.find_or_find_insert_slot(hash, &k) { + Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)), + Err(slot) => { + unsafe { + self.table.insert_in_slot(hash, slot, (k, v)); + } + None + } + } + } + + #[cfg_attr(feature = "inline-more", inline)] + pub(crate) fn find_or_find_insert_slot( + &mut self, + hash: u64, + key: &Q, + ) -> Result, crate::raw::InsertSlot> + where + Q: Equivalent + ?Sized, + { + self.table.find_or_find_insert_slot( + hash, + equivalent_key(key), + make_hasher(&self.hash_builder), + ) + } + + /// Insert a key-value pair into the map without checking + /// if the key already exists in the map. + /// + /// This operation is faster than regular insert, because it does not perform + /// lookup before insertion. + /// + /// This operation is useful during initial population of the map. + /// For example, when constructing a map from another map, we know + /// that keys are unique. + /// + /// Returns a reference to the key and value just inserted. + /// + /// # Safety + /// + /// This operation is safe if a key does not exist in the map. + /// + /// However, if a key exists in the map already, the behavior is unspecified: + /// this operation may panic, loop forever, or any following operation with the map + /// may panic, loop forever or return arbitrary result. + /// + /// That said, this operation (and following operations) are guaranteed to + /// not violate memory safety. + /// + /// However this operation is still unsafe because the resulting `HashMap` + /// may be passed to unsafe code which does expect the map to behave + /// correctly, and would cause unsoundness as a result. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map1 = HashMap::new(); + /// assert_eq!(map1.insert(1, "a"), None); + /// assert_eq!(map1.insert(2, "b"), None); + /// assert_eq!(map1.insert(3, "c"), None); + /// assert_eq!(map1.len(), 3); + /// + /// let mut map2 = HashMap::new(); + /// + /// for (key, value) in map1.into_iter() { + /// unsafe { + /// map2.insert_unique_unchecked(key, value); + /// } + /// } + /// + /// let (key, value) = unsafe { map2.insert_unique_unchecked(4, "d") }; + /// assert_eq!(key, &4); + /// assert_eq!(value, &mut "d"); + /// *value = "e"; + /// + /// assert_eq!(map2[&1], "a"); + /// assert_eq!(map2[&2], "b"); + /// assert_eq!(map2[&3], "c"); + /// assert_eq!(map2[&4], "e"); + /// assert_eq!(map2.len(), 4); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub unsafe fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) { + let hash = make_hash::(&self.hash_builder, &k); + let bucket = self + .table + .insert(hash, (k, v), make_hasher::<_, V, S>(&self.hash_builder)); + let (k_ref, v_ref) = unsafe { bucket.as_mut() }; + (k_ref, v_ref) + } + + /// Tries to insert a key-value pair into the map, and returns + /// a mutable reference to the value in the entry. + /// + /// # Errors + /// + /// If the map already had this key present, nothing is updated, and + /// an error containing the occupied entry and the value is returned. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::OccupiedError; + /// + /// let mut map = HashMap::new(); + /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a"); + /// + /// match map.try_insert(37, "b") { + /// Err(OccupiedError { entry, value }) => { + /// assert_eq!(entry.key(), &37); + /// assert_eq!(entry.get(), &"a"); + /// assert_eq!(value, "b"); + /// } + /// _ => panic!() + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn try_insert( + &mut self, + key: K, + value: V, + ) -> Result<&mut V, OccupiedError<'_, K, V, S, A>> { + match self.entry(key) { + Entry::Occupied(entry) => Err(OccupiedError { entry, value }), + Entry::Vacant(entry) => Ok(entry.insert(value)), + } + } + + /// Removes a key from the map, returning the value at the key if the key + /// was previously in the map. Keeps the allocated memory for reuse. + /// + /// The key may be any borrowed form of the map's key type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the key type. + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// // The map is empty + /// assert!(map.is_empty() && map.capacity() == 0); + /// + /// map.insert(1, "a"); + /// + /// assert_eq!(map.remove(&1), Some("a")); + /// assert_eq!(map.remove(&1), None); + /// + /// // Now map holds none elements + /// assert!(map.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove(&mut self, k: &Q) -> Option + where + Q: Hash + Equivalent + ?Sized, + { + // Avoid `Option::map` because it bloats LLVM IR. + match self.remove_entry(k) { + Some((_, v)) => Some(v), + None => None, + } + } + + /// Removes a key from the map, returning the stored key and value if the + /// key was previously in the map. Keeps the allocated memory for reuse. + /// + /// The key may be any borrowed form of the map's key type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the key type. + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// // The map is empty + /// assert!(map.is_empty() && map.capacity() == 0); + /// + /// map.insert(1, "a"); + /// + /// assert_eq!(map.remove_entry(&1), Some((1, "a"))); + /// assert_eq!(map.remove(&1), None); + /// + /// // Now map hold none elements + /// assert!(map.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> + where + Q: Hash + Equivalent + ?Sized, + { + let hash = make_hash::(&self.hash_builder, k); + self.table.remove_entry(hash, equivalent_key(k)) + } + + /// Returns the total amount of memory allocated internally by the hash + /// set, in bytes. + /// + /// The returned number is informational only. It is intended to be + /// primarily used for memory profiling. + #[inline] + pub fn allocation_size(&self) -> usize { + self.table.allocation_size() + } +} + +impl PartialEq for HashMap +where + K: Eq + Hash, + V: PartialEq, + S: BuildHasher, + A: Allocator, +{ + fn eq(&self, other: &Self) -> bool { + if self.len() != other.len() { + return false; + } + + self.iter() + .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v)) + } +} + +impl Eq for HashMap +where + K: Eq + Hash, + V: Eq, + S: BuildHasher, + A: Allocator, +{ +} + +impl Debug for HashMap +where + K: Debug, + V: Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_map().entries(self.iter()).finish() + } +} + +impl Default for HashMap +where + S: Default, + A: Default + Allocator, +{ + /// Creates an empty `HashMap`, with the `Default` value for the hasher and allocator. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use std::collections::hash_map::RandomState; + /// + /// // You can specify all types of HashMap, including hasher and allocator. + /// // Created map is empty and don't allocate memory + /// let map: HashMap = Default::default(); + /// assert_eq!(map.capacity(), 0); + /// let map: HashMap = HashMap::default(); + /// assert_eq!(map.capacity(), 0); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self::with_hasher_in(Default::default(), Default::default()) + } +} + +impl Index<&Q> for HashMap +where + K: Eq + Hash, + Q: Hash + Equivalent + ?Sized, + S: BuildHasher, + A: Allocator, +{ + type Output = V; + + /// Returns a reference to the value corresponding to the supplied key. + /// + /// # Panics + /// + /// Panics if the key is not present in the `HashMap`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let map: HashMap<_, _> = [("a", "One"), ("b", "Two")].into(); + /// + /// assert_eq!(map[&"a"], "One"); + /// assert_eq!(map[&"b"], "Two"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn index(&self, key: &Q) -> &V { + self.get(key).expect("no entry found for key") + } +} + +// The default hasher is used to match the std implementation signature +#[cfg(feature = "default-hasher")] +impl From<[(K, V); N]> for HashMap +where + K: Eq + Hash, + A: Default + Allocator, +{ + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let map1 = HashMap::from([(1, 2), (3, 4)]); + /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into(); + /// assert_eq!(map1, map2); + /// ``` + fn from(arr: [(K, V); N]) -> Self { + arr.into_iter().collect() + } +} + +/// An iterator over the entries of a `HashMap` in arbitrary order. +/// The iterator element type is `(&'a K, &'a V)`. +/// +/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its +/// documentation for more. +/// +/// [`iter`]: struct.HashMap.html#method.iter +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut iter = map.iter(); +/// let mut vec = vec![iter.next(), iter.next(), iter.next()]; +/// +/// // The `Iter` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some((&1, &"a")), Some((&2, &"b")), Some((&3, &"c"))]); +/// +/// // It is fused iterator +/// assert_eq!(iter.next(), None); +/// assert_eq!(iter.next(), None); +/// ``` +pub struct Iter<'a, K, V> { + inner: RawIter<(K, V)>, + marker: PhantomData<(&'a K, &'a V)>, +} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl Clone for Iter<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Iter { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +impl fmt::Debug for Iter<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A mutable iterator over the entries of a `HashMap` in arbitrary order. +/// The iterator element type is `(&'a K, &'a mut V)`. +/// +/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its +/// documentation for more. +/// +/// [`iter_mut`]: struct.HashMap.html#method.iter_mut +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into(); +/// +/// let mut iter = map.iter_mut(); +/// iter.next().map(|(_, v)| v.push_str(" Mississippi")); +/// iter.next().map(|(_, v)| v.push_str(" Mississippi")); +/// +/// // It is fused iterator +/// assert_eq!(iter.next(), None); +/// assert_eq!(iter.next(), None); +/// +/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned()); +/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned()); +/// ``` +pub struct IterMut<'a, K, V> { + inner: RawIter<(K, V)>, + // To ensure invariance with respect to V + marker: PhantomData<(&'a K, &'a mut V)>, +} + +// We override the default Send impl which has K: Sync instead of K: Send. Both +// are correct, but this one is more general since it allows keys which +// implement Send but not Sync. +unsafe impl Send for IterMut<'_, K, V> {} + +impl IterMut<'_, K, V> { + /// Returns a iterator of references over the remaining items. + #[cfg_attr(feature = "inline-more", inline)] + pub(super) fn iter(&self) -> Iter<'_, K, V> { + Iter { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +/// An owning iterator over the entries of a `HashMap` in arbitrary order. +/// The iterator element type is `(K, V)`. +/// +/// This `struct` is created by the [`into_iter`] method on [`HashMap`] +/// (provided by the [`IntoIterator`] trait). See its documentation for more. +/// The map cannot be used after calling that method. +/// +/// [`into_iter`]: struct.HashMap.html#method.into_iter +/// [`HashMap`]: struct.HashMap.html +/// [`IntoIterator`]: https://doc.rust-lang.org/core/iter/trait.IntoIterator.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut iter = map.into_iter(); +/// let mut vec = vec![iter.next(), iter.next(), iter.next()]; +/// +/// // The `IntoIter` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]); +/// +/// // It is fused iterator +/// assert_eq!(iter.next(), None); +/// assert_eq!(iter.next(), None); +/// ``` +pub struct IntoIter { + inner: RawIntoIter<(K, V), A>, +} + +impl IntoIter { + /// Returns a iterator of references over the remaining items. + #[cfg_attr(feature = "inline-more", inline)] + pub(super) fn iter(&self) -> Iter<'_, K, V> { + Iter { + inner: self.inner.iter(), + marker: PhantomData, + } + } +} + +/// An owning iterator over the keys of a `HashMap` in arbitrary order. +/// The iterator element type is `K`. +/// +/// This `struct` is created by the [`into_keys`] method on [`HashMap`]. +/// See its documentation for more. +/// The map cannot be used after calling that method. +/// +/// [`into_keys`]: struct.HashMap.html#method.into_keys +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut keys = map.into_keys(); +/// let mut vec = vec![keys.next(), keys.next(), keys.next()]; +/// +/// // The `IntoKeys` iterator produces keys in arbitrary order, so the +/// // keys must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some(1), Some(2), Some(3)]); +/// +/// // It is fused iterator +/// assert_eq!(keys.next(), None); +/// assert_eq!(keys.next(), None); +/// ``` +pub struct IntoKeys { + inner: IntoIter, +} + +impl Default for IntoKeys { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + } + } +} +impl Iterator for IntoKeys { + type Item = K; + + #[inline] + fn next(&mut self) -> Option { + self.inner.next().map(|(k, _)| k) + } + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[inline] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, |acc, (k, _)| f(acc, k)) + } +} + +impl ExactSizeIterator for IntoKeys { + #[inline] + fn len(&self) -> usize { + self.inner.len() + } +} + +impl FusedIterator for IntoKeys {} + +impl fmt::Debug for IntoKeys { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(self.inner.iter().map(|(k, _)| k)) + .finish() + } +} + +/// An owning iterator over the values of a `HashMap` in arbitrary order. +/// The iterator element type is `V`. +/// +/// This `struct` is created by the [`into_values`] method on [`HashMap`]. +/// See its documentation for more. The map cannot be used after calling that method. +/// +/// [`into_values`]: struct.HashMap.html#method.into_values +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut values = map.into_values(); +/// let mut vec = vec![values.next(), values.next(), values.next()]; +/// +/// // The `IntoValues` iterator produces values in arbitrary order, so +/// // the values must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some("a"), Some("b"), Some("c")]); +/// +/// // It is fused iterator +/// assert_eq!(values.next(), None); +/// assert_eq!(values.next(), None); +/// ``` +pub struct IntoValues { + inner: IntoIter, +} + +impl Default for IntoValues { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + } + } +} +impl Iterator for IntoValues { + type Item = V; + + #[inline] + fn next(&mut self) -> Option { + self.inner.next().map(|(_, v)| v) + } + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[inline] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, |acc, (_, v)| f(acc, v)) + } +} + +impl ExactSizeIterator for IntoValues { + #[inline] + fn len(&self) -> usize { + self.inner.len() + } +} + +impl FusedIterator for IntoValues {} + +impl fmt::Debug for IntoValues { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(self.inner.iter().map(|(_, v)| v)) + .finish() + } +} + +/// An iterator over the keys of a `HashMap` in arbitrary order. +/// The iterator element type is `&'a K`. +/// +/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its +/// documentation for more. +/// +/// [`keys`]: struct.HashMap.html#method.keys +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut keys = map.keys(); +/// let mut vec = vec![keys.next(), keys.next(), keys.next()]; +/// +/// // The `Keys` iterator produces keys in arbitrary order, so the +/// // keys must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some(&1), Some(&2), Some(&3)]); +/// +/// // It is fused iterator +/// assert_eq!(keys.next(), None); +/// assert_eq!(keys.next(), None); +/// ``` +pub struct Keys<'a, K, V> { + inner: Iter<'a, K, V>, +} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl Clone for Keys<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Keys { + inner: self.inner.clone(), + } + } +} + +impl fmt::Debug for Keys<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// An iterator over the values of a `HashMap` in arbitrary order. +/// The iterator element type is `&'a V`. +/// +/// This `struct` is created by the [`values`] method on [`HashMap`]. See its +/// documentation for more. +/// +/// [`values`]: struct.HashMap.html#method.values +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut values = map.values(); +/// let mut vec = vec![values.next(), values.next(), values.next()]; +/// +/// // The `Values` iterator produces values in arbitrary order, so the +/// // values must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some(&"a"), Some(&"b"), Some(&"c")]); +/// +/// // It is fused iterator +/// assert_eq!(values.next(), None); +/// assert_eq!(values.next(), None); +/// ``` +pub struct Values<'a, K, V> { + inner: Iter<'a, K, V>, +} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl Clone for Values<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Values { + inner: self.inner.clone(), + } + } +} + +impl fmt::Debug for Values<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A draining iterator over the entries of a `HashMap` in arbitrary +/// order. The iterator element type is `(K, V)`. +/// +/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its +/// documentation for more. +/// +/// [`drain`]: struct.HashMap.html#method.drain +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let mut map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut drain_iter = map.drain(); +/// let mut vec = vec![drain_iter.next(), drain_iter.next(), drain_iter.next()]; +/// +/// // The `Drain` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]); +/// +/// // It is fused iterator +/// assert_eq!(drain_iter.next(), None); +/// assert_eq!(drain_iter.next(), None); +/// ``` +pub struct Drain<'a, K, V, A: Allocator = Global> { + inner: RawDrain<'a, (K, V), A>, +} + +impl Drain<'_, K, V, A> { + /// Returns a iterator of references over the remaining items. + #[cfg_attr(feature = "inline-more", inline)] + pub(super) fn iter(&self) -> Iter<'_, K, V> { + Iter { + inner: self.inner.iter(), + marker: PhantomData, + } + } +} + +/// A draining iterator over entries of a `HashMap` which don't satisfy the predicate +/// `f(&k, &mut v)` in arbitrary order. The iterator element type is `(K, V)`. +/// +/// This `struct` is created by the [`extract_if`] method on [`HashMap`]. See its +/// documentation for more. +/// +/// [`extract_if`]: struct.HashMap.html#method.extract_if +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let mut map: HashMap = [(1, "a"), (2, "b"), (3, "c")].into(); +/// +/// let mut extract_if = map.extract_if(|k, _v| k % 2 != 0); +/// let mut vec = vec![extract_if.next(), extract_if.next()]; +/// +/// // The `ExtractIf` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [Some((1, "a")),Some((3, "c"))]); +/// +/// // It is fused iterator +/// assert_eq!(extract_if.next(), None); +/// assert_eq!(extract_if.next(), None); +/// drop(extract_if); +/// +/// assert_eq!(map.len(), 1); +/// ``` +#[must_use = "Iterators are lazy unless consumed"] +pub struct ExtractIf<'a, K, V, F, A: Allocator = Global> +where + F: FnMut(&K, &mut V) -> bool, +{ + f: F, + inner: RawExtractIf<'a, (K, V), A>, +} + +impl Iterator for ExtractIf<'_, K, V, F, A> +where + F: FnMut(&K, &mut V) -> bool, + A: Allocator, +{ + type Item = (K, V); + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option { + self.inner.next(|&mut (ref k, ref mut v)| (self.f)(k, v)) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (0, self.inner.iter.size_hint().1) + } +} + +impl FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {} + +/// A mutable iterator over the values of a `HashMap` in arbitrary order. +/// The iterator element type is `&'a mut V`. +/// +/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its +/// documentation for more. +/// +/// [`values_mut`]: struct.HashMap.html#method.values_mut +/// [`HashMap`]: struct.HashMap.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashMap; +/// +/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into(); +/// +/// let mut values = map.values_mut(); +/// values.next().map(|v| v.push_str(" Mississippi")); +/// values.next().map(|v| v.push_str(" Mississippi")); +/// +/// // It is fused iterator +/// assert_eq!(values.next(), None); +/// assert_eq!(values.next(), None); +/// +/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned()); +/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned()); +/// ``` +pub struct ValuesMut<'a, K, V> { + inner: IterMut<'a, K, V>, +} + +/// A view into a single entry in a map, which may either be vacant or occupied. +/// +/// This `enum` is constructed from the [`entry`] method on [`HashMap`]. +/// +/// [`HashMap`]: struct.HashMap.html +/// [`entry`]: struct.HashMap.html#method.entry +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry}; +/// +/// let mut map = HashMap::new(); +/// map.extend([("a", 10), ("b", 20), ("c", 30)]); +/// assert_eq!(map.len(), 3); +/// +/// // Existing key (insert) +/// let entry: Entry<_, _, _> = map.entry("a"); +/// let _raw_o: OccupiedEntry<_, _, _> = entry.insert(1); +/// assert_eq!(map.len(), 3); +/// // Nonexistent key (insert) +/// map.entry("d").insert(4); +/// +/// // Existing key (or_insert) +/// let v = map.entry("b").or_insert(2); +/// assert_eq!(std::mem::replace(v, 2), 20); +/// // Nonexistent key (or_insert) +/// map.entry("e").or_insert(5); +/// +/// // Existing key (or_insert_with) +/// let v = map.entry("c").or_insert_with(|| 3); +/// assert_eq!(std::mem::replace(v, 3), 30); +/// // Nonexistent key (or_insert_with) +/// map.entry("f").or_insert_with(|| 6); +/// +/// println!("Our HashMap: {:?}", map); +/// +/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect(); +/// // The `Iter` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]); +/// ``` +pub enum Entry<'a, K, V, S, A = Global> +where + A: Allocator, +{ + /// An occupied entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{Entry, HashMap}; + /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into(); + /// + /// match map.entry("a") { + /// Entry::Vacant(_) => unreachable!(), + /// Entry::Occupied(_) => { } + /// } + /// ``` + Occupied(OccupiedEntry<'a, K, V, S, A>), + + /// A vacant entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{Entry, HashMap}; + /// let mut map: HashMap<&str, i32> = HashMap::new(); + /// + /// match map.entry("a") { + /// Entry::Occupied(_) => unreachable!(), + /// Entry::Vacant(_) => { } + /// } + /// ``` + Vacant(VacantEntry<'a, K, V, S, A>), +} + +impl Debug for Entry<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(), + Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(), + } + } +} + +/// A view into an occupied entry in a [`HashMap`]. +/// It is part of the [`Entry`] and [`EntryRef`] enums. +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry}; +/// +/// let mut map = HashMap::new(); +/// map.extend([("a", 10), ("b", 20), ("c", 30)]); +/// +/// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a").insert(100); +/// assert_eq!(map.len(), 3); +/// +/// // Existing key (insert and update) +/// match map.entry("a") { +/// Entry::Vacant(_) => unreachable!(), +/// Entry::Occupied(mut view) => { +/// assert_eq!(view.get(), &100); +/// let v = view.get_mut(); +/// *v *= 10; +/// assert_eq!(view.insert(1111), 1000); +/// } +/// } +/// +/// assert_eq!(map[&"a"], 1111); +/// assert_eq!(map.len(), 3); +/// +/// // Existing key (take) +/// match map.entry("c") { +/// Entry::Vacant(_) => unreachable!(), +/// Entry::Occupied(view) => { +/// assert_eq!(view.remove_entry(), ("c", 30)); +/// } +/// } +/// assert_eq!(map.get(&"c"), None); +/// assert_eq!(map.len(), 2); +/// ``` +pub struct OccupiedEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> { + hash: u64, + elem: Bucket<(K, V)>, + table: &'a mut HashMap, +} + +unsafe impl Send for OccupiedEntry<'_, K, V, S, A> +where + K: Send, + V: Send, + S: Send, + A: Send + Allocator, +{ +} +unsafe impl Sync for OccupiedEntry<'_, K, V, S, A> +where + K: Sync, + V: Sync, + S: Sync, + A: Sync + Allocator, +{ +} + +impl Debug for OccupiedEntry<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OccupiedEntry") + .field("key", self.key()) + .field("value", self.get()) + .finish() + } +} + +/// A view into a vacant entry in a `HashMap`. +/// It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{Entry, HashMap, VacantEntry}; +/// +/// let mut map = HashMap::<&str, i32>::new(); +/// +/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") { +/// Entry::Vacant(view) => view, +/// Entry::Occupied(_) => unreachable!(), +/// }; +/// entry_v.insert(10); +/// assert!(map[&"a"] == 10 && map.len() == 1); +/// +/// // Nonexistent key (insert and update) +/// match map.entry("b") { +/// Entry::Occupied(_) => unreachable!(), +/// Entry::Vacant(view) => { +/// let value = view.insert(2); +/// assert_eq!(*value, 2); +/// *value = 20; +/// } +/// } +/// assert!(map[&"b"] == 20 && map.len() == 2); +/// ``` +pub struct VacantEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> { + hash: u64, + key: K, + table: &'a mut HashMap, +} + +impl Debug for VacantEntry<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("VacantEntry").field(self.key()).finish() + } +} + +/// A view into a single entry in a map, which may either be vacant or occupied, +/// with any borrowed form of the map's key type. +/// +/// +/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`]. +/// +/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those +/// for the key type. It also require that key may be constructed from the borrowed +/// form through the [`From`] trait. +/// +/// [`HashMap`]: struct.HashMap.html +/// [`entry_ref`]: struct.HashMap.html#method.entry_ref +/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html +/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html +/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntry}; +/// +/// let mut map = HashMap::new(); +/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]); +/// assert_eq!(map.len(), 3); +/// +/// // Existing key (insert) +/// let key = String::from("a"); +/// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key); +/// let _raw_o: OccupiedEntry<_, _, _, _> = entry.insert(1); +/// assert_eq!(map.len(), 3); +/// // Nonexistent key (insert) +/// map.entry_ref("d").insert(4); +/// +/// // Existing key (or_insert) +/// let v = map.entry_ref("b").or_insert(2); +/// assert_eq!(std::mem::replace(v, 2), 20); +/// // Nonexistent key (or_insert) +/// map.entry_ref("e").or_insert(5); +/// +/// // Existing key (or_insert_with) +/// let v = map.entry_ref("c").or_insert_with(|| 3); +/// assert_eq!(std::mem::replace(v, 3), 30); +/// // Nonexistent key (or_insert_with) +/// map.entry_ref("f").or_insert_with(|| 6); +/// +/// println!("Our HashMap: {:?}", map); +/// +/// for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) { +/// assert_eq!(map[key], value) +/// } +/// assert_eq!(map.len(), 6); +/// ``` +pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global> +where + A: Allocator, +{ + /// An occupied entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{EntryRef, HashMap}; + /// let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].into(); + /// + /// match map.entry_ref("a") { + /// EntryRef::Vacant(_) => unreachable!(), + /// EntryRef::Occupied(_) => { } + /// } + /// ``` + Occupied(OccupiedEntry<'a, K, V, S, A>), + + /// A vacant entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{EntryRef, HashMap}; + /// let mut map: HashMap = HashMap::new(); + /// + /// match map.entry_ref("a") { + /// EntryRef::Occupied(_) => unreachable!(), + /// EntryRef::Vacant(_) => { } + /// } + /// ``` + Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>), +} + +impl Debug for EntryRef<'_, '_, K, Q, V, S, A> +where + K: Debug + Borrow, + Q: Debug + ?Sized, + V: Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + EntryRef::Vacant(ref v) => f.debug_tuple("EntryRef").field(v).finish(), + EntryRef::Occupied(ref o) => f.debug_tuple("EntryRef").field(o).finish(), + } + } +} + +/// A view into a vacant entry in a `HashMap`. +/// It is part of the [`EntryRef`] enum. +/// +/// [`EntryRef`]: enum.EntryRef.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef}; +/// +/// let mut map = HashMap::::new(); +/// +/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") { +/// EntryRef::Vacant(view) => view, +/// EntryRef::Occupied(_) => unreachable!(), +/// }; +/// entry_v.insert(10); +/// assert!(map["a"] == 10 && map.len() == 1); +/// +/// // Nonexistent key (insert and update) +/// match map.entry_ref("b") { +/// EntryRef::Occupied(_) => unreachable!(), +/// EntryRef::Vacant(view) => { +/// let value = view.insert(2); +/// assert_eq!(*value, 2); +/// *value = 20; +/// } +/// } +/// assert!(map["b"] == 20 && map.len() == 2); +/// ``` +pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator = Global> { + hash: u64, + key: &'b Q, + table: &'a mut HashMap, +} + +impl Debug for VacantEntryRef<'_, '_, K, Q, V, S, A> +where + K: Borrow, + Q: Debug + ?Sized, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("VacantEntryRef").field(&self.key()).finish() + } +} + +/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists. +/// +/// Contains the occupied entry, and the value that was not inserted. +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{HashMap, OccupiedError}; +/// +/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].into(); +/// +/// // try_insert method returns mutable reference to the value if keys are vacant, +/// // but if the map did have key present, nothing is updated, and the provided +/// // value is returned inside `Err(_)` variant +/// match map.try_insert("a", 100) { +/// Err(OccupiedError { mut entry, value }) => { +/// assert_eq!(entry.key(), &"a"); +/// assert_eq!(value, 100); +/// assert_eq!(entry.insert(100), 10) +/// } +/// _ => unreachable!(), +/// } +/// assert_eq!(map[&"a"], 100); +/// ``` +pub struct OccupiedError<'a, K, V, S, A: Allocator = Global> { + /// The entry in the map that was already occupied. + pub entry: OccupiedEntry<'a, K, V, S, A>, + /// The value which was not inserted, because the entry was already occupied. + pub value: V, +} + +impl Debug for OccupiedError<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OccupiedError") + .field("key", self.entry.key()) + .field("old_value", self.entry.get()) + .field("new_value", &self.value) + .finish() + } +} + +impl<'a, K: Debug, V: Debug, S, A: Allocator> fmt::Display for OccupiedError<'a, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "failed to insert {:?}, key {:?} already exists with value {:?}", + self.value, + self.entry.key(), + self.entry.get(), + ) + } +} + +impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap { + type Item = (&'a K, &'a V); + type IntoIter = Iter<'a, K, V>; + + /// Creates an iterator over the entries of a `HashMap` in arbitrary order. + /// The iterator element type is `(&'a K, &'a V)`. + /// + /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`]. + /// + /// [`iter`]: struct.HashMap.html#method.iter + /// [`HashMap`]: struct.HashMap.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into(); + /// let mut map_two = HashMap::new(); + /// + /// for (key, value) in &map_one { + /// println!("Key: {}, Value: {}", key, value); + /// map_two.insert(*key, *value); + /// } + /// + /// assert_eq!(map_one, map_two); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn into_iter(self) -> Iter<'a, K, V> { + self.iter() + } +} + +impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap { + type Item = (&'a K, &'a mut V); + type IntoIter = IterMut<'a, K, V>; + + /// Creates an iterator over the entries of a `HashMap` in arbitrary order + /// with mutable references to the values. The iterator element type is + /// `(&'a K, &'a mut V)`. + /// + /// Return the same `IterMut` struct as by the [`iter_mut`] method on + /// [`HashMap`]. + /// + /// [`iter_mut`]: struct.HashMap.html#method.iter_mut + /// [`HashMap`]: struct.HashMap.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into(); + /// + /// for (key, value) in &mut map { + /// println!("Key: {}, Value: {}", key, value); + /// *value *= 2; + /// } + /// + /// let mut vec = map.iter().collect::>(); + /// // The `Iter` iterator produces items in arbitrary order, so the + /// // items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn into_iter(self) -> IterMut<'a, K, V> { + self.iter_mut() + } +} + +impl IntoIterator for HashMap { + type Item = (K, V); + type IntoIter = IntoIter; + + /// Creates a consuming iterator, that is, one that moves each key-value + /// pair out of the map in arbitrary order. The map cannot be used after + /// calling this. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into(); + /// + /// // Not possible with .iter() + /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect(); + /// // The `IntoIter` iterator produces items in arbitrary order, so + /// // the items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn into_iter(self) -> IntoIter { + IntoIter { + inner: self.table.into_iter(), + } + } +} + +impl<'a, K, V> Default for Iter<'a, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + marker: PhantomData, + } + } +} +impl<'a, K, V> Iterator for Iter<'a, K, V> { + type Item = (&'a K, &'a V); + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<(&'a K, &'a V)> { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some(x) => unsafe { + let r = x.as_ref(); + Some((&r.0, &r.1)) + }, + None => None, + } + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, |acc, x| unsafe { + let (k, v) = x.as_ref(); + f(acc, (k, v)) + }) + } +} +impl ExactSizeIterator for Iter<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.inner.len() + } +} + +impl FusedIterator for Iter<'_, K, V> {} + +impl<'a, K, V> Default for IterMut<'a, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + marker: PhantomData, + } + } +} +impl<'a, K, V> Iterator for IterMut<'a, K, V> { + type Item = (&'a K, &'a mut V); + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<(&'a K, &'a mut V)> { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some(x) => unsafe { + let r = x.as_mut(); + Some((&r.0, &mut r.1)) + }, + None => None, + } + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, |acc, x| unsafe { + let (k, v) = x.as_mut(); + f(acc, (k, v)) + }) + } +} +impl ExactSizeIterator for IterMut<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.inner.len() + } +} +impl FusedIterator for IterMut<'_, K, V> {} + +impl fmt::Debug for IterMut<'_, K, V> +where + K: fmt::Debug, + V: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl Default for IntoIter { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + } + } +} +impl Iterator for IntoIter { + type Item = (K, V); + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<(K, V)> { + self.inner.next() + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, f) + } +} +impl ExactSizeIterator for IntoIter { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.inner.len() + } +} +impl FusedIterator for IntoIter {} + +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl<'a, K, V> Default for Keys<'a, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + } + } +} +impl<'a, K, V> Iterator for Keys<'a, K, V> { + type Item = &'a K; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a K> { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some((k, _)) => Some(k), + None => None, + } + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, |acc, (k, _)| f(acc, k)) + } +} +impl ExactSizeIterator for Keys<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.inner.len() + } +} +impl FusedIterator for Keys<'_, K, V> {} + +impl<'a, K, V> Default for Values<'a, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + } + } +} +impl<'a, K, V> Iterator for Values<'a, K, V> { + type Item = &'a V; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a V> { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some((_, v)) => Some(v), + None => None, + } + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, |acc, (_, v)| f(acc, v)) + } +} +impl ExactSizeIterator for Values<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.inner.len() + } +} +impl FusedIterator for Values<'_, K, V> {} + +impl<'a, K, V> Default for ValuesMut<'a, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + inner: Default::default(), + } + } +} +impl<'a, K, V> Iterator for ValuesMut<'a, K, V> { + type Item = &'a mut V; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a mut V> { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some((_, v)) => Some(v), + None => None, + } + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, |acc, (_, v)| f(acc, v)) + } +} +impl ExactSizeIterator for ValuesMut<'_, K, V> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.inner.len() + } +} +impl FusedIterator for ValuesMut<'_, K, V> {} + +impl fmt::Debug for ValuesMut<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(self.inner.iter().map(|(_, val)| val)) + .finish() + } +} + +impl<'a, K, V, A: Allocator> Iterator for Drain<'a, K, V, A> { + type Item = (K, V); + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<(K, V)> { + self.inner.next() + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, f) + } +} +impl ExactSizeIterator for Drain<'_, K, V, A> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.inner.len() + } +} +impl FusedIterator for Drain<'_, K, V, A> {} + +impl fmt::Debug for Drain<'_, K, V, A> +where + K: fmt::Debug, + V: fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl<'a, K, V, S, A: Allocator> Entry<'a, K, V, S, A> { + /// Sets the value of the entry, and returns an `OccupiedEntry`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// let entry = map.entry("horseyland").insert(37); + /// + /// assert_eq!(entry.key(), &"horseyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A> + where + K: Hash, + S: BuildHasher, + { + match self { + Entry::Occupied(mut entry) => { + entry.insert(value); + entry + } + Entry::Vacant(entry) => entry.insert_entry(value), + } + } + + /// Ensures a value is in the entry by inserting the default if empty, and returns + /// a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// // nonexistent key + /// map.entry("poneyland").or_insert(3); + /// assert_eq!(map["poneyland"], 3); + /// + /// // existing key + /// *map.entry("poneyland").or_insert(10) *= 2; + /// assert_eq!(map["poneyland"], 6); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert(self, default: V) -> &'a mut V + where + K: Hash, + S: BuildHasher, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => entry.insert(default), + } + } + + /// Ensures a value is in the entry by inserting the result of the default function if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// // nonexistent key + /// map.entry("poneyland").or_insert_with(|| 3); + /// assert_eq!(map["poneyland"], 3); + /// + /// // existing key + /// *map.entry("poneyland").or_insert_with(|| 10) *= 2; + /// assert_eq!(map["poneyland"], 6); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert_with V>(self, default: F) -> &'a mut V + where + K: Hash, + S: BuildHasher, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => entry.insert(default()), + } + } + + /// Ensures a value is in the entry by inserting, if empty, the result of the default function. + /// This method allows for generating key-derived values for insertion by providing the default + /// function a reference to the key that was moved during the `.entry(key)` method call. + /// + /// The reference to the moved key is provided so that cloning or copying the key is + /// unnecessary, unlike with `.or_insert_with(|| ... )`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, usize> = HashMap::new(); + /// + /// // nonexistent key + /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count()); + /// assert_eq!(map["poneyland"], 9); + /// + /// // existing key + /// *map.entry("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2; + /// assert_eq!(map["poneyland"], 18); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert_with_key V>(self, default: F) -> &'a mut V + where + K: Hash, + S: BuildHasher, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + let value = default(entry.key()); + entry.insert(value) + } + } + } + + /// Returns a reference to this entry's key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(3); + /// // existing key + /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); + /// // nonexistent key + /// assert_eq!(map.entry("horseland").key(), &"horseland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &K { + match *self { + Entry::Occupied(ref entry) => entry.key(), + Entry::Vacant(ref entry) => entry.key(), + } + } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the map. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// map.entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 42); + /// + /// map.entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 43); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn and_modify(self, f: F) -> Self + where + F: FnOnce(&mut V), + { + match self { + Entry::Occupied(mut entry) => { + f(entry.get_mut()); + Entry::Occupied(entry) + } + Entry::Vacant(entry) => Entry::Vacant(entry), + } + } + + /// Provides shared access to the key and owned access to the value of + /// an occupied entry and allows to replace or remove it based on the + /// value of the returned option. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// let entry = map + /// .entry("poneyland") + /// .and_replace_entry_with(|_k, _v| panic!()); + /// + /// match entry { + /// Entry::Vacant(e) => { + /// assert_eq!(e.key(), &"poneyland"); + /// } + /// Entry::Occupied(_) => panic!(), + /// } + /// + /// map.insert("poneyland", 42); + /// + /// let entry = map + /// .entry("poneyland") + /// .and_replace_entry_with(|k, v| { + /// assert_eq!(k, &"poneyland"); + /// assert_eq!(v, 42); + /// Some(v + 1) + /// }); + /// + /// match entry { + /// Entry::Occupied(e) => { + /// assert_eq!(e.key(), &"poneyland"); + /// assert_eq!(e.get(), &43); + /// } + /// Entry::Vacant(_) => panic!(), + /// } + /// + /// assert_eq!(map["poneyland"], 43); + /// + /// let entry = map + /// .entry("poneyland") + /// .and_replace_entry_with(|_k, _v| None); + /// + /// match entry { + /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland"), + /// Entry::Occupied(_) => panic!(), + /// } + /// + /// assert!(!map.contains_key("poneyland")); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn and_replace_entry_with(self, f: F) -> Self + where + F: FnOnce(&K, V) -> Option, + { + match self { + Entry::Occupied(entry) => entry.replace_entry_with(f), + Entry::Vacant(_) => self, + } + } +} + +impl<'a, K, V: Default, S, A: Allocator> Entry<'a, K, V, S, A> { + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, Option> = HashMap::new(); + /// + /// // nonexistent key + /// map.entry("poneyland").or_default(); + /// assert_eq!(map["poneyland"], None); + /// + /// map.insert("horseland", Some(3)); + /// + /// // existing key + /// assert_eq!(map.entry("horseland").or_default(), &mut Some(3)); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_default(self) -> &'a mut V + where + K: Hash, + S: BuildHasher, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => entry.insert(Default::default()), + } + } +} + +impl<'a, K, V, S, A: Allocator> OccupiedEntry<'a, K, V, S, A> { + /// Gets a reference to the key in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{Entry, HashMap}; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// match map.entry("poneyland") { + /// Entry::Vacant(_) => panic!(), + /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland"), + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &K { + unsafe { &self.elem.as_ref().0 } + } + + /// Take the ownership of the key and value from the map. + /// Keeps the allocated memory for reuse. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// // The map is empty + /// assert!(map.is_empty() && map.capacity() == 0); + /// + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(o) = map.entry("poneyland") { + /// // We delete the entry from the map. + /// assert_eq!(o.remove_entry(), ("poneyland", 12)); + /// } + /// + /// assert_eq!(map.contains_key("poneyland"), false); + /// // Now map hold none elements + /// assert!(map.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove_entry(self) -> (K, V) { + unsafe { self.table.table.remove(self.elem).0 } + } + + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// match map.entry("poneyland") { + /// Entry::Vacant(_) => panic!(), + /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12), + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get(&self) -> &V { + unsafe { &self.elem.as_ref().1 } + } + + /// Gets a mutable reference to the value in the entry. + /// + /// If you need a reference to the `OccupiedEntry` which may outlive the + /// destruction of the `Entry` value, see [`into_mut`]. + /// + /// [`into_mut`]: #method.into_mut + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// assert_eq!(map["poneyland"], 12); + /// if let Entry::Occupied(mut o) = map.entry("poneyland") { + /// *o.get_mut() += 10; + /// assert_eq!(*o.get(), 22); + /// + /// // We can use the same Entry multiple times. + /// *o.get_mut() += 2; + /// } + /// + /// assert_eq!(map["poneyland"], 24); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_mut(&mut self) -> &mut V { + unsafe { &mut self.elem.as_mut().1 } + } + + /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry + /// with a lifetime bound to the map itself. + /// + /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`]. + /// + /// [`get_mut`]: #method.get_mut + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{Entry, HashMap}; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// assert_eq!(map["poneyland"], 12); + /// + /// let value: &mut u32; + /// match map.entry("poneyland") { + /// Entry::Occupied(entry) => value = entry.into_mut(), + /// Entry::Vacant(_) => panic!(), + /// } + /// *value += 10; + /// + /// assert_eq!(map["poneyland"], 22); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_mut(self) -> &'a mut V { + unsafe { &mut self.elem.as_mut().1 } + } + + /// Sets the value of the entry, and returns the entry's old value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(mut o) = map.entry("poneyland") { + /// assert_eq!(o.insert(15), 12); + /// } + /// + /// assert_eq!(map["poneyland"], 15); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(&mut self, value: V) -> V { + mem::replace(self.get_mut(), value) + } + + /// Takes the value out of the entry, and returns it. + /// Keeps the allocated memory for reuse. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// // The map is empty + /// assert!(map.is_empty() && map.capacity() == 0); + /// + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(o) = map.entry("poneyland") { + /// assert_eq!(o.remove(), 12); + /// } + /// + /// assert_eq!(map.contains_key("poneyland"), false); + /// // Now map hold none elements + /// assert!(map.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove(self) -> V { + self.remove_entry().1 + } + + /// Provides shared access to the key and owned access to the value of + /// the entry and allows to replace or remove it based on the + /// value of the returned option. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.insert("poneyland", 42); + /// + /// let entry = match map.entry("poneyland") { + /// Entry::Occupied(e) => { + /// e.replace_entry_with(|k, v| { + /// assert_eq!(k, &"poneyland"); + /// assert_eq!(v, 42); + /// Some(v + 1) + /// }) + /// } + /// Entry::Vacant(_) => panic!(), + /// }; + /// + /// match entry { + /// Entry::Occupied(e) => { + /// assert_eq!(e.key(), &"poneyland"); + /// assert_eq!(e.get(), &43); + /// } + /// Entry::Vacant(_) => panic!(), + /// } + /// + /// assert_eq!(map["poneyland"], 43); + /// + /// let entry = match map.entry("poneyland") { + /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None), + /// Entry::Vacant(_) => panic!(), + /// }; + /// + /// match entry { + /// Entry::Vacant(e) => { + /// assert_eq!(e.key(), &"poneyland"); + /// } + /// Entry::Occupied(_) => panic!(), + /// } + /// + /// assert!(!map.contains_key("poneyland")); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn replace_entry_with(self, f: F) -> Entry<'a, K, V, S, A> + where + F: FnOnce(&K, V) -> Option, + { + unsafe { + let mut spare_key = None; + + self.table + .table + .replace_bucket_with(self.elem.clone(), |(key, value)| { + if let Some(new_value) = f(&key, value) { + Some((key, new_value)) + } else { + spare_key = Some(key); + None + } + }); + + if let Some(key) = spare_key { + Entry::Vacant(VacantEntry { + hash: self.hash, + key, + table: self.table, + }) + } else { + Entry::Occupied(self) + } + } + } +} + +impl<'a, K, V, S, A: Allocator> VacantEntry<'a, K, V, S, A> { + /// Gets a reference to the key that would be used when inserting a value + /// through the `VacantEntry`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &K { + &self.key + } + + /// Take ownership of the key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{Entry, HashMap}; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// match map.entry("poneyland") { + /// Entry::Occupied(_) => panic!(), + /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland"), + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_key(self) -> K { + self.key + } + + /// Sets the value of the entry with the [`VacantEntry`]'s key, + /// and returns a mutable reference to it. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// if let Entry::Vacant(o) = map.entry("poneyland") { + /// o.insert(37); + /// } + /// assert_eq!(map["poneyland"], 37); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self, value: V) -> &'a mut V + where + K: Hash, + S: BuildHasher, + { + let table = &mut self.table.table; + let entry = table.insert_entry( + self.hash, + (self.key, value), + make_hasher::<_, V, S>(&self.table.hash_builder), + ); + &mut entry.1 + } + + /// Sets the value of the entry with the [`VacantEntry`]'s key, + /// and returns an [`OccupiedEntry`]. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// if let Entry::Vacant(v) = map.entry("poneyland") { + /// let o = v.insert_entry(37); + /// assert_eq!(o.get(), &37); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A> + where + K: Hash, + S: BuildHasher, + { + let elem = self.table.table.insert( + self.hash, + (self.key, value), + make_hasher::<_, V, S>(&self.table.hash_builder), + ); + OccupiedEntry { + hash: self.hash, + elem, + table: self.table, + } + } +} + +impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { + /// Sets the value of the entry, and returns an `OccupiedEntry`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::new(); + /// let entry = map.entry_ref("horseyland").insert(37); + /// + /// assert_eq!(entry.key(), "horseyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A> + where + K: Hash + From<&'b Q>, + S: BuildHasher, + { + match self { + EntryRef::Occupied(mut entry) => { + entry.insert(value); + entry + } + EntryRef::Vacant(entry) => entry.insert_entry(value), + } + } + + /// Ensures a value is in the entry by inserting the default if empty, and returns + /// a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::new(); + /// + /// // nonexistent key + /// map.entry_ref("poneyland").or_insert(3); + /// assert_eq!(map["poneyland"], 3); + /// + /// // existing key + /// *map.entry_ref("poneyland").or_insert(10) *= 2; + /// assert_eq!(map["poneyland"], 6); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert(self, default: V) -> &'a mut V + where + K: Hash + From<&'b Q>, + S: BuildHasher, + { + match self { + EntryRef::Occupied(entry) => entry.into_mut(), + EntryRef::Vacant(entry) => entry.insert(default), + } + } + + /// Ensures a value is in the entry by inserting the result of the default function if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::new(); + /// + /// // nonexistent key + /// map.entry_ref("poneyland").or_insert_with(|| 3); + /// assert_eq!(map["poneyland"], 3); + /// + /// // existing key + /// *map.entry_ref("poneyland").or_insert_with(|| 10) *= 2; + /// assert_eq!(map["poneyland"], 6); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert_with V>(self, default: F) -> &'a mut V + where + K: Hash + From<&'b Q>, + S: BuildHasher, + { + match self { + EntryRef::Occupied(entry) => entry.into_mut(), + EntryRef::Vacant(entry) => entry.insert(default()), + } + } + + /// Ensures a value is in the entry by inserting, if empty, the result of the default function. + /// This method allows for generating key-derived values for insertion by providing the default + /// function an access to the borrower form of the key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::new(); + /// + /// // nonexistent key + /// map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count()); + /// assert_eq!(map["poneyland"], 9); + /// + /// // existing key + /// *map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2; + /// assert_eq!(map["poneyland"], 18); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert_with_key V>(self, default: F) -> &'a mut V + where + K: Hash + Borrow + From<&'b Q>, + S: BuildHasher, + { + match self { + EntryRef::Occupied(entry) => entry.into_mut(), + EntryRef::Vacant(entry) => { + let value = default(entry.key); + entry.insert(value) + } + } + } + + /// Returns a reference to this entry's key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::new(); + /// map.entry_ref("poneyland").or_insert(3); + /// // existing key + /// assert_eq!(map.entry_ref("poneyland").key(), "poneyland"); + /// // nonexistent key + /// assert_eq!(map.entry_ref("horseland").key(), "horseland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &Q + where + K: Borrow, + { + match *self { + EntryRef::Occupied(ref entry) => entry.key().borrow(), + EntryRef::Vacant(ref entry) => entry.key(), + } + } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the map. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::new(); + /// + /// map.entry_ref("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 42); + /// + /// map.entry_ref("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 43); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn and_modify(self, f: F) -> Self + where + F: FnOnce(&mut V), + { + match self { + EntryRef::Occupied(mut entry) => { + f(entry.get_mut()); + EntryRef::Occupied(entry) + } + EntryRef::Vacant(entry) => EntryRef::Vacant(entry), + } + } +} + +impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap> = HashMap::new(); + /// + /// // nonexistent key + /// map.entry_ref("poneyland").or_default(); + /// assert_eq!(map["poneyland"], None); + /// + /// map.insert("horseland".to_string(), Some(3)); + /// + /// // existing key + /// assert_eq!(map.entry_ref("horseland").or_default(), &mut Some(3)); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_default(self) -> &'a mut V + where + K: Hash + From<&'b Q>, + S: BuildHasher, + { + match self { + EntryRef::Occupied(entry) => entry.into_mut(), + EntryRef::Vacant(entry) => entry.insert(Default::default()), + } + } +} + +impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S, A> { + /// Gets a reference to the key that would be used when inserting a value + /// through the `VacantEntryRef`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap = HashMap::new(); + /// let key: &str = "poneyland"; + /// assert_eq!(map.entry_ref(key).key(), "poneyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &'b Q { + self.key + } + + /// Sets the value of the entry with the `VacantEntryRef`'s key, + /// and returns a mutable reference to it. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::EntryRef; + /// + /// let mut map: HashMap = HashMap::new(); + /// let key: &str = "poneyland"; + /// + /// if let EntryRef::Vacant(o) = map.entry_ref(key) { + /// o.insert(37); + /// } + /// assert_eq!(map["poneyland"], 37); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self, value: V) -> &'a mut V + where + K: Hash + From<&'b Q>, + S: BuildHasher, + { + let table = &mut self.table.table; + let entry = table.insert_entry( + self.hash, + (self.key.into(), value), + make_hasher::<_, V, S>(&self.table.hash_builder), + ); + &mut entry.1 + } + + /// Sets the value of the entry with the [`VacantEntryRef`]'s key, + /// and returns an [`OccupiedEntry`]. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::EntryRef; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// if let EntryRef::Vacant(v) = map.entry_ref("poneyland") { + /// let o = v.insert_entry(37); + /// assert_eq!(o.get(), &37); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A> + where + K: Hash + From<&'b Q>, + S: BuildHasher, + { + let elem = self.table.table.insert( + self.hash, + (self.key.into(), value), + make_hasher::<_, V, S>(&self.table.hash_builder), + ); + OccupiedEntry { + hash: self.hash, + elem, + table: self.table, + } + } +} + +impl FromIterator<(K, V)> for HashMap +where + K: Eq + Hash, + S: BuildHasher + Default, + A: Default + Allocator, +{ + #[cfg_attr(feature = "inline-more", inline)] + fn from_iter>(iter: T) -> Self { + let iter = iter.into_iter(); + let mut map = + Self::with_capacity_and_hasher_in(iter.size_hint().0, S::default(), A::default()); + iter.for_each(|(k, v)| { + map.insert(k, v); + }); + map + } +} + +/// Inserts all new key-values from the iterator and replaces values with existing +/// keys with new values returned from the iterator. +impl Extend<(K, V)> for HashMap +where + K: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + /// Inserts all new key-values from the iterator to existing `HashMap`. + /// Replace values with existing keys with new values returned from the iterator. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, 100); + /// + /// let some_iter = [(1, 1), (2, 2)].into_iter(); + /// map.extend(some_iter); + /// // Replace values with existing keys with new values returned from the iterator. + /// // So that the map.get(&1) doesn't return Some(&100). + /// assert_eq!(map.get(&1), Some(&1)); + /// + /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; + /// map.extend(some_vec); + /// + /// let some_arr = [(5, 5), (6, 6)]; + /// map.extend(some_arr); + /// let old_map_len = map.len(); + /// + /// // You can also extend from another HashMap + /// let mut new_map = HashMap::new(); + /// new_map.extend(map); + /// assert_eq!(new_map.len(), old_map_len); + /// + /// let mut vec: Vec<_> = new_map.into_iter().collect(); + /// // The `IntoIter` iterator produces items in arbitrary order, so the + /// // items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn extend>(&mut self, iter: T) { + // Keys may be already present or show multiple times in the iterator. + // Reserve the entire hint lower bound if the map is empty. + // Otherwise reserve half the hint (rounded up), so the map + // will only resize twice in the worst case. + let iter = iter.into_iter(); + let reserve = if self.is_empty() { + iter.size_hint().0 + } else { + (iter.size_hint().0 + 1) / 2 + }; + self.reserve(reserve); + iter.for_each(move |(k, v)| { + self.insert(k, v); + }); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_one(&mut self, (k, v): (K, V)) { + self.insert(k, v); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_reserve(&mut self, additional: usize) { + // Keys may be already present or show multiple times in the iterator. + // Reserve the entire hint lower bound if the map is empty. + // Otherwise reserve half the hint (rounded up), so the map + // will only resize twice in the worst case. + let reserve = if self.is_empty() { + additional + } else { + (additional + 1) / 2 + }; + self.reserve(reserve); + } +} + +/// Inserts all new key-values from the iterator and replaces values with existing +/// keys with new values returned from the iterator. +impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap +where + K: Eq + Hash + Copy, + V: Copy, + S: BuildHasher, + A: Allocator, +{ + /// Inserts all new key-values from the iterator to existing `HashMap`. + /// Replace values with existing keys with new values returned from the iterator. + /// The keys and values must implement [`Copy`] trait. + /// + /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, 100); + /// + /// let arr = [(1, 1), (2, 2)]; + /// let some_iter = arr.iter().map(|(k, v)| (k, v)); + /// map.extend(some_iter); + /// // Replace values with existing keys with new values returned from the iterator. + /// // So that the map.get(&1) doesn't return Some(&100). + /// assert_eq!(map.get(&1), Some(&1)); + /// + /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; + /// map.extend(some_vec.iter().map(|(k, v)| (k, v))); + /// + /// let some_arr = [(5, 5), (6, 6)]; + /// map.extend(some_arr.iter().map(|(k, v)| (k, v))); + /// + /// // You can also extend from another HashMap + /// let mut new_map = HashMap::new(); + /// new_map.extend(&map); + /// assert_eq!(new_map, map); + /// + /// let mut vec: Vec<_> = new_map.into_iter().collect(); + /// // The `IntoIter` iterator produces items in arbitrary order, so the + /// // items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn extend>(&mut self, iter: T) { + self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_one(&mut self, (k, v): (&'a K, &'a V)) { + self.insert(*k, *v); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_reserve(&mut self, additional: usize) { + Extend::<(K, V)>::extend_reserve(self, additional); + } +} + +/// Inserts all new key-values from the iterator and replaces values with existing +/// keys with new values returned from the iterator. +impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap +where + K: Eq + Hash + Copy, + V: Copy, + S: BuildHasher, + A: Allocator, +{ + /// Inserts all new key-values from the iterator to existing `HashMap`. + /// Replace values with existing keys with new values returned from the iterator. + /// The keys and values must implement [`Copy`] trait. + /// + /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.insert(1, 100); + /// + /// let arr = [(1, 1), (2, 2)]; + /// let some_iter = arr.iter(); + /// map.extend(some_iter); + /// // Replace values with existing keys with new values returned from the iterator. + /// // So that the map.get(&1) doesn't return Some(&100). + /// assert_eq!(map.get(&1), Some(&1)); + /// + /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; + /// map.extend(&some_vec); + /// + /// let some_arr = [(5, 5), (6, 6)]; + /// map.extend(&some_arr); + /// + /// let mut vec: Vec<_> = map.into_iter().collect(); + /// // The `IntoIter` iterator produces items in arbitrary order, so the + /// // items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn extend>(&mut self, iter: T) { + self.extend(iter.into_iter().map(|&(key, value)| (key, value))); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_one(&mut self, &(k, v): &'a (K, V)) { + self.insert(k, v); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_reserve(&mut self, additional: usize) { + Extend::<(K, V)>::extend_reserve(self, additional); + } +} + +#[allow(dead_code)] +fn assert_covariance() { + fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> { + v + } + fn map_val<'new>(v: HashMap) -> HashMap { + v + } + fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> { + v + } + fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> { + v + } + fn into_iter_key<'new, A: Allocator>( + v: IntoIter<&'static str, u8, A>, + ) -> IntoIter<&'new str, u8, A> { + v + } + fn into_iter_val<'new, A: Allocator>( + v: IntoIter, + ) -> IntoIter { + v + } + fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> { + v + } + fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> { + v + } + fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> { + v + } + fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> { + v + } + fn drain<'new>( + d: Drain<'static, &'static str, &'static str>, + ) -> Drain<'new, &'new str, &'new str> { + d + } +} + +#[cfg(test)] +mod test_map { + use super::DefaultHashBuilder; + use super::Entry::{Occupied, Vacant}; + use super::EntryRef; + use super::HashMap; + use alloc::string::{String, ToString}; + use alloc::sync::Arc; + use allocator_api2::alloc::{AllocError, Allocator, Global}; + use core::alloc::Layout; + use core::ptr::NonNull; + use core::sync::atomic::{AtomicI8, Ordering}; + use rand::{rngs::SmallRng, Rng, SeedableRng}; + use std::borrow::ToOwned; + use std::cell::RefCell; + use std::vec::Vec; + + #[test] + fn test_zero_capacities() { + type HM = HashMap; + + let m = HM::new(); + assert_eq!(m.capacity(), 0); + + let m = HM::default(); + assert_eq!(m.capacity(), 0); + + let m = HM::with_hasher(DefaultHashBuilder::default()); + assert_eq!(m.capacity(), 0); + + let m = HM::with_capacity(0); + assert_eq!(m.capacity(), 0); + + let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default()); + assert_eq!(m.capacity(), 0); + + let mut m = HM::new(); + m.insert(1, 1); + m.insert(2, 2); + m.remove(&1); + m.remove(&2); + m.shrink_to_fit(); + assert_eq!(m.capacity(), 0); + + let mut m = HM::new(); + m.reserve(0); + assert_eq!(m.capacity(), 0); + } + + #[test] + fn test_create_capacity_zero() { + let mut m = HashMap::with_capacity(0); + + assert!(m.insert(1, 1).is_none()); + + assert!(m.contains_key(&1)); + assert!(!m.contains_key(&0)); + } + + #[test] + fn test_insert() { + let mut m = HashMap::new(); + assert_eq!(m.len(), 0); + assert!(m.insert(1, 2).is_none()); + assert_eq!(m.len(), 1); + assert!(m.insert(2, 4).is_none()); + assert_eq!(m.len(), 2); + assert_eq!(*m.get(&1).unwrap(), 2); + assert_eq!(*m.get(&2).unwrap(), 4); + } + + #[test] + fn test_clone() { + let mut m = HashMap::new(); + assert_eq!(m.len(), 0); + assert!(m.insert(1, 2).is_none()); + assert_eq!(m.len(), 1); + assert!(m.insert(2, 4).is_none()); + assert_eq!(m.len(), 2); + #[allow(clippy::redundant_clone)] + let m2 = m.clone(); + assert_eq!(*m2.get(&1).unwrap(), 2); + assert_eq!(*m2.get(&2).unwrap(), 4); + assert_eq!(m2.len(), 2); + } + + #[test] + fn test_clone_from() { + let mut m = HashMap::new(); + let mut m2 = HashMap::new(); + assert_eq!(m.len(), 0); + assert!(m.insert(1, 2).is_none()); + assert_eq!(m.len(), 1); + assert!(m.insert(2, 4).is_none()); + assert_eq!(m.len(), 2); + m2.clone_from(&m); + assert_eq!(*m2.get(&1).unwrap(), 2); + assert_eq!(*m2.get(&2).unwrap(), 4); + assert_eq!(m2.len(), 2); + } + + thread_local! { static DROP_VECTOR: RefCell> = const { RefCell::new(Vec::new()) } } + + #[derive(Hash, PartialEq, Eq)] + struct Droppable { + k: usize, + } + + impl Droppable { + fn new(k: usize) -> Droppable { + DROP_VECTOR.with(|slot| { + slot.borrow_mut()[k] += 1; + }); + + Droppable { k } + } + } + + impl Drop for Droppable { + fn drop(&mut self) { + DROP_VECTOR.with(|slot| { + slot.borrow_mut()[self.k] -= 1; + }); + } + } + + impl Clone for Droppable { + fn clone(&self) -> Self { + Droppable::new(self.k) + } + } + + #[test] + fn test_drops() { + DROP_VECTOR.with(|slot| { + *slot.borrow_mut() = vec![0; 200]; + }); + + { + let mut m = HashMap::new(); + + DROP_VECTOR.with(|v| { + for i in 0..200 { + assert_eq!(v.borrow()[i], 0); + } + }); + + for i in 0..100 { + let d1 = Droppable::new(i); + let d2 = Droppable::new(i + 100); + m.insert(d1, d2); + } + + DROP_VECTOR.with(|v| { + for i in 0..200 { + assert_eq!(v.borrow()[i], 1); + } + }); + + for i in 0..50 { + let k = Droppable::new(i); + let v = m.remove(&k); + + assert!(v.is_some()); + + DROP_VECTOR.with(|v| { + assert_eq!(v.borrow()[i], 1); + assert_eq!(v.borrow()[i + 100], 1); + }); + } + + DROP_VECTOR.with(|v| { + for i in 0..50 { + assert_eq!(v.borrow()[i], 0); + assert_eq!(v.borrow()[i + 100], 0); + } + + for i in 50..100 { + assert_eq!(v.borrow()[i], 1); + assert_eq!(v.borrow()[i + 100], 1); + } + }); + } + + DROP_VECTOR.with(|v| { + for i in 0..200 { + assert_eq!(v.borrow()[i], 0); + } + }); + } + + #[test] + fn test_into_iter_drops() { + DROP_VECTOR.with(|v| { + *v.borrow_mut() = vec![0; 200]; + }); + + let hm = { + let mut hm = HashMap::new(); + + DROP_VECTOR.with(|v| { + for i in 0..200 { + assert_eq!(v.borrow()[i], 0); + } + }); + + for i in 0..100 { + let d1 = Droppable::new(i); + let d2 = Droppable::new(i + 100); + hm.insert(d1, d2); + } + + DROP_VECTOR.with(|v| { + for i in 0..200 { + assert_eq!(v.borrow()[i], 1); + } + }); + + hm + }; + + // By the way, ensure that cloning doesn't screw up the dropping. + drop(hm.clone()); + + { + let mut half = hm.into_iter().take(50); + + DROP_VECTOR.with(|v| { + for i in 0..200 { + assert_eq!(v.borrow()[i], 1); + } + }); + + for _ in half.by_ref() {} + + DROP_VECTOR.with(|v| { + let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count(); + + let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count(); + + assert_eq!(nk, 50); + assert_eq!(nv, 50); + }); + }; + + DROP_VECTOR.with(|v| { + for i in 0..200 { + assert_eq!(v.borrow()[i], 0); + } + }); + } + + #[test] + fn test_empty_remove() { + let mut m: HashMap = HashMap::new(); + assert_eq!(m.remove(&0), None); + } + + #[test] + fn test_empty_entry() { + let mut m: HashMap = HashMap::new(); + match m.entry(0) { + Occupied(_) => panic!(), + Vacant(_) => {} + } + assert!(*m.entry(0).or_insert(true)); + assert_eq!(m.len(), 1); + } + + #[test] + fn test_empty_entry_ref() { + let mut m: HashMap = HashMap::new(); + match m.entry_ref("poneyland") { + EntryRef::Occupied(_) => panic!(), + EntryRef::Vacant(_) => {} + } + assert!(*m.entry_ref("poneyland").or_insert(true)); + assert_eq!(m.len(), 1); + } + + #[test] + fn test_empty_iter() { + let mut m: HashMap = HashMap::new(); + assert_eq!(m.drain().next(), None); + assert_eq!(m.keys().next(), None); + assert_eq!(m.values().next(), None); + assert_eq!(m.values_mut().next(), None); + assert_eq!(m.iter().next(), None); + assert_eq!(m.iter_mut().next(), None); + assert_eq!(m.len(), 0); + assert!(m.is_empty()); + assert_eq!(m.into_iter().next(), None); + } + + #[test] + #[cfg_attr(miri, ignore)] // FIXME: takes too long + fn test_lots_of_insertions() { + let mut m = HashMap::new(); + + // Try this a few times to make sure we never screw up the hashmap's + // internal state. + for _ in 0..10 { + assert!(m.is_empty()); + + for i in 1..1001 { + assert!(m.insert(i, i).is_none()); + + for j in 1..=i { + let r = m.get(&j); + assert_eq!(r, Some(&j)); + } + + for j in i + 1..1001 { + let r = m.get(&j); + assert_eq!(r, None); + } + } + + for i in 1001..2001 { + assert!(!m.contains_key(&i)); + } + + // remove forwards + for i in 1..1001 { + assert!(m.remove(&i).is_some()); + + for j in 1..=i { + assert!(!m.contains_key(&j)); + } + + for j in i + 1..1001 { + assert!(m.contains_key(&j)); + } + } + + for i in 1..1001 { + assert!(!m.contains_key(&i)); + } + + for i in 1..1001 { + assert!(m.insert(i, i).is_none()); + } + + // remove backwards + for i in (1..1001).rev() { + assert!(m.remove(&i).is_some()); + + for j in i..1001 { + assert!(!m.contains_key(&j)); + } + + for j in 1..i { + assert!(m.contains_key(&j)); + } + } + } + } + + #[test] + fn test_find_mut() { + let mut m = HashMap::new(); + assert!(m.insert(1, 12).is_none()); + assert!(m.insert(2, 8).is_none()); + assert!(m.insert(5, 14).is_none()); + let new = 100; + match m.get_mut(&5) { + None => panic!(), + Some(x) => *x = new, + } + assert_eq!(m.get(&5), Some(&new)); + } + + #[test] + fn test_insert_overwrite() { + let mut m = HashMap::new(); + assert!(m.insert(1, 2).is_none()); + assert_eq!(*m.get(&1).unwrap(), 2); + assert!(m.insert(1, 3).is_some()); + assert_eq!(*m.get(&1).unwrap(), 3); + } + + #[test] + fn test_insert_conflicts() { + let mut m = HashMap::with_capacity(4); + assert!(m.insert(1, 2).is_none()); + assert!(m.insert(5, 3).is_none()); + assert!(m.insert(9, 4).is_none()); + assert_eq!(*m.get(&9).unwrap(), 4); + assert_eq!(*m.get(&5).unwrap(), 3); + assert_eq!(*m.get(&1).unwrap(), 2); + } + + #[test] + fn test_conflict_remove() { + let mut m = HashMap::with_capacity(4); + assert!(m.insert(1, 2).is_none()); + assert_eq!(*m.get(&1).unwrap(), 2); + assert!(m.insert(5, 3).is_none()); + assert_eq!(*m.get(&1).unwrap(), 2); + assert_eq!(*m.get(&5).unwrap(), 3); + assert!(m.insert(9, 4).is_none()); + assert_eq!(*m.get(&1).unwrap(), 2); + assert_eq!(*m.get(&5).unwrap(), 3); + assert_eq!(*m.get(&9).unwrap(), 4); + assert!(m.remove(&1).is_some()); + assert_eq!(*m.get(&9).unwrap(), 4); + assert_eq!(*m.get(&5).unwrap(), 3); + } + + #[test] + fn test_insert_unique_unchecked() { + let mut map = HashMap::new(); + let (k1, v1) = unsafe { map.insert_unique_unchecked(10, 11) }; + assert_eq!((&10, &mut 11), (k1, v1)); + let (k2, v2) = unsafe { map.insert_unique_unchecked(20, 21) }; + assert_eq!((&20, &mut 21), (k2, v2)); + assert_eq!(Some(&11), map.get(&10)); + assert_eq!(Some(&21), map.get(&20)); + assert_eq!(None, map.get(&30)); + } + + #[test] + fn test_is_empty() { + let mut m = HashMap::with_capacity(4); + assert!(m.insert(1, 2).is_none()); + assert!(!m.is_empty()); + assert!(m.remove(&1).is_some()); + assert!(m.is_empty()); + } + + #[test] + fn test_remove() { + let mut m = HashMap::new(); + m.insert(1, 2); + assert_eq!(m.remove(&1), Some(2)); + assert_eq!(m.remove(&1), None); + } + + #[test] + fn test_remove_entry() { + let mut m = HashMap::new(); + m.insert(1, 2); + assert_eq!(m.remove_entry(&1), Some((1, 2))); + assert_eq!(m.remove(&1), None); + } + + #[test] + fn test_iterate() { + let mut m = HashMap::with_capacity(4); + for i in 0..32 { + assert!(m.insert(i, i * 2).is_none()); + } + assert_eq!(m.len(), 32); + + let mut observed: u32 = 0; + + for (k, v) in &m { + assert_eq!(*v, *k * 2); + observed |= 1 << *k; + } + assert_eq!(observed, 0xFFFF_FFFF); + } + + #[test] + fn test_keys() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = vec.into_iter().collect(); + let keys: Vec<_> = map.keys().copied().collect(); + assert_eq!(keys.len(), 3); + assert!(keys.contains(&1)); + assert!(keys.contains(&2)); + assert!(keys.contains(&3)); + } + + #[test] + fn test_values() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = vec.into_iter().collect(); + let values: Vec<_> = map.values().copied().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&'a')); + assert!(values.contains(&'b')); + assert!(values.contains(&'c')); + } + + #[test] + fn test_values_mut() { + let vec = vec![(1, 1), (2, 2), (3, 3)]; + let mut map: HashMap<_, _> = vec.into_iter().collect(); + for value in map.values_mut() { + *value *= 2; + } + let values: Vec<_> = map.values().copied().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&2)); + assert!(values.contains(&4)); + assert!(values.contains(&6)); + } + + #[test] + fn test_into_keys() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = vec.into_iter().collect(); + let keys: Vec<_> = map.into_keys().collect(); + + assert_eq!(keys.len(), 3); + assert!(keys.contains(&1)); + assert!(keys.contains(&2)); + assert!(keys.contains(&3)); + } + + #[test] + fn test_into_values() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = vec.into_iter().collect(); + let values: Vec<_> = map.into_values().collect(); + + assert_eq!(values.len(), 3); + assert!(values.contains(&'a')); + assert!(values.contains(&'b')); + assert!(values.contains(&'c')); + } + + #[test] + fn test_find() { + let mut m = HashMap::new(); + assert!(m.get(&1).is_none()); + m.insert(1, 2); + match m.get(&1) { + None => panic!(), + Some(v) => assert_eq!(*v, 2), + } + } + + #[test] + fn test_eq() { + let mut m1 = HashMap::new(); + m1.insert(1, 2); + m1.insert(2, 3); + m1.insert(3, 4); + + let mut m2 = HashMap::new(); + m2.insert(1, 2); + m2.insert(2, 3); + + assert!(m1 != m2); + + m2.insert(3, 4); + + assert_eq!(m1, m2); + } + + #[test] + fn test_show() { + let mut map = HashMap::new(); + let empty: HashMap = HashMap::new(); + + map.insert(1, 2); + map.insert(3, 4); + + let map_str = format!("{map:?}"); + + assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); + assert_eq!(format!("{empty:?}"), "{}"); + } + + #[test] + fn test_expand() { + let mut m = HashMap::new(); + + assert_eq!(m.len(), 0); + assert!(m.is_empty()); + + let mut i = 0; + let old_raw_cap = m.raw_capacity(); + while old_raw_cap == m.raw_capacity() { + m.insert(i, i); + i += 1; + } + + assert_eq!(m.len(), i); + assert!(!m.is_empty()); + } + + #[test] + fn test_behavior_resize_policy() { + let mut m = HashMap::new(); + + assert_eq!(m.len(), 0); + assert_eq!(m.raw_capacity(), 1); + assert!(m.is_empty()); + + m.insert(0, 0); + m.remove(&0); + assert!(m.is_empty()); + let initial_raw_cap = m.raw_capacity(); + m.reserve(initial_raw_cap); + let raw_cap = m.raw_capacity(); + + assert_eq!(raw_cap, initial_raw_cap * 2); + + let mut i = 0; + for _ in 0..raw_cap * 3 / 4 { + m.insert(i, i); + i += 1; + } + // three quarters full + + assert_eq!(m.len(), i); + assert_eq!(m.raw_capacity(), raw_cap); + + for _ in 0..raw_cap / 4 { + m.insert(i, i); + i += 1; + } + // half full + + let new_raw_cap = m.raw_capacity(); + assert_eq!(new_raw_cap, raw_cap * 2); + + for _ in 0..raw_cap / 2 - 1 { + i -= 1; + m.remove(&i); + assert_eq!(m.raw_capacity(), new_raw_cap); + } + // A little more than one quarter full. + m.shrink_to_fit(); + assert_eq!(m.raw_capacity(), raw_cap); + // again, a little more than half full + for _ in 0..raw_cap / 2 { + i -= 1; + m.remove(&i); + } + m.shrink_to_fit(); + + assert_eq!(m.len(), i); + assert!(!m.is_empty()); + assert_eq!(m.raw_capacity(), initial_raw_cap); + } + + #[test] + fn test_reserve_shrink_to_fit() { + let mut m = HashMap::new(); + m.insert(0, 0); + m.remove(&0); + assert!(m.capacity() >= m.len()); + for i in 0..128 { + m.insert(i, i); + } + m.reserve(256); + + let usable_cap = m.capacity(); + for i in 128..(128 + 256) { + m.insert(i, i); + assert_eq!(m.capacity(), usable_cap); + } + + for i in 100..(128 + 256) { + assert_eq!(m.remove(&i), Some(i)); + } + m.shrink_to_fit(); + + assert_eq!(m.len(), 100); + assert!(!m.is_empty()); + assert!(m.capacity() >= m.len()); + + for i in 0..100 { + assert_eq!(m.remove(&i), Some(i)); + } + m.shrink_to_fit(); + m.insert(0, 0); + + assert_eq!(m.len(), 1); + assert!(m.capacity() >= m.len()); + assert_eq!(m.remove(&0), Some(0)); + } + + #[test] + fn test_from_iter() { + let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + + let map: HashMap<_, _> = xs.iter().copied().collect(); + + for &(k, v) in &xs { + assert_eq!(map.get(&k), Some(&v)); + } + + assert_eq!(map.iter().len(), xs.len() - 1); + } + + #[test] + fn test_size_hint() { + let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + + let map: HashMap<_, _> = xs.iter().copied().collect(); + + let mut iter = map.iter(); + + for _ in iter.by_ref().take(3) {} + + assert_eq!(iter.size_hint(), (3, Some(3))); + } + + #[test] + fn test_iter_len() { + let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + + let map: HashMap<_, _> = xs.iter().copied().collect(); + + let mut iter = map.iter(); + + for _ in iter.by_ref().take(3) {} + + assert_eq!(iter.len(), 3); + } + + #[test] + fn test_mut_size_hint() { + let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + + let mut map: HashMap<_, _> = xs.iter().copied().collect(); + + let mut iter = map.iter_mut(); + + for _ in iter.by_ref().take(3) {} + + assert_eq!(iter.size_hint(), (3, Some(3))); + } + + #[test] + fn test_iter_mut_len() { + let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; + + let mut map: HashMap<_, _> = xs.iter().copied().collect(); + + let mut iter = map.iter_mut(); + + for _ in iter.by_ref().take(3) {} + + assert_eq!(iter.len(), 3); + } + + #[test] + fn test_index() { + let mut map = HashMap::new(); + + map.insert(1, 2); + map.insert(2, 1); + map.insert(3, 4); + + assert_eq!(map[&2], 1); + } + + #[test] + #[should_panic] + fn test_index_nonexistent() { + let mut map = HashMap::new(); + + map.insert(1, 2); + map.insert(2, 1); + map.insert(3, 4); + + #[allow(clippy::no_effect)] // false positive lint + map[&4]; + } + + #[test] + fn test_entry() { + let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; + + let mut map: HashMap<_, _> = xs.iter().copied().collect(); + + // Existing key (insert) + match map.entry(1) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + assert_eq!(view.get(), &10); + assert_eq!(view.insert(100), 10); + } + } + assert_eq!(map.get(&1).unwrap(), &100); + assert_eq!(map.len(), 6); + + // Existing key (update) + match map.entry(2) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + let v = view.get_mut(); + let new_v = (*v) * 10; + *v = new_v; + } + } + assert_eq!(map.get(&2).unwrap(), &200); + assert_eq!(map.len(), 6); + + // Existing key (take) + match map.entry(3) { + Vacant(_) => unreachable!(), + Occupied(view) => { + assert_eq!(view.remove(), 30); + } + } + assert_eq!(map.get(&3), None); + assert_eq!(map.len(), 5); + + // Inexistent key (insert) + match map.entry(10) { + Occupied(_) => unreachable!(), + Vacant(view) => { + assert_eq!(*view.insert(1000), 1000); + } + } + assert_eq!(map.get(&10).unwrap(), &1000); + assert_eq!(map.len(), 6); + } + + #[test] + fn test_entry_ref() { + let xs = [ + ("One".to_owned(), 10), + ("Two".to_owned(), 20), + ("Three".to_owned(), 30), + ("Four".to_owned(), 40), + ("Five".to_owned(), 50), + ("Six".to_owned(), 60), + ]; + + let mut map: HashMap<_, _> = xs.iter().cloned().collect(); + + // Existing key (insert) + match map.entry_ref("One") { + EntryRef::Vacant(_) => unreachable!(), + EntryRef::Occupied(mut view) => { + assert_eq!(view.get(), &10); + assert_eq!(view.insert(100), 10); + } + } + assert_eq!(map.get("One").unwrap(), &100); + assert_eq!(map.len(), 6); + + // Existing key (update) + match map.entry_ref("Two") { + EntryRef::Vacant(_) => unreachable!(), + EntryRef::Occupied(mut view) => { + let v = view.get_mut(); + let new_v = (*v) * 10; + *v = new_v; + } + } + assert_eq!(map.get("Two").unwrap(), &200); + assert_eq!(map.len(), 6); + + // Existing key (take) + match map.entry_ref("Three") { + EntryRef::Vacant(_) => unreachable!(), + EntryRef::Occupied(view) => { + assert_eq!(view.remove(), 30); + } + } + assert_eq!(map.get("Three"), None); + assert_eq!(map.len(), 5); + + // Inexistent key (insert) + match map.entry_ref("Ten") { + EntryRef::Occupied(_) => unreachable!(), + EntryRef::Vacant(view) => { + assert_eq!(*view.insert(1000), 1000); + } + } + assert_eq!(map.get("Ten").unwrap(), &1000); + assert_eq!(map.len(), 6); + } + + #[test] + fn test_entry_take_doesnt_corrupt() { + #![allow(deprecated)] //rand + // Test for #19292 + fn check(m: &HashMap) { + for k in m.keys() { + assert!(m.contains_key(k), "{k} is in keys() but not in the map?"); + } + } + + let mut m = HashMap::new(); + + let mut rng = { + let seed = u64::from_le_bytes(*b"testseed"); + SmallRng::seed_from_u64(seed) + }; + + // Populate the map with some items. + for _ in 0..50 { + let x = rng.gen_range(-10..10); + m.insert(x, ()); + } + + for _ in 0..1000 { + let x = rng.gen_range(-10..10); + match m.entry(x) { + Vacant(_) => {} + Occupied(e) => { + e.remove(); + } + } + + check(&m); + } + } + + #[test] + fn test_entry_ref_take_doesnt_corrupt() { + #![allow(deprecated)] //rand + // Test for #19292 + fn check(m: &HashMap) { + for k in m.keys() { + assert!(m.contains_key(k), "{k} is in keys() but not in the map?"); + } + } + + let mut m = HashMap::new(); + + let mut rng = { + let seed = u64::from_le_bytes(*b"testseed"); + SmallRng::seed_from_u64(seed) + }; + + // Populate the map with some items. + for _ in 0..50 { + let mut x = std::string::String::with_capacity(1); + x.push(rng.gen_range('a'..='z')); + m.insert(x, ()); + } + + for _ in 0..1000 { + let mut x = std::string::String::with_capacity(1); + x.push(rng.gen_range('a'..='z')); + match m.entry_ref(x.as_str()) { + EntryRef::Vacant(_) => {} + EntryRef::Occupied(e) => { + e.remove(); + } + } + + check(&m); + } + } + + #[test] + fn test_extend_ref_k_ref_v() { + let mut a = HashMap::new(); + a.insert(1, "one"); + let mut b = HashMap::new(); + b.insert(2, "two"); + b.insert(3, "three"); + + a.extend(&b); + + assert_eq!(a.len(), 3); + assert_eq!(a[&1], "one"); + assert_eq!(a[&2], "two"); + assert_eq!(a[&3], "three"); + } + + #[test] + #[allow(clippy::needless_borrow)] + fn test_extend_ref_kv_tuple() { + use std::ops::AddAssign; + let mut a = HashMap::new(); + a.insert(0, 0); + + fn create_arr + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] { + let mut outs: [(T, T); N] = [(start, start); N]; + let mut element = step; + outs.iter_mut().skip(1).for_each(|(k, v)| { + *k += element; + *v += element; + element += step; + }); + outs + } + + let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect(); + let iter = for_iter.iter(); + let vec: Vec<_> = (100..200).map(|i| (i, i)).collect(); + a.extend(iter); + a.extend(&vec); + a.extend(create_arr::(200, 1)); + + assert_eq!(a.len(), 300); + + for item in 0..300 { + assert_eq!(a[&item], item); + } + } + + #[test] + fn test_capacity_not_less_than_len() { + let mut a = HashMap::new(); + let mut item = 0; + + for _ in 0..116 { + a.insert(item, 0); + item += 1; + } + + assert!(a.capacity() > a.len()); + + let free = a.capacity() - a.len(); + for _ in 0..free { + a.insert(item, 0); + item += 1; + } + + assert_eq!(a.len(), a.capacity()); + + // Insert at capacity should cause allocation. + a.insert(item, 0); + assert!(a.capacity() > a.len()); + } + + #[test] + fn test_occupied_entry_key() { + let mut a = HashMap::new(); + let key = "hello there"; + let value = "value goes here"; + assert!(a.is_empty()); + a.insert(key, value); + assert_eq!(a.len(), 1); + assert_eq!(a[key], value); + + match a.entry(key) { + Vacant(_) => panic!(), + Occupied(e) => assert_eq!(key, *e.key()), + } + assert_eq!(a.len(), 1); + assert_eq!(a[key], value); + } + + #[test] + fn test_occupied_entry_ref_key() { + let mut a = HashMap::new(); + let key = "hello there"; + let value = "value goes here"; + assert!(a.is_empty()); + a.insert(key.to_owned(), value); + assert_eq!(a.len(), 1); + assert_eq!(a[key], value); + + match a.entry_ref(key) { + EntryRef::Vacant(_) => panic!(), + EntryRef::Occupied(e) => assert_eq!(key, e.key()), + } + assert_eq!(a.len(), 1); + assert_eq!(a[key], value); + } + + #[test] + fn test_vacant_entry_key() { + let mut a = HashMap::new(); + let key = "hello there"; + let value = "value goes here"; + + assert!(a.is_empty()); + match a.entry(key) { + Occupied(_) => panic!(), + Vacant(e) => { + assert_eq!(key, *e.key()); + e.insert(value); + } + } + assert_eq!(a.len(), 1); + assert_eq!(a[key], value); + } + + #[test] + fn test_vacant_entry_ref_key() { + let mut a: HashMap = HashMap::new(); + let key = "hello there"; + let value = "value goes here"; + + assert!(a.is_empty()); + match a.entry_ref(key) { + EntryRef::Occupied(_) => panic!(), + EntryRef::Vacant(e) => { + assert_eq!(key, e.key()); + e.insert(value); + } + } + assert_eq!(a.len(), 1); + assert_eq!(a[key], value); + } + + #[test] + fn test_occupied_entry_replace_entry_with() { + let mut a = HashMap::new(); + + let key = "a key"; + let value = "an initial value"; + let new_value = "a new value"; + + let entry = a.entry(key).insert(value).replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, value); + Some(new_value) + }); + + match entry { + Occupied(e) => { + assert_eq!(e.key(), &key); + assert_eq!(e.get(), &new_value); + } + Vacant(_) => panic!(), + } + + assert_eq!(a[key], new_value); + assert_eq!(a.len(), 1); + + let entry = match a.entry(key) { + Occupied(e) => e.replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, new_value); + None + }), + Vacant(_) => panic!(), + }; + + match entry { + Vacant(e) => assert_eq!(e.key(), &key), + Occupied(_) => panic!(), + } + + assert!(!a.contains_key(key)); + assert_eq!(a.len(), 0); + } + + #[test] + fn test_entry_and_replace_entry_with() { + let mut a = HashMap::new(); + + let key = "a key"; + let value = "an initial value"; + let new_value = "a new value"; + + let entry = a.entry(key).and_replace_entry_with(|_, _| panic!()); + + match entry { + Vacant(e) => assert_eq!(e.key(), &key), + Occupied(_) => panic!(), + } + + a.insert(key, value); + + let entry = a.entry(key).and_replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, value); + Some(new_value) + }); + + match entry { + Occupied(e) => { + assert_eq!(e.key(), &key); + assert_eq!(e.get(), &new_value); + } + Vacant(_) => panic!(), + } + + assert_eq!(a[key], new_value); + assert_eq!(a.len(), 1); + + let entry = a.entry(key).and_replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, new_value); + None + }); + + match entry { + Vacant(e) => assert_eq!(e.key(), &key), + Occupied(_) => panic!(), + } + + assert!(!a.contains_key(key)); + assert_eq!(a.len(), 0); + } + + #[test] + fn test_replace_entry_with_doesnt_corrupt() { + #![allow(deprecated)] //rand + // Test for #19292 + fn check(m: &HashMap) { + for k in m.keys() { + assert!(m.contains_key(k), "{k} is in keys() but not in the map?"); + } + } + + let mut m = HashMap::new(); + + let mut rng = { + let seed = u64::from_le_bytes(*b"testseed"); + SmallRng::seed_from_u64(seed) + }; + + // Populate the map with some items. + for _ in 0..50 { + let x = rng.gen_range(-10..10); + m.insert(x, ()); + } + + for _ in 0..1000 { + let x = rng.gen_range(-10..10); + m.entry(x).and_replace_entry_with(|_, _| None); + check(&m); + } + } + + #[test] + fn test_retain() { + let mut map: HashMap = (0..100).map(|x| (x, x * 10)).collect(); + + map.retain(|&k, _| k % 2 == 0); + assert_eq!(map.len(), 50); + assert_eq!(map[&2], 20); + assert_eq!(map[&4], 40); + assert_eq!(map[&6], 60); + } + + #[test] + fn test_extract_if() { + { + let mut map: HashMap = (0..8).map(|x| (x, x * 10)).collect(); + let drained = map.extract_if(|&k, _| k % 2 == 0); + let mut out = drained.collect::>(); + out.sort_unstable(); + assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out); + assert_eq!(map.len(), 4); + } + { + let mut map: HashMap = (0..8).map(|x| (x, x * 10)).collect(); + map.extract_if(|&k, _| k % 2 == 0).for_each(drop); + assert_eq!(map.len(), 4); + } + } + + #[test] + #[cfg_attr(miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613) + fn test_try_reserve() { + use crate::TryReserveError::{AllocError, CapacityOverflow}; + + const MAX_ISIZE: usize = isize::MAX as usize; + + let mut empty_bytes: HashMap = HashMap::new(); + + if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) { + } else { + panic!("usize::MAX should trigger an overflow!"); + } + + if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) { + } else { + panic!("isize::MAX should trigger an overflow!"); + } + + if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) { + } else { + // This may succeed if there is enough free memory. Attempt to + // allocate a few more hashmaps to ensure the allocation will fail. + let mut empty_bytes2: HashMap = HashMap::new(); + let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5); + let mut empty_bytes3: HashMap = HashMap::new(); + let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5); + let mut empty_bytes4: HashMap = HashMap::new(); + if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) { + } else { + panic!("isize::MAX / 5 should trigger an OOM!"); + } + } + } + + #[test] + fn test_const_with_hasher() { + use core::hash::BuildHasher; + use std::collections::hash_map::DefaultHasher; + + #[derive(Clone)] + struct MyHasher; + impl BuildHasher for MyHasher { + type Hasher = DefaultHasher; + + fn build_hasher(&self) -> DefaultHasher { + DefaultHasher::new() + } + } + + const EMPTY_MAP: HashMap = + HashMap::with_hasher(MyHasher); + + let mut map = EMPTY_MAP; + map.insert(17, "seventeen".to_owned()); + assert_eq!("seventeen", map[&17]); + } + + #[test] + fn test_get_many_mut() { + let mut map = HashMap::new(); + map.insert("foo".to_owned(), 0); + map.insert("bar".to_owned(), 10); + map.insert("baz".to_owned(), 20); + map.insert("qux".to_owned(), 30); + + let xs = map.get_many_mut(["foo", "qux"]); + assert_eq!(xs, [Some(&mut 0), Some(&mut 30)]); + + let xs = map.get_many_mut(["foo", "dud"]); + assert_eq!(xs, [Some(&mut 0), None]); + + let ys = map.get_many_key_value_mut(["bar", "baz"]); + assert_eq!( + ys, + [ + Some((&"bar".to_owned(), &mut 10)), + Some((&"baz".to_owned(), &mut 20)) + ], + ); + + let ys = map.get_many_key_value_mut(["bar", "dip"]); + assert_eq!(ys, [Some((&"bar".to_string(), &mut 10)), None]); + } + + #[test] + #[should_panic = "duplicate keys found"] + fn test_get_many_mut_duplicate() { + let mut map = HashMap::new(); + map.insert("foo".to_owned(), 0); + + let _xs = map.get_many_mut(["foo", "foo"]); + } + + #[test] + #[should_panic = "panic in drop"] + fn test_clone_from_double_drop() { + #[derive(Clone)] + struct CheckedDrop { + panic_in_drop: bool, + dropped: bool, + } + impl Drop for CheckedDrop { + fn drop(&mut self) { + if self.panic_in_drop { + self.dropped = true; + panic!("panic in drop"); + } + if self.dropped { + panic!("double drop"); + } + self.dropped = true; + } + } + const DISARMED: CheckedDrop = CheckedDrop { + panic_in_drop: false, + dropped: false, + }; + const ARMED: CheckedDrop = CheckedDrop { + panic_in_drop: true, + dropped: false, + }; + + let mut map1 = HashMap::new(); + map1.insert(1, DISARMED); + map1.insert(2, DISARMED); + map1.insert(3, DISARMED); + map1.insert(4, DISARMED); + + let mut map2 = HashMap::new(); + map2.insert(1, DISARMED); + map2.insert(2, ARMED); + map2.insert(3, DISARMED); + map2.insert(4, DISARMED); + + map2.clone_from(&map1); + } + + #[test] + #[should_panic = "panic in clone"] + fn test_clone_from_memory_leaks() { + use alloc::vec::Vec; + + struct CheckedClone { + panic_in_clone: bool, + need_drop: Vec, + } + impl Clone for CheckedClone { + fn clone(&self) -> Self { + if self.panic_in_clone { + panic!("panic in clone") + } + Self { + panic_in_clone: self.panic_in_clone, + need_drop: self.need_drop.clone(), + } + } + } + let mut map1 = HashMap::new(); + map1.insert( + 1, + CheckedClone { + panic_in_clone: false, + need_drop: vec![0, 1, 2], + }, + ); + map1.insert( + 2, + CheckedClone { + panic_in_clone: false, + need_drop: vec![3, 4, 5], + }, + ); + map1.insert( + 3, + CheckedClone { + panic_in_clone: true, + need_drop: vec![6, 7, 8], + }, + ); + let _map2 = map1.clone(); + } + + struct MyAllocInner { + drop_count: Arc, + } + + #[derive(Clone)] + struct MyAlloc { + _inner: Arc, + } + + impl MyAlloc { + fn new(drop_count: Arc) -> Self { + MyAlloc { + _inner: Arc::new(MyAllocInner { drop_count }), + } + } + } + + impl Drop for MyAllocInner { + fn drop(&mut self) { + println!("MyAlloc freed."); + self.drop_count.fetch_sub(1, Ordering::SeqCst); + } + } + + unsafe impl Allocator for MyAlloc { + fn allocate(&self, layout: Layout) -> std::result::Result, AllocError> { + let g = Global; + g.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + let g = Global; + g.deallocate(ptr, layout) + } + } + + #[test] + fn test_hashmap_into_iter_bug() { + let dropped: Arc = Arc::new(AtomicI8::new(1)); + + { + let mut map = HashMap::with_capacity_in(10, MyAlloc::new(dropped.clone())); + for i in 0..10 { + map.entry(i).or_insert_with(|| "i".to_string()); + } + + for (k, v) in map { + println!("{}, {}", k, v); + } + } + + // All allocator clones should already be dropped. + assert_eq!(dropped.load(Ordering::SeqCst), 0); + } + + #[derive(Debug)] + struct CheckedCloneDrop { + panic_in_clone: bool, + panic_in_drop: bool, + dropped: bool, + data: T, + } + + impl CheckedCloneDrop { + fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self { + CheckedCloneDrop { + panic_in_clone, + panic_in_drop, + dropped: false, + data, + } + } + } + + impl Clone for CheckedCloneDrop { + fn clone(&self) -> Self { + if self.panic_in_clone { + panic!("panic in clone") + } + Self { + panic_in_clone: self.panic_in_clone, + panic_in_drop: self.panic_in_drop, + dropped: self.dropped, + data: self.data.clone(), + } + } + } + + impl Drop for CheckedCloneDrop { + fn drop(&mut self) { + if self.panic_in_drop { + self.dropped = true; + panic!("panic in drop"); + } + if self.dropped { + panic!("double drop"); + } + self.dropped = true; + } + } + + /// Return hashmap with predefined distribution of elements. + /// All elements will be located in the same order as elements + /// returned by iterator. + /// + /// This function does not panic, but returns an error as a `String` + /// to distinguish between a test panic and an error in the input data. + fn get_test_map( + iter: I, + mut fun: impl FnMut(u64) -> T, + alloc: A, + ) -> Result, DefaultHashBuilder, A>, String> + where + I: Iterator + Clone + ExactSizeIterator, + A: Allocator, + T: PartialEq + core::fmt::Debug, + { + use crate::scopeguard::guard; + + let mut map: HashMap, _, A> = + HashMap::with_capacity_in(iter.size_hint().0, alloc); + { + let mut guard = guard(&mut map, |map| { + for (_, value) in map.iter_mut() { + value.panic_in_drop = false + } + }); + + let mut count = 0; + // Hash and Key must be equal to each other for controlling the elements placement. + for (panic_in_clone, panic_in_drop) in iter.clone() { + if core::mem::needs_drop::() && panic_in_drop { + return Err(String::from( + "panic_in_drop can be set with a type that doesn't need to be dropped", + )); + } + guard.table.insert( + count, + ( + count, + CheckedCloneDrop::new(panic_in_clone, panic_in_drop, fun(count)), + ), + |(k, _)| *k, + ); + count += 1; + } + + // Let's check that all elements are located as we wanted + let mut check_count = 0; + for ((key, value), (panic_in_clone, panic_in_drop)) in guard.iter().zip(iter) { + if *key != check_count { + return Err(format!( + "key != check_count,\nkey: `{}`,\ncheck_count: `{}`", + key, check_count + )); + } + if value.dropped + || value.panic_in_clone != panic_in_clone + || value.panic_in_drop != panic_in_drop + || value.data != fun(check_count) + { + return Err(format!( + "Value is not equal to expected,\nvalue: `{:?}`,\nexpected: \ + `CheckedCloneDrop {{ panic_in_clone: {}, panic_in_drop: {}, dropped: {}, data: {:?} }}`", + value, panic_in_clone, panic_in_drop, false, fun(check_count) + )); + } + check_count += 1; + } + + if guard.len() != check_count as usize { + return Err(format!( + "map.len() != check_count,\nmap.len(): `{}`,\ncheck_count: `{}`", + guard.len(), + check_count + )); + } + + if count != check_count { + return Err(format!( + "count != check_count,\ncount: `{}`,\ncheck_count: `{}`", + count, check_count + )); + } + core::mem::forget(guard); + } + Ok(map) + } + + const DISARMED: bool = false; + const ARMED: bool = true; + + const ARMED_FLAGS: [bool; 8] = [ + DISARMED, DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED, + ]; + + const DISARMED_FLAGS: [bool; 8] = [ + DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, + ]; + + #[test] + #[should_panic = "panic in clone"] + fn test_clone_memory_leaks_and_double_drop_one() { + let dropped: Arc = Arc::new(AtomicI8::new(2)); + + { + assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len()); + + let map: HashMap>, DefaultHashBuilder, MyAlloc> = + match get_test_map( + ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), + |n| vec![n], + MyAlloc::new(dropped.clone()), + ) { + Ok(map) => map, + Err(msg) => panic!("{msg}"), + }; + + // Clone should normally clone a few elements, and then (when the + // clone function panics), deallocate both its own memory, memory + // of `dropped: Arc` and the memory of already cloned + // elements (Vec memory inside CheckedCloneDrop). + let _map2 = map.clone(); + } + } + + #[test] + #[should_panic = "panic in drop"] + fn test_clone_memory_leaks_and_double_drop_two() { + let dropped: Arc = Arc::new(AtomicI8::new(2)); + + { + assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len()); + + let map: HashMap, DefaultHashBuilder, _> = match get_test_map( + DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), + |n| n, + MyAlloc::new(dropped.clone()), + ) { + Ok(map) => map, + Err(msg) => panic!("{msg}"), + }; + + let mut map2 = match get_test_map( + DISARMED_FLAGS.into_iter().zip(ARMED_FLAGS), + |n| n, + MyAlloc::new(dropped.clone()), + ) { + Ok(map) => map, + Err(msg) => panic!("{msg}"), + }; + + // The `clone_from` should try to drop the elements of `map2` without + // double drop and leaking the allocator. Elements that have not been + // dropped leak their memory. + map2.clone_from(&map); + } + } + + /// We check that we have a working table if the clone operation from another + /// thread ended in a panic (when buckets of maps are equal to each other). + #[test] + fn test_catch_panic_clone_from_when_len_is_equal() { + use std::thread; + + let dropped: Arc = Arc::new(AtomicI8::new(2)); + + { + assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len()); + + let mut map = match get_test_map( + DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), + |n| vec![n], + MyAlloc::new(dropped.clone()), + ) { + Ok(map) => map, + Err(msg) => panic!("{msg}"), + }; + + thread::scope(|s| { + let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| { + let scope_map = + match get_test_map(ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), |n| vec![n * 2], MyAlloc::new(dropped.clone())) { + Ok(map) => map, + Err(msg) => return msg, + }; + if map.table.buckets() != scope_map.table.buckets() { + return format!( + "map.table.buckets() != scope_map.table.buckets(),\nleft: `{}`,\nright: `{}`", + map.table.buckets(), scope_map.table.buckets() + ); + } + map.clone_from(&scope_map); + "We must fail the cloning!!!".to_owned() + }); + if let Ok(msg) = result.join() { + panic!("{msg}") + } + }); + + // Let's check that all iterators work fine and do not return elements + // (especially `RawIterRange`, which does not depend on the number of + // elements in the table, but looks directly at the control bytes) + // + // SAFETY: We know for sure that `RawTable` will outlive + // the returned `RawIter / RawIterRange` iterator. + assert_eq!(map.len(), 0); + assert_eq!(map.iter().count(), 0); + assert_eq!(unsafe { map.table.iter().count() }, 0); + assert_eq!(unsafe { map.table.iter().iter.count() }, 0); + + for idx in 0..map.table.buckets() { + let idx = idx as u64; + assert!( + map.table.find(idx, |(k, _)| *k == idx).is_none(), + "Index: {idx}" + ); + } + } + + // All allocator clones should already be dropped. + assert_eq!(dropped.load(Ordering::SeqCst), 0); + } + + /// We check that we have a working table if the clone operation from another + /// thread ended in a panic (when buckets of maps are not equal to each other). + #[test] + fn test_catch_panic_clone_from_when_len_is_not_equal() { + use std::thread; + + let dropped: Arc = Arc::new(AtomicI8::new(2)); + + { + assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len()); + + let mut map = match get_test_map( + [DISARMED].into_iter().zip([DISARMED]), + |n| vec![n], + MyAlloc::new(dropped.clone()), + ) { + Ok(map) => map, + Err(msg) => panic!("{msg}"), + }; + + thread::scope(|s| { + let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| { + let scope_map = match get_test_map( + ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), + |n| vec![n * 2], + MyAlloc::new(dropped.clone()), + ) { + Ok(map) => map, + Err(msg) => return msg, + }; + if map.table.buckets() == scope_map.table.buckets() { + return format!( + "map.table.buckets() == scope_map.table.buckets(): `{}`", + map.table.buckets() + ); + } + map.clone_from(&scope_map); + "We must fail the cloning!!!".to_owned() + }); + if let Ok(msg) = result.join() { + panic!("{msg}") + } + }); + + // Let's check that all iterators work fine and do not return elements + // (especially `RawIterRange`, which does not depend on the number of + // elements in the table, but looks directly at the control bytes) + // + // SAFETY: We know for sure that `RawTable` will outlive + // the returned `RawIter / RawIterRange` iterator. + assert_eq!(map.len(), 0); + assert_eq!(map.iter().count(), 0); + assert_eq!(unsafe { map.table.iter().count() }, 0); + assert_eq!(unsafe { map.table.iter().iter.count() }, 0); + + for idx in 0..map.table.buckets() { + let idx = idx as u64; + assert!( + map.table.find(idx, |(k, _)| *k == idx).is_none(), + "Index: {idx}" + ); + } + } + + // All allocator clones should already be dropped. + assert_eq!(dropped.load(Ordering::SeqCst), 0); + } + + #[test] + fn test_allocation_info() { + assert_eq!(HashMap::<(), ()>::new().allocation_size(), 0); + assert_eq!(HashMap::::new().allocation_size(), 0); + assert!( + HashMap::::with_capacity(1).allocation_size() > core::mem::size_of::() + ); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/raw/alloc.rs b/bitbox02-bt/vendor/hashbrown/src/raw/alloc.rs new file mode 100644 index 0000000..15299e7 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/raw/alloc.rs @@ -0,0 +1,86 @@ +pub(crate) use self::inner::{do_alloc, Allocator, Global}; + +// Nightly-case. +// Use unstable `allocator_api` feature. +// This is compatible with `allocator-api2` which can be enabled or not. +// This is used when building for `std`. +#[cfg(feature = "nightly")] +mod inner { + use crate::alloc::alloc::Layout; + pub use crate::alloc::alloc::{Allocator, Global}; + use core::ptr::NonNull; + + #[allow(clippy::map_err_ignore)] + pub(crate) fn do_alloc(alloc: &A, layout: Layout) -> Result, ()> { + match alloc.allocate(layout) { + Ok(ptr) => Ok(ptr.as_non_null_ptr()), + Err(_) => Err(()), + } + } +} + +// Basic non-nightly case. +// This uses `allocator-api2` enabled by default. +// If any crate enables "nightly" in `allocator-api2`, +// this will be equivalent to the nightly case, +// since `allocator_api2::alloc::Allocator` would be re-export of +// `core::alloc::Allocator`. +#[cfg(all(not(feature = "nightly"), feature = "allocator-api2"))] +mod inner { + use crate::alloc::alloc::Layout; + pub use allocator_api2::alloc::{Allocator, Global}; + use core::ptr::NonNull; + + #[allow(clippy::map_err_ignore)] + pub(crate) fn do_alloc(alloc: &A, layout: Layout) -> Result, ()> { + match alloc.allocate(layout) { + Ok(ptr) => Ok(ptr.cast()), + Err(_) => Err(()), + } + } +} + +// No-defaults case. +// When building with default-features turned off and +// neither `nightly` nor `allocator-api2` is enabled, +// this will be used. +// Making it impossible to use any custom allocator with collections defined +// in this crate. +// Any crate in build-tree can enable `allocator-api2`, +// or `nightly` without disturbing users that don't want to use it. +#[cfg(not(any(feature = "nightly", feature = "allocator-api2")))] +mod inner { + use crate::alloc::alloc::{alloc, dealloc, Layout}; + use core::ptr::NonNull; + + #[allow(clippy::missing_safety_doc)] // not exposed outside of this crate + pub unsafe trait Allocator { + fn allocate(&self, layout: Layout) -> Result, ()>; + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout); + } + + #[derive(Copy, Clone)] + pub struct Global; + + unsafe impl Allocator for Global { + #[inline] + fn allocate(&self, layout: Layout) -> Result, ()> { + unsafe { NonNull::new(alloc(layout)).ok_or(()) } + } + #[inline] + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + dealloc(ptr.as_ptr(), layout); + } + } + + impl Default for Global { + #[inline] + fn default() -> Self { + Global + } + } + + pub(crate) fn do_alloc(alloc: &A, layout: Layout) -> Result, ()> { + alloc.allocate(layout) + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/raw/bitmask.rs b/bitbox02-bt/vendor/hashbrown/src/raw/bitmask.rs new file mode 100644 index 0000000..87a5a64 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/raw/bitmask.rs @@ -0,0 +1,117 @@ +use super::imp::{ + BitMaskWord, NonZeroBitMaskWord, BITMASK_ITER_MASK, BITMASK_MASK, BITMASK_STRIDE, +}; + +/// A bit mask which contains the result of a `Match` operation on a `Group` and +/// allows iterating through them. +/// +/// The bit mask is arranged so that low-order bits represent lower memory +/// addresses for group match results. +/// +/// For implementation reasons, the bits in the set may be sparsely packed with +/// groups of 8 bits representing one element. If any of these bits are non-zero +/// then this element is considered to true in the mask. If this is the +/// case, `BITMASK_STRIDE` will be 8 to indicate a divide-by-8 should be +/// performed on counts/indices to normalize this difference. `BITMASK_MASK` is +/// similarly a mask of all the actually-used bits. +/// +/// To iterate over a bit mask, it must be converted to a form where only 1 bit +/// is set per element. This is done by applying `BITMASK_ITER_MASK` on the +/// mask bits. +#[derive(Copy, Clone)] +pub(crate) struct BitMask(pub(crate) BitMaskWord); + +#[allow(clippy::use_self)] +impl BitMask { + /// Returns a new `BitMask` with all bits inverted. + #[inline] + #[must_use] + #[allow(dead_code)] + pub(crate) fn invert(self) -> Self { + BitMask(self.0 ^ BITMASK_MASK) + } + + /// Returns a new `BitMask` with the lowest bit removed. + #[inline] + #[must_use] + fn remove_lowest_bit(self) -> Self { + BitMask(self.0 & (self.0 - 1)) + } + + /// Returns whether the `BitMask` has at least one set bit. + #[inline] + pub(crate) fn any_bit_set(self) -> bool { + self.0 != 0 + } + + /// Returns the first set bit in the `BitMask`, if there is one. + #[inline] + pub(crate) fn lowest_set_bit(self) -> Option { + if let Some(nonzero) = NonZeroBitMaskWord::new(self.0) { + Some(Self::nonzero_trailing_zeros(nonzero)) + } else { + None + } + } + + /// Returns the number of trailing zeroes in the `BitMask`. + #[inline] + pub(crate) fn trailing_zeros(self) -> usize { + // ARM doesn't have a trailing_zeroes instruction, and instead uses + // reverse_bits (RBIT) + leading_zeroes (CLZ). However older ARM + // versions (pre-ARMv7) don't have RBIT and need to emulate it + // instead. Since we only have 1 bit set in each byte on ARM, we can + // use swap_bytes (REV) + leading_zeroes instead. + if cfg!(target_arch = "arm") && BITMASK_STRIDE % 8 == 0 { + self.0.swap_bytes().leading_zeros() as usize / BITMASK_STRIDE + } else { + self.0.trailing_zeros() as usize / BITMASK_STRIDE + } + } + + /// Same as above but takes a `NonZeroBitMaskWord`. + #[inline] + fn nonzero_trailing_zeros(nonzero: NonZeroBitMaskWord) -> usize { + if cfg!(target_arch = "arm") && BITMASK_STRIDE % 8 == 0 { + // SAFETY: A byte-swapped non-zero value is still non-zero. + let swapped = unsafe { NonZeroBitMaskWord::new_unchecked(nonzero.get().swap_bytes()) }; + swapped.leading_zeros() as usize / BITMASK_STRIDE + } else { + nonzero.trailing_zeros() as usize / BITMASK_STRIDE + } + } + + /// Returns the number of leading zeroes in the `BitMask`. + #[inline] + pub(crate) fn leading_zeros(self) -> usize { + self.0.leading_zeros() as usize / BITMASK_STRIDE + } +} + +impl IntoIterator for BitMask { + type Item = usize; + type IntoIter = BitMaskIter; + + #[inline] + fn into_iter(self) -> BitMaskIter { + // A BitMask only requires each element (group of bits) to be non-zero. + // However for iteration we need each element to only contain 1 bit. + BitMaskIter(BitMask(self.0 & BITMASK_ITER_MASK)) + } +} + +/// Iterator over the contents of a `BitMask`, returning the indices of set +/// bits. +#[derive(Copy, Clone)] +pub(crate) struct BitMaskIter(pub(crate) BitMask); + +impl Iterator for BitMaskIter { + type Item = usize; + + #[inline] + fn next(&mut self) -> Option { + let bit = self.0.lowest_set_bit()?; + self.0 = self.0.remove_lowest_bit(); + Some(bit) + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/raw/generic.rs b/bitbox02-bt/vendor/hashbrown/src/raw/generic.rs new file mode 100644 index 0000000..c668b06 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/raw/generic.rs @@ -0,0 +1,157 @@ +use super::bitmask::BitMask; +use super::EMPTY; +use core::{mem, ptr}; + +// Use the native word size as the group size. Using a 64-bit group size on +// a 32-bit architecture will just end up being more expensive because +// shifts and multiplies will need to be emulated. + +cfg_if! { + if #[cfg(any( + target_pointer_width = "64", + target_arch = "aarch64", + target_arch = "x86_64", + target_arch = "wasm32", + ))] { + type GroupWord = u64; + type NonZeroGroupWord = core::num::NonZeroU64; + } else { + type GroupWord = u32; + type NonZeroGroupWord = core::num::NonZeroU32; + } +} + +pub(crate) type BitMaskWord = GroupWord; +pub(crate) type NonZeroBitMaskWord = NonZeroGroupWord; +pub(crate) const BITMASK_STRIDE: usize = 8; +// We only care about the highest bit of each byte for the mask. +#[allow(clippy::cast_possible_truncation, clippy::unnecessary_cast)] +pub(crate) const BITMASK_MASK: BitMaskWord = 0x8080_8080_8080_8080_u64 as GroupWord; +pub(crate) const BITMASK_ITER_MASK: BitMaskWord = !0; + +/// Helper function to replicate a byte across a `GroupWord`. +#[inline] +fn repeat(byte: u8) -> GroupWord { + GroupWord::from_ne_bytes([byte; Group::WIDTH]) +} + +/// Abstraction over a group of control bytes which can be scanned in +/// parallel. +/// +/// This implementation uses a word-sized integer. +#[derive(Copy, Clone)] +pub(crate) struct Group(GroupWord); + +// We perform all operations in the native endianness, and convert to +// little-endian just before creating a BitMask. The can potentially +// enable the compiler to eliminate unnecessary byte swaps if we are +// only checking whether a BitMask is empty. +#[allow(clippy::use_self)] +impl Group { + /// Number of bytes in the group. + pub(crate) const WIDTH: usize = mem::size_of::(); + + /// Returns a full group of empty bytes, suitable for use as the initial + /// value for an empty hash table. + /// + /// This is guaranteed to be aligned to the group size. + #[inline] + pub(crate) const fn static_empty() -> &'static [u8; Group::WIDTH] { + #[repr(C)] + struct AlignedBytes { + _align: [Group; 0], + bytes: [u8; Group::WIDTH], + } + const ALIGNED_BYTES: AlignedBytes = AlignedBytes { + _align: [], + bytes: [EMPTY; Group::WIDTH], + }; + &ALIGNED_BYTES.bytes + } + + /// Loads a group of bytes starting at the given address. + #[inline] + #[allow(clippy::cast_ptr_alignment)] // unaligned load + pub(crate) unsafe fn load(ptr: *const u8) -> Self { + Group(ptr::read_unaligned(ptr.cast())) + } + + /// Loads a group of bytes starting at the given address, which must be + /// aligned to `mem::align_of::()`. + #[inline] + #[allow(clippy::cast_ptr_alignment)] + pub(crate) unsafe fn load_aligned(ptr: *const u8) -> Self { + // FIXME: use align_offset once it stabilizes + debug_assert_eq!(ptr as usize & (mem::align_of::() - 1), 0); + Group(ptr::read(ptr.cast())) + } + + /// Stores the group of bytes to the given address, which must be + /// aligned to `mem::align_of::()`. + #[inline] + #[allow(clippy::cast_ptr_alignment)] + pub(crate) unsafe fn store_aligned(self, ptr: *mut u8) { + // FIXME: use align_offset once it stabilizes + debug_assert_eq!(ptr as usize & (mem::align_of::() - 1), 0); + ptr::write(ptr.cast(), self.0); + } + + /// Returns a `BitMask` indicating all bytes in the group which *may* + /// have the given value. + /// + /// This function may return a false positive in certain cases where + /// the byte in the group differs from the searched value only in its + /// lowest bit. This is fine because: + /// - This never happens for `EMPTY` and `DELETED`, only full entries. + /// - The check for key equality will catch these. + /// - This only happens if there is at least 1 true match. + /// - The chance of this happening is very low (< 1% chance per byte). + #[inline] + pub(crate) fn match_byte(self, byte: u8) -> BitMask { + // This algorithm is derived from + // https://graphics.stanford.edu/~seander/bithacks.html##ValueInWord + let cmp = self.0 ^ repeat(byte); + BitMask((cmp.wrapping_sub(repeat(0x01)) & !cmp & repeat(0x80)).to_le()) + } + + /// Returns a `BitMask` indicating all bytes in the group which are + /// `EMPTY`. + #[inline] + pub(crate) fn match_empty(self) -> BitMask { + // If the high bit is set, then the byte must be either: + // 1111_1111 (EMPTY) or 1000_0000 (DELETED). + // So we can just check if the top two bits are 1 by ANDing them. + BitMask((self.0 & (self.0 << 1) & repeat(0x80)).to_le()) + } + + /// Returns a `BitMask` indicating all bytes in the group which are + /// `EMPTY` or `DELETED`. + #[inline] + pub(crate) fn match_empty_or_deleted(self) -> BitMask { + // A byte is EMPTY or DELETED iff the high bit is set + BitMask((self.0 & repeat(0x80)).to_le()) + } + + /// Returns a `BitMask` indicating all bytes in the group which are full. + #[inline] + pub(crate) fn match_full(self) -> BitMask { + self.match_empty_or_deleted().invert() + } + + /// Performs the following transformation on all bytes in the group: + /// - `EMPTY => EMPTY` + /// - `DELETED => EMPTY` + /// - `FULL => DELETED` + #[inline] + pub(crate) fn convert_special_to_empty_and_full_to_deleted(self) -> Self { + // Map high_bit = 1 (EMPTY or DELETED) to 1111_1111 + // and high_bit = 0 (FULL) to 1000_0000 + // + // Here's this logic expanded to concrete values: + // let full = 1000_0000 (true) or 0000_0000 (false) + // !1000_0000 + 1 = 0111_1111 + 1 = 1000_0000 (no carry) + // !0000_0000 + 0 = 1111_1111 + 0 = 1111_1111 (no carry) + let full = !self.0 & repeat(0x80); + Group(!full + (full >> 7)) + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/raw/mod.rs b/bitbox02-bt/vendor/hashbrown/src/raw/mod.rs new file mode 100644 index 0000000..495557a --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/raw/mod.rs @@ -0,0 +1,4464 @@ +use crate::alloc::alloc::{handle_alloc_error, Layout}; +use crate::scopeguard::{guard, ScopeGuard}; +use crate::TryReserveError; +use core::array; +use core::iter::FusedIterator; +use core::marker::PhantomData; +use core::mem; +use core::ptr::NonNull; +use core::{hint, ptr}; + +cfg_if! { + // Use the SSE2 implementation if possible: it allows us to scan 16 buckets + // at once instead of 8. We don't bother with AVX since it would require + // runtime dispatch and wouldn't gain us much anyways: the probability of + // finding a match drops off drastically after the first few buckets. + // + // I attempted an implementation on ARM using NEON instructions, but it + // turns out that most NEON instructions have multi-cycle latency, which in + // the end outweighs any gains over the generic implementation. + if #[cfg(all( + target_feature = "sse2", + any(target_arch = "x86", target_arch = "x86_64"), + not(miri), + ))] { + mod sse2; + use sse2 as imp; + } else if #[cfg(all( + target_arch = "aarch64", + target_feature = "neon", + // NEON intrinsics are currently broken on big-endian targets. + // See https://github.com/rust-lang/stdarch/issues/1484. + target_endian = "little", + not(miri), + ))] { + mod neon; + use neon as imp; + } else { + mod generic; + use generic as imp; + } +} + +mod alloc; +pub(crate) use self::alloc::{do_alloc, Allocator, Global}; + +mod bitmask; + +use self::bitmask::BitMaskIter; +use self::imp::Group; + +// Branch prediction hint. This is currently only available on nightly but it +// consistently improves performance by 10-15%. +#[cfg(not(feature = "nightly"))] +use core::convert::{identity as likely, identity as unlikely}; +#[cfg(feature = "nightly")] +use core::intrinsics::{likely, unlikely}; + +// FIXME: use strict provenance functions once they are stable. +// Implement it with a transmute for now. +#[inline(always)] +#[allow(clippy::useless_transmute)] // clippy is wrong, cast and transmute are different here +fn invalid_mut(addr: usize) -> *mut T { + unsafe { core::mem::transmute(addr) } +} + +#[inline] +unsafe fn offset_from(to: *const T, from: *const T) -> usize { + to.offset_from(from) as usize +} + +/// Whether memory allocation errors should return an error or abort. +#[derive(Copy, Clone)] +enum Fallibility { + Fallible, + Infallible, +} + +impl Fallibility { + /// Error to return on capacity overflow. + #[cfg_attr(feature = "inline-more", inline)] + fn capacity_overflow(self) -> TryReserveError { + match self { + Fallibility::Fallible => TryReserveError::CapacityOverflow, + Fallibility::Infallible => panic!("Hash table capacity overflow"), + } + } + + /// Error to return on allocation error. + #[cfg_attr(feature = "inline-more", inline)] + fn alloc_err(self, layout: Layout) -> TryReserveError { + match self { + Fallibility::Fallible => TryReserveError::AllocError { layout }, + Fallibility::Infallible => handle_alloc_error(layout), + } + } +} + +trait SizedTypeProperties: Sized { + const IS_ZERO_SIZED: bool = mem::size_of::() == 0; + const NEEDS_DROP: bool = mem::needs_drop::(); +} + +impl SizedTypeProperties for T {} + +/// Control byte value for an empty bucket. +const EMPTY: u8 = 0b1111_1111; + +/// Control byte value for a deleted bucket. +const DELETED: u8 = 0b1000_0000; + +/// Checks whether a control byte represents a full bucket (top bit is clear). +#[inline] +fn is_full(ctrl: u8) -> bool { + ctrl & 0x80 == 0 +} + +/// Checks whether a control byte represents a special value (top bit is set). +#[inline] +fn is_special(ctrl: u8) -> bool { + ctrl & 0x80 != 0 +} + +/// Checks whether a special control value is EMPTY (just check 1 bit). +#[inline] +fn special_is_empty(ctrl: u8) -> bool { + debug_assert!(is_special(ctrl)); + ctrl & 0x01 != 0 +} + +/// Primary hash function, used to select the initial bucket to probe from. +#[inline] +#[allow(clippy::cast_possible_truncation)] +fn h1(hash: u64) -> usize { + // On 32-bit platforms we simply ignore the higher hash bits. + hash as usize +} + +// Constant for h2 function that grabs the top 7 bits of the hash. +const MIN_HASH_LEN: usize = if mem::size_of::() < mem::size_of::() { + mem::size_of::() +} else { + mem::size_of::() +}; + +/// Secondary hash function, saved in the low 7 bits of the control byte. +#[inline] +#[allow(clippy::cast_possible_truncation)] +fn h2(hash: u64) -> u8 { + // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit + // value, some hash functions (such as FxHash) produce a usize result + // instead, which means that the top 32 bits are 0 on 32-bit platforms. + // So we use MIN_HASH_LEN constant to handle this. + let top7 = hash >> (MIN_HASH_LEN * 8 - 7); + (top7 & 0x7f) as u8 // truncation +} + +/// Probe sequence based on triangular numbers, which is guaranteed (since our +/// table size is a power of two) to visit every group of elements exactly once. +/// +/// A triangular probe has us jump by 1 more group every time. So first we +/// jump by 1 group (meaning we just continue our linear scan), then 2 groups +/// (skipping over 1 group), then 3 groups (skipping over 2 groups), and so on. +/// +/// Proof that the probe will visit every group in the table: +/// +#[derive(Clone)] +struct ProbeSeq { + pos: usize, + stride: usize, +} + +impl ProbeSeq { + #[inline] + fn move_next(&mut self, bucket_mask: usize) { + // We should have found an empty bucket by now and ended the probe. + debug_assert!( + self.stride <= bucket_mask, + "Went past end of probe sequence" + ); + + self.stride += Group::WIDTH; + self.pos += self.stride; + self.pos &= bucket_mask; + } +} + +/// Returns the number of buckets needed to hold the given number of items, +/// taking the maximum load factor into account. +/// +/// Returns `None` if an overflow occurs. +// Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 +#[cfg_attr(target_os = "emscripten", inline(never))] +#[cfg_attr(not(target_os = "emscripten"), inline)] +fn capacity_to_buckets(cap: usize) -> Option { + debug_assert_ne!(cap, 0); + + // For small tables we require at least 1 empty bucket so that lookups are + // guaranteed to terminate if an element doesn't exist in the table. + if cap < 8 { + // We don't bother with a table size of 2 buckets since that can only + // hold a single element. Instead we skip directly to a 4 bucket table + // which can hold 3 elements. + return Some(if cap < 4 { 4 } else { 8 }); + } + + // Otherwise require 1/8 buckets to be empty (87.5% load) + // + // Be careful when modifying this, calculate_layout relies on the + // overflow check here. + let adjusted_cap = cap.checked_mul(8)? / 7; + + // Any overflows will have been caught by the checked_mul. Also, any + // rounding errors from the division above will be cleaned up by + // next_power_of_two (which can't overflow because of the previous division). + Some(adjusted_cap.next_power_of_two()) +} + +/// Returns the maximum effective capacity for the given bucket mask, taking +/// the maximum load factor into account. +#[inline] +fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { + if bucket_mask < 8 { + // For tables with 1/2/4/8 buckets, we always reserve one empty slot. + // Keep in mind that the bucket mask is one less than the bucket count. + bucket_mask + } else { + // For larger tables we reserve 12.5% of the slots as empty. + ((bucket_mask + 1) / 8) * 7 + } +} + +/// Helper which allows the max calculation for `ctrl_align` to be statically computed for each `T` +/// while keeping the rest of `calculate_layout_for` independent of `T` +#[derive(Copy, Clone)] +struct TableLayout { + size: usize, + ctrl_align: usize, +} + +impl TableLayout { + #[inline] + const fn new() -> Self { + let layout = Layout::new::(); + Self { + size: layout.size(), + ctrl_align: if layout.align() > Group::WIDTH { + layout.align() + } else { + Group::WIDTH + }, + } + } + + #[inline] + fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { + debug_assert!(buckets.is_power_of_two()); + + let TableLayout { size, ctrl_align } = self; + // Manual layout calculation since Layout methods are not yet stable. + let ctrl_offset = + size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); + let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; + + // We need an additional check to ensure that the allocation doesn't + // exceed `isize::MAX` (https://github.com/rust-lang/rust/pull/95295). + if len > isize::MAX as usize - (ctrl_align - 1) { + return None; + } + + Some(( + unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, + ctrl_offset, + )) + } +} + +/// A reference to an empty bucket into which an can be inserted. +pub struct InsertSlot { + index: usize, +} + +/// A reference to a hash table bucket containing a `T`. +/// +/// This is usually just a pointer to the element itself. However if the element +/// is a ZST, then we instead track the index of the element in the table so +/// that `erase` works properly. +pub struct Bucket { + // Actually it is pointer to next element than element itself + // this is needed to maintain pointer arithmetic invariants + // keeping direct pointer to element introduces difficulty. + // Using `NonNull` for variance and niche layout + ptr: NonNull, +} + +// This Send impl is needed for rayon support. This is safe since Bucket is +// never exposed in a public API. +unsafe impl Send for Bucket {} + +impl Clone for Bucket { + #[inline] + fn clone(&self) -> Self { + Self { ptr: self.ptr } + } +} + +impl Bucket { + /// Creates a [`Bucket`] that contain pointer to the data. + /// The pointer calculation is performed by calculating the + /// offset from given `base` pointer (convenience for + /// `base.as_ptr().sub(index)`). + /// + /// `index` is in units of `T`; e.g., an `index` of 3 represents a pointer + /// offset of `3 * size_of::()` bytes. + /// + /// If the `T` is a ZST, then we instead track the index of the element + /// in the table so that `erase` works properly (return + /// `NonNull::new_unchecked((index + 1) as *mut T)`) + /// + /// # Safety + /// + /// If `mem::size_of::() != 0`, then the safety rules are directly derived + /// from the safety rules for [`<*mut T>::sub`] method of `*mut T` and the safety + /// rules of [`NonNull::new_unchecked`] function. + /// + /// Thus, in order to uphold the safety contracts for the [`<*mut T>::sub`] method + /// and [`NonNull::new_unchecked`] function, as well as for the correct + /// logic of the work of this crate, the following rules are necessary and + /// sufficient: + /// + /// * the `base` pointer must not be `dangling` and must points to the + /// end of the first `value element` from the `data part` of the table, i.e. + /// must be the pointer that returned by [`RawTable::data_end`] or by + /// [`RawTableInner::data_end`]; + /// + /// * `index` must not be greater than `RawTableInner.bucket_mask`, i.e. + /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` + /// must be no greater than the number returned by the function + /// [`RawTable::buckets`] or [`RawTableInner::buckets`]. + /// + /// If `mem::size_of::() == 0`, then the only requirement is that the + /// `index` must not be greater than `RawTableInner.bucket_mask`, i.e. + /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` + /// must be no greater than the number returned by the function + /// [`RawTable::buckets`] or [`RawTableInner::buckets`]. + /// + /// [`Bucket`]: crate::raw::Bucket + /// [`<*mut T>::sub`]: https://doc.rust-lang.org/core/primitive.pointer.html#method.sub-1 + /// [`NonNull::new_unchecked`]: https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.new_unchecked + /// [`RawTable::data_end`]: crate::raw::RawTable::data_end + /// [`RawTableInner::data_end`]: RawTableInner::data_end + /// [`RawTable::buckets`]: crate::raw::RawTable::buckets + /// [`RawTableInner::buckets`]: RawTableInner::buckets + #[inline] + unsafe fn from_base_index(base: NonNull, index: usize) -> Self { + // If mem::size_of::() != 0 then return a pointer to an `element` in + // the data part of the table (we start counting from "0", so that + // in the expression T[last], the "last" index actually one less than the + // "buckets" number in the table, i.e. "last = RawTableInner.bucket_mask"): + // + // `from_base_index(base, 1).as_ptr()` returns a pointer that + // points here in the data part of the table + // (to the start of T1) + // | + // | `base: NonNull` must point here + // | (to the end of T0 or to the start of C0) + // v v + // [Padding], Tlast, ..., |T1|, T0, |C0, C1, ..., Clast + // ^ + // `from_base_index(base, 1)` returns a pointer + // that points here in the data part of the table + // (to the end of T1) + // + // where: T0...Tlast - our stored data; C0...Clast - control bytes + // or metadata for data. + let ptr = if T::IS_ZERO_SIZED { + // won't overflow because index must be less than length (bucket_mask) + // and bucket_mask is guaranteed to be less than `isize::MAX` + // (see TableLayout::calculate_layout_for method) + invalid_mut(index + 1) + } else { + base.as_ptr().sub(index) + }; + Self { + ptr: NonNull::new_unchecked(ptr), + } + } + + /// Calculates the index of a [`Bucket`] as distance between two pointers + /// (convenience for `base.as_ptr().offset_from(self.ptr.as_ptr()) as usize`). + /// The returned value is in units of T: the distance in bytes divided by + /// [`core::mem::size_of::()`]. + /// + /// If the `T` is a ZST, then we return the index of the element in + /// the table so that `erase` works properly (return `self.ptr.as_ptr() as usize - 1`). + /// + /// This function is the inverse of [`from_base_index`]. + /// + /// # Safety + /// + /// If `mem::size_of::() != 0`, then the safety rules are directly derived + /// from the safety rules for [`<*const T>::offset_from`] method of `*const T`. + /// + /// Thus, in order to uphold the safety contracts for [`<*const T>::offset_from`] + /// method, as well as for the correct logic of the work of this crate, the + /// following rules are necessary and sufficient: + /// + /// * `base` contained pointer must not be `dangling` and must point to the + /// end of the first `element` from the `data part` of the table, i.e. + /// must be a pointer that returns by [`RawTable::data_end`] or by + /// [`RawTableInner::data_end`]; + /// + /// * `self` also must not contain dangling pointer; + /// + /// * both `self` and `base` must be created from the same [`RawTable`] + /// (or [`RawTableInner`]). + /// + /// If `mem::size_of::() == 0`, this function is always safe. + /// + /// [`Bucket`]: crate::raw::Bucket + /// [`from_base_index`]: crate::raw::Bucket::from_base_index + /// [`RawTable::data_end`]: crate::raw::RawTable::data_end + /// [`RawTableInner::data_end`]: RawTableInner::data_end + /// [`RawTable`]: crate::raw::RawTable + /// [`RawTableInner`]: RawTableInner + /// [`<*const T>::offset_from`]: https://doc.rust-lang.org/nightly/core/primitive.pointer.html#method.offset_from + #[inline] + unsafe fn to_base_index(&self, base: NonNull) -> usize { + // If mem::size_of::() != 0 then return an index under which we used to store the + // `element` in the data part of the table (we start counting from "0", so + // that in the expression T[last], the "last" index actually is one less than the + // "buckets" number in the table, i.e. "last = RawTableInner.bucket_mask"). + // For example for 5th element in table calculation is performed like this: + // + // mem::size_of::() + // | + // | `self = from_base_index(base, 5)` that returns pointer + // | that points here in the data part of the table + // | (to the end of T5) + // | | `base: NonNull` must point here + // v | (to the end of T0 or to the start of C0) + // /???\ v v + // [Padding], Tlast, ..., |T10|, ..., T5|, T4, T3, T2, T1, T0, |C0, C1, C2, C3, C4, C5, ..., C10, ..., Clast + // \__________ __________/ + // \/ + // `bucket.to_base_index(base)` = 5 + // (base.as_ptr() as usize - self.ptr.as_ptr() as usize) / mem::size_of::() + // + // where: T0...Tlast - our stored data; C0...Clast - control bytes or metadata for data. + if T::IS_ZERO_SIZED { + // this can not be UB + self.ptr.as_ptr() as usize - 1 + } else { + offset_from(base.as_ptr(), self.ptr.as_ptr()) + } + } + + /// Acquires the underlying raw pointer `*mut T` to `data`. + /// + /// # Note + /// + /// If `T` is not [`Copy`], do not use `*mut T` methods that can cause calling the + /// destructor of `T` (for example the [`<*mut T>::drop_in_place`] method), because + /// for properly dropping the data we also need to clear `data` control bytes. If we + /// drop data, but do not clear `data control byte` it leads to double drop when + /// [`RawTable`] goes out of scope. + /// + /// If you modify an already initialized `value`, so [`Hash`] and [`Eq`] on the new + /// `T` value and its borrowed form *must* match those for the old `T` value, as the map + /// will not re-evaluate where the new value should go, meaning the value may become + /// "lost" if their location does not reflect their state. + /// + /// [`RawTable`]: crate::raw::RawTable + /// [`<*mut T>::drop_in_place`]: https://doc.rust-lang.org/core/primitive.pointer.html#method.drop_in_place + /// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html + /// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html + #[inline] + pub fn as_ptr(&self) -> *mut T { + if T::IS_ZERO_SIZED { + // Just return an arbitrary ZST pointer which is properly aligned + // invalid pointer is good enough for ZST + invalid_mut(mem::align_of::()) + } else { + unsafe { self.ptr.as_ptr().sub(1) } + } + } + + /// Acquires the underlying non-null pointer `*mut T` to `data`. + #[inline] + fn as_non_null(&self) -> NonNull { + // SAFETY: `self.ptr` is already a `NonNull` + unsafe { NonNull::new_unchecked(self.as_ptr()) } + } + + /// Create a new [`Bucket`] that is offset from the `self` by the given + /// `offset`. The pointer calculation is performed by calculating the + /// offset from `self` pointer (convenience for `self.ptr.as_ptr().sub(offset)`). + /// This function is used for iterators. + /// + /// `offset` is in units of `T`; e.g., a `offset` of 3 represents a pointer + /// offset of `3 * size_of::()` bytes. + /// + /// # Safety + /// + /// If `mem::size_of::() != 0`, then the safety rules are directly derived + /// from the safety rules for [`<*mut T>::sub`] method of `*mut T` and safety + /// rules of [`NonNull::new_unchecked`] function. + /// + /// Thus, in order to uphold the safety contracts for [`<*mut T>::sub`] method + /// and [`NonNull::new_unchecked`] function, as well as for the correct + /// logic of the work of this crate, the following rules are necessary and + /// sufficient: + /// + /// * `self` contained pointer must not be `dangling`; + /// + /// * `self.to_base_index() + offset` must not be greater than `RawTableInner.bucket_mask`, + /// i.e. `(self.to_base_index() + offset) <= RawTableInner.bucket_mask` or, in other + /// words, `self.to_base_index() + offset + 1` must be no greater than the number returned + /// by the function [`RawTable::buckets`] or [`RawTableInner::buckets`]. + /// + /// If `mem::size_of::() == 0`, then the only requirement is that the + /// `self.to_base_index() + offset` must not be greater than `RawTableInner.bucket_mask`, + /// i.e. `(self.to_base_index() + offset) <= RawTableInner.bucket_mask` or, in other words, + /// `self.to_base_index() + offset + 1` must be no greater than the number returned by the + /// function [`RawTable::buckets`] or [`RawTableInner::buckets`]. + /// + /// [`Bucket`]: crate::raw::Bucket + /// [`<*mut T>::sub`]: https://doc.rust-lang.org/core/primitive.pointer.html#method.sub-1 + /// [`NonNull::new_unchecked`]: https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.new_unchecked + /// [`RawTable::buckets`]: crate::raw::RawTable::buckets + /// [`RawTableInner::buckets`]: RawTableInner::buckets + #[inline] + unsafe fn next_n(&self, offset: usize) -> Self { + let ptr = if T::IS_ZERO_SIZED { + // invalid pointer is good enough for ZST + invalid_mut(self.ptr.as_ptr() as usize + offset) + } else { + self.ptr.as_ptr().sub(offset) + }; + Self { + ptr: NonNull::new_unchecked(ptr), + } + } + + /// Executes the destructor (if any) of the pointed-to `data`. + /// + /// # Safety + /// + /// See [`ptr::drop_in_place`] for safety concerns. + /// + /// You should use [`RawTable::erase`] instead of this function, + /// or be careful with calling this function directly, because for + /// properly dropping the data we need also clear `data` control bytes. + /// If we drop data, but do not erase `data control byte` it leads to + /// double drop when [`RawTable`] goes out of scope. + /// + /// [`ptr::drop_in_place`]: https://doc.rust-lang.org/core/ptr/fn.drop_in_place.html + /// [`RawTable`]: crate::raw::RawTable + /// [`RawTable::erase`]: crate::raw::RawTable::erase + #[cfg_attr(feature = "inline-more", inline)] + pub(crate) unsafe fn drop(&self) { + self.as_ptr().drop_in_place(); + } + + /// Reads the `value` from `self` without moving it. This leaves the + /// memory in `self` unchanged. + /// + /// # Safety + /// + /// See [`ptr::read`] for safety concerns. + /// + /// You should use [`RawTable::remove`] instead of this function, + /// or be careful with calling this function directly, because compiler + /// calls its destructor when the read `value` goes out of scope. It + /// can cause double dropping when [`RawTable`] goes out of scope, + /// because of not erased `data control byte`. + /// + /// [`ptr::read`]: https://doc.rust-lang.org/core/ptr/fn.read.html + /// [`RawTable`]: crate::raw::RawTable + /// [`RawTable::remove`]: crate::raw::RawTable::remove + #[inline] + pub(crate) unsafe fn read(&self) -> T { + self.as_ptr().read() + } + + /// Overwrites a memory location with the given `value` without reading + /// or dropping the old value (like [`ptr::write`] function). + /// + /// # Safety + /// + /// See [`ptr::write`] for safety concerns. + /// + /// # Note + /// + /// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match + /// those for the old `T` value, as the map will not re-evaluate where the new + /// value should go, meaning the value may become "lost" if their location + /// does not reflect their state. + /// + /// [`ptr::write`]: https://doc.rust-lang.org/core/ptr/fn.write.html + /// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html + /// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html + #[inline] + pub(crate) unsafe fn write(&self, val: T) { + self.as_ptr().write(val); + } + + /// Returns a shared immutable reference to the `value`. + /// + /// # Safety + /// + /// See [`NonNull::as_ref`] for safety concerns. + /// + /// [`NonNull::as_ref`]: https://doc.rust-lang.org/core/ptr/struct.NonNull.html#method.as_ref + #[inline] + pub unsafe fn as_ref<'a>(&self) -> &'a T { + &*self.as_ptr() + } + + /// Returns a unique mutable reference to the `value`. + /// + /// # Safety + /// + /// See [`NonNull::as_mut`] for safety concerns. + /// + /// # Note + /// + /// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match + /// those for the old `T` value, as the map will not re-evaluate where the new + /// value should go, meaning the value may become "lost" if their location + /// does not reflect their state. + /// + /// [`NonNull::as_mut`]: https://doc.rust-lang.org/core/ptr/struct.NonNull.html#method.as_mut + /// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html + /// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html + #[inline] + pub unsafe fn as_mut<'a>(&self) -> &'a mut T { + &mut *self.as_ptr() + } +} + +/// A raw hash table with an unsafe API. +pub struct RawTable { + table: RawTableInner, + alloc: A, + // Tell dropck that we own instances of T. + marker: PhantomData, +} + +/// Non-generic part of `RawTable` which allows functions to be instantiated only once regardless +/// of how many different key-value types are used. +struct RawTableInner { + // Mask to get an index from a hash value. The value is one less than the + // number of buckets in the table. + bucket_mask: usize, + + // [Padding], T_n, ..., T1, T0, C0, C1, ... + // ^ points here + ctrl: NonNull, + + // Number of elements that can be inserted before we need to grow the table + growth_left: usize, + + // Number of elements in the table, only really used by len() + items: usize, +} + +impl RawTable { + /// Creates a new empty hash table without allocating any memory. + /// + /// In effect this returns a table with exactly 1 bucket. However we can + /// leave the data pointer dangling since that bucket is never written to + /// due to our load factor forcing us to always have at least 1 free bucket. + #[inline] + pub const fn new() -> Self { + Self { + table: RawTableInner::NEW, + alloc: Global, + marker: PhantomData, + } + } + + /// Allocates a new hash table with at least enough capacity for inserting + /// the given number of elements without reallocating. + pub fn with_capacity(capacity: usize) -> Self { + Self::with_capacity_in(capacity, Global) + } +} + +impl RawTable { + const TABLE_LAYOUT: TableLayout = TableLayout::new::(); + + /// Creates a new empty hash table without allocating any memory, using the + /// given allocator. + /// + /// In effect this returns a table with exactly 1 bucket. However we can + /// leave the data pointer dangling since that bucket is never written to + /// due to our load factor forcing us to always have at least 1 free bucket. + #[inline] + pub const fn new_in(alloc: A) -> Self { + Self { + table: RawTableInner::NEW, + alloc, + marker: PhantomData, + } + } + + /// Allocates a new hash table with the given number of buckets. + /// + /// The control bytes are left uninitialized. + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn new_uninitialized( + alloc: A, + buckets: usize, + fallibility: Fallibility, + ) -> Result { + debug_assert!(buckets.is_power_of_two()); + + Ok(Self { + table: RawTableInner::new_uninitialized( + &alloc, + Self::TABLE_LAYOUT, + buckets, + fallibility, + )?, + alloc, + marker: PhantomData, + }) + } + + /// Allocates a new hash table using the given allocator, with at least enough capacity for + /// inserting the given number of elements without reallocating. + pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { + Self { + table: RawTableInner::with_capacity(&alloc, Self::TABLE_LAYOUT, capacity), + alloc, + marker: PhantomData, + } + } + + /// Returns a reference to the underlying allocator. + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } + + /// Returns pointer to one past last `data` element in the table as viewed from + /// the start point of the allocation. + /// + /// The caller must ensure that the `RawTable` outlives the returned [`NonNull`], + /// otherwise using it may result in [`undefined behavior`]. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + pub fn data_end(&self) -> NonNull { + // `self.table.ctrl.cast()` returns pointer that + // points here (to the end of `T0`) + // ∨ + // [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, CTa_0, CTa_1, ..., CTa_m + // \________ ________/ + // \/ + // `n = buckets - 1`, i.e. `RawTable::buckets() - 1` + // + // where: T0...T_n - our stored data; + // CT0...CT_n - control bytes or metadata for `data`. + // CTa_0...CTa_m - additional control bytes, where `m = Group::WIDTH - 1` (so that the search + // with loading `Group` bytes from the heap works properly, even if the result + // of `h1(hash) & self.bucket_mask` is equal to `self.bucket_mask`). See also + // `RawTableInner::set_ctrl` function. + // + // P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.buckets()` because the number + // of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + self.table.ctrl.cast() + } + + /// Returns pointer to start of data table. + #[inline] + #[cfg(feature = "nightly")] + pub unsafe fn data_start(&self) -> NonNull { + NonNull::new_unchecked(self.data_end().as_ptr().wrapping_sub(self.buckets())) + } + + /// Returns the total amount of memory allocated internally by the hash + /// table, in bytes. + /// + /// The returned number is informational only. It is intended to be + /// primarily used for memory profiling. + #[inline] + pub fn allocation_size(&self) -> usize { + // SAFETY: We use the same `table_layout` that was used to allocate + // this table. + unsafe { self.table.allocation_size_or_zero(Self::TABLE_LAYOUT) } + } + + /// Returns the index of a bucket from a `Bucket`. + #[inline] + pub unsafe fn bucket_index(&self, bucket: &Bucket) -> usize { + bucket.to_base_index(self.data_end()) + } + + /// Returns a pointer to an element in the table. + /// + /// The caller must ensure that the `RawTable` outlives the returned [`Bucket`], + /// otherwise using it may result in [`undefined behavior`]. + /// + /// # Safety + /// + /// If `mem::size_of::() != 0`, then the caller of this function must observe the + /// following safety rules: + /// + /// * The table must already be allocated; + /// + /// * The `index` must not be greater than the number returned by the [`RawTable::buckets`] + /// function, i.e. `(index + 1) <= self.buckets()`. + /// + /// It is safe to call this function with index of zero (`index == 0`) on a table that has + /// not been allocated, but using the returned [`Bucket`] results in [`undefined behavior`]. + /// + /// If `mem::size_of::() == 0`, then the only requirement is that the `index` must + /// not be greater than the number returned by the [`RawTable::buckets`] function, i.e. + /// `(index + 1) <= self.buckets()`. + /// + /// [`RawTable::buckets`]: RawTable::buckets + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + pub unsafe fn bucket(&self, index: usize) -> Bucket { + // If mem::size_of::() != 0 then return a pointer to the `element` in the `data part` of the table + // (we start counting from "0", so that in the expression T[n], the "n" index actually one less than + // the "buckets" number of our `RawTable`, i.e. "n = RawTable::buckets() - 1"): + // + // `table.bucket(3).as_ptr()` returns a pointer that points here in the `data` + // part of the `RawTable`, i.e. to the start of T3 (see `Bucket::as_ptr`) + // | + // | `base = self.data_end()` points here + // | (to the start of CT0 or to the end of T0) + // v v + // [Pad], T_n, ..., |T3|, T2, T1, T0, |CT0, CT1, CT2, CT3, ..., CT_n, CTa_0, CTa_1, ..., CTa_m + // ^ \__________ __________/ + // `table.bucket(3)` returns a pointer that points \/ + // here in the `data` part of the `RawTable` (to additional control bytes + // the end of T3) `m = Group::WIDTH - 1` + // + // where: T0...T_n - our stored data; + // CT0...CT_n - control bytes or metadata for `data`; + // CTa_0...CTa_m - additional control bytes (so that the search with loading `Group` bytes from + // the heap works properly, even if the result of `h1(hash) & self.table.bucket_mask` + // is equal to `self.table.bucket_mask`). See also `RawTableInner::set_ctrl` function. + // + // P.S. `h1(hash) & self.table.bucket_mask` is the same as `hash as usize % self.buckets()` because the number + // of buckets is a power of two, and `self.table.bucket_mask = self.buckets() - 1`. + debug_assert_ne!(self.table.bucket_mask, 0); + debug_assert!(index < self.buckets()); + Bucket::from_base_index(self.data_end(), index) + } + + /// Erases an element from the table without dropping it. + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn erase_no_drop(&mut self, item: &Bucket) { + let index = self.bucket_index(item); + self.table.erase(index); + } + + /// Erases an element from the table, dropping it in place. + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::needless_pass_by_value)] + pub unsafe fn erase(&mut self, item: Bucket) { + // Erase the element from the table first since drop might panic. + self.erase_no_drop(&item); + item.drop(); + } + + /// Removes an element from the table, returning it. + /// + /// This also returns an `InsertSlot` pointing to the newly free bucket. + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::needless_pass_by_value)] + pub unsafe fn remove(&mut self, item: Bucket) -> (T, InsertSlot) { + self.erase_no_drop(&item); + ( + item.read(), + InsertSlot { + index: self.bucket_index(&item), + }, + ) + } + + /// Finds and removes an element from the table, returning it. + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { + // Avoid `Option::map` because it bloats LLVM IR. + match self.find(hash, eq) { + Some(bucket) => Some(unsafe { self.remove(bucket).0 }), + None => None, + } + } + + /// Marks all table buckets as empty without dropping their contents. + #[cfg_attr(feature = "inline-more", inline)] + pub fn clear_no_drop(&mut self) { + self.table.clear_no_drop(); + } + + /// Removes all elements from the table without freeing the backing memory. + #[cfg_attr(feature = "inline-more", inline)] + pub fn clear(&mut self) { + if self.is_empty() { + // Special case empty table to avoid surprising O(capacity) time. + return; + } + // Ensure that the table is reset even if one of the drops panic + let mut self_ = guard(self, |self_| self_.clear_no_drop()); + unsafe { + // SAFETY: ScopeGuard sets to zero the `items` field of the table + // even in case of panic during the dropping of the elements so + // that there will be no double drop of the elements. + self_.table.drop_elements::(); + } + } + + /// Shrinks the table to fit `max(self.len(), min_size)` elements. + #[cfg_attr(feature = "inline-more", inline)] + pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { + // Calculate the minimal number of elements that we need to reserve + // space for. + let min_size = usize::max(self.table.items, min_size); + if min_size == 0 { + let mut old_inner = mem::replace(&mut self.table, RawTableInner::NEW); + unsafe { + // SAFETY: + // 1. We call the function only once; + // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`] + // and [`TableLayout`] that were used to allocate this table. + // 3. If any elements' drop function panics, then there will only be a memory leak, + // because we have replaced the inner table with a new one. + old_inner.drop_inner_table::(&self.alloc, Self::TABLE_LAYOUT); + } + return; + } + + // Calculate the number of buckets that we need for this number of + // elements. If the calculation overflows then the requested bucket + // count must be larger than what we have right and nothing needs to be + // done. + let min_buckets = match capacity_to_buckets(min_size) { + Some(buckets) => buckets, + None => return, + }; + + // If we have more buckets than we need, shrink the table. + if min_buckets < self.buckets() { + // Fast path if the table is empty + if self.table.items == 0 { + let new_inner = + RawTableInner::with_capacity(&self.alloc, Self::TABLE_LAYOUT, min_size); + let mut old_inner = mem::replace(&mut self.table, new_inner); + unsafe { + // SAFETY: + // 1. We call the function only once; + // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`] + // and [`TableLayout`] that were used to allocate this table. + // 3. If any elements' drop function panics, then there will only be a memory leak, + // because we have replaced the inner table with a new one. + old_inner.drop_inner_table::(&self.alloc, Self::TABLE_LAYOUT); + } + } else { + // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. + unsafe { + // SAFETY: + // 1. We know for sure that `min_size >= self.table.items`. + // 2. The [`RawTableInner`] must already have properly initialized control bytes since + // we will never expose RawTable::new_uninitialized in a public API. + if self + .resize(min_size, hasher, Fallibility::Infallible) + .is_err() + { + // SAFETY: The result of calling the `resize` function cannot be an error + // because `fallibility == Fallibility::Infallible. + hint::unreachable_unchecked() + } + } + } + } + } + + /// Ensures that at least `additional` items can be inserted into the table + /// without reallocation. + #[cfg_attr(feature = "inline-more", inline)] + pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { + if unlikely(additional > self.table.growth_left) { + // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. + unsafe { + // SAFETY: The [`RawTableInner`] must already have properly initialized control + // bytes since we will never expose RawTable::new_uninitialized in a public API. + if self + .reserve_rehash(additional, hasher, Fallibility::Infallible) + .is_err() + { + // SAFETY: All allocation errors will be caught inside `RawTableInner::reserve_rehash`. + hint::unreachable_unchecked() + } + } + } + } + + /// Tries to ensure that at least `additional` items can be inserted into + /// the table without reallocation. + #[cfg_attr(feature = "inline-more", inline)] + pub fn try_reserve( + &mut self, + additional: usize, + hasher: impl Fn(&T) -> u64, + ) -> Result<(), TryReserveError> { + if additional > self.table.growth_left { + // SAFETY: The [`RawTableInner`] must already have properly initialized control + // bytes since we will never expose RawTable::new_uninitialized in a public API. + unsafe { self.reserve_rehash(additional, hasher, Fallibility::Fallible) } + } else { + Ok(()) + } + } + + /// Out-of-line slow path for `reserve` and `try_reserve`. + /// + /// # Safety + /// + /// The [`RawTableInner`] must have properly initialized control bytes, + /// otherwise calling this function results in [`undefined behavior`] + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[cold] + #[inline(never)] + unsafe fn reserve_rehash( + &mut self, + additional: usize, + hasher: impl Fn(&T) -> u64, + fallibility: Fallibility, + ) -> Result<(), TryReserveError> { + unsafe { + // SAFETY: + // 1. We know for sure that `alloc` and `layout` matches the [`Allocator`] and + // [`TableLayout`] that were used to allocate this table. + // 2. The `drop` function is the actual drop function of the elements stored in + // the table. + // 3. The caller ensures that the control bytes of the `RawTableInner` + // are already initialized. + self.table.reserve_rehash_inner( + &self.alloc, + additional, + &|table, index| hasher(table.bucket::(index).as_ref()), + fallibility, + Self::TABLE_LAYOUT, + if T::NEEDS_DROP { + Some(|ptr| ptr::drop_in_place(ptr as *mut T)) + } else { + None + }, + ) + } + } + + /// Allocates a new table of a different size and moves the contents of the + /// current table into it. + /// + /// # Safety + /// + /// The [`RawTableInner`] must have properly initialized control bytes, + /// otherwise calling this function results in [`undefined behavior`] + /// + /// The caller of this function must ensure that `capacity >= self.table.items` + /// otherwise: + /// + /// * If `self.table.items != 0`, calling of this function with `capacity` + /// equal to 0 (`capacity == 0`) results in [`undefined behavior`]. + /// + /// * If `capacity_to_buckets(capacity) < Group::WIDTH` and + /// `self.table.items > capacity_to_buckets(capacity)` + /// calling this function results in [`undefined behavior`]. + /// + /// * If `capacity_to_buckets(capacity) >= Group::WIDTH` and + /// `self.table.items > capacity_to_buckets(capacity)` + /// calling this function are never return (will go into an + /// infinite loop). + /// + /// See [`RawTableInner::find_insert_slot`] for more information. + /// + /// [`RawTableInner::find_insert_slot`]: RawTableInner::find_insert_slot + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + unsafe fn resize( + &mut self, + capacity: usize, + hasher: impl Fn(&T) -> u64, + fallibility: Fallibility, + ) -> Result<(), TryReserveError> { + // SAFETY: + // 1. The caller of this function guarantees that `capacity >= self.table.items`. + // 2. We know for sure that `alloc` and `layout` matches the [`Allocator`] and + // [`TableLayout`] that were used to allocate this table. + // 3. The caller ensures that the control bytes of the `RawTableInner` + // are already initialized. + self.table.resize_inner( + &self.alloc, + capacity, + &|table, index| hasher(table.bucket::(index).as_ref()), + fallibility, + Self::TABLE_LAYOUT, + ) + } + + /// Inserts a new element into the table, and returns its raw bucket. + /// + /// This does not check if the given element already exists in the table. + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { + unsafe { + // SAFETY: + // 1. The [`RawTableInner`] must already have properly initialized control bytes since + // we will never expose `RawTable::new_uninitialized` in a public API. + // + // 2. We reserve additional space (if necessary) right after calling this function. + let mut slot = self.table.find_insert_slot(hash); + + // We can avoid growing the table once we have reached our load factor if we are replacing + // a tombstone. This works since the number of EMPTY slots does not change in this case. + // + // SAFETY: The function is guaranteed to return [`InsertSlot`] that contains an index + // in the range `0..=self.buckets()`. + let old_ctrl = *self.table.ctrl(slot.index); + if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { + self.reserve(1, hasher); + // SAFETY: We know for sure that `RawTableInner` has control bytes + // initialized and that there is extra space in the table. + slot = self.table.find_insert_slot(hash); + } + + self.insert_in_slot(hash, slot, value) + } + } + + /// Inserts a new element into the table, and returns a mutable reference to it. + /// + /// This does not check if the given element already exists in the table. + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { + unsafe { self.insert(hash, value, hasher).as_mut() } + } + + /// Inserts a new element into the table, without growing the table. + /// + /// There must be enough space in the table to insert the new element. + /// + /// This does not check if the given element already exists in the table. + #[cfg_attr(feature = "inline-more", inline)] + #[cfg(feature = "rustc-internal-api")] + pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { + let (index, old_ctrl) = self.table.prepare_insert_slot(hash); + let bucket = self.table.bucket(index); + + // If we are replacing a DELETED entry then we don't need to update + // the load counter. + self.table.growth_left -= special_is_empty(old_ctrl) as usize; + + bucket.write(value); + self.table.items += 1; + bucket + } + + /// Temporary removes a bucket, applying the given function to the removed + /// element and optionally put back the returned value in the same bucket. + /// + /// Returns `true` if the bucket still contains an element + /// + /// This does not check if the given bucket is actually occupied. + #[cfg_attr(feature = "inline-more", inline)] + pub unsafe fn replace_bucket_with(&mut self, bucket: Bucket, f: F) -> bool + where + F: FnOnce(T) -> Option, + { + let index = self.bucket_index(&bucket); + let old_ctrl = *self.table.ctrl(index); + debug_assert!(self.is_bucket_full(index)); + let old_growth_left = self.table.growth_left; + let item = self.remove(bucket).0; + if let Some(new_item) = f(item) { + self.table.growth_left = old_growth_left; + self.table.set_ctrl(index, old_ctrl); + self.table.items += 1; + self.bucket(index).write(new_item); + true + } else { + false + } + } + + /// Searches for an element in the table. If the element is not found, + /// returns `Err` with the position of a slot where an element with the + /// same hash could be inserted. + /// + /// This function may resize the table if additional space is required for + /// inserting an element. + #[inline] + pub fn find_or_find_insert_slot( + &mut self, + hash: u64, + mut eq: impl FnMut(&T) -> bool, + hasher: impl Fn(&T) -> u64, + ) -> Result, InsertSlot> { + self.reserve(1, hasher); + + unsafe { + // SAFETY: + // 1. We know for sure that there is at least one empty `bucket` in the table. + // 2. The [`RawTableInner`] must already have properly initialized control bytes since we will + // never expose `RawTable::new_uninitialized` in a public API. + // 3. The `find_or_find_insert_slot_inner` function returns the `index` of only the full bucket, + // which is in the range `0..self.buckets()` (since there is at least one empty `bucket` in + // the table), so calling `self.bucket(index)` and `Bucket::as_ref` is safe. + match self + .table + .find_or_find_insert_slot_inner(hash, &mut |index| eq(self.bucket(index).as_ref())) + { + // SAFETY: See explanation above. + Ok(index) => Ok(self.bucket(index)), + Err(slot) => Err(slot), + } + } + } + + /// Inserts a new element into the table in the given slot, and returns its + /// raw bucket. + /// + /// # Safety + /// + /// `slot` must point to a slot previously returned by + /// `find_or_find_insert_slot`, and no mutation of the table must have + /// occurred since that call. + #[inline] + pub unsafe fn insert_in_slot(&mut self, hash: u64, slot: InsertSlot, value: T) -> Bucket { + let old_ctrl = *self.table.ctrl(slot.index); + self.table.record_item_insert_at(slot.index, old_ctrl, hash); + + let bucket = self.bucket(slot.index); + bucket.write(value); + bucket + } + + /// Searches for an element in the table. + #[inline] + pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { + unsafe { + // SAFETY: + // 1. The [`RawTableInner`] must already have properly initialized control bytes since we + // will never expose `RawTable::new_uninitialized` in a public API. + // 1. The `find_inner` function returns the `index` of only the full bucket, which is in + // the range `0..self.buckets()`, so calling `self.bucket(index)` and `Bucket::as_ref` + // is safe. + let result = self + .table + .find_inner(hash, &mut |index| eq(self.bucket(index).as_ref())); + + // Avoid `Option::map` because it bloats LLVM IR. + match result { + // SAFETY: See explanation above. + Some(index) => Some(self.bucket(index)), + None => None, + } + } + } + + /// Gets a reference to an element in the table. + #[inline] + pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { + // Avoid `Option::map` because it bloats LLVM IR. + match self.find(hash, eq) { + Some(bucket) => Some(unsafe { bucket.as_ref() }), + None => None, + } + } + + /// Gets a mutable reference to an element in the table. + #[inline] + pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { + // Avoid `Option::map` because it bloats LLVM IR. + match self.find(hash, eq) { + Some(bucket) => Some(unsafe { bucket.as_mut() }), + None => None, + } + } + + /// Attempts to get mutable references to `N` entries in the table at once. + /// + /// Returns an array of length `N` with the results of each query. + /// + /// At most one mutable reference will be returned to any entry. `None` will be returned if any + /// of the hashes are duplicates. `None` will be returned if the hash is not found. + /// + /// The `eq` argument should be a closure such that `eq(i, k)` returns true if `k` is equal to + /// the `i`th key to be looked up. + pub fn get_many_mut( + &mut self, + hashes: [u64; N], + eq: impl FnMut(usize, &T) -> bool, + ) -> [Option<&'_ mut T>; N] { + unsafe { + let ptrs = self.get_many_mut_pointers(hashes, eq); + + for (i, cur) in ptrs.iter().enumerate() { + if cur.is_some() && ptrs[..i].contains(cur) { + panic!("duplicate keys found"); + } + } + // All bucket are distinct from all previous buckets so we're clear to return the result + // of the lookup. + + ptrs.map(|ptr| ptr.map(|mut ptr| ptr.as_mut())) + } + } + + pub unsafe fn get_many_unchecked_mut( + &mut self, + hashes: [u64; N], + eq: impl FnMut(usize, &T) -> bool, + ) -> [Option<&'_ mut T>; N] { + let ptrs = self.get_many_mut_pointers(hashes, eq); + ptrs.map(|ptr| ptr.map(|mut ptr| ptr.as_mut())) + } + + unsafe fn get_many_mut_pointers( + &mut self, + hashes: [u64; N], + mut eq: impl FnMut(usize, &T) -> bool, + ) -> [Option>; N] { + array::from_fn(|i| { + self.find(hashes[i], |k| eq(i, k)) + .map(|cur| cur.as_non_null()) + }) + } + + /// Returns the number of elements the map can hold without reallocating. + /// + /// This number is a lower bound; the table might be able to hold + /// more, but is guaranteed to be able to hold at least this many. + #[inline] + pub fn capacity(&self) -> usize { + self.table.items + self.table.growth_left + } + + /// Returns the number of elements in the table. + #[inline] + pub fn len(&self) -> usize { + self.table.items + } + + /// Returns `true` if the table contains no elements. + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the number of buckets in the table. + #[inline] + pub fn buckets(&self) -> usize { + self.table.bucket_mask + 1 + } + + /// Checks whether the bucket at `index` is full. + /// + /// # Safety + /// + /// The caller must ensure `index` is less than the number of buckets. + #[inline] + pub unsafe fn is_bucket_full(&self, index: usize) -> bool { + self.table.is_bucket_full(index) + } + + /// Returns an iterator over every element in the table. It is up to + /// the caller to ensure that the `RawTable` outlives the `RawIter`. + /// Because we cannot make the `next` method unsafe on the `RawIter` + /// struct, we have to make the `iter` method unsafe. + #[inline] + pub unsafe fn iter(&self) -> RawIter { + // SAFETY: + // 1. The caller must uphold the safety contract for `iter` method. + // 2. The [`RawTableInner`] must already have properly initialized control bytes since + // we will never expose RawTable::new_uninitialized in a public API. + self.table.iter() + } + + /// Returns an iterator over occupied buckets that could match a given hash. + /// + /// `RawTable` only stores 7 bits of the hash value, so this iterator may + /// return items that have a hash value different than the one provided. You + /// should always validate the returned values before using them. + /// + /// It is up to the caller to ensure that the `RawTable` outlives the + /// `RawIterHash`. Because we cannot make the `next` method unsafe on the + /// `RawIterHash` struct, we have to make the `iter_hash` method unsafe. + #[cfg_attr(feature = "inline-more", inline)] + pub unsafe fn iter_hash(&self, hash: u64) -> RawIterHash { + RawIterHash::new(self, hash) + } + + /// Returns an iterator which removes all elements from the table without + /// freeing the memory. + #[cfg_attr(feature = "inline-more", inline)] + pub fn drain(&mut self) -> RawDrain<'_, T, A> { + unsafe { + let iter = self.iter(); + self.drain_iter_from(iter) + } + } + + /// Returns an iterator which removes all elements from the table without + /// freeing the memory. + /// + /// Iteration starts at the provided iterator's current location. + /// + /// It is up to the caller to ensure that the iterator is valid for this + /// `RawTable` and covers all items that remain in the table. + #[cfg_attr(feature = "inline-more", inline)] + pub unsafe fn drain_iter_from(&mut self, iter: RawIter) -> RawDrain<'_, T, A> { + debug_assert_eq!(iter.len(), self.len()); + RawDrain { + iter, + table: mem::replace(&mut self.table, RawTableInner::NEW), + orig_table: NonNull::from(&mut self.table), + marker: PhantomData, + } + } + + /// Returns an iterator which consumes all elements from the table. + /// + /// Iteration starts at the provided iterator's current location. + /// + /// It is up to the caller to ensure that the iterator is valid for this + /// `RawTable` and covers all items that remain in the table. + pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { + debug_assert_eq!(iter.len(), self.len()); + + let allocation = self.into_allocation(); + RawIntoIter { + iter, + allocation, + marker: PhantomData, + } + } + + /// Converts the table into a raw allocation. The contents of the table + /// should be dropped using a `RawIter` before freeing the allocation. + #[cfg_attr(feature = "inline-more", inline)] + pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout, A)> { + let alloc = if self.table.is_empty_singleton() { + None + } else { + // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. + let (layout, ctrl_offset) = + match Self::TABLE_LAYOUT.calculate_layout_for(self.table.buckets()) { + Some(lco) => lco, + None => unsafe { hint::unreachable_unchecked() }, + }; + Some(( + unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, + layout, + unsafe { ptr::read(&self.alloc) }, + )) + }; + mem::forget(self); + alloc + } +} + +unsafe impl Send for RawTable +where + T: Send, + A: Send, +{ +} +unsafe impl Sync for RawTable +where + T: Sync, + A: Sync, +{ +} + +impl RawTableInner { + const NEW: Self = RawTableInner::new(); + + /// Creates a new empty hash table without allocating any memory. + /// + /// In effect this returns a table with exactly 1 bucket. However we can + /// leave the data pointer dangling since that bucket is never accessed + /// due to our load factor forcing us to always have at least 1 free bucket. + #[inline] + const fn new() -> Self { + Self { + // Be careful to cast the entire slice to a raw pointer. + ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, + bucket_mask: 0, + items: 0, + growth_left: 0, + } + } +} + +impl RawTableInner { + /// Allocates a new [`RawTableInner`] with the given number of buckets. + /// The control bytes and buckets are left uninitialized. + /// + /// # Safety + /// + /// The caller of this function must ensure that the `buckets` is power of two + /// and also initialize all control bytes of the length `self.bucket_mask + 1 + + /// Group::WIDTH` with the [`EMPTY`] bytes. + /// + /// See also [`Allocator`] API for other safety concerns. + /// + /// [`Allocator`]: https://doc.rust-lang.org/alloc/alloc/trait.Allocator.html + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn new_uninitialized( + alloc: &A, + table_layout: TableLayout, + buckets: usize, + fallibility: Fallibility, + ) -> Result + where + A: Allocator, + { + debug_assert!(buckets.is_power_of_two()); + + // Avoid `Option::ok_or_else` because it bloats LLVM IR. + let (layout, ctrl_offset) = match table_layout.calculate_layout_for(buckets) { + Some(lco) => lco, + None => return Err(fallibility.capacity_overflow()), + }; + + let ptr: NonNull = match do_alloc(alloc, layout) { + Ok(block) => block.cast(), + Err(_) => return Err(fallibility.alloc_err(layout)), + }; + + // SAFETY: null pointer will be caught in above check + let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); + Ok(Self { + ctrl, + bucket_mask: buckets - 1, + items: 0, + growth_left: bucket_mask_to_capacity(buckets - 1), + }) + } + + /// Attempts to allocate a new [`RawTableInner`] with at least enough + /// capacity for inserting the given number of elements without reallocating. + /// + /// All the control bytes are initialized with the [`EMPTY`] bytes. + #[inline] + fn fallible_with_capacity( + alloc: &A, + table_layout: TableLayout, + capacity: usize, + fallibility: Fallibility, + ) -> Result + where + A: Allocator, + { + if capacity == 0 { + Ok(Self::NEW) + } else { + // SAFETY: We checked that we could successfully allocate the new table, and then + // initialized all control bytes with the constant `EMPTY` byte. + unsafe { + let buckets = + capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; + + let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; + // SAFETY: We checked that the table is allocated and therefore the table already has + // `self.bucket_mask + 1 + Group::WIDTH` number of control bytes (see TableLayout::calculate_layout_for) + // so writing `self.num_ctrl_bytes() == bucket_mask + 1 + Group::WIDTH` bytes is safe. + result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); + + Ok(result) + } + } + } + + /// Allocates a new [`RawTableInner`] with at least enough capacity for inserting + /// the given number of elements without reallocating. + /// + /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program + /// in case of allocation error. Use [`fallible_with_capacity`] instead if you want to + /// handle memory allocation failure. + /// + /// All the control bytes are initialized with the [`EMPTY`] bytes. + /// + /// [`fallible_with_capacity`]: RawTableInner::fallible_with_capacity + /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html + fn with_capacity(alloc: &A, table_layout: TableLayout, capacity: usize) -> Self + where + A: Allocator, + { + // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. + match Self::fallible_with_capacity(alloc, table_layout, capacity, Fallibility::Infallible) { + Ok(table_inner) => table_inner, + // SAFETY: All allocation errors will be caught inside `RawTableInner::new_uninitialized`. + Err(_) => unsafe { hint::unreachable_unchecked() }, + } + } + + /// Fixes up an insertion slot returned by the [`RawTableInner::find_insert_slot_in_group`] method. + /// + /// In tables smaller than the group width (`self.buckets() < Group::WIDTH`), trailing control + /// bytes outside the range of the table are filled with [`EMPTY`] entries. These will unfortunately + /// trigger a match of [`RawTableInner::find_insert_slot_in_group`] function. This is because + /// the `Some(bit)` returned by `group.match_empty_or_deleted().lowest_set_bit()` after masking + /// (`(probe_seq.pos + bit) & self.bucket_mask`) may point to a full bucket that is already occupied. + /// We detect this situation here and perform a second scan starting at the beginning of the table. + /// This second scan is guaranteed to find an empty slot (due to the load factor) before hitting the + /// trailing control bytes (containing [`EMPTY`] bytes). + /// + /// If this function is called correctly, it is guaranteed to return [`InsertSlot`] with an + /// index of an empty or deleted bucket in the range `0..self.buckets()` (see `Warning` and + /// `Safety`). + /// + /// # Warning + /// + /// The table must have at least 1 empty or deleted `bucket`, otherwise if the table is less than + /// the group width (`self.buckets() < Group::WIDTH`) this function returns an index outside of the + /// table indices range `0..self.buckets()` (`0..=self.bucket_mask`). Attempt to write data at that + /// index will cause immediate [`undefined behavior`]. + /// + /// # Safety + /// + /// The safety rules are directly derived from the safety rules for [`RawTableInner::ctrl`] method. + /// Thus, in order to uphold those safety contracts, as well as for the correct logic of the work + /// of this crate, the following rules are necessary and sufficient: + /// + /// * The [`RawTableInner`] must have properly initialized control bytes otherwise calling this + /// function results in [`undefined behavior`]. + /// + /// * This function must only be used on insertion slots found by [`RawTableInner::find_insert_slot_in_group`] + /// (after the `find_insert_slot_in_group` function, but before insertion into the table). + /// + /// * The `index` must not be greater than the `self.bucket_mask`, i.e. `(index + 1) <= self.buckets()` + /// (this one is provided by the [`RawTableInner::find_insert_slot_in_group`] function). + /// + /// Calling this function with an index not provided by [`RawTableInner::find_insert_slot_in_group`] + /// may result in [`undefined behavior`] even if the index satisfies the safety rules of the + /// [`RawTableInner::ctrl`] function (`index < self.bucket_mask + 1 + Group::WIDTH`). + /// + /// [`RawTableInner::ctrl`]: RawTableInner::ctrl + /// [`RawTableInner::find_insert_slot_in_group`]: RawTableInner::find_insert_slot_in_group + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn fix_insert_slot(&self, mut index: usize) -> InsertSlot { + // SAFETY: The caller of this function ensures that `index` is in the range `0..=self.bucket_mask`. + if unlikely(self.is_bucket_full(index)) { + debug_assert!(self.bucket_mask < Group::WIDTH); + // SAFETY: + // + // * Since the caller of this function ensures that the control bytes are properly + // initialized and `ptr = self.ctrl(0)` points to the start of the array of control + // bytes, therefore: `ctrl` is valid for reads, properly aligned to `Group::WIDTH` + // and points to the properly initialized control bytes (see also + // `TableLayout::calculate_layout_for` and `ptr::read`); + // + // * Because the caller of this function ensures that the index was provided by the + // `self.find_insert_slot_in_group()` function, so for for tables larger than the + // group width (self.buckets() >= Group::WIDTH), we will never end up in the given + // branch, since `(probe_seq.pos + bit) & self.bucket_mask` in `find_insert_slot_in_group` + // cannot return a full bucket index. For tables smaller than the group width, calling + // the `unwrap_unchecked` function is also safe, as the trailing control bytes outside + // the range of the table are filled with EMPTY bytes (and we know for sure that there + // is at least one FULL bucket), so this second scan either finds an empty slot (due to + // the load factor) or hits the trailing control bytes (containing EMPTY). + index = Group::load_aligned(self.ctrl(0)) + .match_empty_or_deleted() + .lowest_set_bit() + .unwrap_unchecked(); + } + InsertSlot { index } + } + + /// Finds the position to insert something in a group. + /// + /// **This may have false positives and must be fixed up with `fix_insert_slot` + /// before it's used.** + /// + /// The function is guaranteed to return the index of an empty or deleted [`Bucket`] + /// in the range `0..self.buckets()` (`0..=self.bucket_mask`). + #[inline] + fn find_insert_slot_in_group(&self, group: &Group, probe_seq: &ProbeSeq) -> Option { + let bit = group.match_empty_or_deleted().lowest_set_bit(); + + if likely(bit.is_some()) { + // This is the same as `(probe_seq.pos + bit) % self.buckets()` because the number + // of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + Some((probe_seq.pos + bit.unwrap()) & self.bucket_mask) + } else { + None + } + } + + /// Searches for an element in the table, or a potential slot where that element could + /// be inserted (an empty or deleted [`Bucket`] index). + /// + /// This uses dynamic dispatch to reduce the amount of code generated, but that is + /// eliminated by LLVM optimizations. + /// + /// This function does not make any changes to the `data` part of the table, or any + /// changes to the `items` or `growth_left` field of the table. + /// + /// The table must have at least 1 empty or deleted `bucket`, otherwise, if the + /// `eq: &mut dyn FnMut(usize) -> bool` function does not return `true`, this function + /// will never return (will go into an infinite loop) for tables larger than the group + /// width, or return an index outside of the table indices range if the table is less + /// than the group width. + /// + /// This function is guaranteed to provide the `eq: &mut dyn FnMut(usize) -> bool` + /// function with only `FULL` buckets' indices and return the `index` of the found + /// element (as `Ok(index)`). If the element is not found and there is at least 1 + /// empty or deleted [`Bucket`] in the table, the function is guaranteed to return + /// [`InsertSlot`] with an index in the range `0..self.buckets()`, but in any case, + /// if this function returns [`InsertSlot`], it will contain an index in the range + /// `0..=self.buckets()`. + /// + /// # Safety + /// + /// The [`RawTableInner`] must have properly initialized control bytes otherwise calling + /// this function results in [`undefined behavior`]. + /// + /// Attempt to write data at the [`InsertSlot`] returned by this function when the table is + /// less than the group width and if there was not at least one empty or deleted bucket in + /// the table will cause immediate [`undefined behavior`]. This is because in this case the + /// function will return `self.bucket_mask + 1` as an index due to the trailing [`EMPTY`] + /// control bytes outside the table range. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn find_or_find_insert_slot_inner( + &self, + hash: u64, + eq: &mut dyn FnMut(usize) -> bool, + ) -> Result { + let mut insert_slot = None; + + let h2_hash = h2(hash); + let mut probe_seq = self.probe_seq(hash); + + loop { + // SAFETY: + // * Caller of this function ensures that the control bytes are properly initialized. + // + // * `ProbeSeq.pos` cannot be greater than `self.bucket_mask = self.buckets() - 1` + // of the table due to masking with `self.bucket_mask` and also because the number + // of buckets is a power of two (see `self.probe_seq` function). + // + // * Even if `ProbeSeq.pos` returns `position == self.bucket_mask`, it is safe to + // call `Group::load` due to the extended control bytes range, which is + // `self.bucket_mask + 1 + Group::WIDTH` (in fact, this means that the last control + // byte will never be read for the allocated table); + // + // * Also, even if `RawTableInner` is not already allocated, `ProbeSeq.pos` will + // always return "0" (zero), so Group::load will read unaligned `Group::static_empty()` + // bytes, which is safe (see RawTableInner::new). + let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; + + for bit in group.match_byte(h2_hash) { + let index = (probe_seq.pos + bit) & self.bucket_mask; + + if likely(eq(index)) { + return Ok(index); + } + } + + // We didn't find the element we were looking for in the group, try to get an + // insertion slot from the group if we don't have one yet. + if likely(insert_slot.is_none()) { + insert_slot = self.find_insert_slot_in_group(&group, &probe_seq); + } + + // Only stop the search if the group contains at least one empty element. + // Otherwise, the element that we are looking for might be in a following group. + if likely(group.match_empty().any_bit_set()) { + // We must have found a insert slot by now, since the current group contains at + // least one. For tables smaller than the group width, there will still be an + // empty element in the current (and only) group due to the load factor. + unsafe { + // SAFETY: + // * Caller of this function ensures that the control bytes are properly initialized. + // + // * We use this function with the slot / index found by `self.find_insert_slot_in_group` + return Err(self.fix_insert_slot(insert_slot.unwrap_unchecked())); + } + } + + probe_seq.move_next(self.bucket_mask); + } + } + + /// Searches for an empty or deleted bucket which is suitable for inserting a new + /// element and sets the hash for that slot. Returns an index of that slot and the + /// old control byte stored in the found index. + /// + /// This function does not check if the given element exists in the table. Also, + /// this function does not check if there is enough space in the table to insert + /// a new element. The caller of the function must make sure that the table has at + /// least 1 empty or deleted `bucket`, otherwise this function will never return + /// (will go into an infinite loop) for tables larger than the group width, or + /// return an index outside of the table indices range if the table is less than + /// the group width. + /// + /// If there is at least 1 empty or deleted `bucket` in the table, the function is + /// guaranteed to return an `index` in the range `0..self.buckets()`, but in any case, + /// if this function returns an `index` it will be in the range `0..=self.buckets()`. + /// + /// This function does not make any changes to the `data` parts of the table, + /// or any changes to the `items` or `growth_left` field of the table. + /// + /// # Safety + /// + /// The safety rules are directly derived from the safety rules for the + /// [`RawTableInner::set_ctrl_h2`] and [`RawTableInner::find_insert_slot`] methods. + /// Thus, in order to uphold the safety contracts for that methods, as well as for + /// the correct logic of the work of this crate, you must observe the following rules + /// when calling this function: + /// + /// * The [`RawTableInner`] has already been allocated and has properly initialized + /// control bytes otherwise calling this function results in [`undefined behavior`]. + /// + /// * The caller of this function must ensure that the "data" parts of the table + /// will have an entry in the returned index (matching the given hash) right + /// after calling this function. + /// + /// Attempt to write data at the `index` returned by this function when the table is + /// less than the group width and if there was not at least one empty or deleted bucket in + /// the table will cause immediate [`undefined behavior`]. This is because in this case the + /// function will return `self.bucket_mask + 1` as an index due to the trailing [`EMPTY`] + /// control bytes outside the table range. + /// + /// The caller must independently increase the `items` field of the table, and also, + /// if the old control byte was [`EMPTY`], then decrease the table's `growth_left` + /// field, and do not change it if the old control byte was [`DELETED`]. + /// + /// See also [`Bucket::as_ptr`] method, for more information about of properly removing + /// or saving `element` from / into the [`RawTable`] / [`RawTableInner`]. + /// + /// [`Bucket::as_ptr`]: Bucket::as_ptr + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + /// [`RawTableInner::ctrl`]: RawTableInner::ctrl + /// [`RawTableInner::set_ctrl_h2`]: RawTableInner::set_ctrl_h2 + /// [`RawTableInner::find_insert_slot`]: RawTableInner::find_insert_slot + #[inline] + unsafe fn prepare_insert_slot(&mut self, hash: u64) -> (usize, u8) { + // SAFETY: Caller of this function ensures that the control bytes are properly initialized. + let index: usize = self.find_insert_slot(hash).index; + // SAFETY: + // 1. The `find_insert_slot` function either returns an `index` less than or + // equal to `self.buckets() = self.bucket_mask + 1` of the table, or never + // returns if it cannot find an empty or deleted slot. + // 2. The caller of this function guarantees that the table has already been + // allocated + let old_ctrl = *self.ctrl(index); + self.set_ctrl_h2(index, hash); + (index, old_ctrl) + } + + /// Searches for an empty or deleted bucket which is suitable for inserting + /// a new element, returning the `index` for the new [`Bucket`]. + /// + /// This function does not make any changes to the `data` part of the table, or any + /// changes to the `items` or `growth_left` field of the table. + /// + /// The table must have at least 1 empty or deleted `bucket`, otherwise this function + /// will never return (will go into an infinite loop) for tables larger than the group + /// width, or return an index outside of the table indices range if the table is less + /// than the group width. + /// + /// If there is at least 1 empty or deleted `bucket` in the table, the function is + /// guaranteed to return [`InsertSlot`] with an index in the range `0..self.buckets()`, + /// but in any case, if this function returns [`InsertSlot`], it will contain an index + /// in the range `0..=self.buckets()`. + /// + /// # Safety + /// + /// The [`RawTableInner`] must have properly initialized control bytes otherwise calling + /// this function results in [`undefined behavior`]. + /// + /// Attempt to write data at the [`InsertSlot`] returned by this function when the table is + /// less than the group width and if there was not at least one empty or deleted bucket in + /// the table will cause immediate [`undefined behavior`]. This is because in this case the + /// function will return `self.bucket_mask + 1` as an index due to the trailing [`EMPTY`] + /// control bytes outside the table range. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn find_insert_slot(&self, hash: u64) -> InsertSlot { + let mut probe_seq = self.probe_seq(hash); + loop { + // SAFETY: + // * Caller of this function ensures that the control bytes are properly initialized. + // + // * `ProbeSeq.pos` cannot be greater than `self.bucket_mask = self.buckets() - 1` + // of the table due to masking with `self.bucket_mask` and also because the number + // of buckets is a power of two (see `self.probe_seq` function). + // + // * Even if `ProbeSeq.pos` returns `position == self.bucket_mask`, it is safe to + // call `Group::load` due to the extended control bytes range, which is + // `self.bucket_mask + 1 + Group::WIDTH` (in fact, this means that the last control + // byte will never be read for the allocated table); + // + // * Also, even if `RawTableInner` is not already allocated, `ProbeSeq.pos` will + // always return "0" (zero), so Group::load will read unaligned `Group::static_empty()` + // bytes, which is safe (see RawTableInner::new). + let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; + + let index = self.find_insert_slot_in_group(&group, &probe_seq); + if likely(index.is_some()) { + // SAFETY: + // * Caller of this function ensures that the control bytes are properly initialized. + // + // * We use this function with the slot / index found by `self.find_insert_slot_in_group` + unsafe { + return self.fix_insert_slot(index.unwrap_unchecked()); + } + } + probe_seq.move_next(self.bucket_mask); + } + } + + /// Searches for an element in a table, returning the `index` of the found element. + /// This uses dynamic dispatch to reduce the amount of code generated, but it is + /// eliminated by LLVM optimizations. + /// + /// This function does not make any changes to the `data` part of the table, or any + /// changes to the `items` or `growth_left` field of the table. + /// + /// The table must have at least 1 empty `bucket`, otherwise, if the + /// `eq: &mut dyn FnMut(usize) -> bool` function does not return `true`, + /// this function will also never return (will go into an infinite loop). + /// + /// This function is guaranteed to provide the `eq: &mut dyn FnMut(usize) -> bool` + /// function with only `FULL` buckets' indices and return the `index` of the found + /// element as `Some(index)`, so the index will always be in the range + /// `0..self.buckets()`. + /// + /// # Safety + /// + /// The [`RawTableInner`] must have properly initialized control bytes otherwise calling + /// this function results in [`undefined behavior`]. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline(always)] + unsafe fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { + let h2_hash = h2(hash); + let mut probe_seq = self.probe_seq(hash); + + loop { + // SAFETY: + // * Caller of this function ensures that the control bytes are properly initialized. + // + // * `ProbeSeq.pos` cannot be greater than `self.bucket_mask = self.buckets() - 1` + // of the table due to masking with `self.bucket_mask`. + // + // * Even if `ProbeSeq.pos` returns `position == self.bucket_mask`, it is safe to + // call `Group::load` due to the extended control bytes range, which is + // `self.bucket_mask + 1 + Group::WIDTH` (in fact, this means that the last control + // byte will never be read for the allocated table); + // + // * Also, even if `RawTableInner` is not already allocated, `ProbeSeq.pos` will + // always return "0" (zero), so Group::load will read unaligned `Group::static_empty()` + // bytes, which is safe (see RawTableInner::new_in). + let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; + + for bit in group.match_byte(h2_hash) { + // This is the same as `(probe_seq.pos + bit) % self.buckets()` because the number + // of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + let index = (probe_seq.pos + bit) & self.bucket_mask; + + if likely(eq(index)) { + return Some(index); + } + } + + if likely(group.match_empty().any_bit_set()) { + return None; + } + + probe_seq.move_next(self.bucket_mask); + } + } + + /// Prepares for rehashing data in place (that is, without allocating new memory). + /// Converts all full index `control bytes` to `DELETED` and all `DELETED` control + /// bytes to `EMPTY`, i.e. performs the following conversion: + /// + /// - `EMPTY` control bytes -> `EMPTY`; + /// - `DELETED` control bytes -> `EMPTY`; + /// - `FULL` control bytes -> `DELETED`. + /// + /// This function does not make any changes to the `data` parts of the table, + /// or any changes to the `items` or `growth_left` field of the table. + /// + /// # Safety + /// + /// You must observe the following safety rules when calling this function: + /// + /// * The [`RawTableInner`] has already been allocated; + /// + /// * The caller of this function must convert the `DELETED` bytes back to `FULL` + /// bytes when re-inserting them into their ideal position (which was impossible + /// to do during the first insert due to tombstones). If the caller does not do + /// this, then calling this function may result in a memory leak. + /// + /// * The [`RawTableInner`] must have properly initialized control bytes otherwise + /// calling this function results in [`undefined behavior`]. + /// + /// Calling this function on a table that has not been allocated results in + /// [`undefined behavior`]. + /// + /// See also [`Bucket::as_ptr`] method, for more information about of properly removing + /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`]. + /// + /// [`Bucket::as_ptr`]: Bucket::as_ptr + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[allow(clippy::mut_mut)] + #[inline] + unsafe fn prepare_rehash_in_place(&mut self) { + // Bulk convert all full control bytes to DELETED, and all DELETED control bytes to EMPTY. + // This effectively frees up all buckets containing a DELETED entry. + // + // SAFETY: + // 1. `i` is guaranteed to be within bounds since we are iterating from zero to `buckets - 1`; + // 2. Even if `i` will be `i == self.bucket_mask`, it is safe to call `Group::load_aligned` + // due to the extended control bytes range, which is `self.bucket_mask + 1 + Group::WIDTH`; + // 3. The caller of this function guarantees that [`RawTableInner`] has already been allocated; + // 4. We can use `Group::load_aligned` and `Group::store_aligned` here since we start from 0 + // and go to the end with a step equal to `Group::WIDTH` (see TableLayout::calculate_layout_for). + for i in (0..self.buckets()).step_by(Group::WIDTH) { + let group = Group::load_aligned(self.ctrl(i)); + let group = group.convert_special_to_empty_and_full_to_deleted(); + group.store_aligned(self.ctrl(i)); + } + + // Fix up the trailing control bytes. See the comments in set_ctrl + // for the handling of tables smaller than the group width. + // + // SAFETY: The caller of this function guarantees that [`RawTableInner`] + // has already been allocated + if unlikely(self.buckets() < Group::WIDTH) { + // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of control bytes, + // so copying `self.buckets() == self.bucket_mask + 1` bytes with offset equal to + // `Group::WIDTH` is safe + self.ctrl(0) + .copy_to(self.ctrl(Group::WIDTH), self.buckets()); + } else { + // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of + // control bytes,so copying `Group::WIDTH` bytes with offset equal + // to `self.buckets() == self.bucket_mask + 1` is safe + self.ctrl(0) + .copy_to(self.ctrl(self.buckets()), Group::WIDTH); + } + } + + /// Returns an iterator over every element in the table. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result + /// is [`undefined behavior`]: + /// + /// * The caller has to ensure that the `RawTableInner` outlives the + /// `RawIter`. Because we cannot make the `next` method unsafe on + /// the `RawIter` struct, we have to make the `iter` method unsafe. + /// + /// * The [`RawTableInner`] must have properly initialized control bytes. + /// + /// The type `T` must be the actual type of the elements stored in the table, + /// otherwise using the returned [`RawIter`] results in [`undefined behavior`]. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn iter(&self) -> RawIter { + // SAFETY: + // 1. Since the caller of this function ensures that the control bytes + // are properly initialized and `self.data_end()` points to the start + // of the array of control bytes, therefore: `ctrl` is valid for reads, + // properly aligned to `Group::WIDTH` and points to the properly initialized + // control bytes. + // 2. `data` bucket index in the table is equal to the `ctrl` index (i.e. + // equal to zero). + // 3. We pass the exact value of buckets of the table to the function. + // + // `ctrl` points here (to the start + // of the first control byte `CT0`) + // ∨ + // [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, CTa_0, CTa_1, ..., CTa_m + // \________ ________/ + // \/ + // `n = buckets - 1`, i.e. `RawTableInner::buckets() - 1` + // + // where: T0...T_n - our stored data; + // CT0...CT_n - control bytes or metadata for `data`. + // CTa_0...CTa_m - additional control bytes, where `m = Group::WIDTH - 1` (so that the search + // with loading `Group` bytes from the heap works properly, even if the result + // of `h1(hash) & self.bucket_mask` is equal to `self.bucket_mask`). See also + // `RawTableInner::set_ctrl` function. + // + // P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.buckets()` because the number + // of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + let data = Bucket::from_base_index(self.data_end(), 0); + RawIter { + // SAFETY: See explanation above + iter: RawIterRange::new(self.ctrl.as_ptr(), data, self.buckets()), + items: self.items, + } + } + + /// Executes the destructors (if any) of the values stored in the table. + /// + /// # Note + /// + /// This function does not erase the control bytes of the table and does + /// not make any changes to the `items` or `growth_left` fields of the + /// table. If necessary, the caller of this function must manually set + /// up these table fields, for example using the [`clear_no_drop`] function. + /// + /// Be careful during calling this function, because drop function of + /// the elements can panic, and this can leave table in an inconsistent + /// state. + /// + /// # Safety + /// + /// The type `T` must be the actual type of the elements stored in the table, + /// otherwise calling this function may result in [`undefined behavior`]. + /// + /// If `T` is a type that should be dropped and **the table is not empty**, + /// calling this function more than once results in [`undefined behavior`]. + /// + /// If `T` is not [`Copy`], attempting to use values stored in the table after + /// calling this function may result in [`undefined behavior`]. + /// + /// It is safe to call this function on a table that has not been allocated, + /// on a table with uninitialized control bytes, and on a table with no actual + /// data but with `Full` control bytes if `self.items == 0`. + /// + /// See also [`Bucket::drop`] / [`Bucket::as_ptr`] methods, for more information + /// about of properly removing or saving `element` from / into the [`RawTable`] / + /// [`RawTableInner`]. + /// + /// [`Bucket::drop`]: Bucket::drop + /// [`Bucket::as_ptr`]: Bucket::as_ptr + /// [`clear_no_drop`]: RawTableInner::clear_no_drop + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + unsafe fn drop_elements(&mut self) { + // Check that `self.items != 0`. Protects against the possibility + // of creating an iterator on an table with uninitialized control bytes. + if T::NEEDS_DROP && self.items != 0 { + // SAFETY: We know for sure that RawTableInner will outlive the + // returned `RawIter` iterator, and the caller of this function + // must uphold the safety contract for `drop_elements` method. + for item in self.iter::() { + // SAFETY: The caller must uphold the safety contract for + // `drop_elements` method. + item.drop(); + } + } + } + + /// Executes the destructors (if any) of the values stored in the table and than + /// deallocates the table. + /// + /// # Note + /// + /// Calling this function automatically makes invalid (dangling) all instances of + /// buckets ([`Bucket`]) and makes invalid (dangling) the `ctrl` field of the table. + /// + /// This function does not make any changes to the `bucket_mask`, `items` or `growth_left` + /// fields of the table. If necessary, the caller of this function must manually set + /// up these table fields. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is [`undefined behavior`]: + /// + /// * Calling this function more than once; + /// + /// * The type `T` must be the actual type of the elements stored in the table. + /// + /// * The `alloc` must be the same [`Allocator`] as the `Allocator` that was used + /// to allocate this table. + /// + /// * The `table_layout` must be the same [`TableLayout`] as the `TableLayout` that + /// was used to allocate this table. + /// + /// The caller of this function should pay attention to the possibility of the + /// elements' drop function panicking, because this: + /// + /// * May leave the table in an inconsistent state; + /// + /// * Memory is never deallocated, so a memory leak may occur. + /// + /// Attempt to use the `ctrl` field of the table (dereference) after calling this + /// function results in [`undefined behavior`]. + /// + /// It is safe to call this function on a table that has not been allocated, + /// on a table with uninitialized control bytes, and on a table with no actual + /// data but with `Full` control bytes if `self.items == 0`. + /// + /// See also [`RawTableInner::drop_elements`] or [`RawTableInner::free_buckets`] + /// for more information. + /// + /// [`RawTableInner::drop_elements`]: RawTableInner::drop_elements + /// [`RawTableInner::free_buckets`]: RawTableInner::free_buckets + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + unsafe fn drop_inner_table(&mut self, alloc: &A, table_layout: TableLayout) { + if !self.is_empty_singleton() { + unsafe { + // SAFETY: The caller must uphold the safety contract for `drop_inner_table` method. + self.drop_elements::(); + // SAFETY: + // 1. We have checked that our table is allocated. + // 2. The caller must uphold the safety contract for `drop_inner_table` method. + self.free_buckets(alloc, table_layout); + } + } + } + + /// Returns a pointer to an element in the table (convenience for + /// `Bucket::from_base_index(self.data_end::(), index)`). + /// + /// The caller must ensure that the `RawTableInner` outlives the returned [`Bucket`], + /// otherwise using it may result in [`undefined behavior`]. + /// + /// # Safety + /// + /// If `mem::size_of::() != 0`, then the safety rules are directly derived from the + /// safety rules of the [`Bucket::from_base_index`] function. Therefore, when calling + /// this function, the following safety rules must be observed: + /// + /// * The table must already be allocated; + /// + /// * The `index` must not be greater than the number returned by the [`RawTableInner::buckets`] + /// function, i.e. `(index + 1) <= self.buckets()`. + /// + /// * The type `T` must be the actual type of the elements stored in the table, otherwise + /// using the returned [`Bucket`] may result in [`undefined behavior`]. + /// + /// It is safe to call this function with index of zero (`index == 0`) on a table that has + /// not been allocated, but using the returned [`Bucket`] results in [`undefined behavior`]. + /// + /// If `mem::size_of::() == 0`, then the only requirement is that the `index` must + /// not be greater than the number returned by the [`RawTable::buckets`] function, i.e. + /// `(index + 1) <= self.buckets()`. + /// + /// ```none + /// If mem::size_of::() != 0 then return a pointer to the `element` in the `data part` of the table + /// (we start counting from "0", so that in the expression T[n], the "n" index actually one less than + /// the "buckets" number of our `RawTableInner`, i.e. "n = RawTableInner::buckets() - 1"): + /// + /// `table.bucket(3).as_ptr()` returns a pointer that points here in the `data` + /// part of the `RawTableInner`, i.e. to the start of T3 (see [`Bucket::as_ptr`]) + /// | + /// | `base = table.data_end::()` points here + /// | (to the start of CT0 or to the end of T0) + /// v v + /// [Pad], T_n, ..., |T3|, T2, T1, T0, |CT0, CT1, CT2, CT3, ..., CT_n, CTa_0, CTa_1, ..., CTa_m + /// ^ \__________ __________/ + /// `table.bucket(3)` returns a pointer that points \/ + /// here in the `data` part of the `RawTableInner` additional control bytes + /// (to the end of T3) `m = Group::WIDTH - 1` + /// + /// where: T0...T_n - our stored data; + /// CT0...CT_n - control bytes or metadata for `data`; + /// CTa_0...CTa_m - additional control bytes (so that the search with loading `Group` bytes from + /// the heap works properly, even if the result of `h1(hash) & self.bucket_mask` + /// is equal to `self.bucket_mask`). See also `RawTableInner::set_ctrl` function. + /// + /// P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.buckets()` because the number + /// of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + /// ``` + /// + /// [`Bucket::from_base_index`]: Bucket::from_base_index + /// [`RawTableInner::buckets`]: RawTableInner::buckets + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn bucket(&self, index: usize) -> Bucket { + debug_assert_ne!(self.bucket_mask, 0); + debug_assert!(index < self.buckets()); + Bucket::from_base_index(self.data_end(), index) + } + + /// Returns a raw `*mut u8` pointer to the start of the `data` element in the table + /// (convenience for `self.data_end::().as_ptr().sub((index + 1) * size_of)`). + /// + /// The caller must ensure that the `RawTableInner` outlives the returned `*mut u8`, + /// otherwise using it may result in [`undefined behavior`]. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is [`undefined behavior`]: + /// + /// * The table must already be allocated; + /// + /// * The `index` must not be greater than the number returned by the [`RawTableInner::buckets`] + /// function, i.e. `(index + 1) <= self.buckets()`; + /// + /// * The `size_of` must be equal to the size of the elements stored in the table; + /// + /// ```none + /// If mem::size_of::() != 0 then return a pointer to the `element` in the `data part` of the table + /// (we start counting from "0", so that in the expression T[n], the "n" index actually one less than + /// the "buckets" number of our `RawTableInner`, i.e. "n = RawTableInner::buckets() - 1"): + /// + /// `table.bucket_ptr(3, mem::size_of::())` returns a pointer that points here in the + /// `data` part of the `RawTableInner`, i.e. to the start of T3 + /// | + /// | `base = table.data_end::()` points here + /// | (to the start of CT0 or to the end of T0) + /// v v + /// [Pad], T_n, ..., |T3|, T2, T1, T0, |CT0, CT1, CT2, CT3, ..., CT_n, CTa_0, CTa_1, ..., CTa_m + /// \__________ __________/ + /// \/ + /// additional control bytes + /// `m = Group::WIDTH - 1` + /// + /// where: T0...T_n - our stored data; + /// CT0...CT_n - control bytes or metadata for `data`; + /// CTa_0...CTa_m - additional control bytes (so that the search with loading `Group` bytes from + /// the heap works properly, even if the result of `h1(hash) & self.bucket_mask` + /// is equal to `self.bucket_mask`). See also `RawTableInner::set_ctrl` function. + /// + /// P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.buckets()` because the number + /// of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + /// ``` + /// + /// [`RawTableInner::buckets`]: RawTableInner::buckets + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { + debug_assert_ne!(self.bucket_mask, 0); + debug_assert!(index < self.buckets()); + let base: *mut u8 = self.data_end().as_ptr(); + base.sub((index + 1) * size_of) + } + + /// Returns pointer to one past last `data` element in the table as viewed from + /// the start point of the allocation (convenience for `self.ctrl.cast()`). + /// + /// This function actually returns a pointer to the end of the `data element` at + /// index "0" (zero). + /// + /// The caller must ensure that the `RawTableInner` outlives the returned [`NonNull`], + /// otherwise using it may result in [`undefined behavior`]. + /// + /// # Note + /// + /// The type `T` must be the actual type of the elements stored in the table, otherwise + /// using the returned [`NonNull`] may result in [`undefined behavior`]. + /// + /// ```none + /// `table.data_end::()` returns pointer that points here + /// (to the end of `T0`) + /// ∨ + /// [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, CTa_0, CTa_1, ..., CTa_m + /// \________ ________/ + /// \/ + /// `n = buckets - 1`, i.e. `RawTableInner::buckets() - 1` + /// + /// where: T0...T_n - our stored data; + /// CT0...CT_n - control bytes or metadata for `data`. + /// CTa_0...CTa_m - additional control bytes, where `m = Group::WIDTH - 1` (so that the search + /// with loading `Group` bytes from the heap works properly, even if the result + /// of `h1(hash) & self.bucket_mask` is equal to `self.bucket_mask`). See also + /// `RawTableInner::set_ctrl` function. + /// + /// P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.buckets()` because the number + /// of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + /// ``` + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + fn data_end(&self) -> NonNull { + self.ctrl.cast() + } + + /// Returns an iterator-like object for a probe sequence on the table. + /// + /// This iterator never terminates, but is guaranteed to visit each bucket + /// group exactly once. The loop using `probe_seq` must terminate upon + /// reaching a group containing an empty bucket. + #[inline] + fn probe_seq(&self, hash: u64) -> ProbeSeq { + ProbeSeq { + // This is the same as `hash as usize % self.buckets()` because the number + // of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + pos: h1(hash) & self.bucket_mask, + stride: 0, + } + } + + #[inline] + unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { + self.growth_left -= usize::from(special_is_empty(old_ctrl)); + self.set_ctrl_h2(index, hash); + self.items += 1; + } + + #[inline] + fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { + let probe_seq_pos = self.probe_seq(hash).pos; + let probe_index = + |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; + probe_index(i) == probe_index(new_i) + } + + /// Sets a control byte to the hash, and possibly also the replicated control byte at + /// the end of the array. + /// + /// This function does not make any changes to the `data` parts of the table, + /// or any changes to the `items` or `growth_left` field of the table. + /// + /// # Safety + /// + /// The safety rules are directly derived from the safety rules for [`RawTableInner::set_ctrl`] + /// method. Thus, in order to uphold the safety contracts for the method, you must observe the + /// following rules when calling this function: + /// + /// * The [`RawTableInner`] has already been allocated; + /// + /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e. + /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must + /// be no greater than the number returned by the function [`RawTableInner::buckets`]. + /// + /// Calling this function on a table that has not been allocated results in [`undefined behavior`]. + /// + /// See also [`Bucket::as_ptr`] method, for more information about of properly removing + /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`]. + /// + /// [`RawTableInner::set_ctrl`]: RawTableInner::set_ctrl + /// [`RawTableInner::buckets`]: RawTableInner::buckets + /// [`Bucket::as_ptr`]: Bucket::as_ptr + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn set_ctrl_h2(&mut self, index: usize, hash: u64) { + // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::set_ctrl_h2`] + self.set_ctrl(index, h2(hash)); + } + + /// Replaces the hash in the control byte at the given index with the provided one, + /// and possibly also replicates the new control byte at the end of the array of control + /// bytes, returning the old control byte. + /// + /// This function does not make any changes to the `data` parts of the table, + /// or any changes to the `items` or `growth_left` field of the table. + /// + /// # Safety + /// + /// The safety rules are directly derived from the safety rules for [`RawTableInner::set_ctrl_h2`] + /// and [`RawTableInner::ctrl`] methods. Thus, in order to uphold the safety contracts for both + /// methods, you must observe the following rules when calling this function: + /// + /// * The [`RawTableInner`] has already been allocated; + /// + /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e. + /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must + /// be no greater than the number returned by the function [`RawTableInner::buckets`]. + /// + /// Calling this function on a table that has not been allocated results in [`undefined behavior`]. + /// + /// See also [`Bucket::as_ptr`] method, for more information about of properly removing + /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`]. + /// + /// [`RawTableInner::set_ctrl_h2`]: RawTableInner::set_ctrl_h2 + /// [`RawTableInner::buckets`]: RawTableInner::buckets + /// [`Bucket::as_ptr`]: Bucket::as_ptr + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn replace_ctrl_h2(&mut self, index: usize, hash: u64) -> u8 { + // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::replace_ctrl_h2`] + let prev_ctrl = *self.ctrl(index); + self.set_ctrl_h2(index, hash); + prev_ctrl + } + + /// Sets a control byte, and possibly also the replicated control byte at + /// the end of the array. + /// + /// This function does not make any changes to the `data` parts of the table, + /// or any changes to the `items` or `growth_left` field of the table. + /// + /// # Safety + /// + /// You must observe the following safety rules when calling this function: + /// + /// * The [`RawTableInner`] has already been allocated; + /// + /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e. + /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must + /// be no greater than the number returned by the function [`RawTableInner::buckets`]. + /// + /// Calling this function on a table that has not been allocated results in [`undefined behavior`]. + /// + /// See also [`Bucket::as_ptr`] method, for more information about of properly removing + /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`]. + /// + /// [`RawTableInner::buckets`]: RawTableInner::buckets + /// [`Bucket::as_ptr`]: Bucket::as_ptr + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn set_ctrl(&mut self, index: usize, ctrl: u8) { + // Replicate the first Group::WIDTH control bytes at the end of + // the array without using a branch. If the tables smaller than + // the group width (self.buckets() < Group::WIDTH), + // `index2 = Group::WIDTH + index`, otherwise `index2` is: + // + // - If index >= Group::WIDTH then index == index2. + // - Otherwise index2 == self.bucket_mask + 1 + index. + // + // The very last replicated control byte is never actually read because + // we mask the initial index for unaligned loads, but we write it + // anyways because it makes the set_ctrl implementation simpler. + // + // If there are fewer buckets than Group::WIDTH then this code will + // replicate the buckets at the end of the trailing group. For example + // with 2 buckets and a group size of 4, the control bytes will look + // like this: + // + // Real | Replicated + // --------------------------------------------- + // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | + // --------------------------------------------- + + // This is the same as `(index.wrapping_sub(Group::WIDTH)) % self.buckets() + Group::WIDTH` + // because the number of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; + + // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::set_ctrl`] + *self.ctrl(index) = ctrl; + *self.ctrl(index2) = ctrl; + } + + /// Returns a pointer to a control byte. + /// + /// # Safety + /// + /// For the allocated [`RawTableInner`], the result is [`Undefined Behavior`], + /// if the `index` is greater than the `self.bucket_mask + 1 + Group::WIDTH`. + /// In that case, calling this function with `index == self.bucket_mask + 1 + Group::WIDTH` + /// will return a pointer to the end of the allocated table and it is useless on its own. + /// + /// Calling this function with `index >= self.bucket_mask + 1 + Group::WIDTH` on a + /// table that has not been allocated results in [`Undefined Behavior`]. + /// + /// So to satisfy both requirements you should always follow the rule that + /// `index < self.bucket_mask + 1 + Group::WIDTH` + /// + /// Calling this function on [`RawTableInner`] that are not already allocated is safe + /// for read-only purpose. + /// + /// See also [`Bucket::as_ptr()`] method, for more information about of properly removing + /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`]. + /// + /// [`Bucket::as_ptr()`]: Bucket::as_ptr() + /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn ctrl(&self, index: usize) -> *mut u8 { + debug_assert!(index < self.num_ctrl_bytes()); + // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::ctrl`] + self.ctrl.as_ptr().add(index) + } + + #[inline] + fn buckets(&self) -> usize { + self.bucket_mask + 1 + } + + /// Checks whether the bucket at `index` is full. + /// + /// # Safety + /// + /// The caller must ensure `index` is less than the number of buckets. + #[inline] + unsafe fn is_bucket_full(&self, index: usize) -> bool { + debug_assert!(index < self.buckets()); + is_full(*self.ctrl(index)) + } + + #[inline] + fn num_ctrl_bytes(&self) -> usize { + self.bucket_mask + 1 + Group::WIDTH + } + + #[inline] + fn is_empty_singleton(&self) -> bool { + self.bucket_mask == 0 + } + + /// Attempts to allocate a new hash table with at least enough capacity + /// for inserting the given number of elements without reallocating, + /// and return it inside `ScopeGuard` to protect against panic in the hash + /// function. + /// + /// # Note + /// + /// It is recommended (but not required): + /// + /// * That the new table's `capacity` be greater than or equal to `self.items`. + /// + /// * The `alloc` is the same [`Allocator`] as the `Allocator` used + /// to allocate this table. + /// + /// * The `table_layout` is the same [`TableLayout`] as the `TableLayout` used + /// to allocate this table. + /// + /// If `table_layout` does not match the `TableLayout` that was used to allocate + /// this table, then using `mem::swap` with the `self` and the new table returned + /// by this function results in [`undefined behavior`]. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[allow(clippy::mut_mut)] + #[inline] + fn prepare_resize<'a, A>( + &self, + alloc: &'a A, + table_layout: TableLayout, + capacity: usize, + fallibility: Fallibility, + ) -> Result, TryReserveError> + where + A: Allocator, + { + debug_assert!(self.items <= capacity); + + // Allocate and initialize the new table. + let new_table = + RawTableInner::fallible_with_capacity(alloc, table_layout, capacity, fallibility)?; + + // The hash function may panic, in which case we simply free the new + // table without dropping any elements that may have been copied into + // it. + // + // This guard is also used to free the old table on success, see + // the comment at the bottom of this function. + Ok(guard(new_table, move |self_| { + if !self_.is_empty_singleton() { + // SAFETY: + // 1. We have checked that our table is allocated. + // 2. We know for sure that the `alloc` and `table_layout` matches the + // [`Allocator`] and [`TableLayout`] used to allocate this table. + unsafe { self_.free_buckets(alloc, table_layout) }; + } + })) + } + + /// Reserves or rehashes to make room for `additional` more elements. + /// + /// This uses dynamic dispatch to reduce the amount of + /// code generated, but it is eliminated by LLVM optimizations when inlined. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is + /// [`undefined behavior`]: + /// + /// * The `alloc` must be the same [`Allocator`] as the `Allocator` used + /// to allocate this table. + /// + /// * The `layout` must be the same [`TableLayout`] as the `TableLayout` + /// used to allocate this table. + /// + /// * The `drop` function (`fn(*mut u8)`) must be the actual drop function of + /// the elements stored in the table. + /// + /// * The [`RawTableInner`] must have properly initialized control bytes. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[allow(clippy::inline_always)] + #[inline(always)] + unsafe fn reserve_rehash_inner( + &mut self, + alloc: &A, + additional: usize, + hasher: &dyn Fn(&mut Self, usize) -> u64, + fallibility: Fallibility, + layout: TableLayout, + drop: Option, + ) -> Result<(), TryReserveError> + where + A: Allocator, + { + // Avoid `Option::ok_or_else` because it bloats LLVM IR. + let new_items = match self.items.checked_add(additional) { + Some(new_items) => new_items, + None => return Err(fallibility.capacity_overflow()), + }; + let full_capacity = bucket_mask_to_capacity(self.bucket_mask); + if new_items <= full_capacity / 2 { + // Rehash in-place without re-allocating if we have plenty of spare + // capacity that is locked up due to DELETED entries. + + // SAFETY: + // 1. We know for sure that `[`RawTableInner`]` has already been allocated + // (since new_items <= full_capacity / 2); + // 2. The caller ensures that `drop` function is the actual drop function of + // the elements stored in the table. + // 3. The caller ensures that `layout` matches the [`TableLayout`] that was + // used to allocate this table. + // 4. The caller ensures that the control bytes of the `RawTableInner` + // are already initialized. + self.rehash_in_place(hasher, layout.size, drop); + Ok(()) + } else { + // Otherwise, conservatively resize to at least the next size up + // to avoid churning deletes into frequent rehashes. + // + // SAFETY: + // 1. We know for sure that `capacity >= self.items`. + // 2. The caller ensures that `alloc` and `layout` matches the [`Allocator`] and + // [`TableLayout`] that were used to allocate this table. + // 3. The caller ensures that the control bytes of the `RawTableInner` + // are already initialized. + self.resize_inner( + alloc, + usize::max(new_items, full_capacity + 1), + hasher, + fallibility, + layout, + ) + } + } + + /// Returns an iterator over full buckets indices in the table. + /// + /// # Safety + /// + /// Behavior is undefined if any of the following conditions are violated: + /// + /// * The caller has to ensure that the `RawTableInner` outlives the + /// `FullBucketsIndices`. Because we cannot make the `next` method + /// unsafe on the `FullBucketsIndices` struct, we have to make the + /// `full_buckets_indices` method unsafe. + /// + /// * The [`RawTableInner`] must have properly initialized control bytes. + #[inline(always)] + unsafe fn full_buckets_indices(&self) -> FullBucketsIndices { + // SAFETY: + // 1. Since the caller of this function ensures that the control bytes + // are properly initialized and `self.ctrl(0)` points to the start + // of the array of control bytes, therefore: `ctrl` is valid for reads, + // properly aligned to `Group::WIDTH` and points to the properly initialized + // control bytes. + // 2. The value of `items` is equal to the amount of data (values) added + // to the table. + // + // `ctrl` points here (to the start + // of the first control byte `CT0`) + // ∨ + // [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, Group::WIDTH + // \________ ________/ + // \/ + // `n = buckets - 1`, i.e. `RawTableInner::buckets() - 1` + // + // where: T0...T_n - our stored data; + // CT0...CT_n - control bytes or metadata for `data`. + let ctrl = NonNull::new_unchecked(self.ctrl(0)); + + FullBucketsIndices { + // Load the first group + // SAFETY: See explanation above. + current_group: Group::load_aligned(ctrl.as_ptr()).match_full().into_iter(), + group_first_index: 0, + ctrl, + items: self.items, + } + } + + /// Allocates a new table of a different size and moves the contents of the + /// current table into it. + /// + /// This uses dynamic dispatch to reduce the amount of + /// code generated, but it is eliminated by LLVM optimizations when inlined. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is + /// [`undefined behavior`]: + /// + /// * The `alloc` must be the same [`Allocator`] as the `Allocator` used + /// to allocate this table; + /// + /// * The `layout` must be the same [`TableLayout`] as the `TableLayout` + /// used to allocate this table; + /// + /// * The [`RawTableInner`] must have properly initialized control bytes. + /// + /// The caller of this function must ensure that `capacity >= self.items` + /// otherwise: + /// + /// * If `self.items != 0`, calling of this function with `capacity == 0` + /// results in [`undefined behavior`]. + /// + /// * If `capacity_to_buckets(capacity) < Group::WIDTH` and + /// `self.items > capacity_to_buckets(capacity)` calling this function + /// results in [`undefined behavior`]. + /// + /// * If `capacity_to_buckets(capacity) >= Group::WIDTH` and + /// `self.items > capacity_to_buckets(capacity)` calling this function + /// are never return (will go into an infinite loop). + /// + /// Note: It is recommended (but not required) that the new table's `capacity` + /// be greater than or equal to `self.items`. In case if `capacity <= self.items` + /// this function can never return. See [`RawTableInner::find_insert_slot`] for + /// more information. + /// + /// [`RawTableInner::find_insert_slot`]: RawTableInner::find_insert_slot + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[allow(clippy::inline_always)] + #[inline(always)] + unsafe fn resize_inner( + &mut self, + alloc: &A, + capacity: usize, + hasher: &dyn Fn(&mut Self, usize) -> u64, + fallibility: Fallibility, + layout: TableLayout, + ) -> Result<(), TryReserveError> + where + A: Allocator, + { + // SAFETY: We know for sure that `alloc` and `layout` matches the [`Allocator`] and [`TableLayout`] + // that were used to allocate this table. + let mut new_table = self.prepare_resize(alloc, layout, capacity, fallibility)?; + + // SAFETY: We know for sure that RawTableInner will outlive the + // returned `FullBucketsIndices` iterator, and the caller of this + // function ensures that the control bytes are properly initialized. + for full_byte_index in self.full_buckets_indices() { + // This may panic. + let hash = hasher(self, full_byte_index); + + // SAFETY: + // We can use a simpler version of insert() here since: + // 1. There are no DELETED entries. + // 2. We know there is enough space in the table. + // 3. All elements are unique. + // 4. The caller of this function guarantees that `capacity > 0` + // so `new_table` must already have some allocated memory. + // 5. We set `growth_left` and `items` fields of the new table + // after the loop. + // 6. We insert into the table, at the returned index, the data + // matching the given hash immediately after calling this function. + let (new_index, _) = new_table.prepare_insert_slot(hash); + + // SAFETY: + // + // * `src` is valid for reads of `layout.size` bytes, since the + // table is alive and the `full_byte_index` is guaranteed to be + // within bounds (see `FullBucketsIndices::next_impl`); + // + // * `dst` is valid for writes of `layout.size` bytes, since the + // caller ensures that `table_layout` matches the [`TableLayout`] + // that was used to allocate old table and we have the `new_index` + // returned by `prepare_insert_slot`. + // + // * Both `src` and `dst` are properly aligned. + // + // * Both `src` and `dst` point to different region of memory. + ptr::copy_nonoverlapping( + self.bucket_ptr(full_byte_index, layout.size), + new_table.bucket_ptr(new_index, layout.size), + layout.size, + ); + } + + // The hash function didn't panic, so we can safely set the + // `growth_left` and `items` fields of the new table. + new_table.growth_left -= self.items; + new_table.items = self.items; + + // We successfully copied all elements without panicking. Now replace + // self with the new table. The old table will have its memory freed but + // the items will not be dropped (since they have been moved into the + // new table). + // SAFETY: The caller ensures that `table_layout` matches the [`TableLayout`] + // that was used to allocate this table. + mem::swap(self, &mut new_table); + + Ok(()) + } + + /// Rehashes the contents of the table in place (i.e. without changing the + /// allocation). + /// + /// If `hasher` panics then some the table's contents may be lost. + /// + /// This uses dynamic dispatch to reduce the amount of + /// code generated, but it is eliminated by LLVM optimizations when inlined. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is [`undefined behavior`]: + /// + /// * The `size_of` must be equal to the size of the elements stored in the table; + /// + /// * The `drop` function (`fn(*mut u8)`) must be the actual drop function of + /// the elements stored in the table. + /// + /// * The [`RawTableInner`] has already been allocated; + /// + /// * The [`RawTableInner`] must have properly initialized control bytes. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[allow(clippy::inline_always)] + #[cfg_attr(feature = "inline-more", inline(always))] + #[cfg_attr(not(feature = "inline-more"), inline)] + unsafe fn rehash_in_place( + &mut self, + hasher: &dyn Fn(&mut Self, usize) -> u64, + size_of: usize, + drop: Option, + ) { + // If the hash function panics then properly clean up any elements + // that we haven't rehashed yet. We unfortunately can't preserve the + // element since we lost their hash and have no way of recovering it + // without risking another panic. + self.prepare_rehash_in_place(); + + let mut guard = guard(self, move |self_| { + if let Some(drop) = drop { + for i in 0..self_.buckets() { + if *self_.ctrl(i) == DELETED { + self_.set_ctrl(i, EMPTY); + drop(self_.bucket_ptr(i, size_of)); + self_.items -= 1; + } + } + } + self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items; + }); + + // At this point, DELETED elements are elements that we haven't + // rehashed yet. Find them and re-insert them at their ideal + // position. + 'outer: for i in 0..guard.buckets() { + if *guard.ctrl(i) != DELETED { + continue; + } + + let i_p = guard.bucket_ptr(i, size_of); + + 'inner: loop { + // Hash the current item + let hash = hasher(*guard, i); + + // Search for a suitable place to put it + // + // SAFETY: Caller of this function ensures that the control bytes + // are properly initialized. + let new_i = guard.find_insert_slot(hash).index; + + // Probing works by scanning through all of the control + // bytes in groups, which may not be aligned to the group + // size. If both the new and old position fall within the + // same unaligned group, then there is no benefit in moving + // it and we can just continue to the next item. + if likely(guard.is_in_same_group(i, new_i, hash)) { + guard.set_ctrl_h2(i, hash); + continue 'outer; + } + + let new_i_p = guard.bucket_ptr(new_i, size_of); + + // We are moving the current item to a new position. Write + // our H2 to the control byte of the new position. + let prev_ctrl = guard.replace_ctrl_h2(new_i, hash); + if prev_ctrl == EMPTY { + guard.set_ctrl(i, EMPTY); + // If the target slot is empty, simply move the current + // element into the new slot and clear the old control + // byte. + ptr::copy_nonoverlapping(i_p, new_i_p, size_of); + continue 'outer; + } else { + // If the target slot is occupied, swap the two elements + // and then continue processing the element that we just + // swapped into the old slot. + debug_assert_eq!(prev_ctrl, DELETED); + ptr::swap_nonoverlapping(i_p, new_i_p, size_of); + continue 'inner; + } + } + } + + guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items; + + mem::forget(guard); + } + + /// Deallocates the table without dropping any entries. + /// + /// # Note + /// + /// This function must be called only after [`drop_elements`](RawTableInner::drop_elements), + /// else it can lead to leaking of memory. Also calling this function automatically + /// makes invalid (dangling) all instances of buckets ([`Bucket`]) and makes invalid + /// (dangling) the `ctrl` field of the table. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is [`Undefined Behavior`]: + /// + /// * The [`RawTableInner`] has already been allocated; + /// + /// * The `alloc` must be the same [`Allocator`] as the `Allocator` that was used + /// to allocate this table. + /// + /// * The `table_layout` must be the same [`TableLayout`] as the `TableLayout` that was used + /// to allocate this table. + /// + /// See also [`GlobalAlloc::dealloc`] or [`Allocator::deallocate`] for more information. + /// + /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + /// [`GlobalAlloc::dealloc`]: https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc + /// [`Allocator::deallocate`]: https://doc.rust-lang.org/alloc/alloc/trait.Allocator.html#tymethod.deallocate + #[inline] + unsafe fn free_buckets(&mut self, alloc: &A, table_layout: TableLayout) + where + A: Allocator, + { + // SAFETY: The caller must uphold the safety contract for `free_buckets` + // method. + let (ptr, layout) = self.allocation_info(table_layout); + alloc.deallocate(ptr, layout); + } + + /// Returns a pointer to the allocated memory and the layout that was used to + /// allocate the table. + /// + /// # Safety + /// + /// Caller of this function must observe the following safety rules: + /// + /// * The [`RawTableInner`] has already been allocated, otherwise + /// calling this function results in [`undefined behavior`] + /// + /// * The `table_layout` must be the same [`TableLayout`] as the `TableLayout` + /// that was used to allocate this table. Failure to comply with this condition + /// may result in [`undefined behavior`]. + /// + /// See also [`GlobalAlloc::dealloc`] or [`Allocator::deallocate`] for more information. + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + /// [`GlobalAlloc::dealloc`]: https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc + /// [`Allocator::deallocate`]: https://doc.rust-lang.org/alloc/alloc/trait.Allocator.html#tymethod.deallocate + #[inline] + unsafe fn allocation_info(&self, table_layout: TableLayout) -> (NonNull, Layout) { + debug_assert!( + !self.is_empty_singleton(), + "this function can only be called on non-empty tables" + ); + + // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. + let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { + Some(lco) => lco, + None => unsafe { hint::unreachable_unchecked() }, + }; + ( + // SAFETY: The caller must uphold the safety contract for `allocation_info` method. + unsafe { NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)) }, + layout, + ) + } + + /// Returns the total amount of memory allocated internally by the hash + /// table, in bytes. + /// + /// The returned number is informational only. It is intended to be + /// primarily used for memory profiling. + /// + /// # Safety + /// + /// The `table_layout` must be the same [`TableLayout`] as the `TableLayout` + /// that was used to allocate this table. Failure to comply with this condition + /// may result in [`undefined behavior`]. + /// + /// + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn allocation_size_or_zero(&self, table_layout: TableLayout) -> usize { + if self.is_empty_singleton() { + 0 + } else { + // SAFETY: + // 1. We have checked that our table is allocated. + // 2. The caller ensures that `table_layout` matches the [`TableLayout`] + // that was used to allocate this table. + unsafe { self.allocation_info(table_layout).1.size() } + } + } + + /// Marks all table buckets as empty without dropping their contents. + #[inline] + fn clear_no_drop(&mut self) { + if !self.is_empty_singleton() { + unsafe { + self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); + } + } + self.items = 0; + self.growth_left = bucket_mask_to_capacity(self.bucket_mask); + } + + /// Erases the [`Bucket`]'s control byte at the given index so that it does not + /// triggered as full, decreases the `items` of the table and, if it can be done, + /// increases `self.growth_left`. + /// + /// This function does not actually erase / drop the [`Bucket`] itself, i.e. it + /// does not make any changes to the `data` parts of the table. The caller of this + /// function must take care to properly drop the `data`, otherwise calling this + /// function may result in a memory leak. + /// + /// # Safety + /// + /// You must observe the following safety rules when calling this function: + /// + /// * The [`RawTableInner`] has already been allocated; + /// + /// * It must be the full control byte at the given position; + /// + /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e. + /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must + /// be no greater than the number returned by the function [`RawTableInner::buckets`]. + /// + /// Calling this function on a table that has not been allocated results in [`undefined behavior`]. + /// + /// Calling this function on a table with no elements is unspecified, but calling subsequent + /// functions is likely to result in [`undefined behavior`] due to overflow subtraction + /// (`self.items -= 1 cause overflow when self.items == 0`). + /// + /// See also [`Bucket::as_ptr`] method, for more information about of properly removing + /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`]. + /// + /// [`RawTableInner::buckets`]: RawTableInner::buckets + /// [`Bucket::as_ptr`]: Bucket::as_ptr + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline] + unsafe fn erase(&mut self, index: usize) { + debug_assert!(self.is_bucket_full(index)); + + // This is the same as `index.wrapping_sub(Group::WIDTH) % self.buckets()` because + // the number of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`. + let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask; + // SAFETY: + // - The caller must uphold the safety contract for `erase` method; + // - `index_before` is guaranteed to be in range due to masking with `self.bucket_mask` + let empty_before = Group::load(self.ctrl(index_before)).match_empty(); + let empty_after = Group::load(self.ctrl(index)).match_empty(); + + // Inserting and searching in the map is performed by two key functions: + // + // - The `find_insert_slot` function that looks up the index of any `EMPTY` or `DELETED` + // slot in a group to be able to insert. If it doesn't find an `EMPTY` or `DELETED` + // slot immediately in the first group, it jumps to the next `Group` looking for it, + // and so on until it has gone through all the groups in the control bytes. + // + // - The `find_inner` function that looks for the index of the desired element by looking + // at all the `FULL` bytes in the group. If it did not find the element right away, and + // there is no `EMPTY` byte in the group, then this means that the `find_insert_slot` + // function may have found a suitable slot in the next group. Therefore, `find_inner` + // jumps further, and if it does not find the desired element and again there is no `EMPTY` + // byte, then it jumps further, and so on. The search stops only if `find_inner` function + // finds the desired element or hits an `EMPTY` slot/byte. + // + // Accordingly, this leads to two consequences: + // + // - The map must have `EMPTY` slots (bytes); + // + // - You can't just mark the byte to be erased as `EMPTY`, because otherwise the `find_inner` + // function may stumble upon an `EMPTY` byte before finding the desired element and stop + // searching. + // + // Thus it is necessary to check all bytes after and before the erased element. If we are in + // a contiguous `Group` of `FULL` or `DELETED` bytes (the number of `FULL` or `DELETED` bytes + // before and after is greater than or equal to `Group::WIDTH`), then we must mark our byte as + // `DELETED` in order for the `find_inner` function to go further. On the other hand, if there + // is at least one `EMPTY` slot in the `Group`, then the `find_inner` function will still stumble + // upon an `EMPTY` byte, so we can safely mark our erased byte as `EMPTY` as well. + // + // Finally, since `index_before == (index.wrapping_sub(Group::WIDTH) & self.bucket_mask) == index` + // and given all of the above, tables smaller than the group width (self.buckets() < Group::WIDTH) + // cannot have `DELETED` bytes. + // + // Note that in this context `leading_zeros` refers to the bytes at the end of a group, while + // `trailing_zeros` refers to the bytes at the beginning of a group. + let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { + DELETED + } else { + self.growth_left += 1; + EMPTY + }; + // SAFETY: the caller must uphold the safety contract for `erase` method. + self.set_ctrl(index, ctrl); + self.items -= 1; + } +} + +impl Clone for RawTable { + fn clone(&self) -> Self { + if self.table.is_empty_singleton() { + Self::new_in(self.alloc.clone()) + } else { + unsafe { + // Avoid `Result::ok_or_else` because it bloats LLVM IR. + // + // SAFETY: This is safe as we are taking the size of an already allocated table + // and therefore capacity overflow cannot occur, `self.table.buckets()` is power + // of two and all allocator errors will be caught inside `RawTableInner::new_uninitialized`. + let mut new_table = match Self::new_uninitialized( + self.alloc.clone(), + self.table.buckets(), + Fallibility::Infallible, + ) { + Ok(table) => table, + Err(_) => hint::unreachable_unchecked(), + }; + + // Cloning elements may fail (the clone function may panic). But we don't + // need to worry about uninitialized control bits, since: + // 1. The number of items (elements) in the table is zero, which means that + // the control bits will not be read by Drop function. + // 2. The `clone_from_spec` method will first copy all control bits from + // `self` (thus initializing them). But this will not affect the `Drop` + // function, since the `clone_from_spec` function sets `items` only after + // successfully cloning all elements. + new_table.clone_from_spec(self); + new_table + } + } + } + + fn clone_from(&mut self, source: &Self) { + if source.table.is_empty_singleton() { + let mut old_inner = mem::replace(&mut self.table, RawTableInner::NEW); + unsafe { + // SAFETY: + // 1. We call the function only once; + // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`] + // and [`TableLayout`] that were used to allocate this table. + // 3. If any elements' drop function panics, then there will only be a memory leak, + // because we have replaced the inner table with a new one. + old_inner.drop_inner_table::(&self.alloc, Self::TABLE_LAYOUT); + } + } else { + unsafe { + // Make sure that if any panics occurs, we clear the table and + // leave it in an empty state. + let mut self_ = guard(self, |self_| { + self_.clear_no_drop(); + }); + + // First, drop all our elements without clearing the control + // bytes. If this panics then the scope guard will clear the + // table, leaking any elements that were not dropped yet. + // + // This leak is unavoidable: we can't try dropping more elements + // since this could lead to another panic and abort the process. + // + // SAFETY: If something gets wrong we clear our table right after + // dropping the elements, so there is no double drop, since `items` + // will be equal to zero. + self_.table.drop_elements::(); + + // If necessary, resize our table to match the source. + if self_.buckets() != source.buckets() { + let new_inner = match RawTableInner::new_uninitialized( + &self_.alloc, + Self::TABLE_LAYOUT, + source.buckets(), + Fallibility::Infallible, + ) { + Ok(table) => table, + Err(_) => hint::unreachable_unchecked(), + }; + // Replace the old inner with new uninitialized one. It's ok, since if something gets + // wrong `ScopeGuard` will initialize all control bytes and leave empty table. + let mut old_inner = mem::replace(&mut self_.table, new_inner); + if !old_inner.is_empty_singleton() { + // SAFETY: + // 1. We have checked that our table is allocated. + // 2. We know for sure that `alloc` and `table_layout` matches + // the [`Allocator`] and [`TableLayout`] that were used to allocate this table. + old_inner.free_buckets(&self_.alloc, Self::TABLE_LAYOUT); + } + } + + // Cloning elements may fail (the clone function may panic), but the `ScopeGuard` + // inside the `clone_from_impl` function will take care of that, dropping all + // cloned elements if necessary. Our `ScopeGuard` will clear the table. + self_.clone_from_spec(source); + + // Disarm the scope guard if cloning was successful. + ScopeGuard::into_inner(self_); + } + } + } +} + +/// Specialization of `clone_from` for `Copy` types +trait RawTableClone { + unsafe fn clone_from_spec(&mut self, source: &Self); +} +impl RawTableClone for RawTable { + default_fn! { + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn clone_from_spec(&mut self, source: &Self) { + self.clone_from_impl(source); + } + } +} +#[cfg(feature = "nightly")] +impl RawTableClone for RawTable { + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn clone_from_spec(&mut self, source: &Self) { + source + .table + .ctrl(0) + .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); + source + .data_start() + .as_ptr() + .copy_to_nonoverlapping(self.data_start().as_ptr(), self.table.buckets()); + + self.table.items = source.table.items; + self.table.growth_left = source.table.growth_left; + } +} + +impl RawTable { + /// Common code for `clone` and `clone_from`. Assumes: + /// - `self.buckets() == source.buckets()`. + /// - Any existing elements have been dropped. + /// - The control bytes are not initialized yet. + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn clone_from_impl(&mut self, source: &Self) { + // Copy the control bytes unchanged. We do this in a single pass + source + .table + .ctrl(0) + .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); + + // The cloning of elements may panic, in which case we need + // to make sure we drop only the elements that have been + // cloned so far. + let mut guard = guard((0, &mut *self), |(index, self_)| { + if T::NEEDS_DROP { + for i in 0..*index { + if self_.is_bucket_full(i) { + self_.bucket(i).drop(); + } + } + } + }); + + for from in source.iter() { + let index = source.bucket_index(&from); + let to = guard.1.bucket(index); + to.write(from.as_ref().clone()); + + // Update the index in case we need to unwind. + guard.0 = index + 1; + } + + // Successfully cloned all items, no need to clean up. + mem::forget(guard); + + self.table.items = source.table.items; + self.table.growth_left = source.table.growth_left; + } +} + +impl Default for RawTable { + #[inline] + fn default() -> Self { + Self::new_in(Default::default()) + } +} + +#[cfg(feature = "nightly")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawTable { + #[cfg_attr(feature = "inline-more", inline)] + fn drop(&mut self) { + unsafe { + // SAFETY: + // 1. We call the function only once; + // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`] + // and [`TableLayout`] that were used to allocate this table. + // 3. If the drop function of any elements fails, then only a memory leak will occur, + // and we don't care because we are inside the `Drop` function of the `RawTable`, + // so there won't be any table left in an inconsistent state. + self.table + .drop_inner_table::(&self.alloc, Self::TABLE_LAYOUT); + } + } +} +#[cfg(not(feature = "nightly"))] +impl Drop for RawTable { + #[cfg_attr(feature = "inline-more", inline)] + fn drop(&mut self) { + unsafe { + // SAFETY: + // 1. We call the function only once; + // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`] + // and [`TableLayout`] that were used to allocate this table. + // 3. If the drop function of any elements fails, then only a memory leak will occur, + // and we don't care because we are inside the `Drop` function of the `RawTable`, + // so there won't be any table left in an inconsistent state. + self.table + .drop_inner_table::(&self.alloc, Self::TABLE_LAYOUT); + } + } +} + +impl IntoIterator for RawTable { + type Item = T; + type IntoIter = RawIntoIter; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_iter(self) -> RawIntoIter { + unsafe { + let iter = self.iter(); + self.into_iter_from(iter) + } + } +} + +/// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does +/// not track an item count. +pub(crate) struct RawIterRange { + // Mask of full buckets in the current group. Bits are cleared from this + // mask as each element is processed. + current_group: BitMaskIter, + + // Pointer to the buckets for the current group. + data: Bucket, + + // Pointer to the next group of control bytes, + // Must be aligned to the group size. + next_ctrl: *const u8, + + // Pointer one past the last control byte of this range. + end: *const u8, +} + +impl RawIterRange { + /// Returns a `RawIterRange` covering a subset of a table. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is + /// [`undefined behavior`]: + /// + /// * `ctrl` must be [valid] for reads, i.e. table outlives the `RawIterRange`; + /// + /// * `ctrl` must be properly aligned to the group size (`Group::WIDTH`); + /// + /// * `ctrl` must point to the array of properly initialized control bytes; + /// + /// * `data` must be the [`Bucket`] at the `ctrl` index in the table; + /// + /// * the value of `len` must be less than or equal to the number of table buckets, + /// and the returned value of `ctrl.as_ptr().add(len).offset_from(ctrl.as_ptr())` + /// must be positive. + /// + /// * The `ctrl.add(len)` pointer must be either in bounds or one + /// byte past the end of the same [allocated table]. + /// + /// * The `len` must be a power of two. + /// + /// [valid]: https://doc.rust-lang.org/std/ptr/index.html#safety + /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn new(ctrl: *const u8, data: Bucket, len: usize) -> Self { + debug_assert_ne!(len, 0); + debug_assert_eq!(ctrl as usize % Group::WIDTH, 0); + // SAFETY: The caller must uphold the safety rules for the [`RawIterRange::new`] + let end = ctrl.add(len); + + // Load the first group and advance ctrl to point to the next group + // SAFETY: The caller must uphold the safety rules for the [`RawIterRange::new`] + let current_group = Group::load_aligned(ctrl).match_full(); + let next_ctrl = ctrl.add(Group::WIDTH); + + Self { + current_group: current_group.into_iter(), + data, + next_ctrl, + end, + } + } + + /// Splits a `RawIterRange` into two halves. + /// + /// Returns `None` if the remaining range is smaller than or equal to the + /// group width. + #[cfg_attr(feature = "inline-more", inline)] + #[cfg(feature = "rayon")] + pub(crate) fn split(mut self) -> (Self, Option>) { + unsafe { + if self.end <= self.next_ctrl { + // Nothing to split if the group that we are current processing + // is the last one. + (self, None) + } else { + // len is the remaining number of elements after the group that + // we are currently processing. It must be a multiple of the + // group size (small tables are caught by the check above). + let len = offset_from(self.end, self.next_ctrl); + debug_assert_eq!(len % Group::WIDTH, 0); + + // Split the remaining elements into two halves, but round the + // midpoint down in case there is an odd number of groups + // remaining. This ensures that: + // - The tail is at least 1 group long. + // - The split is roughly even considering we still have the + // current group to process. + let mid = (len / 2) & !(Group::WIDTH - 1); + + let tail = Self::new( + self.next_ctrl.add(mid), + self.data.next_n(Group::WIDTH).next_n(mid), + len - mid, + ); + debug_assert_eq!( + self.data.next_n(Group::WIDTH).next_n(mid).ptr, + tail.data.ptr + ); + debug_assert_eq!(self.end, tail.end); + self.end = self.next_ctrl.add(mid); + debug_assert_eq!(self.end.add(Group::WIDTH), tail.next_ctrl); + (self, Some(tail)) + } + } + } + + /// # Safety + /// If `DO_CHECK_PTR_RANGE` is false, caller must ensure that we never try to iterate + /// after yielding all elements. + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn next_impl(&mut self) -> Option> { + loop { + if let Some(index) = self.current_group.next() { + return Some(self.data.next_n(index)); + } + + if DO_CHECK_PTR_RANGE && self.next_ctrl >= self.end { + return None; + } + + // We might read past self.end up to the next group boundary, + // but this is fine because it only occurs on tables smaller + // than the group size where the trailing control bytes are all + // EMPTY. On larger tables self.end is guaranteed to be aligned + // to the group size (since tables are power-of-two sized). + self.current_group = Group::load_aligned(self.next_ctrl).match_full().into_iter(); + self.data = self.data.next_n(Group::WIDTH); + self.next_ctrl = self.next_ctrl.add(Group::WIDTH); + } + } + + /// Folds every element into an accumulator by applying an operation, + /// returning the final result. + /// + /// `fold_impl()` takes three arguments: the number of items remaining in + /// the iterator, an initial value, and a closure with two arguments: an + /// 'accumulator', and an element. The closure returns the value that the + /// accumulator should have for the next iteration. + /// + /// The initial value is the value the accumulator will have on the first call. + /// + /// After applying this closure to every element of the iterator, `fold_impl()` + /// returns the accumulator. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is + /// [`Undefined Behavior`]: + /// + /// * The [`RawTableInner`] / [`RawTable`] must be alive and not moved, + /// i.e. table outlives the `RawIterRange`; + /// + /// * The provided `n` value must match the actual number of items + /// in the table. + /// + /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[allow(clippy::while_let_on_iterator)] + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn fold_impl(mut self, mut n: usize, mut acc: B, mut f: F) -> B + where + F: FnMut(B, Bucket) -> B, + { + loop { + while let Some(index) = self.current_group.next() { + // The returned `index` will always be in the range `0..Group::WIDTH`, + // so that calling `self.data.next_n(index)` is safe (see detailed explanation below). + debug_assert!(n != 0); + let bucket = self.data.next_n(index); + acc = f(acc, bucket); + n -= 1; + } + + if n == 0 { + return acc; + } + + // SAFETY: The caller of this function ensures that: + // + // 1. The provided `n` value matches the actual number of items in the table; + // 2. The table is alive and did not moved. + // + // Taking the above into account, we always stay within the bounds, because: + // + // 1. For tables smaller than the group width (self.buckets() <= Group::WIDTH), + // we will never end up in the given branch, since we should have already + // yielded all the elements of the table. + // + // 2. For tables larger than the group width. The number of buckets is a + // power of two (2 ^ n), Group::WIDTH is also power of two (2 ^ k). Since + // `(2 ^ n) > (2 ^ k)`, than `(2 ^ n) % (2 ^ k) = 0`. As we start from the + // start of the array of control bytes, and never try to iterate after + // getting all the elements, the last `self.current_group` will read bytes + // from the `self.buckets() - Group::WIDTH` index. We know also that + // `self.current_group.next()` will always return indices within the range + // `0..Group::WIDTH`. + // + // Knowing all of the above and taking into account that we are synchronizing + // the `self.data` index with the index we used to read the `self.current_group`, + // the subsequent `self.data.next_n(index)` will always return a bucket with + // an index number less than `self.buckets()`. + // + // The last `self.next_ctrl`, whose index would be `self.buckets()`, will never + // actually be read, since we should have already yielded all the elements of + // the table. + self.current_group = Group::load_aligned(self.next_ctrl).match_full().into_iter(); + self.data = self.data.next_n(Group::WIDTH); + self.next_ctrl = self.next_ctrl.add(Group::WIDTH); + } + } +} + +// We make raw iterators unconditionally Send and Sync, and let the PhantomData +// in the actual iterator implementations determine the real Send/Sync bounds. +unsafe impl Send for RawIterRange {} +unsafe impl Sync for RawIterRange {} + +impl Clone for RawIterRange { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + data: self.data.clone(), + next_ctrl: self.next_ctrl, + current_group: self.current_group, + end: self.end, + } + } +} + +impl Iterator for RawIterRange { + type Item = Bucket; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option> { + unsafe { + // SAFETY: We set checker flag to true. + self.next_impl::() + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + // We don't have an item count, so just guess based on the range size. + let remaining_buckets = if self.end > self.next_ctrl { + unsafe { offset_from(self.end, self.next_ctrl) } + } else { + 0 + }; + + // Add a group width to include the group we are currently processing. + (0, Some(Group::WIDTH + remaining_buckets)) + } +} + +impl FusedIterator for RawIterRange {} + +/// Iterator which returns a raw pointer to every full bucket in the table. +/// +/// For maximum flexibility this iterator is not bound by a lifetime, but you +/// must observe several rules when using it: +/// - You must not free the hash table while iterating (including via growing/shrinking). +/// - It is fine to erase a bucket that has been yielded by the iterator. +/// - Erasing a bucket that has not yet been yielded by the iterator may still +/// result in the iterator yielding that bucket (unless `reflect_remove` is called). +/// - It is unspecified whether an element inserted after the iterator was +/// created will be yielded by that iterator (unless `reflect_insert` is called). +/// - The order in which the iterator yields bucket is unspecified and may +/// change in the future. +pub struct RawIter { + pub(crate) iter: RawIterRange, + items: usize, +} + +impl RawIter { + unsafe fn drop_elements(&mut self) { + if T::NEEDS_DROP && self.items != 0 { + for item in self { + item.drop(); + } + } + } +} + +impl Clone for RawIter { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + iter: self.iter.clone(), + items: self.items, + } + } +} +impl Default for RawIter { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + // SAFETY: Because the table is static, it always outlives the iter. + unsafe { RawTableInner::NEW.iter() } + } +} + +impl Iterator for RawIter { + type Item = Bucket; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option> { + // Inner iterator iterates over buckets + // so it can do unnecessary work if we already yielded all items. + if self.items == 0 { + return None; + } + + let nxt = unsafe { + // SAFETY: We check number of items to yield using `items` field. + self.iter.next_impl::() + }; + + debug_assert!(nxt.is_some()); + self.items -= 1; + + nxt + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (self.items, Some(self.items)) + } + + #[inline] + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + unsafe { self.iter.fold_impl(self.items, init, f) } + } +} + +impl ExactSizeIterator for RawIter {} +impl FusedIterator for RawIter {} + +/// Iterator which returns an index of every full bucket in the table. +/// +/// For maximum flexibility this iterator is not bound by a lifetime, but you +/// must observe several rules when using it: +/// - You must not free the hash table while iterating (including via growing/shrinking). +/// - It is fine to erase a bucket that has been yielded by the iterator. +/// - Erasing a bucket that has not yet been yielded by the iterator may still +/// result in the iterator yielding index of that bucket. +/// - It is unspecified whether an element inserted after the iterator was +/// created will be yielded by that iterator. +/// - The order in which the iterator yields indices of the buckets is unspecified +/// and may change in the future. +pub(crate) struct FullBucketsIndices { + // Mask of full buckets in the current group. Bits are cleared from this + // mask as each element is processed. + current_group: BitMaskIter, + + // Initial value of the bytes' indices of the current group (relative + // to the start of the control bytes). + group_first_index: usize, + + // Pointer to the current group of control bytes, + // Must be aligned to the group size (Group::WIDTH). + ctrl: NonNull, + + // Number of elements in the table. + items: usize, +} + +impl FullBucketsIndices { + /// Advances the iterator and returns the next value. + /// + /// # Safety + /// + /// If any of the following conditions are violated, the result is + /// [`Undefined Behavior`]: + /// + /// * The [`RawTableInner`] / [`RawTable`] must be alive and not moved, + /// i.e. table outlives the `FullBucketsIndices`; + /// + /// * It never tries to iterate after getting all elements. + /// + /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + #[inline(always)] + unsafe fn next_impl(&mut self) -> Option { + loop { + if let Some(index) = self.current_group.next() { + // The returned `self.group_first_index + index` will always + // be in the range `0..self.buckets()`. See explanation below. + return Some(self.group_first_index + index); + } + + // SAFETY: The caller of this function ensures that: + // + // 1. It never tries to iterate after getting all the elements; + // 2. The table is alive and did not moved; + // 3. The first `self.ctrl` pointed to the start of the array of control bytes. + // + // Taking the above into account, we always stay within the bounds, because: + // + // 1. For tables smaller than the group width (self.buckets() <= Group::WIDTH), + // we will never end up in the given branch, since we should have already + // yielded all the elements of the table. + // + // 2. For tables larger than the group width. The number of buckets is a + // power of two (2 ^ n), Group::WIDTH is also power of two (2 ^ k). Since + // `(2 ^ n) > (2 ^ k)`, than `(2 ^ n) % (2 ^ k) = 0`. As we start from the + // the start of the array of control bytes, and never try to iterate after + // getting all the elements, the last `self.ctrl` will be equal to + // the `self.buckets() - Group::WIDTH`, so `self.current_group.next()` + // will always contains indices within the range `0..Group::WIDTH`, + // and subsequent `self.group_first_index + index` will always return a + // number less than `self.buckets()`. + self.ctrl = NonNull::new_unchecked(self.ctrl.as_ptr().add(Group::WIDTH)); + + // SAFETY: See explanation above. + self.current_group = Group::load_aligned(self.ctrl.as_ptr()) + .match_full() + .into_iter(); + self.group_first_index += Group::WIDTH; + } + } +} + +impl Iterator for FullBucketsIndices { + type Item = usize; + + /// Advances the iterator and returns the next value. It is up to + /// the caller to ensure that the `RawTable` outlives the `FullBucketsIndices`, + /// because we cannot make the `next` method unsafe. + #[inline(always)] + fn next(&mut self) -> Option { + // Return if we already yielded all items. + if self.items == 0 { + return None; + } + + let nxt = unsafe { + // SAFETY: + // 1. We check number of items to yield using `items` field. + // 2. The caller ensures that the table is alive and has not moved. + self.next_impl() + }; + + debug_assert!(nxt.is_some()); + self.items -= 1; + + nxt + } + + #[inline(always)] + fn size_hint(&self) -> (usize, Option) { + (self.items, Some(self.items)) + } +} + +impl ExactSizeIterator for FullBucketsIndices {} +impl FusedIterator for FullBucketsIndices {} + +/// Iterator which consumes a table and returns elements. +pub struct RawIntoIter { + iter: RawIter, + allocation: Option<(NonNull, Layout, A)>, + marker: PhantomData, +} + +impl RawIntoIter { + #[cfg_attr(feature = "inline-more", inline)] + pub fn iter(&self) -> RawIter { + self.iter.clone() + } +} + +unsafe impl Send for RawIntoIter +where + T: Send, + A: Send, +{ +} +unsafe impl Sync for RawIntoIter +where + T: Sync, + A: Sync, +{ +} + +#[cfg(feature = "nightly")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawIntoIter { + #[cfg_attr(feature = "inline-more", inline)] + fn drop(&mut self) { + unsafe { + // Drop all remaining elements + self.iter.drop_elements(); + + // Free the table + if let Some((ptr, layout, ref alloc)) = self.allocation { + alloc.deallocate(ptr, layout); + } + } + } +} +#[cfg(not(feature = "nightly"))] +impl Drop for RawIntoIter { + #[cfg_attr(feature = "inline-more", inline)] + fn drop(&mut self) { + unsafe { + // Drop all remaining elements + self.iter.drop_elements(); + + // Free the table + if let Some((ptr, layout, ref alloc)) = self.allocation { + alloc.deallocate(ptr, layout); + } + } + } +} + +impl Default for RawIntoIter { + fn default() -> Self { + Self { + iter: Default::default(), + allocation: None, + marker: PhantomData, + } + } +} +impl Iterator for RawIntoIter { + type Item = T; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option { + unsafe { Some(self.iter.next()?.read()) } + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl ExactSizeIterator for RawIntoIter {} +impl FusedIterator for RawIntoIter {} + +/// Iterator which consumes elements without freeing the table storage. +pub struct RawDrain<'a, T, A: Allocator = Global> { + iter: RawIter, + + // The table is moved into the iterator for the duration of the drain. This + // ensures that an empty table is left if the drain iterator is leaked + // without dropping. + table: RawTableInner, + orig_table: NonNull, + + // We don't use a &'a mut RawTable because we want RawDrain to be + // covariant over T. + marker: PhantomData<&'a RawTable>, +} + +impl RawDrain<'_, T, A> { + #[cfg_attr(feature = "inline-more", inline)] + pub fn iter(&self) -> RawIter { + self.iter.clone() + } +} + +unsafe impl Send for RawDrain<'_, T, A> +where + T: Send, + A: Send, +{ +} +unsafe impl Sync for RawDrain<'_, T, A> +where + T: Sync, + A: Sync, +{ +} + +impl Drop for RawDrain<'_, T, A> { + #[cfg_attr(feature = "inline-more", inline)] + fn drop(&mut self) { + unsafe { + // Drop all remaining elements. Note that this may panic. + self.iter.drop_elements(); + + // Reset the contents of the table now that all elements have been + // dropped. + self.table.clear_no_drop(); + + // Move the now empty table back to its original location. + self.orig_table + .as_ptr() + .copy_from_nonoverlapping(&self.table, 1); + } + } +} + +impl Iterator for RawDrain<'_, T, A> { + type Item = T; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option { + unsafe { + let item = self.iter.next()?; + Some(item.read()) + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl ExactSizeIterator for RawDrain<'_, T, A> {} +impl FusedIterator for RawDrain<'_, T, A> {} + +/// Iterator over occupied buckets that could match a given hash. +/// +/// `RawTable` only stores 7 bits of the hash value, so this iterator may return +/// items that have a hash value different than the one provided. You should +/// always validate the returned values before using them. +/// +/// For maximum flexibility this iterator is not bound by a lifetime, but you +/// must observe several rules when using it: +/// - You must not free the hash table while iterating (including via growing/shrinking). +/// - It is fine to erase a bucket that has been yielded by the iterator. +/// - Erasing a bucket that has not yet been yielded by the iterator may still +/// result in the iterator yielding that bucket. +/// - It is unspecified whether an element inserted after the iterator was +/// created will be yielded by that iterator. +/// - The order in which the iterator yields buckets is unspecified and may +/// change in the future. +pub struct RawIterHash { + inner: RawIterHashInner, + _marker: PhantomData, +} + +#[derive(Clone)] +struct RawIterHashInner { + // See `RawTableInner`'s corresponding fields for details. + // We can't store a `*const RawTableInner` as it would get + // invalidated by the user calling `&mut` methods on `RawTable`. + bucket_mask: usize, + ctrl: NonNull, + + // The top 7 bits of the hash. + h2_hash: u8, + + // The sequence of groups to probe in the search. + probe_seq: ProbeSeq, + + group: Group, + + // The elements within the group with a matching h2-hash. + bitmask: BitMaskIter, +} + +impl RawIterHash { + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn new(table: &RawTable, hash: u64) -> Self { + RawIterHash { + inner: RawIterHashInner::new(&table.table, hash), + _marker: PhantomData, + } + } +} + +impl Clone for RawIterHash { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + _marker: PhantomData, + } + } +} + +impl Default for RawIterHash { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + // SAFETY: Because the table is static, it always outlives the iter. + inner: unsafe { RawIterHashInner::new(&RawTableInner::NEW, 0) }, + _marker: PhantomData, + } + } +} + +impl RawIterHashInner { + #[cfg_attr(feature = "inline-more", inline)] + unsafe fn new(table: &RawTableInner, hash: u64) -> Self { + let h2_hash = h2(hash); + let probe_seq = table.probe_seq(hash); + let group = Group::load(table.ctrl(probe_seq.pos)); + let bitmask = group.match_byte(h2_hash).into_iter(); + + RawIterHashInner { + bucket_mask: table.bucket_mask, + ctrl: table.ctrl, + h2_hash, + probe_seq, + group, + bitmask, + } + } +} + +impl Iterator for RawIterHash { + type Item = Bucket; + + fn next(&mut self) -> Option> { + unsafe { + match self.inner.next() { + Some(index) => { + // Can't use `RawTable::bucket` here as we don't have + // an actual `RawTable` reference to use. + debug_assert!(index <= self.inner.bucket_mask); + let bucket = Bucket::from_base_index(self.inner.ctrl.cast(), index); + Some(bucket) + } + None => None, + } + } + } +} + +impl Iterator for RawIterHashInner { + type Item = usize; + + fn next(&mut self) -> Option { + unsafe { + loop { + if let Some(bit) = self.bitmask.next() { + let index = (self.probe_seq.pos + bit) & self.bucket_mask; + return Some(index); + } + if likely(self.group.match_empty().any_bit_set()) { + return None; + } + self.probe_seq.move_next(self.bucket_mask); + + // Can't use `RawTableInner::ctrl` here as we don't have + // an actual `RawTableInner` reference to use. + let index = self.probe_seq.pos; + debug_assert!(index < self.bucket_mask + 1 + Group::WIDTH); + let group_ctrl = self.ctrl.as_ptr().add(index); + + self.group = Group::load(group_ctrl); + self.bitmask = self.group.match_byte(self.h2_hash).into_iter(); + } + } + } +} + +pub(crate) struct RawExtractIf<'a, T, A: Allocator> { + pub iter: RawIter, + pub table: &'a mut RawTable, +} + +impl RawExtractIf<'_, T, A> { + #[cfg_attr(feature = "inline-more", inline)] + pub(crate) fn next(&mut self, mut f: F) -> Option + where + F: FnMut(&mut T) -> bool, + { + unsafe { + for item in &mut self.iter { + if f(item.as_mut()) { + return Some(self.table.remove(item).0); + } + } + } + None + } +} + +#[cfg(test)] +mod test_map { + use super::*; + + fn rehash_in_place(table: &mut RawTable, hasher: impl Fn(&T) -> u64) { + unsafe { + table.table.rehash_in_place( + &|table, index| hasher(table.bucket::(index).as_ref()), + mem::size_of::(), + if mem::needs_drop::() { + Some(|ptr| ptr::drop_in_place(ptr as *mut T)) + } else { + None + }, + ); + } + } + + #[test] + fn rehash() { + let mut table = RawTable::new(); + let hasher = |i: &u64| *i; + for i in 0..100 { + table.insert(i, i, hasher); + } + + for i in 0..100 { + unsafe { + assert_eq!(table.find(i, |x| *x == i).map(|b| b.read()), Some(i)); + } + assert!(table.find(i + 100, |x| *x == i + 100).is_none()); + } + + rehash_in_place(&mut table, hasher); + + for i in 0..100 { + unsafe { + assert_eq!(table.find(i, |x| *x == i).map(|b| b.read()), Some(i)); + } + assert!(table.find(i + 100, |x| *x == i + 100).is_none()); + } + } + + /// CHECKING THAT WE ARE NOT TRYING TO READ THE MEMORY OF + /// AN UNINITIALIZED TABLE DURING THE DROP + #[test] + fn test_drop_uninitialized() { + use ::alloc::vec::Vec; + + let table = unsafe { + // SAFETY: The `buckets` is power of two and we're not + // trying to actually use the returned RawTable. + RawTable::<(u64, Vec)>::new_uninitialized(Global, 8, Fallibility::Infallible) + .unwrap() + }; + drop(table); + } + + /// CHECKING THAT WE DON'T TRY TO DROP DATA IF THE `ITEMS` + /// ARE ZERO, EVEN IF WE HAVE `FULL` CONTROL BYTES. + #[test] + fn test_drop_zero_items() { + use ::alloc::vec::Vec; + unsafe { + // SAFETY: The `buckets` is power of two and we're not + // trying to actually use the returned RawTable. + let table = + RawTable::<(u64, Vec)>::new_uninitialized(Global, 8, Fallibility::Infallible) + .unwrap(); + + // WE SIMULATE, AS IT WERE, A FULL TABLE. + + // SAFETY: We checked that the table is allocated and therefore the table already has + // `self.bucket_mask + 1 + Group::WIDTH` number of control bytes (see TableLayout::calculate_layout_for) + // so writing `table.table.num_ctrl_bytes() == bucket_mask + 1 + Group::WIDTH` bytes is safe. + table + .table + .ctrl(0) + .write_bytes(EMPTY, table.table.num_ctrl_bytes()); + + // SAFETY: table.capacity() is guaranteed to be smaller than table.buckets() + table.table.ctrl(0).write_bytes(0, table.capacity()); + + // Fix up the trailing control bytes. See the comments in set_ctrl + // for the handling of tables smaller than the group width. + if table.buckets() < Group::WIDTH { + // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of control bytes, + // so copying `self.buckets() == self.bucket_mask + 1` bytes with offset equal to + // `Group::WIDTH` is safe + table + .table + .ctrl(0) + .copy_to(table.table.ctrl(Group::WIDTH), table.table.buckets()); + } else { + // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of + // control bytes,so copying `Group::WIDTH` bytes with offset equal + // to `self.buckets() == self.bucket_mask + 1` is safe + table + .table + .ctrl(0) + .copy_to(table.table.ctrl(table.table.buckets()), Group::WIDTH); + } + drop(table); + } + } + + /// CHECKING THAT WE DON'T TRY TO DROP DATA IF THE `ITEMS` + /// ARE ZERO, EVEN IF WE HAVE `FULL` CONTROL BYTES. + #[test] + fn test_catch_panic_clone_from() { + use ::alloc::sync::Arc; + use ::alloc::vec::Vec; + use allocator_api2::alloc::{AllocError, Allocator, Global}; + use core::sync::atomic::{AtomicI8, Ordering}; + use std::thread; + + struct MyAllocInner { + drop_count: Arc, + } + + #[derive(Clone)] + struct MyAlloc { + _inner: Arc, + } + + impl Drop for MyAllocInner { + fn drop(&mut self) { + println!("MyAlloc freed."); + self.drop_count.fetch_sub(1, Ordering::SeqCst); + } + } + + unsafe impl Allocator for MyAlloc { + fn allocate(&self, layout: Layout) -> std::result::Result, AllocError> { + let g = Global; + g.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + let g = Global; + g.deallocate(ptr, layout) + } + } + + const DISARMED: bool = false; + const ARMED: bool = true; + + struct CheckedCloneDrop { + panic_in_clone: bool, + dropped: bool, + need_drop: Vec, + } + + impl Clone for CheckedCloneDrop { + fn clone(&self) -> Self { + if self.panic_in_clone { + panic!("panic in clone") + } + Self { + panic_in_clone: self.panic_in_clone, + dropped: self.dropped, + need_drop: self.need_drop.clone(), + } + } + } + + impl Drop for CheckedCloneDrop { + fn drop(&mut self) { + if self.dropped { + panic!("double drop"); + } + self.dropped = true; + } + } + + let dropped: Arc = Arc::new(AtomicI8::new(2)); + + let mut table = RawTable::new_in(MyAlloc { + _inner: Arc::new(MyAllocInner { + drop_count: dropped.clone(), + }), + }); + + for (idx, panic_in_clone) in core::iter::repeat(DISARMED).take(7).enumerate() { + let idx = idx as u64; + table.insert( + idx, + ( + idx, + CheckedCloneDrop { + panic_in_clone, + dropped: false, + need_drop: vec![idx], + }, + ), + |(k, _)| *k, + ); + } + + assert_eq!(table.len(), 7); + + thread::scope(|s| { + let result = s.spawn(|| { + let armed_flags = [ + DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED, + ]; + let mut scope_table = RawTable::new_in(MyAlloc { + _inner: Arc::new(MyAllocInner { + drop_count: dropped.clone(), + }), + }); + for (idx, &panic_in_clone) in armed_flags.iter().enumerate() { + let idx = idx as u64; + scope_table.insert( + idx, + ( + idx, + CheckedCloneDrop { + panic_in_clone, + dropped: false, + need_drop: vec![idx + 100], + }, + ), + |(k, _)| *k, + ); + } + table.clone_from(&scope_table); + }); + assert!(result.join().is_err()); + }); + + // Let's check that all iterators work fine and do not return elements + // (especially `RawIterRange`, which does not depend on the number of + // elements in the table, but looks directly at the control bytes) + // + // SAFETY: We know for sure that `RawTable` will outlive + // the returned `RawIter / RawIterRange` iterator. + assert_eq!(table.len(), 0); + assert_eq!(unsafe { table.iter().count() }, 0); + assert_eq!(unsafe { table.iter().iter.count() }, 0); + + for idx in 0..table.buckets() { + let idx = idx as u64; + assert!( + table.find(idx, |(k, _)| *k == idx).is_none(), + "Index: {idx}" + ); + } + + // All allocator clones should already be dropped. + assert_eq!(dropped.load(Ordering::SeqCst), 1); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/raw/neon.rs b/bitbox02-bt/vendor/hashbrown/src/raw/neon.rs new file mode 100644 index 0000000..44e82d5 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/raw/neon.rs @@ -0,0 +1,124 @@ +use super::bitmask::BitMask; +use super::EMPTY; +use core::arch::aarch64 as neon; +use core::mem; +use core::num::NonZeroU64; + +pub(crate) type BitMaskWord = u64; +pub(crate) type NonZeroBitMaskWord = NonZeroU64; +pub(crate) const BITMASK_STRIDE: usize = 8; +pub(crate) const BITMASK_MASK: BitMaskWord = !0; +pub(crate) const BITMASK_ITER_MASK: BitMaskWord = 0x8080_8080_8080_8080; + +/// Abstraction over a group of control bytes which can be scanned in +/// parallel. +/// +/// This implementation uses a 64-bit NEON value. +#[derive(Copy, Clone)] +pub(crate) struct Group(neon::uint8x8_t); + +#[allow(clippy::use_self)] +impl Group { + /// Number of bytes in the group. + pub(crate) const WIDTH: usize = mem::size_of::(); + + /// Returns a full group of empty bytes, suitable for use as the initial + /// value for an empty hash table. + /// + /// This is guaranteed to be aligned to the group size. + #[inline] + pub(crate) const fn static_empty() -> &'static [u8; Group::WIDTH] { + #[repr(C)] + struct AlignedBytes { + _align: [Group; 0], + bytes: [u8; Group::WIDTH], + } + const ALIGNED_BYTES: AlignedBytes = AlignedBytes { + _align: [], + bytes: [EMPTY; Group::WIDTH], + }; + &ALIGNED_BYTES.bytes + } + + /// Loads a group of bytes starting at the given address. + #[inline] + #[allow(clippy::cast_ptr_alignment)] // unaligned load + pub(crate) unsafe fn load(ptr: *const u8) -> Self { + Group(neon::vld1_u8(ptr)) + } + + /// Loads a group of bytes starting at the given address, which must be + /// aligned to `mem::align_of::()`. + #[inline] + #[allow(clippy::cast_ptr_alignment)] + pub(crate) unsafe fn load_aligned(ptr: *const u8) -> Self { + // FIXME: use align_offset once it stabilizes + debug_assert_eq!(ptr as usize & (mem::align_of::() - 1), 0); + Group(neon::vld1_u8(ptr)) + } + + /// Stores the group of bytes to the given address, which must be + /// aligned to `mem::align_of::()`. + #[inline] + #[allow(clippy::cast_ptr_alignment)] + pub(crate) unsafe fn store_aligned(self, ptr: *mut u8) { + // FIXME: use align_offset once it stabilizes + debug_assert_eq!(ptr as usize & (mem::align_of::() - 1), 0); + neon::vst1_u8(ptr, self.0); + } + + /// Returns a `BitMask` indicating all bytes in the group which *may* + /// have the given value. + #[inline] + pub(crate) fn match_byte(self, byte: u8) -> BitMask { + unsafe { + let cmp = neon::vceq_u8(self.0, neon::vdup_n_u8(byte)); + BitMask(neon::vget_lane_u64(neon::vreinterpret_u64_u8(cmp), 0)) + } + } + + /// Returns a `BitMask` indicating all bytes in the group which are + /// `EMPTY`. + #[inline] + pub(crate) fn match_empty(self) -> BitMask { + self.match_byte(EMPTY) + } + + /// Returns a `BitMask` indicating all bytes in the group which are + /// `EMPTY` or `DELETED`. + #[inline] + pub(crate) fn match_empty_or_deleted(self) -> BitMask { + unsafe { + let cmp = neon::vcltz_s8(neon::vreinterpret_s8_u8(self.0)); + BitMask(neon::vget_lane_u64(neon::vreinterpret_u64_u8(cmp), 0)) + } + } + + /// Returns a `BitMask` indicating all bytes in the group which are full. + #[inline] + pub(crate) fn match_full(self) -> BitMask { + unsafe { + let cmp = neon::vcgez_s8(neon::vreinterpret_s8_u8(self.0)); + BitMask(neon::vget_lane_u64(neon::vreinterpret_u64_u8(cmp), 0)) + } + } + + /// Performs the following transformation on all bytes in the group: + /// - `EMPTY => EMPTY` + /// - `DELETED => EMPTY` + /// - `FULL => DELETED` + #[inline] + pub(crate) fn convert_special_to_empty_and_full_to_deleted(self) -> Self { + // Map high_bit = 1 (EMPTY or DELETED) to 1111_1111 + // and high_bit = 0 (FULL) to 1000_0000 + // + // Here's this logic expanded to concrete values: + // let special = 0 > byte = 1111_1111 (true) or 0000_0000 (false) + // 1111_1111 | 1000_0000 = 1111_1111 + // 0000_0000 | 1000_0000 = 1000_0000 + unsafe { + let special = neon::vcltz_s8(neon::vreinterpret_s8_u8(self.0)); + Group(neon::vorr_u8(special, neon::vdup_n_u8(0x80))) + } + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/raw/sse2.rs b/bitbox02-bt/vendor/hashbrown/src/raw/sse2.rs new file mode 100644 index 0000000..956ba5d --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/raw/sse2.rs @@ -0,0 +1,149 @@ +use super::bitmask::BitMask; +use super::EMPTY; +use core::mem; +use core::num::NonZeroU16; + +#[cfg(target_arch = "x86")] +use core::arch::x86; +#[cfg(target_arch = "x86_64")] +use core::arch::x86_64 as x86; + +pub(crate) type BitMaskWord = u16; +pub(crate) type NonZeroBitMaskWord = NonZeroU16; +pub(crate) const BITMASK_STRIDE: usize = 1; +pub(crate) const BITMASK_MASK: BitMaskWord = 0xffff; +pub(crate) const BITMASK_ITER_MASK: BitMaskWord = !0; + +/// Abstraction over a group of control bytes which can be scanned in +/// parallel. +/// +/// This implementation uses a 128-bit SSE value. +#[derive(Copy, Clone)] +pub(crate) struct Group(x86::__m128i); + +// FIXME: https://github.com/rust-lang/rust-clippy/issues/3859 +#[allow(clippy::use_self)] +impl Group { + /// Number of bytes in the group. + pub(crate) const WIDTH: usize = mem::size_of::(); + + /// Returns a full group of empty bytes, suitable for use as the initial + /// value for an empty hash table. + /// + /// This is guaranteed to be aligned to the group size. + #[inline] + #[allow(clippy::items_after_statements)] + pub(crate) const fn static_empty() -> &'static [u8; Group::WIDTH] { + #[repr(C)] + struct AlignedBytes { + _align: [Group; 0], + bytes: [u8; Group::WIDTH], + } + const ALIGNED_BYTES: AlignedBytes = AlignedBytes { + _align: [], + bytes: [EMPTY; Group::WIDTH], + }; + &ALIGNED_BYTES.bytes + } + + /// Loads a group of bytes starting at the given address. + #[inline] + #[allow(clippy::cast_ptr_alignment)] // unaligned load + pub(crate) unsafe fn load(ptr: *const u8) -> Self { + Group(x86::_mm_loadu_si128(ptr.cast())) + } + + /// Loads a group of bytes starting at the given address, which must be + /// aligned to `mem::align_of::()`. + #[inline] + #[allow(clippy::cast_ptr_alignment)] + pub(crate) unsafe fn load_aligned(ptr: *const u8) -> Self { + // FIXME: use align_offset once it stabilizes + debug_assert_eq!(ptr as usize & (mem::align_of::() - 1), 0); + Group(x86::_mm_load_si128(ptr.cast())) + } + + /// Stores the group of bytes to the given address, which must be + /// aligned to `mem::align_of::()`. + #[inline] + #[allow(clippy::cast_ptr_alignment)] + pub(crate) unsafe fn store_aligned(self, ptr: *mut u8) { + // FIXME: use align_offset once it stabilizes + debug_assert_eq!(ptr as usize & (mem::align_of::() - 1), 0); + x86::_mm_store_si128(ptr.cast(), self.0); + } + + /// Returns a `BitMask` indicating all bytes in the group which have + /// the given value. + #[inline] + pub(crate) fn match_byte(self, byte: u8) -> BitMask { + #[allow( + clippy::cast_possible_wrap, // byte: u8 as i8 + // byte: i32 as u16 + // note: _mm_movemask_epi8 returns a 16-bit mask in a i32, the + // upper 16-bits of the i32 are zeroed: + clippy::cast_sign_loss, + clippy::cast_possible_truncation + )] + unsafe { + let cmp = x86::_mm_cmpeq_epi8(self.0, x86::_mm_set1_epi8(byte as i8)); + BitMask(x86::_mm_movemask_epi8(cmp) as u16) + } + } + + /// Returns a `BitMask` indicating all bytes in the group which are + /// `EMPTY`. + #[inline] + pub(crate) fn match_empty(self) -> BitMask { + self.match_byte(EMPTY) + } + + /// Returns a `BitMask` indicating all bytes in the group which are + /// `EMPTY` or `DELETED`. + #[inline] + pub(crate) fn match_empty_or_deleted(self) -> BitMask { + #[allow( + // byte: i32 as u16 + // note: _mm_movemask_epi8 returns a 16-bit mask in a i32, the + // upper 16-bits of the i32 are zeroed: + clippy::cast_sign_loss, + clippy::cast_possible_truncation + )] + unsafe { + // A byte is EMPTY or DELETED iff the high bit is set + BitMask(x86::_mm_movemask_epi8(self.0) as u16) + } + } + + /// Returns a `BitMask` indicating all bytes in the group which are full. + #[inline] + pub(crate) fn match_full(&self) -> BitMask { + self.match_empty_or_deleted().invert() + } + + /// Performs the following transformation on all bytes in the group: + /// - `EMPTY => EMPTY` + /// - `DELETED => EMPTY` + /// - `FULL => DELETED` + #[inline] + pub(crate) fn convert_special_to_empty_and_full_to_deleted(self) -> Self { + // Map high_bit = 1 (EMPTY or DELETED) to 1111_1111 + // and high_bit = 0 (FULL) to 1000_0000 + // + // Here's this logic expanded to concrete values: + // let special = 0 > byte = 1111_1111 (true) or 0000_0000 (false) + // 1111_1111 | 1000_0000 = 1111_1111 + // 0000_0000 | 1000_0000 = 1000_0000 + #[allow( + clippy::cast_possible_wrap, // byte: 0x80_u8 as i8 + )] + unsafe { + let zero = x86::_mm_setzero_si128(); + let special = x86::_mm_cmpgt_epi8(zero, self.0); + Group(x86::_mm_or_si128( + special, + x86::_mm_set1_epi8(0x80_u8 as i8), + )) + } + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/raw_entry.rs b/bitbox02-bt/vendor/hashbrown/src/raw_entry.rs new file mode 100644 index 0000000..480ebdb --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/raw_entry.rs @@ -0,0 +1,1740 @@ +use crate::hash_map::{equivalent, make_hash, make_hasher}; +use crate::raw::{Allocator, Bucket, Global, RawTable}; +use crate::{Equivalent, HashMap}; +use core::fmt::{self, Debug}; +use core::hash::{BuildHasher, Hash}; +use core::mem; + +impl HashMap { + /// Creates a raw entry builder for the `HashMap`. + /// + /// Raw entries provide the lowest level of control for searching and + /// manipulating a map. They must be manually initialized with a hash and + /// then manually searched. After this, insertions into a vacant entry + /// still require an owned key to be provided. + /// + /// Raw entries are useful for such exotic situations as: + /// + /// * Hash memoization + /// * Deferring the creation of an owned key until it is known to be required + /// * Using a search key that doesn't work with the Borrow trait + /// * Using custom comparison logic without newtype wrappers + /// + /// Because raw entries provide much more low-level control, it's much easier + /// to put the `HashMap` into an inconsistent state which, while memory-safe, + /// will cause the map to produce seemingly random results. Higher-level and + /// more foolproof APIs like `entry` should be preferred when possible. + /// + /// In particular, the hash used to initialized the raw entry must still be + /// consistent with the hash of the key that is ultimately stored in the entry. + /// This is because implementations of `HashMap` may need to recompute hashes + /// when resizing, at which point only the keys are available. + /// + /// Raw entries give mutable access to the keys. This must not be used + /// to modify how the key would compare or hash, as the map will not re-evaluate + /// where the key should go, meaning the keys may become "lost" if their + /// location does not reflect their state. For instance, if you change a key + /// so that the map now contains keys which compare equal, search may start + /// acting erratically, with two keys randomly masking each other. Implementations + /// are free to assume this doesn't happen (within the limits of memory-safety). + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map = HashMap::new(); + /// map.extend([("a", 100), ("b", 200), ("c", 300)]); + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// // Existing key (insert and update) + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => unreachable!(), + /// RawEntryMut::Occupied(mut view) => { + /// assert_eq!(view.get(), &100); + /// let v = view.get_mut(); + /// let new_v = (*v) * 10; + /// *v = new_v; + /// assert_eq!(view.insert(1111), 1000); + /// } + /// } + /// + /// assert_eq!(map[&"a"], 1111); + /// assert_eq!(map.len(), 3); + /// + /// // Existing key (take) + /// let hash = compute_hash(map.hasher(), &"c"); + /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c") { + /// RawEntryMut::Vacant(_) => unreachable!(), + /// RawEntryMut::Occupied(view) => { + /// assert_eq!(view.remove_entry(), ("c", 300)); + /// } + /// } + /// assert_eq!(map.raw_entry().from_key(&"c"), None); + /// assert_eq!(map.len(), 2); + /// + /// // Nonexistent key (insert and update) + /// let key = "d"; + /// let hash = compute_hash(map.hasher(), &key); + /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) { + /// RawEntryMut::Occupied(_) => unreachable!(), + /// RawEntryMut::Vacant(view) => { + /// let (k, value) = view.insert("d", 4000); + /// assert_eq!((*k, *value), ("d", 4000)); + /// *value = 40000; + /// } + /// } + /// assert_eq!(map[&"d"], 40000); + /// assert_eq!(map.len(), 3); + /// + /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) { + /// RawEntryMut::Vacant(_) => unreachable!(), + /// RawEntryMut::Occupied(view) => { + /// assert_eq!(view.remove_entry(), ("d", 40000)); + /// } + /// } + /// assert_eq!(map.get(&"d"), None); + /// assert_eq!(map.len(), 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S, A> { + RawEntryBuilderMut { map: self } + } + + /// Creates a raw immutable entry builder for the `HashMap`. + /// + /// Raw entries provide the lowest level of control for searching and + /// manipulating a map. They must be manually initialized with a hash and + /// then manually searched. + /// + /// This is useful for + /// * Hash memoization + /// * Using a search key that doesn't work with the Borrow trait + /// * Using custom comparison logic without newtype wrappers + /// + /// Unless you are in such a situation, higher-level and more foolproof APIs like + /// `get` should be preferred. + /// + /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::HashMap; + /// + /// let mut map = HashMap::new(); + /// map.extend([("a", 100), ("b", 200), ("c", 300)]); + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// for k in ["a", "b", "c", "d", "e", "f"] { + /// let hash = compute_hash(map.hasher(), k); + /// let v = map.get(&k).cloned(); + /// let kv = v.as_ref().map(|v| (&k, v)); + /// + /// println!("Key: {} and value: {:?}", k, v); + /// + /// assert_eq!(map.raw_entry().from_key(&k), kv); + /// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv); + /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S, A> { + RawEntryBuilder { map: self } + } +} + +/// A builder for computing where in a [`HashMap`] a key-value pair would be stored. +/// +/// See the [`HashMap::raw_entry_mut`] docs for usage examples. +/// +/// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{RawEntryBuilderMut, RawEntryMut::Vacant, RawEntryMut::Occupied}; +/// use hashbrown::HashMap; +/// use core::hash::{BuildHasher, Hash}; +/// +/// let mut map = HashMap::new(); +/// map.extend([(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16)]); +/// assert_eq!(map.len(), 6); +/// +/// fn compute_hash(hash_builder: &S, key: &K) -> u64 { +/// use core::hash::Hasher; +/// let mut state = hash_builder.build_hasher(); +/// key.hash(&mut state); +/// state.finish() +/// } +/// +/// let builder: RawEntryBuilderMut<_, _, _> = map.raw_entry_mut(); +/// +/// // Existing key +/// match builder.from_key(&6) { +/// Vacant(_) => unreachable!(), +/// Occupied(view) => assert_eq!(view.get(), &16), +/// } +/// +/// for key in 0..12 { +/// let hash = compute_hash(map.hasher(), &key); +/// let value = map.get(&key).cloned(); +/// let key_value = value.as_ref().map(|v| (&key, v)); +/// +/// println!("Key: {} and value: {:?}", key, value); +/// +/// match map.raw_entry_mut().from_key(&key) { +/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value), +/// Vacant(_) => assert_eq!(value, None), +/// } +/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) { +/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value), +/// Vacant(_) => assert_eq!(value, None), +/// } +/// match map.raw_entry_mut().from_hash(hash, |q| *q == key) { +/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value), +/// Vacant(_) => assert_eq!(value, None), +/// } +/// } +/// +/// assert_eq!(map.len(), 6); +/// ``` +pub struct RawEntryBuilderMut<'a, K, V, S, A: Allocator = Global> { + map: &'a mut HashMap, +} + +/// A view into a single entry in a map, which may either be vacant or occupied. +/// +/// This is a lower-level version of [`Entry`]. +/// +/// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`], +/// then calling one of the methods of that [`RawEntryBuilderMut`]. +/// +/// [`HashMap`]: struct.HashMap.html +/// [`Entry`]: enum.Entry.html +/// [`raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut +/// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html +/// +/// # Examples +/// +/// ``` +/// use core::hash::{BuildHasher, Hash}; +/// use hashbrown::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut}; +/// +/// let mut map = HashMap::new(); +/// map.extend([('a', 1), ('b', 2), ('c', 3)]); +/// assert_eq!(map.len(), 3); +/// +/// fn compute_hash(hash_builder: &S, key: &K) -> u64 { +/// use core::hash::Hasher; +/// let mut state = hash_builder.build_hasher(); +/// key.hash(&mut state); +/// state.finish() +/// } +/// +/// // Existing key (insert) +/// let raw: RawEntryMut<_, _, _> = map.raw_entry_mut().from_key(&'a'); +/// let _raw_o: RawOccupiedEntryMut<_, _, _> = raw.insert('a', 10); +/// assert_eq!(map.len(), 3); +/// +/// // Nonexistent key (insert) +/// map.raw_entry_mut().from_key(&'d').insert('d', 40); +/// assert_eq!(map.len(), 4); +/// +/// // Existing key (or_insert) +/// let hash = compute_hash(map.hasher(), &'b'); +/// let kv = map +/// .raw_entry_mut() +/// .from_key_hashed_nocheck(hash, &'b') +/// .or_insert('b', 20); +/// assert_eq!(kv, (&mut 'b', &mut 2)); +/// *kv.1 = 20; +/// assert_eq!(map.len(), 4); +/// +/// // Nonexistent key (or_insert) +/// let hash = compute_hash(map.hasher(), &'e'); +/// let kv = map +/// .raw_entry_mut() +/// .from_key_hashed_nocheck(hash, &'e') +/// .or_insert('e', 50); +/// assert_eq!(kv, (&mut 'e', &mut 50)); +/// assert_eq!(map.len(), 5); +/// +/// // Existing key (or_insert_with) +/// let hash = compute_hash(map.hasher(), &'c'); +/// let kv = map +/// .raw_entry_mut() +/// .from_hash(hash, |q| q == &'c') +/// .or_insert_with(|| ('c', 30)); +/// assert_eq!(kv, (&mut 'c', &mut 3)); +/// *kv.1 = 30; +/// assert_eq!(map.len(), 5); +/// +/// // Nonexistent key (or_insert_with) +/// let hash = compute_hash(map.hasher(), &'f'); +/// let kv = map +/// .raw_entry_mut() +/// .from_hash(hash, |q| q == &'f') +/// .or_insert_with(|| ('f', 60)); +/// assert_eq!(kv, (&mut 'f', &mut 60)); +/// assert_eq!(map.len(), 6); +/// +/// println!("Our HashMap: {:?}", map); +/// +/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect(); +/// // The `Iter` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, [('a', 10), ('b', 20), ('c', 30), ('d', 40), ('e', 50), ('f', 60)]); +/// ``` +pub enum RawEntryMut<'a, K, V, S, A: Allocator = Global> { + /// An occupied entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::{hash_map::RawEntryMut, HashMap}; + /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => unreachable!(), + /// RawEntryMut::Occupied(_) => { } + /// } + /// ``` + Occupied(RawOccupiedEntryMut<'a, K, V, S, A>), + /// A vacant entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::{hash_map::RawEntryMut, HashMap}; + /// let mut map: HashMap<&str, i32> = HashMap::new(); + /// + /// match map.raw_entry_mut().from_key("a") { + /// RawEntryMut::Occupied(_) => unreachable!(), + /// RawEntryMut::Vacant(_) => { } + /// } + /// ``` + Vacant(RawVacantEntryMut<'a, K, V, S, A>), +} + +/// A view into an occupied entry in a `HashMap`. +/// It is part of the [`RawEntryMut`] enum. +/// +/// [`RawEntryMut`]: enum.RawEntryMut.html +/// +/// # Examples +/// +/// ``` +/// use core::hash::{BuildHasher, Hash}; +/// use hashbrown::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut}; +/// +/// let mut map = HashMap::new(); +/// map.extend([("a", 10), ("b", 20), ("c", 30)]); +/// +/// fn compute_hash(hash_builder: &S, key: &K) -> u64 { +/// use core::hash::Hasher; +/// let mut state = hash_builder.build_hasher(); +/// key.hash(&mut state); +/// state.finish() +/// } +/// +/// let _raw_o: RawOccupiedEntryMut<_, _, _> = map.raw_entry_mut().from_key(&"a").insert("a", 100); +/// assert_eq!(map.len(), 3); +/// +/// // Existing key (insert and update) +/// match map.raw_entry_mut().from_key(&"a") { +/// RawEntryMut::Vacant(_) => unreachable!(), +/// RawEntryMut::Occupied(mut view) => { +/// assert_eq!(view.get(), &100); +/// let v = view.get_mut(); +/// let new_v = (*v) * 10; +/// *v = new_v; +/// assert_eq!(view.insert(1111), 1000); +/// } +/// } +/// +/// assert_eq!(map[&"a"], 1111); +/// assert_eq!(map.len(), 3); +/// +/// // Existing key (take) +/// let hash = compute_hash(map.hasher(), &"c"); +/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c") { +/// RawEntryMut::Vacant(_) => unreachable!(), +/// RawEntryMut::Occupied(view) => { +/// assert_eq!(view.remove_entry(), ("c", 30)); +/// } +/// } +/// assert_eq!(map.raw_entry().from_key(&"c"), None); +/// assert_eq!(map.len(), 2); +/// +/// let hash = compute_hash(map.hasher(), &"b"); +/// match map.raw_entry_mut().from_hash(hash, |q| *q == "b") { +/// RawEntryMut::Vacant(_) => unreachable!(), +/// RawEntryMut::Occupied(view) => { +/// assert_eq!(view.remove_entry(), ("b", 20)); +/// } +/// } +/// assert_eq!(map.get(&"b"), None); +/// assert_eq!(map.len(), 1); +/// ``` +pub struct RawOccupiedEntryMut<'a, K, V, S, A: Allocator = Global> { + elem: Bucket<(K, V)>, + table: &'a mut RawTable<(K, V), A>, + hash_builder: &'a S, +} + +unsafe impl Send for RawOccupiedEntryMut<'_, K, V, S, A> +where + K: Send, + V: Send, + S: Send, + A: Send + Allocator, +{ +} +unsafe impl Sync for RawOccupiedEntryMut<'_, K, V, S, A> +where + K: Sync, + V: Sync, + S: Sync, + A: Sync + Allocator, +{ +} + +/// A view into a vacant entry in a `HashMap`. +/// It is part of the [`RawEntryMut`] enum. +/// +/// [`RawEntryMut`]: enum.RawEntryMut.html +/// +/// # Examples +/// +/// ``` +/// use core::hash::{BuildHasher, Hash}; +/// use hashbrown::hash_map::{HashMap, RawEntryMut, RawVacantEntryMut}; +/// +/// let mut map = HashMap::<&str, i32>::new(); +/// +/// fn compute_hash(hash_builder: &S, key: &K) -> u64 { +/// use core::hash::Hasher; +/// let mut state = hash_builder.build_hasher(); +/// key.hash(&mut state); +/// state.finish() +/// } +/// +/// let raw_v: RawVacantEntryMut<_, _, _> = match map.raw_entry_mut().from_key(&"a") { +/// RawEntryMut::Vacant(view) => view, +/// RawEntryMut::Occupied(_) => unreachable!(), +/// }; +/// raw_v.insert("a", 10); +/// assert!(map[&"a"] == 10 && map.len() == 1); +/// +/// // Nonexistent key (insert and update) +/// let hash = compute_hash(map.hasher(), &"b"); +/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"b") { +/// RawEntryMut::Occupied(_) => unreachable!(), +/// RawEntryMut::Vacant(view) => { +/// let (k, value) = view.insert("b", 2); +/// assert_eq!((*k, *value), ("b", 2)); +/// *value = 20; +/// } +/// } +/// assert!(map[&"b"] == 20 && map.len() == 2); +/// +/// let hash = compute_hash(map.hasher(), &"c"); +/// match map.raw_entry_mut().from_hash(hash, |q| *q == "c") { +/// RawEntryMut::Occupied(_) => unreachable!(), +/// RawEntryMut::Vacant(view) => { +/// assert_eq!(view.insert("c", 30), (&mut "c", &mut 30)); +/// } +/// } +/// assert!(map[&"c"] == 30 && map.len() == 3); +/// ``` +pub struct RawVacantEntryMut<'a, K, V, S, A: Allocator = Global> { + table: &'a mut RawTable<(K, V), A>, + hash_builder: &'a S, +} + +/// A builder for computing where in a [`HashMap`] a key-value pair would be stored. +/// +/// See the [`HashMap::raw_entry`] docs for usage examples. +/// +/// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_map::{HashMap, RawEntryBuilder}; +/// use core::hash::{BuildHasher, Hash}; +/// +/// let mut map = HashMap::new(); +/// map.extend([(1, 10), (2, 20), (3, 30)]); +/// +/// fn compute_hash(hash_builder: &S, key: &K) -> u64 { +/// use core::hash::Hasher; +/// let mut state = hash_builder.build_hasher(); +/// key.hash(&mut state); +/// state.finish() +/// } +/// +/// for k in 0..6 { +/// let hash = compute_hash(map.hasher(), &k); +/// let v = map.get(&k).cloned(); +/// let kv = v.as_ref().map(|v| (&k, v)); +/// +/// println!("Key: {} and value: {:?}", k, v); +/// let builder: RawEntryBuilder<_, _, _> = map.raw_entry(); +/// assert_eq!(builder.from_key(&k), kv); +/// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv); +/// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv); +/// } +/// ``` +pub struct RawEntryBuilder<'a, K, V, S, A: Allocator = Global> { + map: &'a HashMap, +} + +impl<'a, K, V, S, A: Allocator> RawEntryBuilderMut<'a, K, V, S, A> { + /// Creates a `RawEntryMut` from the given key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// let key = "a"; + /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key(&key); + /// entry.insert(key, 100); + /// assert_eq!(map[&"a"], 100); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::wrong_self_convention)] + pub fn from_key(self, k: &Q) -> RawEntryMut<'a, K, V, S, A> + where + S: BuildHasher, + Q: Hash + Equivalent + ?Sized, + { + let hash = make_hash::(&self.map.hash_builder, k); + self.from_key_hashed_nocheck(hash, k) + } + + /// Creates a `RawEntryMut` from the given key and its hash. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// let key = "a"; + /// let hash = compute_hash(map.hasher(), &key); + /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key_hashed_nocheck(hash, &key); + /// entry.insert(key, 100); + /// assert_eq!(map[&"a"], 100); + /// ``` + #[inline] + #[allow(clippy::wrong_self_convention)] + pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> + where + Q: Equivalent + ?Sized, + { + self.from_hash(hash, equivalent(k)) + } +} + +impl<'a, K, V, S, A: Allocator> RawEntryBuilderMut<'a, K, V, S, A> { + /// Creates a `RawEntryMut` from the given hash and matching function. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// let key = "a"; + /// let hash = compute_hash(map.hasher(), &key); + /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_hash(hash, |k| k == &key); + /// entry.insert(key, 100); + /// assert_eq!(map[&"a"], 100); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::wrong_self_convention)] + pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> + where + for<'b> F: FnMut(&'b K) -> bool, + { + self.search(hash, is_match) + } + + #[cfg_attr(feature = "inline-more", inline)] + fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> + where + for<'b> F: FnMut(&'b K) -> bool, + { + match self.map.table.find(hash, |(k, _)| is_match(k)) { + Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { + elem, + table: &mut self.map.table, + hash_builder: &self.map.hash_builder, + }), + None => RawEntryMut::Vacant(RawVacantEntryMut { + table: &mut self.map.table, + hash_builder: &self.map.hash_builder, + }), + } + } +} + +impl<'a, K, V, S, A: Allocator> RawEntryBuilder<'a, K, V, S, A> { + /// Access an immutable entry by key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// let key = "a"; + /// assert_eq!(map.raw_entry().from_key(&key), Some((&"a", &100))); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::wrong_self_convention)] + pub fn from_key(self, k: &Q) -> Option<(&'a K, &'a V)> + where + S: BuildHasher, + Q: Hash + Equivalent + ?Sized, + { + let hash = make_hash::(&self.map.hash_builder, k); + self.from_key_hashed_nocheck(hash, k) + } + + /// Access an immutable entry by a key and its hash. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::HashMap; + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// let key = "a"; + /// let hash = compute_hash(map.hasher(), &key); + /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &key), Some((&"a", &100))); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::wrong_self_convention)] + pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> + where + Q: Equivalent + ?Sized, + { + self.from_hash(hash, equivalent(k)) + } + + #[cfg_attr(feature = "inline-more", inline)] + fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> + where + F: FnMut(&K) -> bool, + { + match self.map.table.get(hash, |(k, _)| is_match(k)) { + Some((key, value)) => Some((key, value)), + None => None, + } + } + + /// Access an immutable entry by hash and matching function. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::HashMap; + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// let key = "a"; + /// let hash = compute_hash(map.hasher(), &key); + /// assert_eq!(map.raw_entry().from_hash(hash, |k| k == &key), Some((&"a", &100))); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::wrong_self_convention)] + pub fn from_hash(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)> + where + F: FnMut(&K) -> bool, + { + self.search(hash, is_match) + } +} + +impl<'a, K, V, S, A: Allocator> RawEntryMut<'a, K, V, S, A> { + /// Sets the value of the entry, and returns a `RawOccupiedEntryMut`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// let entry = map.raw_entry_mut().from_key("horseyland").insert("horseyland", 37); + /// + /// assert_eq!(entry.remove_entry(), ("horseyland", 37)); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A> + where + K: Hash, + S: BuildHasher, + { + match self { + RawEntryMut::Occupied(mut entry) => { + entry.insert(value); + entry + } + RawEntryMut::Vacant(entry) => entry.insert_entry(key, value), + } + } + + /// Ensures a value is in the entry by inserting the default if empty, and returns + /// mutable references to the key and value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3); + /// assert_eq!(map["poneyland"], 3); + /// + /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2; + /// assert_eq!(map["poneyland"], 6); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V) + where + K: Hash, + S: BuildHasher, + { + match self { + RawEntryMut::Occupied(entry) => entry.into_key_value(), + RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val), + } + } + + /// Ensures a value is in the entry by inserting the result of the default function if empty, + /// and returns mutable references to the key and value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, String> = HashMap::new(); + /// + /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| { + /// ("poneyland", "hoho".to_string()) + /// }); + /// + /// assert_eq!(map["poneyland"], "hoho".to_string()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert_with(self, default: F) -> (&'a mut K, &'a mut V) + where + F: FnOnce() -> (K, V), + K: Hash, + S: BuildHasher, + { + match self { + RawEntryMut::Occupied(entry) => entry.into_key_value(), + RawEntryMut::Vacant(entry) => { + let (k, v) = default(); + entry.insert(k, v) + } + } + } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the map. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// map.raw_entry_mut() + /// .from_key("poneyland") + /// .and_modify(|_k, v| { *v += 1 }) + /// .or_insert("poneyland", 42); + /// assert_eq!(map["poneyland"], 42); + /// + /// map.raw_entry_mut() + /// .from_key("poneyland") + /// .and_modify(|_k, v| { *v += 1 }) + /// .or_insert("poneyland", 0); + /// assert_eq!(map["poneyland"], 43); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn and_modify(self, f: F) -> Self + where + F: FnOnce(&mut K, &mut V), + { + match self { + RawEntryMut::Occupied(mut entry) => { + { + let (k, v) = entry.get_key_value_mut(); + f(k, v); + } + RawEntryMut::Occupied(entry) + } + RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry), + } + } + + /// Provides shared access to the key and owned access to the value of + /// an occupied entry and allows to replace or remove it based on the + /// value of the returned option. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RawEntryMut; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// let entry = map + /// .raw_entry_mut() + /// .from_key("poneyland") + /// .and_replace_entry_with(|_k, _v| panic!()); + /// + /// match entry { + /// RawEntryMut::Vacant(_) => {}, + /// RawEntryMut::Occupied(_) => panic!(), + /// } + /// + /// map.insert("poneyland", 42); + /// + /// let entry = map + /// .raw_entry_mut() + /// .from_key("poneyland") + /// .and_replace_entry_with(|k, v| { + /// assert_eq!(k, &"poneyland"); + /// assert_eq!(v, 42); + /// Some(v + 1) + /// }); + /// + /// match entry { + /// RawEntryMut::Occupied(e) => { + /// assert_eq!(e.key(), &"poneyland"); + /// assert_eq!(e.get(), &43); + /// }, + /// RawEntryMut::Vacant(_) => panic!(), + /// } + /// + /// assert_eq!(map["poneyland"], 43); + /// + /// let entry = map + /// .raw_entry_mut() + /// .from_key("poneyland") + /// .and_replace_entry_with(|_k, _v| None); + /// + /// match entry { + /// RawEntryMut::Vacant(_) => {}, + /// RawEntryMut::Occupied(_) => panic!(), + /// } + /// + /// assert!(!map.contains_key("poneyland")); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn and_replace_entry_with(self, f: F) -> Self + where + F: FnOnce(&K, V) -> Option, + { + match self { + RawEntryMut::Occupied(entry) => entry.replace_entry_with(f), + RawEntryMut::Vacant(_) => self, + } + } +} + +impl<'a, K, V, S, A: Allocator> RawOccupiedEntryMut<'a, K, V, S, A> { + /// Gets a reference to the key in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => assert_eq!(o.key(), &"a") + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &K { + unsafe { &self.elem.as_ref().0 } + } + + /// Gets a mutable reference to the key in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// use std::rc::Rc; + /// + /// let key_one = Rc::new("a"); + /// let key_two = Rc::new("a"); + /// + /// let mut map: HashMap, u32> = HashMap::new(); + /// map.insert(key_one.clone(), 10); + /// + /// assert_eq!(map[&key_one], 10); + /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); + /// + /// match map.raw_entry_mut().from_key(&key_one) { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(mut o) => { + /// *o.key_mut() = key_two.clone(); + /// } + /// } + /// assert_eq!(map[&key_two], 10); + /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key_mut(&mut self) -> &mut K { + unsafe { &mut self.elem.as_mut().0 } + } + + /// Converts the entry into a mutable reference to the key in the entry + /// with a lifetime bound to the map itself. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// use std::rc::Rc; + /// + /// let key_one = Rc::new("a"); + /// let key_two = Rc::new("a"); + /// + /// let mut map: HashMap, u32> = HashMap::new(); + /// map.insert(key_one.clone(), 10); + /// + /// assert_eq!(map[&key_one], 10); + /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); + /// + /// let inside_key: &mut Rc<&str>; + /// + /// match map.raw_entry_mut().from_key(&key_one) { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => inside_key = o.into_key(), + /// } + /// *inside_key = key_two.clone(); + /// + /// assert_eq!(map[&key_two], 10); + /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_key(self) -> &'a mut K { + unsafe { &mut self.elem.as_mut().0 } + } + + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => assert_eq!(o.get(), &100), + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get(&self) -> &V { + unsafe { &self.elem.as_ref().1 } + } + + /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry + /// with a lifetime bound to the map itself. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// let value: &mut u32; + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => value = o.into_mut(), + /// } + /// *value += 900; + /// + /// assert_eq!(map[&"a"], 1000); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_mut(self) -> &'a mut V { + unsafe { &mut self.elem.as_mut().1 } + } + + /// Gets a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(mut o) => *o.get_mut() += 900, + /// } + /// + /// assert_eq!(map[&"a"], 1000); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_mut(&mut self) -> &mut V { + unsafe { &mut self.elem.as_mut().1 } + } + + /// Gets a reference to the key and value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => assert_eq!(o.get_key_value(), (&"a", &100)), + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_key_value(&self) -> (&K, &V) { + unsafe { + let (key, value) = self.elem.as_ref(); + (key, value) + } + } + + /// Gets a mutable reference to the key and value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// use std::rc::Rc; + /// + /// let key_one = Rc::new("a"); + /// let key_two = Rc::new("a"); + /// + /// let mut map: HashMap, u32> = HashMap::new(); + /// map.insert(key_one.clone(), 10); + /// + /// assert_eq!(map[&key_one], 10); + /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); + /// + /// match map.raw_entry_mut().from_key(&key_one) { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(mut o) => { + /// let (inside_key, inside_value) = o.get_key_value_mut(); + /// *inside_key = key_two.clone(); + /// *inside_value = 100; + /// } + /// } + /// assert_eq!(map[&key_two], 100); + /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) { + unsafe { + let &mut (ref mut key, ref mut value) = self.elem.as_mut(); + (key, value) + } + } + + /// Converts the `OccupiedEntry` into a mutable reference to the key and value in the entry + /// with a lifetime bound to the map itself. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// use std::rc::Rc; + /// + /// let key_one = Rc::new("a"); + /// let key_two = Rc::new("a"); + /// + /// let mut map: HashMap, u32> = HashMap::new(); + /// map.insert(key_one.clone(), 10); + /// + /// assert_eq!(map[&key_one], 10); + /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); + /// + /// let inside_key: &mut Rc<&str>; + /// let inside_value: &mut u32; + /// match map.raw_entry_mut().from_key(&key_one) { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => { + /// let tuple = o.into_key_value(); + /// inside_key = tuple.0; + /// inside_value = tuple.1; + /// } + /// } + /// *inside_key = key_two.clone(); + /// *inside_value = 100; + /// assert_eq!(map[&key_two], 100); + /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_key_value(self) -> (&'a mut K, &'a mut V) { + unsafe { + let &mut (ref mut key, ref mut value) = self.elem.as_mut(); + (key, value) + } + } + + /// Sets the value of the entry, and returns the entry's old value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(mut o) => assert_eq!(o.insert(1000), 100), + /// } + /// + /// assert_eq!(map[&"a"], 1000); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(&mut self, value: V) -> V { + mem::replace(self.get_mut(), value) + } + + /// Sets the value of the entry, and returns the entry's old value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// use std::rc::Rc; + /// + /// let key_one = Rc::new("a"); + /// let key_two = Rc::new("a"); + /// + /// let mut map: HashMap, u32> = HashMap::new(); + /// map.insert(key_one.clone(), 10); + /// + /// assert_eq!(map[&key_one], 10); + /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); + /// + /// match map.raw_entry_mut().from_key(&key_one) { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(mut o) => { + /// let old_key = o.insert_key(key_two.clone()); + /// assert!(Rc::ptr_eq(&old_key, &key_one)); + /// } + /// } + /// assert_eq!(map[&key_two], 10); + /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert_key(&mut self, key: K) -> K { + mem::replace(self.key_mut(), key) + } + + /// Takes the value out of the entry, and returns it. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => assert_eq!(o.remove(), 100), + /// } + /// assert_eq!(map.get(&"a"), None); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove(self) -> V { + self.remove_entry().1 + } + + /// Take the ownership of the key and value from the map. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => assert_eq!(o.remove_entry(), ("a", 100)), + /// } + /// assert_eq!(map.get(&"a"), None); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove_entry(self) -> (K, V) { + unsafe { self.table.remove(self.elem).0 } + } + + /// Provides shared access to the key and owned access to the value of + /// the entry and allows to replace or remove it based on the + /// value of the returned option. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// let raw_entry = match map.raw_entry_mut().from_key(&"a") { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| { + /// assert_eq!(k, &"a"); + /// assert_eq!(v, 100); + /// Some(v + 900) + /// }), + /// }; + /// let raw_entry = match raw_entry { + /// RawEntryMut::Vacant(_) => panic!(), + /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| { + /// assert_eq!(k, &"a"); + /// assert_eq!(v, 1000); + /// None + /// }), + /// }; + /// match raw_entry { + /// RawEntryMut::Vacant(_) => { }, + /// RawEntryMut::Occupied(_) => panic!(), + /// }; + /// assert_eq!(map.get(&"a"), None); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn replace_entry_with(self, f: F) -> RawEntryMut<'a, K, V, S, A> + where + F: FnOnce(&K, V) -> Option, + { + unsafe { + let still_occupied = self + .table + .replace_bucket_with(self.elem.clone(), |(key, value)| { + f(&key, value).map(|new_value| (key, new_value)) + }); + + if still_occupied { + RawEntryMut::Occupied(self) + } else { + RawEntryMut::Vacant(RawVacantEntryMut { + table: self.table, + hash_builder: self.hash_builder, + }) + } + } + } +} + +impl<'a, K, V, S, A: Allocator> RawVacantEntryMut<'a, K, V, S, A> { + /// Sets the value of the entry with the `VacantEntry`'s key, + /// and returns a mutable reference to it. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// + /// match map.raw_entry_mut().from_key(&"c") { + /// RawEntryMut::Occupied(_) => panic!(), + /// RawEntryMut::Vacant(v) => assert_eq!(v.insert("c", 300), (&mut "c", &mut 300)), + /// } + /// + /// assert_eq!(map[&"c"], 300); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V) + where + K: Hash, + S: BuildHasher, + { + let hash = make_hash::(self.hash_builder, &key); + self.insert_hashed_nocheck(hash, key, value) + } + + /// Sets the value of the entry with the `VacantEntry`'s key, + /// and returns a mutable reference to it. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into(); + /// let key = "c"; + /// let hash = compute_hash(map.hasher(), &key); + /// + /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) { + /// RawEntryMut::Occupied(_) => panic!(), + /// RawEntryMut::Vacant(v) => assert_eq!( + /// v.insert_hashed_nocheck(hash, key, 300), + /// (&mut "c", &mut 300) + /// ), + /// } + /// + /// assert_eq!(map[&"c"], 300); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + #[allow(clippy::shadow_unrelated)] + pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) + where + K: Hash, + S: BuildHasher, + { + let &mut (ref mut k, ref mut v) = self.table.insert_entry( + hash, + (key, value), + make_hasher::<_, V, S>(self.hash_builder), + ); + (k, v) + } + + /// Set the value of an entry with a custom hasher function. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use hashbrown::hash_map::{HashMap, RawEntryMut}; + /// + /// fn make_hasher(hash_builder: &S) -> impl Fn(&K) -> u64 + '_ + /// where + /// K: Hash + ?Sized, + /// S: BuildHasher, + /// { + /// move |key: &K| { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// } + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// let key = "a"; + /// let hash_builder = map.hasher().clone(); + /// let hash = make_hasher(&hash_builder)(&key); + /// + /// match map.raw_entry_mut().from_hash(hash, |q| q == &key) { + /// RawEntryMut::Occupied(_) => panic!(), + /// RawEntryMut::Vacant(v) => assert_eq!( + /// v.insert_with_hasher(hash, key, 100, make_hasher(&hash_builder)), + /// (&mut "a", &mut 100) + /// ), + /// } + /// map.extend([("b", 200), ("c", 300), ("d", 400), ("e", 500), ("f", 600)]); + /// assert_eq!(map[&"a"], 100); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert_with_hasher( + self, + hash: u64, + key: K, + value: V, + hasher: H, + ) -> (&'a mut K, &'a mut V) + where + H: Fn(&K) -> u64, + { + let &mut (ref mut k, ref mut v) = self + .table + .insert_entry(hash, (key, value), |x| hasher(&x.0)); + (k, v) + } + + #[cfg_attr(feature = "inline-more", inline)] + fn insert_entry(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A> + where + K: Hash, + S: BuildHasher, + { + let hash = make_hash::(self.hash_builder, &key); + let elem = self.table.insert( + hash, + (key, value), + make_hasher::<_, V, S>(self.hash_builder), + ); + RawOccupiedEntryMut { + elem, + table: self.table, + hash_builder: self.hash_builder, + } + } +} + +impl Debug for RawEntryBuilderMut<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawEntryBuilder").finish() + } +} + +impl Debug for RawEntryMut<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(), + RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(), + } + } +} + +impl Debug for RawOccupiedEntryMut<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawOccupiedEntryMut") + .field("key", self.key()) + .field("value", self.get()) + .finish() + } +} + +impl Debug for RawVacantEntryMut<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawVacantEntryMut").finish() + } +} + +impl Debug for RawEntryBuilder<'_, K, V, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawEntryBuilder").finish() + } +} + +#[cfg(test)] +mod test_map { + use super::HashMap; + use super::RawEntryMut; + + #[test] + fn test_raw_occupied_entry_replace_entry_with() { + let mut a = HashMap::new(); + + let key = "a key"; + let value = "an initial value"; + let new_value = "a new value"; + + let entry = a + .raw_entry_mut() + .from_key(&key) + .insert(key, value) + .replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, value); + Some(new_value) + }); + + match entry { + RawEntryMut::Occupied(e) => { + assert_eq!(e.key(), &key); + assert_eq!(e.get(), &new_value); + } + RawEntryMut::Vacant(_) => panic!(), + } + + assert_eq!(a[key], new_value); + assert_eq!(a.len(), 1); + + let entry = match a.raw_entry_mut().from_key(&key) { + RawEntryMut::Occupied(e) => e.replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, new_value); + None + }), + RawEntryMut::Vacant(_) => panic!(), + }; + + match entry { + RawEntryMut::Vacant(_) => {} + RawEntryMut::Occupied(_) => panic!(), + } + + assert!(!a.contains_key(key)); + assert_eq!(a.len(), 0); + } + + #[test] + fn test_raw_entry_and_replace_entry_with() { + let mut a = HashMap::new(); + + let key = "a key"; + let value = "an initial value"; + let new_value = "a new value"; + + let entry = a + .raw_entry_mut() + .from_key(&key) + .and_replace_entry_with(|_, _| panic!()); + + match entry { + RawEntryMut::Vacant(_) => {} + RawEntryMut::Occupied(_) => panic!(), + } + + a.insert(key, value); + + let entry = a + .raw_entry_mut() + .from_key(&key) + .and_replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, value); + Some(new_value) + }); + + match entry { + RawEntryMut::Occupied(e) => { + assert_eq!(e.key(), &key); + assert_eq!(e.get(), &new_value); + } + RawEntryMut::Vacant(_) => panic!(), + } + + assert_eq!(a[key], new_value); + assert_eq!(a.len(), 1); + + let entry = a + .raw_entry_mut() + .from_key(&key) + .and_replace_entry_with(|k, v| { + assert_eq!(k, &key); + assert_eq!(v, new_value); + None + }); + + match entry { + RawEntryMut::Vacant(_) => {} + RawEntryMut::Occupied(_) => panic!(), + } + + assert!(!a.contains_key(key)); + assert_eq!(a.len(), 0); + } + + #[test] + fn test_raw_entry() { + use super::RawEntryMut::{Occupied, Vacant}; + + let xs = [(1_i32, 10_i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; + + let mut map: HashMap<_, _> = xs.iter().copied().collect(); + + let compute_hash = |map: &HashMap, k: i32| -> u64 { + super::make_hash::(map.hasher(), &k) + }; + + // Existing key (insert) + match map.raw_entry_mut().from_key(&1) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + assert_eq!(view.get(), &10); + assert_eq!(view.insert(100), 10); + } + } + let hash1 = compute_hash(&map, 1); + assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100)); + assert_eq!( + map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), + (&1, &100) + ); + assert_eq!( + map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), + (&1, &100) + ); + assert_eq!(map.len(), 6); + + // Existing key (update) + match map.raw_entry_mut().from_key(&2) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + let v = view.get_mut(); + let new_v = (*v) * 10; + *v = new_v; + } + } + let hash2 = compute_hash(&map, 2); + assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200)); + assert_eq!( + map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), + (&2, &200) + ); + assert_eq!( + map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), + (&2, &200) + ); + assert_eq!(map.len(), 6); + + // Existing key (take) + let hash3 = compute_hash(&map, 3); + match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) { + Vacant(_) => unreachable!(), + Occupied(view) => { + assert_eq!(view.remove_entry(), (3, 30)); + } + } + assert_eq!(map.raw_entry().from_key(&3), None); + assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None); + assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None); + assert_eq!(map.len(), 5); + + // Nonexistent key (insert) + match map.raw_entry_mut().from_key(&10) { + Occupied(_) => unreachable!(), + Vacant(view) => { + assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000)); + } + } + assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000)); + assert_eq!(map.len(), 6); + + // Ensure all lookup methods produce equivalent results. + for k in 0..12 { + let hash = compute_hash(&map, k); + let v = map.get(&k).copied(); + let kv = v.as_ref().map(|v| (&k, v)); + + assert_eq!(map.raw_entry().from_key(&k), kv); + assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv); + assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv); + + match map.raw_entry_mut().from_key(&k) { + Occupied(o) => assert_eq!(Some(o.get_key_value()), kv), + Vacant(_) => assert_eq!(v, None), + } + match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) { + Occupied(o) => assert_eq!(Some(o.get_key_value()), kv), + Vacant(_) => assert_eq!(v, None), + } + match map.raw_entry_mut().from_hash(hash, |q| *q == k) { + Occupied(o) => assert_eq!(Some(o.get_key_value()), kv), + Vacant(_) => assert_eq!(v, None), + } + } + } + + #[test] + fn test_key_without_hash_impl() { + #[derive(Debug)] + struct IntWrapper(u64); + + let mut m: HashMap = HashMap::default(); + { + assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none()); + } + { + let vacant_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) { + RawEntryMut::Occupied(..) => panic!("Found entry for key 0"), + RawEntryMut::Vacant(e) => e, + }; + vacant_entry.insert_with_hasher(0, IntWrapper(0), (), |k| k.0); + } + { + assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some()); + assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_none()); + assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none()); + } + { + let vacant_entry = match m.raw_entry_mut().from_hash(1, |k| k.0 == 1) { + RawEntryMut::Occupied(..) => panic!("Found entry for key 1"), + RawEntryMut::Vacant(e) => e, + }; + vacant_entry.insert_with_hasher(1, IntWrapper(1), (), |k| k.0); + } + { + assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some()); + assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some()); + assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none()); + } + { + let occupied_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) { + RawEntryMut::Occupied(e) => e, + RawEntryMut::Vacant(..) => panic!("Couldn't find entry for key 0"), + }; + occupied_entry.remove(); + } + assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none()); + assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some()); + assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none()); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/rustc_entry.rs b/bitbox02-bt/vendor/hashbrown/src/rustc_entry.rs new file mode 100644 index 0000000..cb48be0 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/rustc_entry.rs @@ -0,0 +1,567 @@ +use self::RustcEntry::*; +use crate::map::{make_hash, Drain, HashMap, IntoIter, Iter, IterMut}; +use crate::raw::{Allocator, Bucket, Global, RawTable}; +use core::fmt::{self, Debug}; +use core::hash::{BuildHasher, Hash}; +use core::mem; + +impl HashMap +where + K: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + /// Gets the given key's corresponding entry in the map for in-place manipulation. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut letters = HashMap::new(); + /// + /// for ch in "a short treatise on fungi".chars() { + /// let counter = letters.rustc_entry(ch).or_insert(0); + /// *counter += 1; + /// } + /// + /// assert_eq!(letters[&'s'], 2); + /// assert_eq!(letters[&'t'], 3); + /// assert_eq!(letters[&'u'], 1); + /// assert_eq!(letters.get(&'y'), None); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn rustc_entry(&mut self, key: K) -> RustcEntry<'_, K, V, A> { + let hash = make_hash(&self.hash_builder, &key); + if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) { + RustcEntry::Occupied(RustcOccupiedEntry { + elem, + table: &mut self.table, + }) + } else { + // Ideally we would put this in VacantEntry::insert, but Entry is not + // generic over the BuildHasher and adding a generic parameter would be + // a breaking change. + self.reserve(1); + + RustcEntry::Vacant(RustcVacantEntry { + hash, + key, + table: &mut self.table, + }) + } + } +} + +/// A view into a single entry in a map, which may either be vacant or occupied. +/// +/// This `enum` is constructed from the [`rustc_entry`] method on [`HashMap`]. +/// +/// [`HashMap`]: struct.HashMap.html +/// [`rustc_entry`]: struct.HashMap.html#method.rustc_entry +pub enum RustcEntry<'a, K, V, A = Global> +where + A: Allocator, +{ + /// An occupied entry. + Occupied(RustcOccupiedEntry<'a, K, V, A>), + + /// A vacant entry. + Vacant(RustcVacantEntry<'a, K, V, A>), +} + +impl Debug for RustcEntry<'_, K, V, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(), + Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(), + } + } +} + +/// A view into an occupied entry in a `HashMap`. +/// It is part of the [`RustcEntry`] enum. +/// +/// [`RustcEntry`]: enum.RustcEntry.html +pub struct RustcOccupiedEntry<'a, K, V, A = Global> +where + A: Allocator, +{ + elem: Bucket<(K, V)>, + table: &'a mut RawTable<(K, V), A>, +} + +unsafe impl Send for RustcOccupiedEntry<'_, K, V, A> +where + K: Send, + V: Send, + A: Allocator + Send, +{ +} +unsafe impl Sync for RustcOccupiedEntry<'_, K, V, A> +where + K: Sync, + V: Sync, + A: Allocator + Sync, +{ +} + +impl Debug for RustcOccupiedEntry<'_, K, V, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OccupiedEntry") + .field("key", self.key()) + .field("value", self.get()) + .finish() + } +} + +/// A view into a vacant entry in a `HashMap`. +/// It is part of the [`RustcEntry`] enum. +/// +/// [`RustcEntry`]: enum.RustcEntry.html +pub struct RustcVacantEntry<'a, K, V, A = Global> +where + A: Allocator, +{ + hash: u64, + key: K, + table: &'a mut RawTable<(K, V), A>, +} + +impl Debug for RustcVacantEntry<'_, K, V, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("VacantEntry").field(self.key()).finish() + } +} + +impl<'a, K, V, A: Allocator> RustcEntry<'a, K, V, A> { + /// Sets the value of the entry, and returns a RustcOccupiedEntry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// let entry = map.rustc_entry("horseyland").insert(37); + /// + /// assert_eq!(entry.key(), &"horseyland"); + /// ``` + pub fn insert(self, value: V) -> RustcOccupiedEntry<'a, K, V, A> { + match self { + Vacant(entry) => entry.insert_entry(value), + Occupied(mut entry) => { + entry.insert(value); + entry + } + } + } + + /// Ensures a value is in the entry by inserting the default if empty, and returns + /// a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// map.rustc_entry("poneyland").or_insert(3); + /// assert_eq!(map["poneyland"], 3); + /// + /// *map.rustc_entry("poneyland").or_insert(10) *= 2; + /// assert_eq!(map["poneyland"], 6); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert(self, default: V) -> &'a mut V + where + K: Hash, + { + match self { + Occupied(entry) => entry.into_mut(), + Vacant(entry) => entry.insert(default), + } + } + + /// Ensures a value is in the entry by inserting the result of the default function if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, String> = HashMap::new(); + /// let s = "hoho".to_string(); + /// + /// map.rustc_entry("poneyland").or_insert_with(|| s); + /// + /// assert_eq!(map["poneyland"], "hoho".to_string()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert_with V>(self, default: F) -> &'a mut V + where + K: Hash, + { + match self { + Occupied(entry) => entry.into_mut(), + Vacant(entry) => entry.insert(default()), + } + } + + /// Returns a reference to this entry's key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// assert_eq!(map.rustc_entry("poneyland").key(), &"poneyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &K { + match *self { + Occupied(ref entry) => entry.key(), + Vacant(ref entry) => entry.key(), + } + } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the map. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// map.rustc_entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 42); + /// + /// map.rustc_entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 43); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn and_modify(self, f: F) -> Self + where + F: FnOnce(&mut V), + { + match self { + Occupied(mut entry) => { + f(entry.get_mut()); + Occupied(entry) + } + Vacant(entry) => Vacant(entry), + } + } +} + +impl<'a, K, V: Default, A: Allocator> RustcEntry<'a, K, V, A> { + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// # fn main() { + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, Option> = HashMap::new(); + /// map.rustc_entry("poneyland").or_default(); + /// + /// assert_eq!(map["poneyland"], None); + /// # } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_default(self) -> &'a mut V + where + K: Hash, + { + match self { + Occupied(entry) => entry.into_mut(), + Vacant(entry) => entry.insert(Default::default()), + } + } +} + +impl<'a, K, V, A: Allocator> RustcOccupiedEntry<'a, K, V, A> { + /// Gets a reference to the key in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.rustc_entry("poneyland").or_insert(12); + /// assert_eq!(map.rustc_entry("poneyland").key(), &"poneyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &K { + unsafe { &self.elem.as_ref().0 } + } + + /// Take the ownership of the key and value from the map. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.rustc_entry("poneyland").or_insert(12); + /// + /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { + /// // We delete the entry from the map. + /// o.remove_entry(); + /// } + /// + /// assert_eq!(map.contains_key("poneyland"), false); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove_entry(self) -> (K, V) { + unsafe { self.table.remove(self.elem).0 } + } + + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.rustc_entry("poneyland").or_insert(12); + /// + /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { + /// assert_eq!(o.get(), &12); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get(&self) -> &V { + unsafe { &self.elem.as_ref().1 } + } + + /// Gets a mutable reference to the value in the entry. + /// + /// If you need a reference to the `RustcOccupiedEntry` which may outlive the + /// destruction of the `RustcEntry` value, see [`into_mut`]. + /// + /// [`into_mut`]: #method.into_mut + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.rustc_entry("poneyland").or_insert(12); + /// + /// assert_eq!(map["poneyland"], 12); + /// if let RustcEntry::Occupied(mut o) = map.rustc_entry("poneyland") { + /// *o.get_mut() += 10; + /// assert_eq!(*o.get(), 22); + /// + /// // We can use the same RustcEntry multiple times. + /// *o.get_mut() += 2; + /// } + /// + /// assert_eq!(map["poneyland"], 24); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_mut(&mut self) -> &mut V { + unsafe { &mut self.elem.as_mut().1 } + } + + /// Converts the RustcOccupiedEntry into a mutable reference to the value in the entry + /// with a lifetime bound to the map itself. + /// + /// If you need multiple references to the `RustcOccupiedEntry`, see [`get_mut`]. + /// + /// [`get_mut`]: #method.get_mut + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.rustc_entry("poneyland").or_insert(12); + /// + /// assert_eq!(map["poneyland"], 12); + /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { + /// *o.into_mut() += 10; + /// } + /// + /// assert_eq!(map["poneyland"], 22); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_mut(self) -> &'a mut V { + unsafe { &mut self.elem.as_mut().1 } + } + + /// Sets the value of the entry, and returns the entry's old value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.rustc_entry("poneyland").or_insert(12); + /// + /// if let RustcEntry::Occupied(mut o) = map.rustc_entry("poneyland") { + /// assert_eq!(o.insert(15), 12); + /// } + /// + /// assert_eq!(map["poneyland"], 15); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(&mut self, value: V) -> V { + mem::replace(self.get_mut(), value) + } + + /// Takes the value out of the entry, and returns it. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.rustc_entry("poneyland").or_insert(12); + /// + /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { + /// assert_eq!(o.remove(), 12); + /// } + /// + /// assert_eq!(map.contains_key("poneyland"), false); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove(self) -> V { + self.remove_entry().1 + } +} + +impl<'a, K, V, A: Allocator> RustcVacantEntry<'a, K, V, A> { + /// Gets a reference to the key that would be used when inserting a value + /// through the `RustcVacantEntry`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// assert_eq!(map.rustc_entry("poneyland").key(), &"poneyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn key(&self) -> &K { + &self.key + } + + /// Take ownership of the key. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// if let RustcEntry::Vacant(v) = map.rustc_entry("poneyland") { + /// v.into_key(); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_key(self) -> K { + self.key + } + + /// Sets the value of the entry with the RustcVacantEntry's key, + /// and returns a mutable reference to it. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// if let RustcEntry::Vacant(o) = map.rustc_entry("poneyland") { + /// o.insert(37); + /// } + /// assert_eq!(map["poneyland"], 37); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self, value: V) -> &'a mut V { + unsafe { + let bucket = self.table.insert_no_grow(self.hash, (self.key, value)); + &mut bucket.as_mut().1 + } + } + + /// Sets the value of the entry with the RustcVacantEntry's key, + /// and returns a RustcOccupiedEntry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashMap; + /// use hashbrown::hash_map::RustcEntry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// if let RustcEntry::Vacant(v) = map.rustc_entry("poneyland") { + /// let o = v.insert_entry(37); + /// assert_eq!(o.get(), &37); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert_entry(self, value: V) -> RustcOccupiedEntry<'a, K, V, A> { + let bucket = unsafe { self.table.insert_no_grow(self.hash, (self.key, value)) }; + RustcOccupiedEntry { + elem: bucket, + table: self.table, + } + } +} + +impl IterMut<'_, K, V> { + /// Returns a iterator of references over the remaining items. + #[cfg_attr(feature = "inline-more", inline)] + pub fn rustc_iter(&self) -> Iter<'_, K, V> { + self.iter() + } +} + +impl IntoIter { + /// Returns a iterator of references over the remaining items. + #[cfg_attr(feature = "inline-more", inline)] + pub fn rustc_iter(&self) -> Iter<'_, K, V> { + self.iter() + } +} + +impl Drain<'_, K, V> { + /// Returns a iterator of references over the remaining items. + #[cfg_attr(feature = "inline-more", inline)] + pub fn rustc_iter(&self) -> Iter<'_, K, V> { + self.iter() + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/scopeguard.rs b/bitbox02-bt/vendor/hashbrown/src/scopeguard.rs new file mode 100644 index 0000000..382d060 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/scopeguard.rs @@ -0,0 +1,72 @@ +// Extracted from the scopeguard crate +use core::{ + mem::ManuallyDrop, + ops::{Deref, DerefMut}, + ptr, +}; + +pub struct ScopeGuard +where + F: FnMut(&mut T), +{ + dropfn: F, + value: T, +} + +#[inline] +pub fn guard(value: T, dropfn: F) -> ScopeGuard +where + F: FnMut(&mut T), +{ + ScopeGuard { dropfn, value } +} + +impl ScopeGuard +where + F: FnMut(&mut T), +{ + #[inline] + pub fn into_inner(guard: Self) -> T { + // Cannot move out of Drop-implementing types, so + // ptr::read the value out of a ManuallyDrop + // Don't use mem::forget as that might invalidate value + let guard = ManuallyDrop::new(guard); + unsafe { + let value = ptr::read(&guard.value); + // read the closure so that it is dropped + let _ = ptr::read(&guard.dropfn); + value + } + } +} + +impl Deref for ScopeGuard +where + F: FnMut(&mut T), +{ + type Target = T; + #[inline] + fn deref(&self) -> &T { + &self.value + } +} + +impl DerefMut for ScopeGuard +where + F: FnMut(&mut T), +{ + #[inline] + fn deref_mut(&mut self) -> &mut T { + &mut self.value + } +} + +impl Drop for ScopeGuard +where + F: FnMut(&mut T), +{ + #[inline] + fn drop(&mut self) { + (self.dropfn)(&mut self.value); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/set.rs b/bitbox02-bt/vendor/hashbrown/src/set.rs new file mode 100644 index 0000000..442e1cf --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/set.rs @@ -0,0 +1,3106 @@ +use crate::{Equivalent, TryReserveError}; +use core::hash::{BuildHasher, Hash}; +use core::iter::{Chain, FusedIterator}; +use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Sub, SubAssign}; +use core::{fmt, mem}; +use map::make_hash; + +use super::map::{self, HashMap, Keys}; +use crate::raw::{Allocator, Global, RawExtractIf}; +use crate::DefaultHashBuilder; + +// Future Optimization (FIXME!) +// ============================= +// +// Iteration over zero sized values is a noop. There is no need +// for `bucket.val` in the case of HashSet. I suppose we would need HKT +// to get rid of it properly. + +/// A hash set implemented as a `HashMap` where the value is `()`. +/// +/// As with the [`HashMap`] type, a `HashSet` requires that the elements +/// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by +/// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself, +/// it is important that the following property holds: +/// +/// ```text +/// k1 == k2 -> hash(k1) == hash(k2) +/// ``` +/// +/// In other words, if two keys are equal, their hashes must be equal. +/// +/// +/// It is a logic error for an item to be modified in such a way that the +/// item's hash, as determined by the [`Hash`] trait, or its equality, as +/// determined by the [`Eq`] trait, changes while it is in the set. This is +/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or +/// unsafe code. +/// +/// It is also a logic error for the [`Hash`] implementation of a key to panic. +/// This is generally only possible if the trait is implemented manually. If a +/// panic does occur then the contents of the `HashSet` may become corrupted and +/// some items may be dropped from the table. +/// +/// # Examples +/// +/// ``` +/// use hashbrown::HashSet; +/// // Type inference lets us omit an explicit type signature (which +/// // would be `HashSet` in this example). +/// let mut books = HashSet::new(); +/// +/// // Add some books. +/// books.insert("A Dance With Dragons".to_string()); +/// books.insert("To Kill a Mockingbird".to_string()); +/// books.insert("The Odyssey".to_string()); +/// books.insert("The Great Gatsby".to_string()); +/// +/// // Check for a specific one. +/// if !books.contains("The Winds of Winter") { +/// println!("We have {} books, but The Winds of Winter ain't one.", +/// books.len()); +/// } +/// +/// // Remove a book. +/// books.remove("The Odyssey"); +/// +/// // Iterate over everything. +/// for book in &books { +/// println!("{}", book); +/// } +/// ``` +/// +/// The easiest way to use `HashSet` with a custom type is to derive +/// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`]. This will in the +/// future be implied by [`Eq`]. +/// +/// ``` +/// use hashbrown::HashSet; +/// #[derive(Hash, Eq, PartialEq, Debug)] +/// struct Viking { +/// name: String, +/// power: usize, +/// } +/// +/// let mut vikings = HashSet::new(); +/// +/// vikings.insert(Viking { name: "Einar".to_string(), power: 9 }); +/// vikings.insert(Viking { name: "Einar".to_string(), power: 9 }); +/// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 }); +/// vikings.insert(Viking { name: "Harald".to_string(), power: 8 }); +/// +/// // Use derived implementation to print the vikings. +/// for x in &vikings { +/// println!("{:?}", x); +/// } +/// ``` +/// +/// A `HashSet` with fixed list of elements can be initialized from an array: +/// +/// ``` +/// use hashbrown::HashSet; +/// +/// let viking_names: HashSet<&'static str> = +/// [ "Einar", "Olaf", "Harald" ].into_iter().collect(); +/// // use the values stored in the set +/// ``` +/// +/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html +/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html +/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html +/// [`HashMap`]: struct.HashMap.html +/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html +/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html +pub struct HashSet { + pub(crate) map: HashMap, +} + +impl Clone for HashSet { + fn clone(&self) -> Self { + HashSet { + map: self.map.clone(), + } + } + + fn clone_from(&mut self, source: &Self) { + self.map.clone_from(&source.map); + } +} + +#[cfg(feature = "default-hasher")] +impl HashSet { + /// Creates an empty `HashSet`. + /// + /// The hash set is initially created with a capacity of 0, so it will not allocate until it + /// is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`], for example with + /// [`with_hasher`](HashSet::with_hasher) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let set: HashSet = HashSet::new(); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn new() -> Self { + Self { + map: HashMap::new(), + } + } + + /// Creates an empty `HashSet` with the specified capacity. + /// + /// The hash set will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash set will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`], for example with + /// [`with_capacity_and_hasher`](HashSet::with_capacity_and_hasher) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let set: HashSet = HashSet::with_capacity(10); + /// assert!(set.capacity() >= 10); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity(capacity: usize) -> Self { + Self { + map: HashMap::with_capacity(capacity), + } + } +} + +#[cfg(feature = "default-hasher")] +impl HashSet { + /// Creates an empty `HashSet`. + /// + /// The hash set is initially created with a capacity of 0, so it will not allocate until it + /// is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`], for example with + /// [`with_hasher_in`](HashSet::with_hasher_in) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let set: HashSet = HashSet::new(); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn new_in(alloc: A) -> Self { + Self { + map: HashMap::new_in(alloc), + } + } + + /// Creates an empty `HashSet` with the specified capacity. + /// + /// The hash set will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash set will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`], for example with + /// [`with_capacity_and_hasher_in`](HashSet::with_capacity_and_hasher_in) method. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let set: HashSet = HashSet::with_capacity(10); + /// assert!(set.capacity() >= 10); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { + Self { + map: HashMap::with_capacity_in(capacity, alloc), + } + } +} + +impl HashSet { + /// Returns the number of elements the set can hold without reallocating. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let set: HashSet = HashSet::with_capacity(100); + /// assert!(set.capacity() >= 100); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn capacity(&self) -> usize { + self.map.capacity() + } + + /// An iterator visiting all elements in arbitrary order. + /// The iterator element type is `&'a T`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let mut set = HashSet::new(); + /// set.insert("a"); + /// set.insert("b"); + /// + /// // Will print in an arbitrary order. + /// for x in set.iter() { + /// println!("{}", x); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn iter(&self) -> Iter<'_, T> { + Iter { + iter: self.map.keys(), + } + } + + /// Returns the number of elements in the set. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut v = HashSet::new(); + /// assert_eq!(v.len(), 0); + /// v.insert(1); + /// assert_eq!(v.len(), 1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns `true` if the set contains no elements. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut v = HashSet::new(); + /// assert!(v.is_empty()); + /// v.insert(1); + /// assert!(!v.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + + /// Clears the set, returning all elements in an iterator. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// assert!(!set.is_empty()); + /// + /// // print 1, 2, 3 in an arbitrary order + /// for i in set.drain() { + /// println!("{}", i); + /// } + /// + /// assert!(set.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn drain(&mut self) -> Drain<'_, T, A> { + Drain { + iter: self.map.drain(), + } + } + + /// Retains only the elements specified by the predicate. + /// + /// In other words, remove all elements `e` such that `f(&e)` returns `false`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let xs = [1,2,3,4,5,6]; + /// let mut set: HashSet = xs.into_iter().collect(); + /// set.retain(|&k| k % 2 == 0); + /// assert_eq!(set.len(), 3); + /// ``` + pub fn retain(&mut self, mut f: F) + where + F: FnMut(&T) -> bool, + { + self.map.retain(|k, _| f(k)); + } + + /// Drains elements which are true under the given predicate, + /// and returns an iterator over the removed items. + /// + /// In other words, move all elements `e` such that `f(&e)` returns `true` out + /// into another iterator. + /// + /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating + /// or the iteration short-circuits, then the remaining elements will be retained. + /// Use [`retain()`] with a negated predicate if you do not need the returned iterator. + /// + /// [`retain()`]: HashSet::retain + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet = (0..8).collect(); + /// let drained: HashSet = set.extract_if(|v| v % 2 == 0).collect(); + /// + /// let mut evens = drained.into_iter().collect::>(); + /// let mut odds = set.into_iter().collect::>(); + /// evens.sort(); + /// odds.sort(); + /// + /// assert_eq!(evens, vec![0, 2, 4, 6]); + /// assert_eq!(odds, vec![1, 3, 5, 7]); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn extract_if(&mut self, f: F) -> ExtractIf<'_, T, F, A> + where + F: FnMut(&T) -> bool, + { + ExtractIf { + f, + inner: RawExtractIf { + iter: unsafe { self.map.table.iter() }, + table: &mut self.map.table, + }, + } + } + + /// Clears the set, removing all values. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut v = HashSet::new(); + /// v.insert(1); + /// v.clear(); + /// assert!(v.is_empty()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn clear(&mut self) { + self.map.clear(); + } +} + +impl HashSet { + /// Creates a new empty hash set which will use the given hasher to hash + /// keys. + /// + /// The hash set is initially created with a capacity of 0, so it will not + /// allocate until it is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`]. + /// + /// The `hash_builder` passed should implement the [`BuildHasher`] trait for + /// the `HashSet` to be useful, see its documentation for details. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut set = HashSet::with_hasher(s); + /// set.insert(2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub const fn with_hasher(hasher: S) -> Self { + Self { + map: HashMap::with_hasher(hasher), + } + } + + /// Creates an empty `HashSet` with the specified capacity, using + /// `hasher` to hash the keys. + /// + /// The hash set will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash set will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`]. + /// + /// The `hash_builder` passed should implement the [`BuildHasher`] trait for + /// the `HashSet` to be useful, see its documentation for details. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut set = HashSet::with_capacity_and_hasher(10, s); + /// set.insert(1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self { + Self { + map: HashMap::with_capacity_and_hasher(capacity, hasher), + } + } +} + +impl HashSet +where + A: Allocator, +{ + /// Returns a reference to the underlying allocator. + #[inline] + pub fn allocator(&self) -> &A { + self.map.allocator() + } + + /// Creates a new empty hash set which will use the given hasher to hash + /// keys. + /// + /// The hash set is initially created with a capacity of 0, so it will not + /// allocate until it is first inserted into. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`]. + /// + /// The `hash_builder` passed should implement the [`BuildHasher`] trait for + /// the `HashSet` to be useful, see its documentation for details. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut set = HashSet::with_hasher(s); + /// set.insert(2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub const fn with_hasher_in(hasher: S, alloc: A) -> Self { + Self { + map: HashMap::with_hasher_in(hasher, alloc), + } + } + + /// Creates an empty `HashSet` with the specified capacity, using + /// `hasher` to hash the keys. + /// + /// The hash set will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash set will not allocate. + /// + /// # HashDoS resistance + /// + /// The `hash_builder` normally use a fixed key by default and that does + /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`]. + /// Users who require HashDoS resistance should explicitly use + /// [`std::collections::hash_map::RandomState`] + /// as the hasher when creating a [`HashSet`]. + /// + /// The `hash_builder` passed should implement the [`BuildHasher`] trait for + /// the `HashSet` to be useful, see its documentation for details. + /// + /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack + /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::DefaultHashBuilder; + /// + /// let s = DefaultHashBuilder::default(); + /// let mut set = HashSet::with_capacity_and_hasher(10, s); + /// set.insert(1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn with_capacity_and_hasher_in(capacity: usize, hasher: S, alloc: A) -> Self { + Self { + map: HashMap::with_capacity_and_hasher_in(capacity, hasher, alloc), + } + } + + /// Returns a reference to the set's [`BuildHasher`]. + /// + /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::DefaultHashBuilder; + /// + /// let hasher = DefaultHashBuilder::default(); + /// let set: HashSet = HashSet::with_hasher(hasher); + /// let hasher: &DefaultHashBuilder = set.hasher(); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn hasher(&self) -> &S { + self.map.hasher() + } +} + +impl HashSet +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the `HashSet`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program + /// in case of allocation error. Use [`try_reserve`](HashSet::try_reserve) instead + /// if you want to handle memory allocation failure. + /// + /// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html + /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let mut set: HashSet = HashSet::new(); + /// set.reserve(10); + /// assert!(set.capacity() >= 10); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn reserve(&mut self, additional: usize) { + self.map.reserve(additional); + } + + /// Tries to reserve capacity for at least `additional` more elements to be inserted + /// in the given `HashSet`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let mut set: HashSet = HashSet::new(); + /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.map.try_reserve(additional) + } + + /// Shrinks the capacity of the set as much as possible. It will drop + /// down as much as possible while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set = HashSet::with_capacity(100); + /// set.insert(1); + /// set.insert(2); + /// assert!(set.capacity() >= 100); + /// set.shrink_to_fit(); + /// assert!(set.capacity() >= 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn shrink_to_fit(&mut self) { + self.map.shrink_to_fit(); + } + + /// Shrinks the capacity of the set with a lower limit. It will drop + /// down no lower than the supplied limit while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set = HashSet::with_capacity(100); + /// set.insert(1); + /// set.insert(2); + /// assert!(set.capacity() >= 100); + /// set.shrink_to(10); + /// assert!(set.capacity() >= 10); + /// set.shrink_to(0); + /// assert!(set.capacity() >= 2); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.map.shrink_to(min_capacity); + } + + /// Visits the values representing the difference, + /// i.e., the values that are in `self` but not in `other`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let a: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect(); + /// + /// // Can be seen as `a - b`. + /// for x in a.difference(&b) { + /// println!("{}", x); // Print 1 + /// } + /// + /// let diff: HashSet<_> = a.difference(&b).collect(); + /// assert_eq!(diff, [1].iter().collect()); + /// + /// // Note that difference is not symmetric, + /// // and `b - a` means something else: + /// let diff: HashSet<_> = b.difference(&a).collect(); + /// assert_eq!(diff, [4].iter().collect()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, T, S, A> { + Difference { + iter: self.iter(), + other, + } + } + + /// Visits the values representing the symmetric difference, + /// i.e., the values that are in `self` or in `other` but not in both. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let a: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect(); + /// + /// // Print 1, 4 in arbitrary order. + /// for x in a.symmetric_difference(&b) { + /// println!("{}", x); + /// } + /// + /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect(); + /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect(); + /// + /// assert_eq!(diff1, diff2); + /// assert_eq!(diff1, [1, 4].iter().collect()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, T, S, A> { + SymmetricDifference { + iter: self.difference(other).chain(other.difference(self)), + } + } + + /// Visits the values representing the intersection, + /// i.e., the values that are both in `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let a: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect(); + /// + /// // Print 2, 3 in arbitrary order. + /// for x in a.intersection(&b) { + /// println!("{}", x); + /// } + /// + /// let intersection: HashSet<_> = a.intersection(&b).collect(); + /// assert_eq!(intersection, [2, 3].iter().collect()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T, S, A> { + let (smaller, larger) = if self.len() <= other.len() { + (self, other) + } else { + (other, self) + }; + Intersection { + iter: smaller.iter(), + other: larger, + } + } + + /// Visits the values representing the union, + /// i.e., all the values in `self` or `other`, without duplicates. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let a: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect(); + /// + /// // Print 1, 2, 3, 4 in arbitrary order. + /// for x in a.union(&b) { + /// println!("{}", x); + /// } + /// + /// let union: HashSet<_> = a.union(&b).collect(); + /// assert_eq!(union, [1, 2, 3, 4].iter().collect()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T, S, A> { + // We'll iterate one set in full, and only the remaining difference from the other. + // Use the smaller set for the difference in order to reduce hash lookups. + let (smaller, larger) = if self.len() <= other.len() { + (self, other) + } else { + (other, self) + }; + Union { + iter: larger.iter().chain(smaller.difference(larger)), + } + } + + /// Returns `true` if the set contains a value. + /// + /// The value may be any borrowed form of the set's value type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the value type. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let set: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// assert_eq!(set.contains(&1), true); + /// assert_eq!(set.contains(&4), false); + /// ``` + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + #[cfg_attr(feature = "inline-more", inline)] + pub fn contains(&self, value: &Q) -> bool + where + Q: Hash + Equivalent + ?Sized, + { + self.map.contains_key(value) + } + + /// Returns a reference to the value in the set, if any, that is equal to the given value. + /// + /// The value may be any borrowed form of the set's value type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the value type. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let set: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// assert_eq!(set.get(&2), Some(&2)); + /// assert_eq!(set.get(&4), None); + /// ``` + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + #[cfg_attr(feature = "inline-more", inline)] + pub fn get(&self, value: &Q) -> Option<&T> + where + Q: Hash + Equivalent + ?Sized, + { + // Avoid `Option::map` because it bloats LLVM IR. + match self.map.get_key_value(value) { + Some((k, _)) => Some(k), + None => None, + } + } + + /// Inserts the given `value` into the set if it is not present, then + /// returns a reference to the value in the set. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// assert_eq!(set.len(), 3); + /// assert_eq!(set.get_or_insert(2), &2); + /// assert_eq!(set.get_or_insert(100), &100); + /// assert_eq!(set.len(), 4); // 100 was inserted + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_or_insert(&mut self, value: T) -> &T { + let hash = make_hash(&self.map.hash_builder, &value); + let bucket = match self.map.find_or_find_insert_slot(hash, &value) { + Ok(bucket) => bucket, + Err(slot) => unsafe { self.map.table.insert_in_slot(hash, slot, (value, ())) }, + }; + unsafe { &bucket.as_ref().0 } + } + + /// Inserts a value computed from `f` into the set if the given `value` is + /// not present, then returns a reference to the value in the set. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet = ["cat", "dog", "horse"] + /// .iter().map(|&pet| pet.to_owned()).collect(); + /// + /// assert_eq!(set.len(), 3); + /// for &pet in &["cat", "dog", "fish"] { + /// let value = set.get_or_insert_with(pet, str::to_owned); + /// assert_eq!(value, pet); + /// } + /// assert_eq!(set.len(), 4); // a new "fish" was inserted + /// ``` + /// + /// The following example will panic because the new value doesn't match. + /// + /// ```should_panic + /// let mut set = hashbrown::HashSet::new(); + /// set.get_or_insert_with("rust", |_| String::new()); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get_or_insert_with(&mut self, value: &Q, f: F) -> &T + where + Q: Hash + Equivalent + ?Sized, + F: FnOnce(&Q) -> T, + { + let hash = make_hash(&self.map.hash_builder, value); + let bucket = match self.map.find_or_find_insert_slot(hash, value) { + Ok(bucket) => bucket, + Err(slot) => { + let new = f(value); + assert!(value.equivalent(&new), "new value is not equivalent"); + unsafe { self.map.table.insert_in_slot(hash, slot, (new, ())) } + } + }; + unsafe { &bucket.as_ref().0 } + } + + /// Gets the given value's corresponding entry in the set for in-place manipulation. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::hash_set::Entry::*; + /// + /// let mut singles = HashSet::new(); + /// let mut dupes = HashSet::new(); + /// + /// for ch in "a short treatise on fungi".chars() { + /// if let Vacant(dupe_entry) = dupes.entry(ch) { + /// // We haven't already seen a duplicate, so + /// // check if we've at least seen it once. + /// match singles.entry(ch) { + /// Vacant(single_entry) => { + /// // We found a new character for the first time. + /// single_entry.insert(); + /// } + /// Occupied(single_entry) => { + /// // We've already seen this once, "move" it to dupes. + /// single_entry.remove(); + /// dupe_entry.insert(); + /// } + /// } + /// } + /// } + /// + /// assert!(!singles.contains(&'t') && dupes.contains(&'t')); + /// assert!(singles.contains(&'u') && !dupes.contains(&'u')); + /// assert!(!singles.contains(&'v') && !dupes.contains(&'v')); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn entry(&mut self, value: T) -> Entry<'_, T, S, A> { + match self.map.entry(value) { + map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { inner: entry }), + map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { inner: entry }), + } + } + + /// Returns `true` if `self` has no elements in common with `other`. + /// This is equivalent to checking for an empty intersection. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let a: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// let mut b = HashSet::new(); + /// + /// assert_eq!(a.is_disjoint(&b), true); + /// b.insert(4); + /// assert_eq!(a.is_disjoint(&b), true); + /// b.insert(1); + /// assert_eq!(a.is_disjoint(&b), false); + /// ``` + pub fn is_disjoint(&self, other: &Self) -> bool { + self.intersection(other).next().is_none() + } + + /// Returns `true` if the set is a subset of another, + /// i.e., `other` contains at least all the values in `self`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let sup: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// let mut set = HashSet::new(); + /// + /// assert_eq!(set.is_subset(&sup), true); + /// set.insert(2); + /// assert_eq!(set.is_subset(&sup), true); + /// set.insert(4); + /// assert_eq!(set.is_subset(&sup), false); + /// ``` + pub fn is_subset(&self, other: &Self) -> bool { + self.len() <= other.len() && self.iter().all(|v| other.contains(v)) + } + + /// Returns `true` if the set is a superset of another, + /// i.e., `self` contains at least all the values in `other`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let sub: HashSet<_> = [1, 2].into_iter().collect(); + /// let mut set = HashSet::new(); + /// + /// assert_eq!(set.is_superset(&sub), false); + /// + /// set.insert(0); + /// set.insert(1); + /// assert_eq!(set.is_superset(&sub), false); + /// + /// set.insert(2); + /// assert_eq!(set.is_superset(&sub), true); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn is_superset(&self, other: &Self) -> bool { + other.is_subset(self) + } + + /// Adds a value to the set. + /// + /// If the set did not have this value present, `true` is returned. + /// + /// If the set did have this value present, `false` is returned. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set = HashSet::new(); + /// + /// assert_eq!(set.insert(2), true); + /// assert_eq!(set.insert(2), false); + /// assert_eq!(set.len(), 1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(&mut self, value: T) -> bool { + self.map.insert(value, ()).is_none() + } + + /// Insert a value the set without checking if the value already exists in the set. + /// + /// This operation is faster than regular insert, because it does not perform + /// lookup before insertion. + /// + /// This operation is useful during initial population of the set. + /// For example, when constructing a set from another set, we know + /// that values are unique. + /// + /// # Safety + /// + /// This operation is safe if a value does not exist in the set. + /// + /// However, if a value exists in the set already, the behavior is unspecified: + /// this operation may panic, loop forever, or any following operation with the set + /// may panic, loop forever or return arbitrary result. + /// + /// That said, this operation (and following operations) are guaranteed to + /// not violate memory safety. + /// + /// However this operation is still unsafe because the resulting `HashSet` + /// may be passed to unsafe code which does expect the set to behave + /// correctly, and would cause unsoundness as a result. + #[cfg_attr(feature = "inline-more", inline)] + pub unsafe fn insert_unique_unchecked(&mut self, value: T) -> &T { + self.map.insert_unique_unchecked(value, ()).0 + } + + /// Adds a value to the set, replacing the existing value, if any, that is equal to the given + /// one. Returns the replaced value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set = HashSet::new(); + /// set.insert(Vec::::new()); + /// + /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0); + /// set.replace(Vec::with_capacity(10)); + /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn replace(&mut self, value: T) -> Option { + let hash = make_hash(&self.map.hash_builder, &value); + match self.map.find_or_find_insert_slot(hash, &value) { + Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().0 }, value)), + Err(slot) => { + unsafe { + self.map.table.insert_in_slot(hash, slot, (value, ())); + } + None + } + } + } + + /// Removes a value from the set. Returns whether the value was + /// present in the set. + /// + /// The value may be any borrowed form of the set's value type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the value type. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set = HashSet::new(); + /// + /// set.insert(2); + /// assert_eq!(set.remove(&2), true); + /// assert_eq!(set.remove(&2), false); + /// ``` + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove(&mut self, value: &Q) -> bool + where + Q: Hash + Equivalent + ?Sized, + { + self.map.remove(value).is_some() + } + + /// Removes and returns the value in the set, if any, that is equal to the given one. + /// + /// The value may be any borrowed form of the set's value type, but + /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for + /// the value type. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet<_> = [1, 2, 3].into_iter().collect(); + /// assert_eq!(set.take(&2), Some(2)); + /// assert_eq!(set.take(&2), None); + /// ``` + /// + /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html + /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html + #[cfg_attr(feature = "inline-more", inline)] + pub fn take(&mut self, value: &Q) -> Option + where + Q: Hash + Equivalent + ?Sized, + { + // Avoid `Option::map` because it bloats LLVM IR. + match self.map.remove_entry(value) { + Some((k, _)) => Some(k), + None => None, + } + } + + /// Returns the total amount of memory allocated internally by the hash + /// set, in bytes. + /// + /// The returned number is informational only. It is intended to be + /// primarily used for memory profiling. + #[inline] + pub fn allocation_size(&self) -> usize { + self.map.allocation_size() + } +} + +impl PartialEq for HashSet +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + fn eq(&self, other: &Self) -> bool { + if self.len() != other.len() { + return false; + } + + self.iter().all(|key| other.contains(key)) + } +} + +impl Eq for HashSet +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ +} + +impl fmt::Debug for HashSet +where + T: fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set().entries(self.iter()).finish() + } +} + +impl From> for HashSet +where + A: Allocator, +{ + fn from(map: HashMap) -> Self { + Self { map } + } +} + +impl FromIterator for HashSet +where + T: Eq + Hash, + S: BuildHasher + Default, + A: Default + Allocator, +{ + #[cfg_attr(feature = "inline-more", inline)] + fn from_iter>(iter: I) -> Self { + let mut set = Self::with_hasher_in(Default::default(), Default::default()); + set.extend(iter); + set + } +} + +// The default hasher is used to match the std implementation signature +#[cfg(feature = "default-hasher")] +impl From<[T; N]> for HashSet +where + T: Eq + Hash, + A: Default + Allocator, +{ + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let set1 = HashSet::from([1, 2, 3, 4]); + /// let set2: HashSet<_> = [1, 2, 3, 4].into(); + /// assert_eq!(set1, set2); + /// ``` + fn from(arr: [T; N]) -> Self { + arr.into_iter().collect() + } +} + +impl Extend for HashSet +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + #[cfg_attr(feature = "inline-more", inline)] + fn extend>(&mut self, iter: I) { + self.map.extend(iter.into_iter().map(|k| (k, ()))); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_one(&mut self, k: T) { + self.map.insert(k, ()); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_reserve(&mut self, additional: usize) { + Extend::<(T, ())>::extend_reserve(&mut self.map, additional); + } +} + +impl<'a, T, S, A> Extend<&'a T> for HashSet +where + T: 'a + Eq + Hash + Copy, + S: BuildHasher, + A: Allocator, +{ + #[cfg_attr(feature = "inline-more", inline)] + fn extend>(&mut self, iter: I) { + self.extend(iter.into_iter().copied()); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_one(&mut self, k: &'a T) { + self.map.insert(*k, ()); + } + + #[inline] + #[cfg(feature = "nightly")] + fn extend_reserve(&mut self, additional: usize) { + Extend::<(T, ())>::extend_reserve(&mut self.map, additional); + } +} + +impl Default for HashSet +where + S: Default, + A: Default + Allocator, +{ + /// Creates an empty `HashSet` with the `Default` value for the hasher. + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Self { + map: HashMap::default(), + } + } +} + +impl BitOr<&HashSet> for &HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, + A: Allocator + Default, +{ + type Output = HashSet; + + /// Returns the union of `self` and `rhs` as a new `HashSet`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect(); + /// + /// let set = &a | &b; + /// + /// let mut i = 0; + /// let expected = [1, 2, 3, 4, 5]; + /// for x in &set { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn bitor(self, rhs: &HashSet) -> HashSet { + self.union(rhs).cloned().collect() + } +} + +impl BitAnd<&HashSet> for &HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, + A: Allocator + Default, +{ + type Output = HashSet; + + /// Returns the intersection of `self` and `rhs` as a new `HashSet`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect(); + /// + /// let set = &a & &b; + /// + /// let mut i = 0; + /// let expected = [2, 3]; + /// for x in &set { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn bitand(self, rhs: &HashSet) -> HashSet { + self.intersection(rhs).cloned().collect() + } +} + +impl BitXor<&HashSet> for &HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, + A: Allocator + Default, +{ + type Output = HashSet; + + /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect(); + /// + /// let set = &a ^ &b; + /// + /// let mut i = 0; + /// let expected = [1, 2, 4, 5]; + /// for x in &set { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn bitxor(self, rhs: &HashSet) -> HashSet { + self.symmetric_difference(rhs).cloned().collect() + } +} + +impl Sub<&HashSet> for &HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, + A: Allocator + Default, +{ + type Output = HashSet; + + /// Returns the difference of `self` and `rhs` as a new `HashSet`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect(); + /// + /// let set = &a - &b; + /// + /// let mut i = 0; + /// let expected = [1, 2]; + /// for x in &set { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn sub(self, rhs: &HashSet) -> HashSet { + self.difference(rhs).cloned().collect() + } +} + +impl BitOrAssign<&HashSet> for HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher, + A: Allocator, +{ + /// Modifies this set to contain the union of `self` and `rhs`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect(); + /// + /// a |= &b; + /// + /// let mut i = 0; + /// let expected = [1, 2, 3, 4, 5]; + /// for x in &a { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn bitor_assign(&mut self, rhs: &HashSet) { + for item in rhs { + if !self.contains(item) { + self.insert(item.clone()); + } + } + } +} + +impl BitAndAssign<&HashSet> for HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher, + A: Allocator, +{ + /// Modifies this set to contain the intersection of `self` and `rhs`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect(); + /// + /// a &= &b; + /// + /// let mut i = 0; + /// let expected = [2, 3]; + /// for x in &a { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn bitand_assign(&mut self, rhs: &HashSet) { + self.retain(|item| rhs.contains(item)); + } +} + +impl BitXorAssign<&HashSet> for HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher, + A: Allocator, +{ + /// Modifies this set to contain the symmetric difference of `self` and `rhs`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect(); + /// + /// a ^= &b; + /// + /// let mut i = 0; + /// let expected = [1, 2, 4, 5]; + /// for x in &a { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn bitxor_assign(&mut self, rhs: &HashSet) { + for item in rhs { + let hash = make_hash(&self.map.hash_builder, item); + match self.map.find_or_find_insert_slot(hash, item) { + Ok(bucket) => unsafe { + self.map.table.remove(bucket); + }, + Err(slot) => unsafe { + self.map + .table + .insert_in_slot(hash, slot, (item.clone(), ())); + }, + } + } + } +} + +impl SubAssign<&HashSet> for HashSet +where + T: Eq + Hash + Clone, + S: BuildHasher, + A: Allocator, +{ + /// Modifies this set to contain the difference of `self` and `rhs`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect(); + /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect(); + /// + /// a -= &b; + /// + /// let mut i = 0; + /// let expected = [1, 2]; + /// for x in &a { + /// assert!(expected.contains(x)); + /// i += 1; + /// } + /// assert_eq!(i, expected.len()); + /// ``` + fn sub_assign(&mut self, rhs: &HashSet) { + if rhs.len() < self.len() { + for item in rhs { + self.remove(item); + } + } else { + self.retain(|item| !rhs.contains(item)); + } + } +} + +/// An iterator over the items of a `HashSet`. +/// +/// This `struct` is created by the [`iter`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`iter`]: struct.HashSet.html#method.iter +pub struct Iter<'a, K> { + iter: Keys<'a, K, ()>, +} + +/// An owning iterator over the items of a `HashSet`. +/// +/// This `struct` is created by the [`into_iter`] method on [`HashSet`] +/// (provided by the `IntoIterator` trait). See its documentation for more. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`into_iter`]: struct.HashSet.html#method.into_iter +pub struct IntoIter { + iter: map::IntoIter, +} + +/// A draining iterator over the items of a `HashSet`. +/// +/// This `struct` is created by the [`drain`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`drain`]: struct.HashSet.html#method.drain +pub struct Drain<'a, K, A: Allocator = Global> { + iter: map::Drain<'a, K, (), A>, +} + +/// A draining iterator over entries of a `HashSet` which don't satisfy the predicate `f`. +/// +/// This `struct` is created by the [`extract_if`] method on [`HashSet`]. See its +/// documentation for more. +/// +/// [`extract_if`]: struct.HashSet.html#method.extract_if +/// [`HashSet`]: struct.HashSet.html +#[must_use = "Iterators are lazy unless consumed"] +pub struct ExtractIf<'a, K, F, A: Allocator = Global> +where + F: FnMut(&K) -> bool, +{ + f: F, + inner: RawExtractIf<'a, (K, ()), A>, +} + +/// A lazy iterator producing elements in the intersection of `HashSet`s. +/// +/// This `struct` is created by the [`intersection`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`intersection`]: struct.HashSet.html#method.intersection +pub struct Intersection<'a, T, S, A: Allocator = Global> { + // iterator of the first set + iter: Iter<'a, T>, + // the second set + other: &'a HashSet, +} + +/// A lazy iterator producing elements in the difference of `HashSet`s. +/// +/// This `struct` is created by the [`difference`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`difference`]: struct.HashSet.html#method.difference +pub struct Difference<'a, T, S, A: Allocator = Global> { + // iterator of the first set + iter: Iter<'a, T>, + // the second set + other: &'a HashSet, +} + +/// A lazy iterator producing elements in the symmetric difference of `HashSet`s. +/// +/// This `struct` is created by the [`symmetric_difference`] method on +/// [`HashSet`]. See its documentation for more. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference +pub struct SymmetricDifference<'a, T, S, A: Allocator = Global> { + iter: Chain, Difference<'a, T, S, A>>, +} + +/// A lazy iterator producing elements in the union of `HashSet`s. +/// +/// This `struct` is created by the [`union`] method on [`HashSet`]. +/// See its documentation for more. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`union`]: struct.HashSet.html#method.union +pub struct Union<'a, T, S, A: Allocator = Global> { + iter: Chain, Difference<'a, T, S, A>>, +} + +impl<'a, T, S, A: Allocator> IntoIterator for &'a HashSet { + type Item = &'a T; + type IntoIter = Iter<'a, T>; + + #[cfg_attr(feature = "inline-more", inline)] + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl IntoIterator for HashSet { + type Item = T; + type IntoIter = IntoIter; + + /// Creates a consuming iterator, that is, one that moves each value out + /// of the set in arbitrary order. The set cannot be used after calling + /// this. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// let mut set = HashSet::new(); + /// set.insert("a".to_string()); + /// set.insert("b".to_string()); + /// + /// // Not possible to collect to a Vec with a regular `.iter()`. + /// let v: Vec = set.into_iter().collect(); + /// + /// // Will print in an arbitrary order. + /// for x in &v { + /// println!("{}", x); + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + fn into_iter(self) -> IntoIter { + IntoIter { + iter: self.map.into_iter(), + } + } +} + +impl Clone for Iter<'_, K> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Iter { + iter: self.iter.clone(), + } + } +} +impl Default for Iter<'_, K> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Iter { + iter: Default::default(), + } + } +} +impl<'a, K> Iterator for Iter<'a, K> { + type Item = &'a K; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a K> { + self.iter.next() + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, f) + } +} +impl<'a, K> ExactSizeIterator for Iter<'a, K> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.iter.len() + } +} +impl FusedIterator for Iter<'_, K> {} + +impl fmt::Debug for Iter<'_, K> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl Default for IntoIter { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + IntoIter { + iter: Default::default(), + } + } +} +impl Iterator for IntoIter { + type Item = K; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option { + // Avoid `Option::map` because it bloats LLVM IR. + match self.iter.next() { + Some((k, _)) => Some(k), + None => None, + } + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, |acc, (k, ())| f(acc, k)) + } +} +impl ExactSizeIterator for IntoIter { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.iter.len() + } +} +impl FusedIterator for IntoIter {} + +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let entries_iter = self.iter.iter().map(|(k, _)| k); + f.debug_list().entries(entries_iter).finish() + } +} + +impl Iterator for Drain<'_, K, A> { + type Item = K; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option { + // Avoid `Option::map` because it bloats LLVM IR. + match self.iter.next() { + Some((k, _)) => Some(k), + None => None, + } + } + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, |acc, (k, ())| f(acc, k)) + } +} +impl ExactSizeIterator for Drain<'_, K, A> { + #[cfg_attr(feature = "inline-more", inline)] + fn len(&self) -> usize { + self.iter.len() + } +} +impl FusedIterator for Drain<'_, K, A> {} + +impl fmt::Debug for Drain<'_, K, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let entries_iter = self.iter.iter().map(|(k, _)| k); + f.debug_list().entries(entries_iter).finish() + } +} + +impl Iterator for ExtractIf<'_, K, F, A> +where + F: FnMut(&K) -> bool, +{ + type Item = K; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option { + self.inner + .next(|&mut (ref k, ())| (self.f)(k)) + .map(|(k, ())| k) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (0, self.inner.iter.size_hint().1) + } +} + +impl FusedIterator for ExtractIf<'_, K, F, A> where F: FnMut(&K) -> bool {} + +impl Clone for Intersection<'_, T, S, A> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Intersection { + iter: self.iter.clone(), + ..*self + } + } +} + +impl<'a, T, S, A> Iterator for Intersection<'a, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + type Item = &'a T; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a T> { + loop { + let elt = self.iter.next()?; + if self.other.contains(elt) { + return Some(elt); + } + } + } + + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + let (_, upper) = self.iter.size_hint(); + (0, upper) + } + + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, |acc, elt| { + if self.other.contains(elt) { + f(acc, elt) + } else { + acc + } + }) + } +} + +impl fmt::Debug for Intersection<'_, T, S, A> +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl FusedIterator for Intersection<'_, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ +} + +impl Clone for Difference<'_, T, S, A> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Difference { + iter: self.iter.clone(), + ..*self + } + } +} + +impl<'a, T, S, A> Iterator for Difference<'a, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + type Item = &'a T; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a T> { + loop { + let elt = self.iter.next()?; + if !self.other.contains(elt) { + return Some(elt); + } + } + } + + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + let (lower, upper) = self.iter.size_hint(); + (lower.saturating_sub(self.other.len()), upper) + } + + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, |acc, elt| { + if self.other.contains(elt) { + acc + } else { + f(acc, elt) + } + }) + } +} + +impl FusedIterator for Difference<'_, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ +} + +impl fmt::Debug for Difference<'_, T, S, A> +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl Clone for SymmetricDifference<'_, T, S, A> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + SymmetricDifference { + iter: self.iter.clone(), + } + } +} + +impl<'a, T, S, A> Iterator for SymmetricDifference<'a, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + type Item = &'a T; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a T> { + self.iter.next() + } + + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, f) + } +} + +impl FusedIterator for SymmetricDifference<'_, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ +} + +impl fmt::Debug for SymmetricDifference<'_, T, S, A> +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl Clone for Union<'_, T, S, A> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Self { + Union { + iter: self.iter.clone(), + } + } +} + +impl FusedIterator for Union<'_, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ +} + +impl fmt::Debug for Union<'_, T, S, A> +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl<'a, T, S, A> Iterator for Union<'a, T, S, A> +where + T: Eq + Hash, + S: BuildHasher, + A: Allocator, +{ + type Item = &'a T; + + #[cfg_attr(feature = "inline-more", inline)] + fn next(&mut self) -> Option<&'a T> { + self.iter.next() + } + + #[cfg_attr(feature = "inline-more", inline)] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + #[cfg_attr(feature = "inline-more", inline)] + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, f) + } +} + +/// A view into a single entry in a set, which may either be vacant or occupied. +/// +/// This `enum` is constructed from the [`entry`] method on [`HashSet`]. +/// +/// [`HashSet`]: struct.HashSet.html +/// [`entry`]: struct.HashSet.html#method.entry +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_set::{Entry, HashSet, OccupiedEntry}; +/// +/// let mut set = HashSet::new(); +/// set.extend(["a", "b", "c"]); +/// assert_eq!(set.len(), 3); +/// +/// // Existing value (insert) +/// let entry: Entry<_, _> = set.entry("a"); +/// let _raw_o: OccupiedEntry<_, _> = entry.insert(); +/// assert_eq!(set.len(), 3); +/// // Nonexistent value (insert) +/// set.entry("d").insert(); +/// +/// // Existing value (or_insert) +/// set.entry("b").or_insert(); +/// // Nonexistent value (or_insert) +/// set.entry("e").or_insert(); +/// +/// println!("Our HashSet: {:?}", set); +/// +/// let mut vec: Vec<_> = set.iter().copied().collect(); +/// // The `Iter` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, ["a", "b", "c", "d", "e"]); +/// ``` +pub enum Entry<'a, T, S, A = Global> +where + A: Allocator, +{ + /// An occupied entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_set::{Entry, HashSet}; + /// let mut set: HashSet<_> = ["a", "b"].into(); + /// + /// match set.entry("a") { + /// Entry::Vacant(_) => unreachable!(), + /// Entry::Occupied(_) => { } + /// } + /// ``` + Occupied(OccupiedEntry<'a, T, S, A>), + + /// A vacant entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_set::{Entry, HashSet}; + /// let mut set: HashSet<&str> = HashSet::new(); + /// + /// match set.entry("a") { + /// Entry::Occupied(_) => unreachable!(), + /// Entry::Vacant(_) => { } + /// } + /// ``` + Vacant(VacantEntry<'a, T, S, A>), +} + +impl fmt::Debug for Entry<'_, T, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(), + Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(), + } + } +} + +/// A view into an occupied entry in a `HashSet`. +/// It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_set::{Entry, HashSet, OccupiedEntry}; +/// +/// let mut set = HashSet::new(); +/// set.extend(["a", "b", "c"]); +/// +/// let _entry_o: OccupiedEntry<_, _> = set.entry("a").insert(); +/// assert_eq!(set.len(), 3); +/// +/// // Existing key +/// match set.entry("a") { +/// Entry::Vacant(_) => unreachable!(), +/// Entry::Occupied(view) => { +/// assert_eq!(view.get(), &"a"); +/// } +/// } +/// +/// assert_eq!(set.len(), 3); +/// +/// // Existing key (take) +/// match set.entry("c") { +/// Entry::Vacant(_) => unreachable!(), +/// Entry::Occupied(view) => { +/// assert_eq!(view.remove(), "c"); +/// } +/// } +/// assert_eq!(set.get(&"c"), None); +/// assert_eq!(set.len(), 2); +/// ``` +pub struct OccupiedEntry<'a, T, S, A: Allocator = Global> { + inner: map::OccupiedEntry<'a, T, (), S, A>, +} + +impl fmt::Debug for OccupiedEntry<'_, T, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OccupiedEntry") + .field("value", self.get()) + .finish() + } +} + +/// A view into a vacant entry in a `HashSet`. +/// It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +/// +/// # Examples +/// +/// ``` +/// use hashbrown::hash_set::{Entry, HashSet, VacantEntry}; +/// +/// let mut set = HashSet::<&str>::new(); +/// +/// let entry_v: VacantEntry<_, _> = match set.entry("a") { +/// Entry::Vacant(view) => view, +/// Entry::Occupied(_) => unreachable!(), +/// }; +/// entry_v.insert(); +/// assert!(set.contains("a") && set.len() == 1); +/// +/// // Nonexistent key (insert) +/// match set.entry("b") { +/// Entry::Vacant(view) => { view.insert(); }, +/// Entry::Occupied(_) => unreachable!(), +/// } +/// assert!(set.contains("b") && set.len() == 2); +/// ``` +pub struct VacantEntry<'a, T, S, A: Allocator = Global> { + inner: map::VacantEntry<'a, T, (), S, A>, +} + +impl fmt::Debug for VacantEntry<'_, T, S, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("VacantEntry").field(self.get()).finish() + } +} + +impl<'a, T, S, A: Allocator> Entry<'a, T, S, A> { + /// Sets the value of the entry, and returns an `OccupiedEntry`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// let entry = set.entry("horseyland").insert(); + /// + /// assert_eq!(entry.get(), &"horseyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self) -> OccupiedEntry<'a, T, S, A> + where + T: Hash, + S: BuildHasher, + { + match self { + Entry::Occupied(entry) => entry, + Entry::Vacant(entry) => entry.insert(), + } + } + + /// Ensures a value is in the entry by inserting if it was vacant. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// + /// // nonexistent key + /// set.entry("poneyland").or_insert(); + /// assert!(set.contains("poneyland")); + /// + /// // existing key + /// set.entry("poneyland").or_insert(); + /// assert!(set.contains("poneyland")); + /// assert_eq!(set.len(), 1); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert(self) + where + T: Hash, + S: BuildHasher, + { + if let Entry::Vacant(entry) = self { + entry.insert(); + } + } + + /// Returns a reference to this entry's value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// set.entry("poneyland").or_insert(); + /// // existing key + /// assert_eq!(set.entry("poneyland").get(), &"poneyland"); + /// // nonexistent key + /// assert_eq!(set.entry("horseland").get(), &"horseland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get(&self) -> &T { + match *self { + Entry::Occupied(ref entry) => entry.get(), + Entry::Vacant(ref entry) => entry.get(), + } + } +} + +impl OccupiedEntry<'_, T, S, A> { + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_set::{Entry, HashSet}; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// set.entry("poneyland").or_insert(); + /// + /// match set.entry("poneyland") { + /// Entry::Vacant(_) => panic!(), + /// Entry::Occupied(entry) => assert_eq!(entry.get(), &"poneyland"), + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get(&self) -> &T { + self.inner.key() + } + + /// Takes the value out of the entry, and returns it. + /// Keeps the allocated memory for reuse. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::hash_set::Entry; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// // The set is empty + /// assert!(set.is_empty() && set.capacity() == 0); + /// + /// set.entry("poneyland").or_insert(); + /// let capacity_before_remove = set.capacity(); + /// + /// if let Entry::Occupied(o) = set.entry("poneyland") { + /// assert_eq!(o.remove(), "poneyland"); + /// } + /// + /// assert_eq!(set.contains("poneyland"), false); + /// // Now set hold none elements but capacity is equal to the old one + /// assert!(set.len() == 0 && set.capacity() == capacity_before_remove); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove(self) -> T { + self.inner.remove_entry().0 + } +} + +impl<'a, T, S, A: Allocator> VacantEntry<'a, T, S, A> { + /// Gets a reference to the value that would be used when inserting + /// through the `VacantEntry`. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// assert_eq!(set.entry("poneyland").get(), &"poneyland"); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn get(&self) -> &T { + self.inner.key() + } + + /// Take ownership of the value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::hash_set::{Entry, HashSet}; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// + /// match set.entry("poneyland") { + /// Entry::Occupied(_) => panic!(), + /// Entry::Vacant(v) => assert_eq!(v.into_value(), "poneyland"), + /// } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn into_value(self) -> T { + self.inner.into_key() + } + + /// Sets the value of the entry with the `VacantEntry`'s value. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashSet; + /// use hashbrown::hash_set::Entry; + /// + /// let mut set: HashSet<&str> = HashSet::new(); + /// + /// if let Entry::Vacant(o) = set.entry("poneyland") { + /// o.insert(); + /// } + /// assert!(set.contains("poneyland")); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn insert(self) -> OccupiedEntry<'a, T, S, A> + where + T: Hash, + S: BuildHasher, + { + OccupiedEntry { + inner: self.inner.insert_entry(()), + } + } +} + +#[allow(dead_code)] +fn assert_covariance() { + fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> { + v + } + fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> { + v + } + fn into_iter<'new, A: Allocator>(v: IntoIter<&'static str, A>) -> IntoIter<&'new str, A> { + v + } + fn difference<'a, 'new, A: Allocator>( + v: Difference<'a, &'static str, DefaultHashBuilder, A>, + ) -> Difference<'a, &'new str, DefaultHashBuilder, A> { + v + } + fn symmetric_difference<'a, 'new, A: Allocator>( + v: SymmetricDifference<'a, &'static str, DefaultHashBuilder, A>, + ) -> SymmetricDifference<'a, &'new str, DefaultHashBuilder, A> { + v + } + fn intersection<'a, 'new, A: Allocator>( + v: Intersection<'a, &'static str, DefaultHashBuilder, A>, + ) -> Intersection<'a, &'new str, DefaultHashBuilder, A> { + v + } + fn union<'a, 'new, A: Allocator>( + v: Union<'a, &'static str, DefaultHashBuilder, A>, + ) -> Union<'a, &'new str, DefaultHashBuilder, A> { + v + } + fn drain<'new, A: Allocator>(d: Drain<'static, &'static str, A>) -> Drain<'new, &'new str, A> { + d + } +} + +#[cfg(test)] +mod test_set { + use super::{make_hash, Equivalent, HashSet}; + use crate::DefaultHashBuilder; + use std::vec::Vec; + + #[test] + fn test_zero_capacities() { + type HS = HashSet; + + let s = HS::new(); + assert_eq!(s.capacity(), 0); + + let s = HS::default(); + assert_eq!(s.capacity(), 0); + + let s = HS::with_hasher(DefaultHashBuilder::default()); + assert_eq!(s.capacity(), 0); + + let s = HS::with_capacity(0); + assert_eq!(s.capacity(), 0); + + let s = HS::with_capacity_and_hasher(0, DefaultHashBuilder::default()); + assert_eq!(s.capacity(), 0); + + let mut s = HS::new(); + s.insert(1); + s.insert(2); + s.remove(&1); + s.remove(&2); + s.shrink_to_fit(); + assert_eq!(s.capacity(), 0); + + let mut s = HS::new(); + s.reserve(0); + assert_eq!(s.capacity(), 0); + } + + #[test] + fn test_disjoint() { + let mut xs = HashSet::new(); + let mut ys = HashSet::new(); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(5)); + assert!(ys.insert(11)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(7)); + assert!(xs.insert(19)); + assert!(xs.insert(4)); + assert!(ys.insert(2)); + assert!(ys.insert(-11)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(ys.insert(7)); + assert!(!xs.is_disjoint(&ys)); + assert!(!ys.is_disjoint(&xs)); + } + + #[test] + fn test_subset_and_superset() { + let mut a = HashSet::new(); + assert!(a.insert(0)); + assert!(a.insert(5)); + assert!(a.insert(11)); + assert!(a.insert(7)); + + let mut b = HashSet::new(); + assert!(b.insert(0)); + assert!(b.insert(7)); + assert!(b.insert(19)); + assert!(b.insert(250)); + assert!(b.insert(11)); + assert!(b.insert(200)); + + assert!(!a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(!b.is_superset(&a)); + + assert!(b.insert(5)); + + assert!(a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(b.is_superset(&a)); + } + + #[test] + fn test_iterate() { + let mut a = HashSet::new(); + for i in 0..32 { + assert!(a.insert(i)); + } + let mut observed: u32 = 0; + for k in &a { + observed |= 1 << *k; + } + assert_eq!(observed, 0xFFFF_FFFF); + } + + #[test] + fn test_intersection() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(11)); + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(77)); + assert!(a.insert(103)); + assert!(a.insert(5)); + assert!(a.insert(-5)); + + assert!(b.insert(2)); + assert!(b.insert(11)); + assert!(b.insert(77)); + assert!(b.insert(-9)); + assert!(b.insert(-42)); + assert!(b.insert(5)); + assert!(b.insert(3)); + + let mut i = 0; + let expected = [3, 5, 11, 77]; + for x in a.intersection(&b) { + assert!(expected.contains(x)); + i += 1; + } + assert_eq!(i, expected.len()); + } + + #[test] + fn test_difference() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(3)); + assert!(b.insert(9)); + + let mut i = 0; + let expected = [1, 5, 11]; + for x in a.difference(&b) { + assert!(expected.contains(x)); + i += 1; + } + assert_eq!(i, expected.len()); + } + + #[test] + fn test_symmetric_difference() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(-2)); + assert!(b.insert(3)); + assert!(b.insert(9)); + assert!(b.insert(14)); + assert!(b.insert(22)); + + let mut i = 0; + let expected = [-2, 1, 5, 11, 14, 22]; + for x in a.symmetric_difference(&b) { + assert!(expected.contains(x)); + i += 1; + } + assert_eq!(i, expected.len()); + } + + #[test] + fn test_union() { + let mut a = HashSet::new(); + let mut b = HashSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + assert!(a.insert(16)); + assert!(a.insert(19)); + assert!(a.insert(24)); + + assert!(b.insert(-2)); + assert!(b.insert(1)); + assert!(b.insert(5)); + assert!(b.insert(9)); + assert!(b.insert(13)); + assert!(b.insert(19)); + + let mut i = 0; + let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]; + for x in a.union(&b) { + assert!(expected.contains(x)); + i += 1; + } + assert_eq!(i, expected.len()); + } + + #[test] + fn test_from_map() { + let mut a = crate::HashMap::new(); + a.insert(1, ()); + a.insert(2, ()); + a.insert(3, ()); + a.insert(4, ()); + + let a: HashSet<_> = a.into(); + + assert_eq!(a.len(), 4); + assert!(a.contains(&1)); + assert!(a.contains(&2)); + assert!(a.contains(&3)); + assert!(a.contains(&4)); + } + + #[test] + fn test_from_iter() { + let xs = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9]; + + let set: HashSet<_> = xs.iter().copied().collect(); + + for x in &xs { + assert!(set.contains(x)); + } + + assert_eq!(set.iter().len(), xs.len() - 1); + } + + #[test] + fn test_move_iter() { + let hs = { + let mut hs = HashSet::new(); + + hs.insert('a'); + hs.insert('b'); + + hs + }; + + let v = hs.into_iter().collect::>(); + assert!(v == ['a', 'b'] || v == ['b', 'a']); + } + + #[test] + fn test_eq() { + // These constants once happened to expose a bug in insert(). + // I'm keeping them around to prevent a regression. + let mut s1 = HashSet::new(); + + s1.insert(1); + s1.insert(2); + s1.insert(3); + + let mut s2 = HashSet::new(); + + s2.insert(1); + s2.insert(2); + + assert!(s1 != s2); + + s2.insert(3); + + assert_eq!(s1, s2); + } + + #[test] + fn test_show() { + let mut set = HashSet::new(); + let empty = HashSet::::new(); + + set.insert(1); + set.insert(2); + + let set_str = format!("{set:?}"); + + assert!(set_str == "{1, 2}" || set_str == "{2, 1}"); + assert_eq!(format!("{empty:?}"), "{}"); + } + + #[test] + fn test_trivial_drain() { + let mut s = HashSet::::new(); + for _ in s.drain() {} + assert!(s.is_empty()); + drop(s); + + let mut s = HashSet::::new(); + drop(s.drain()); + assert!(s.is_empty()); + } + + #[test] + fn test_drain() { + let mut s: HashSet<_> = (1..100).collect(); + + // try this a bunch of times to make sure we don't screw up internal state. + for _ in 0..20 { + assert_eq!(s.len(), 99); + + { + let mut last_i = 0; + let mut d = s.drain(); + for (i, x) in d.by_ref().take(50).enumerate() { + last_i = i; + assert!(x != 0); + } + assert_eq!(last_i, 49); + } + + if !s.is_empty() { + panic!("s should be empty!"); + } + + // reset to try again. + s.extend(1..100); + } + } + + #[test] + fn test_replace() { + use core::hash; + + #[derive(Debug)] + #[allow(dead_code)] + struct Foo(&'static str, i32); + + impl PartialEq for Foo { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } + } + + impl Eq for Foo {} + + impl hash::Hash for Foo { + fn hash(&self, h: &mut H) { + self.0.hash(h); + } + } + + let mut s = HashSet::new(); + assert_eq!(s.replace(Foo("a", 1)), None); + assert_eq!(s.len(), 1); + assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1))); + assert_eq!(s.len(), 1); + + let mut it = s.iter(); + assert_eq!(it.next(), Some(&Foo("a", 2))); + assert_eq!(it.next(), None); + } + + #[test] + #[allow(clippy::needless_borrow)] + fn test_extend_ref() { + let mut a = HashSet::new(); + a.insert(1); + + a.extend([2, 3, 4]); + + assert_eq!(a.len(), 4); + assert!(a.contains(&1)); + assert!(a.contains(&2)); + assert!(a.contains(&3)); + assert!(a.contains(&4)); + + let mut b = HashSet::new(); + b.insert(5); + b.insert(6); + + a.extend(&b); + + assert_eq!(a.len(), 6); + assert!(a.contains(&1)); + assert!(a.contains(&2)); + assert!(a.contains(&3)); + assert!(a.contains(&4)); + assert!(a.contains(&5)); + assert!(a.contains(&6)); + } + + #[test] + fn test_retain() { + let xs = [1, 2, 3, 4, 5, 6]; + let mut set: HashSet = xs.iter().copied().collect(); + set.retain(|&k| k % 2 == 0); + assert_eq!(set.len(), 3); + assert!(set.contains(&2)); + assert!(set.contains(&4)); + assert!(set.contains(&6)); + } + + #[test] + fn test_extract_if() { + { + let mut set: HashSet = (0..8).collect(); + let drained = set.extract_if(|&k| k % 2 == 0); + let mut out = drained.collect::>(); + out.sort_unstable(); + assert_eq!(vec![0, 2, 4, 6], out); + assert_eq!(set.len(), 4); + } + { + let mut set: HashSet = (0..8).collect(); + set.extract_if(|&k| k % 2 == 0).for_each(drop); + assert_eq!(set.len(), 4, "Removes non-matching items on drop"); + } + } + + #[test] + fn test_const_with_hasher() { + use core::hash::BuildHasher; + use std::collections::hash_map::DefaultHasher; + + #[derive(Clone)] + struct MyHasher; + impl BuildHasher for MyHasher { + type Hasher = DefaultHasher; + + fn build_hasher(&self) -> DefaultHasher { + DefaultHasher::new() + } + } + + const EMPTY_SET: HashSet = HashSet::with_hasher(MyHasher); + + let mut set = EMPTY_SET; + set.insert(19); + assert!(set.contains(&19)); + } + + #[test] + fn rehash_in_place() { + let mut set = HashSet::new(); + + for i in 0..224 { + set.insert(i); + } + + assert_eq!( + set.capacity(), + 224, + "The set must be at or close to capacity to trigger a re hashing" + ); + + for i in 100..1400 { + set.remove(&(i - 100)); + set.insert(i); + } + } + + #[test] + fn collect() { + // At the time of writing, this hits the ZST case in from_base_index + // (and without the `map`, it does not). + let mut _set: HashSet<_> = (0..3).map(|_| ()).collect(); + } + + #[test] + fn test_allocation_info() { + assert_eq!(HashSet::<()>::new().allocation_size(), 0); + assert_eq!(HashSet::::new().allocation_size(), 0); + assert!(HashSet::::with_capacity(1).allocation_size() > core::mem::size_of::()); + } + + #[test] + fn duplicate_insert() { + let mut set = HashSet::new(); + set.insert(1); + set.get_or_insert_with(&1, |_| 1); + set.get_or_insert_with(&1, |_| 1); + assert!([1].iter().eq(set.iter())); + } + + #[test] + #[should_panic] + fn some_invalid_equivalent() { + use core::hash::{Hash, Hasher}; + struct Invalid { + count: u32, + other: u32, + } + + struct InvalidRef { + count: u32, + other: u32, + } + + impl PartialEq for Invalid { + fn eq(&self, other: &Self) -> bool { + self.count == other.count && self.other == other.other + } + } + impl Eq for Invalid {} + + impl Equivalent for InvalidRef { + fn equivalent(&self, key: &Invalid) -> bool { + self.count == key.count && self.other == key.other + } + } + impl Hash for Invalid { + fn hash(&self, state: &mut H) { + self.count.hash(state); + } + } + impl Hash for InvalidRef { + fn hash(&self, state: &mut H) { + self.count.hash(state); + } + } + let mut set: HashSet = HashSet::new(); + let key = InvalidRef { count: 1, other: 1 }; + let value = Invalid { count: 1, other: 2 }; + if make_hash(set.hasher(), &key) == make_hash(set.hasher(), &value) { + set.get_or_insert_with(&key, |_| value); + } + } +} diff --git a/bitbox02-bt/vendor/hashbrown/src/table.rs b/bitbox02-bt/vendor/hashbrown/src/table.rs new file mode 100644 index 0000000..d442a01 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/src/table.rs @@ -0,0 +1,2383 @@ +use core::{fmt, iter::FusedIterator, marker::PhantomData}; + +use crate::{ + raw::{ + Allocator, Bucket, Global, InsertSlot, RawDrain, RawExtractIf, RawIntoIter, RawIter, + RawIterHash, RawTable, + }, + TryReserveError, +}; + +/// Low-level hash table with explicit hashing. +/// +/// The primary use case for this type over [`HashMap`] or [`HashSet`] is to +/// support types that do not implement the [`Hash`] and [`Eq`] traits, but +/// instead require additional data not contained in the key itself to compute a +/// hash and compare two elements for equality. +/// +/// Examples of when this can be useful include: +/// - An `IndexMap` implementation where indices into a `Vec` are stored as +/// elements in a `HashTable`. Hashing and comparing the elements +/// requires indexing the associated `Vec` to get the actual value referred to +/// by the index. +/// - Avoiding re-computing a hash when it is already known. +/// - Mutating the key of an element in a way that doesn't affect its hash. +/// +/// To achieve this, `HashTable` methods that search for an element in the table +/// require a hash value and equality function to be explicitly passed in as +/// arguments. The method will then iterate over the elements with the given +/// hash and call the equality function on each of them, until a match is found. +/// +/// In most cases, a `HashTable` will not be exposed directly in an API. It will +/// instead be wrapped in a helper type which handles the work of calculating +/// hash values and comparing elements. +/// +/// Due to its low-level nature, this type provides fewer guarantees than +/// [`HashMap`] and [`HashSet`]. Specifically, the API allows you to shoot +/// yourself in the foot by having multiple elements with identical keys in the +/// table. The table itself will still function correctly and lookups will +/// arbitrarily return one of the matching elements. However you should avoid +/// doing this because it changes the runtime of hash table operations from +/// `O(1)` to `O(k)` where `k` is the number of duplicate entries. +/// +/// [`HashMap`]: super::HashMap +/// [`HashSet`]: super::HashSet +/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html +/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html +pub struct HashTable +where + A: Allocator, +{ + pub(crate) raw: RawTable, +} + +impl HashTable { + /// Creates an empty `HashTable`. + /// + /// The hash table is initially created with a capacity of 0, so it will not allocate until it + /// is first inserted into. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashTable; + /// let mut table: HashTable<&str> = HashTable::new(); + /// assert_eq!(table.len(), 0); + /// assert_eq!(table.capacity(), 0); + /// ``` + pub const fn new() -> Self { + Self { + raw: RawTable::new(), + } + } + + /// Creates an empty `HashTable` with the specified capacity. + /// + /// The hash table will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash table will not allocate. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashTable; + /// let mut table: HashTable<&str> = HashTable::with_capacity(10); + /// assert_eq!(table.len(), 0); + /// assert!(table.capacity() >= 10); + /// ``` + pub fn with_capacity(capacity: usize) -> Self { + Self { + raw: RawTable::with_capacity(capacity), + } + } +} + +impl HashTable +where + A: Allocator, +{ + /// Creates an empty `HashTable` using the given allocator. + /// + /// The hash table is initially created with a capacity of 0, so it will not allocate until it + /// is first inserted into. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use bumpalo::Bump; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let bump = Bump::new(); + /// let mut table = HashTable::new_in(&bump); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// // The created HashTable holds none elements + /// assert_eq!(table.len(), 0); + /// + /// // The created HashTable also doesn't allocate memory + /// assert_eq!(table.capacity(), 0); + /// + /// // Now we insert element inside created HashTable + /// table.insert_unique(hasher(&"One"), "One", hasher); + /// // We can see that the HashTable holds 1 element + /// assert_eq!(table.len(), 1); + /// // And it also allocates some capacity + /// assert!(table.capacity() > 1); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub const fn new_in(alloc: A) -> Self { + Self { + raw: RawTable::new_in(alloc), + } + } + + /// Creates an empty `HashTable` with the specified capacity using the given allocator. + /// + /// The hash table will be able to hold at least `capacity` elements without + /// reallocating. If `capacity` is 0, the hash table will not allocate. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use bumpalo::Bump; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let bump = Bump::new(); + /// let mut table = HashTable::with_capacity_in(5, &bump); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// // The created HashTable holds none elements + /// assert_eq!(table.len(), 0); + /// // But it can hold at least 5 elements without reallocating + /// let empty_map_capacity = table.capacity(); + /// assert!(empty_map_capacity >= 5); + /// + /// // Now we insert some 5 elements inside created HashTable + /// table.insert_unique(hasher(&"One"), "One", hasher); + /// table.insert_unique(hasher(&"Two"), "Two", hasher); + /// table.insert_unique(hasher(&"Three"), "Three", hasher); + /// table.insert_unique(hasher(&"Four"), "Four", hasher); + /// table.insert_unique(hasher(&"Five"), "Five", hasher); + /// + /// // We can see that the HashTable holds 5 elements + /// assert_eq!(table.len(), 5); + /// // But its capacity isn't changed + /// assert_eq!(table.capacity(), empty_map_capacity) + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { + Self { + raw: RawTable::with_capacity_in(capacity, alloc), + } + } + + /// Returns a reference to the underlying allocator. + pub fn allocator(&self) -> &A { + self.raw.allocator() + } + + /// Returns a reference to an entry in the table with the given hash and + /// which satisfies the equality function passed. + /// + /// This method will call `eq` for all entries with the given hash, but may + /// also call it for entries with a different hash. `eq` should only return + /// true for the desired entry, at which point the search is stopped. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), 1, hasher); + /// table.insert_unique(hasher(&2), 2, hasher); + /// table.insert_unique(hasher(&3), 3, hasher); + /// assert_eq!(table.find(hasher(&2), |&val| val == 2), Some(&2)); + /// assert_eq!(table.find(hasher(&4), |&val| val == 4), None); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn find(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { + self.raw.get(hash, eq) + } + + /// Returns a mutable reference to an entry in the table with the given hash + /// and which satisfies the equality function passed. + /// + /// This method will call `eq` for all entries with the given hash, but may + /// also call it for entries with a different hash. `eq` should only return + /// true for the desired entry, at which point the search is stopped. + /// + /// When mutating an entry, you should ensure that it still retains the same + /// hash value as when it was inserted, otherwise lookups of that entry may + /// fail to find it. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), (1, "a"), |val| hasher(&val.0)); + /// if let Some(val) = table.find_mut(hasher(&1), |val| val.0 == 1) { + /// val.1 = "b"; + /// } + /// assert_eq!(table.find(hasher(&1), |val| val.0 == 1), Some(&(1, "b"))); + /// assert_eq!(table.find(hasher(&2), |val| val.0 == 2), None); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn find_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { + self.raw.get_mut(hash, eq) + } + + /// Returns an `OccupiedEntry` for an entry in the table with the given hash + /// and which satisfies the equality function passed. + /// + /// This can be used to remove the entry from the table. Call + /// [`HashTable::entry`] instead if you wish to insert an entry if the + /// lookup fails. + /// + /// This method will call `eq` for all entries with the given hash, but may + /// also call it for entries with a different hash. `eq` should only return + /// true for the desired entry, at which point the search is stopped. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), (1, "a"), |val| hasher(&val.0)); + /// if let Ok(entry) = table.find_entry(hasher(&1), |val| val.0 == 1) { + /// entry.remove(); + /// } + /// assert_eq!(table.find(hasher(&1), |val| val.0 == 1), None); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn find_entry( + &mut self, + hash: u64, + eq: impl FnMut(&T) -> bool, + ) -> Result, AbsentEntry<'_, T, A>> { + match self.raw.find(hash, eq) { + Some(bucket) => Ok(OccupiedEntry { + hash, + bucket, + table: self, + }), + None => Err(AbsentEntry { table: self }), + } + } + + /// Returns an `Entry` for an entry in the table with the given hash + /// and which satisfies the equality function passed. + /// + /// This can be used to remove the entry from the table, or insert a new + /// entry with the given hash if one doesn't already exist. + /// + /// This method will call `eq` for all entries with the given hash, but may + /// also call it for entries with a different hash. `eq` should only return + /// true for the desired entry, at which point the search is stopped. + /// + /// This method may grow the table in preparation for an insertion. Call + /// [`HashTable::find_entry`] if this is undesirable. + /// + /// `hasher` is called if entries need to be moved or copied to a new table. + /// This must return the same hash value that each entry was inserted with. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), (1, "a"), |val| hasher(&val.0)); + /// if let Entry::Occupied(entry) = table.entry(hasher(&1), |val| val.0 == 1, |val| hasher(&val.0)) + /// { + /// entry.remove(); + /// } + /// if let Entry::Vacant(entry) = table.entry(hasher(&2), |val| val.0 == 2, |val| hasher(&val.0)) { + /// entry.insert((2, "b")); + /// } + /// assert_eq!(table.find(hasher(&1), |val| val.0 == 1), None); + /// assert_eq!(table.find(hasher(&2), |val| val.0 == 2), Some(&(2, "b"))); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn entry( + &mut self, + hash: u64, + eq: impl FnMut(&T) -> bool, + hasher: impl Fn(&T) -> u64, + ) -> Entry<'_, T, A> { + match self.raw.find_or_find_insert_slot(hash, eq, hasher) { + Ok(bucket) => Entry::Occupied(OccupiedEntry { + hash, + bucket, + table: self, + }), + Err(insert_slot) => Entry::Vacant(VacantEntry { + hash, + insert_slot, + table: self, + }), + } + } + + /// Inserts an element into the `HashTable` with the given hash value, but + /// without checking whether an equivalent element already exists within the + /// table. + /// + /// `hasher` is called if entries need to be moved or copied to a new table. + /// This must return the same hash value that each entry was inserted with. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut v = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// v.insert_unique(hasher(&1), 1, hasher); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn insert_unique( + &mut self, + hash: u64, + value: T, + hasher: impl Fn(&T) -> u64, + ) -> OccupiedEntry<'_, T, A> { + let bucket = self.raw.insert(hash, value, hasher); + OccupiedEntry { + hash, + bucket, + table: self, + } + } + + /// Clears the table, removing all values. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut v = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// v.insert_unique(hasher(&1), 1, hasher); + /// v.clear(); + /// assert!(v.is_empty()); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn clear(&mut self) { + self.raw.clear(); + } + + /// Shrinks the capacity of the table as much as possible. It will drop + /// down as much as possible while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// `hasher` is called if entries need to be moved or copied to a new table. + /// This must return the same hash value that each entry was inserted with. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::with_capacity(100); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), 1, hasher); + /// table.insert_unique(hasher(&2), 2, hasher); + /// assert!(table.capacity() >= 100); + /// table.shrink_to_fit(hasher); + /// assert!(table.capacity() >= 2); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn shrink_to_fit(&mut self, hasher: impl Fn(&T) -> u64) { + self.raw.shrink_to(self.len(), hasher) + } + + /// Shrinks the capacity of the table with a lower limit. It will drop + /// down no lower than the supplied limit while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// `hasher` is called if entries need to be moved or copied to a new table. + /// This must return the same hash value that each entry was inserted with. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::with_capacity(100); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), 1, hasher); + /// table.insert_unique(hasher(&2), 2, hasher); + /// assert!(table.capacity() >= 100); + /// table.shrink_to(10, hasher); + /// assert!(table.capacity() >= 10); + /// table.shrink_to(0, hasher); + /// assert!(table.capacity() >= 2); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn shrink_to(&mut self, min_capacity: usize, hasher: impl Fn(&T) -> u64) { + self.raw.shrink_to(min_capacity, hasher); + } + + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the `HashTable`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// `hasher` is called if entries need to be moved or copied to a new table. + /// This must return the same hash value that each entry was inserted with. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program + /// in case of allocation error. Use [`try_reserve`](HashTable::try_reserve) instead + /// if you want to handle memory allocation failure. + /// + /// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html + /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.reserve(10, hasher); + /// assert!(table.capacity() >= 10); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { + self.raw.reserve(additional, hasher) + } + + /// Tries to reserve capacity for at least `additional` more elements to be inserted + /// in the given `HashTable`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// `hasher` is called if entries need to be moved or copied to a new table. + /// This must return the same hash value that each entry was inserted with. + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table + /// .try_reserve(10, hasher) + /// .expect("why is the test harness OOMing on 10 bytes?"); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn try_reserve( + &mut self, + additional: usize, + hasher: impl Fn(&T) -> u64, + ) -> Result<(), TryReserveError> { + self.raw.try_reserve(additional, hasher) + } + + /// Returns the number of elements the table can hold without reallocating. + /// + /// # Examples + /// + /// ``` + /// use hashbrown::HashTable; + /// let table: HashTable = HashTable::with_capacity(100); + /// assert!(table.capacity() >= 100); + /// ``` + pub fn capacity(&self) -> usize { + self.raw.capacity() + } + + /// Returns the number of elements in the table. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// let mut v = HashTable::new(); + /// assert_eq!(v.len(), 0); + /// v.insert_unique(hasher(&1), 1, hasher); + /// assert_eq!(v.len(), 1); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn len(&self) -> usize { + self.raw.len() + } + + /// Returns `true` if the set contains no elements. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// let mut v = HashTable::new(); + /// assert!(v.is_empty()); + /// v.insert_unique(hasher(&1), 1, hasher); + /// assert!(!v.is_empty()); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn is_empty(&self) -> bool { + self.raw.is_empty() + } + + /// An iterator visiting all elements in arbitrary order. + /// The iterator element type is `&'a T`. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&"a"), "b", hasher); + /// table.insert_unique(hasher(&"b"), "b", hasher); + /// + /// // Will print in an arbitrary order. + /// for x in table.iter() { + /// println!("{}", x); + /// } + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn iter(&self) -> Iter<'_, T> { + Iter { + inner: unsafe { self.raw.iter() }, + marker: PhantomData, + } + } + + /// An iterator visiting all elements in arbitrary order, + /// with mutable references to the elements. + /// The iterator element type is `&'a mut T`. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), 1, hasher); + /// table.insert_unique(hasher(&2), 2, hasher); + /// table.insert_unique(hasher(&3), 3, hasher); + /// + /// // Update all values + /// for val in table.iter_mut() { + /// *val *= 2; + /// } + /// + /// assert_eq!(table.len(), 3); + /// let mut vec: Vec = Vec::new(); + /// + /// for val in &table { + /// println!("val: {}", val); + /// vec.push(*val); + /// } + /// + /// // The `Iter` iterator produces items in arbitrary order, so the + /// // items must be sorted to test them against a sorted array. + /// vec.sort_unstable(); + /// assert_eq!(vec, [2, 4, 6]); + /// + /// assert_eq!(table.len(), 3); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn iter_mut(&mut self) -> IterMut<'_, T> { + IterMut { + inner: unsafe { self.raw.iter() }, + marker: PhantomData, + } + } + + /// An iterator visiting all elements which may match a hash. + /// The iterator element type is `&'a T`. + /// + /// This iterator may return elements from the table that have a hash value + /// different than the one provided. You should always validate the returned + /// values before using them. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&"a"), "a", hasher); + /// table.insert_unique(hasher(&"a"), "b", hasher); + /// table.insert_unique(hasher(&"b"), "c", hasher); + /// + /// // Will print "a" and "b" (and possibly "c") in an arbitrary order. + /// for x in table.iter_hash(hasher(&"a")) { + /// println!("{}", x); + /// } + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn iter_hash(&self, hash: u64) -> IterHash<'_, T> { + IterHash { + inner: unsafe { self.raw.iter_hash(hash) }, + marker: PhantomData, + } + } + + /// A mutable iterator visiting all elements which may match a hash. + /// The iterator element type is `&'a mut T`. + /// + /// This iterator may return elements from the table that have a hash value + /// different than the one provided. You should always validate the returned + /// values before using them. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&1), 2, hasher); + /// table.insert_unique(hasher(&1), 3, hasher); + /// table.insert_unique(hasher(&2), 5, hasher); + /// + /// // Update matching values + /// for val in table.iter_hash_mut(hasher(&1)) { + /// *val *= 2; + /// } + /// + /// assert_eq!(table.len(), 3); + /// let mut vec: Vec = Vec::new(); + /// + /// for val in &table { + /// println!("val: {}", val); + /// vec.push(*val); + /// } + /// + /// // The values will contain 4 and 6 and may contain either 5 or 10. + /// assert!(vec.contains(&4)); + /// assert!(vec.contains(&6)); + /// + /// assert_eq!(table.len(), 3); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn iter_hash_mut(&mut self, hash: u64) -> IterHashMut<'_, T> { + IterHashMut { + inner: unsafe { self.raw.iter_hash(hash) }, + marker: PhantomData, + } + } + + /// Retains only the elements specified by the predicate. + /// + /// In other words, remove all elements `e` such that `f(&e)` returns `false`. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// for x in 1..=6 { + /// table.insert_unique(hasher(&x), x, hasher); + /// } + /// table.retain(|&mut x| x % 2 == 0); + /// assert_eq!(table.len(), 3); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) { + // Here we only use `iter` as a temporary, preventing use-after-free + unsafe { + for item in self.raw.iter() { + if !f(item.as_mut()) { + self.raw.erase(item); + } + } + } + } + + /// Clears the set, returning all elements in an iterator. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// for x in 1..=3 { + /// table.insert_unique(hasher(&x), x, hasher); + /// } + /// assert!(!table.is_empty()); + /// + /// // print 1, 2, 3 in an arbitrary order + /// for i in table.drain() { + /// println!("{}", i); + /// } + /// + /// assert!(table.is_empty()); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn drain(&mut self) -> Drain<'_, T, A> { + Drain { + inner: self.raw.drain(), + } + } + + /// Drains elements which are true under the given predicate, + /// and returns an iterator over the removed items. + /// + /// In other words, move all elements `e` such that `f(&e)` returns `true` out + /// into another iterator. + /// + /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating + /// or the iteration short-circuits, then the remaining elements will be retained. + /// Use [`retain()`] with a negated predicate if you do not need the returned iterator. + /// + /// [`retain()`]: HashTable::retain + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// for x in 0..8 { + /// table.insert_unique(hasher(&x), x, hasher); + /// } + /// let drained: Vec = table.extract_if(|&mut v| v % 2 == 0).collect(); + /// + /// let mut evens = drained.into_iter().collect::>(); + /// let mut odds = table.into_iter().collect::>(); + /// evens.sort(); + /// odds.sort(); + /// + /// assert_eq!(evens, vec![0, 2, 4, 6]); + /// assert_eq!(odds, vec![1, 3, 5, 7]); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn extract_if(&mut self, f: F) -> ExtractIf<'_, T, F, A> + where + F: FnMut(&mut T) -> bool, + { + ExtractIf { + f, + inner: RawExtractIf { + iter: unsafe { self.raw.iter() }, + table: &mut self.raw, + }, + } + } + + /// Attempts to get mutable references to `N` values in the map at once. + /// + /// The `eq` argument should be a closure such that `eq(i, k)` returns true if `k` is equal to + /// the `i`th key to be looked up. + /// + /// Returns an array of length `N` with the results of each query. For soundness, at most one + /// mutable reference will be returned to any value. `None` will be used if the key is missing. + /// + /// # Panics + /// + /// Panics if any keys are overlapping. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut libraries: HashTable<(&str, u32)> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// for (k, v) in [ + /// ("Bodleian Library", 1602), + /// ("Athenæum", 1807), + /// ("Herzogin-Anna-Amalia-Bibliothek", 1691), + /// ("Library of Congress", 1800), + /// ] { + /// libraries.insert_unique(hasher(&k), (k, v), |(k, _)| hasher(&k)); + /// } + /// + /// let keys = ["Athenæum", "Library of Congress"]; + /// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0); + /// assert_eq!( + /// got, + /// [Some(&mut ("Athenæum", 1807)), Some(&mut ("Library of Congress", 1800))], + /// ); + /// + /// // Missing keys result in None + /// let keys = ["Athenæum", "New York Public Library"]; + /// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0); + /// assert_eq!(got, [Some(&mut ("Athenæum", 1807)), None]); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + /// + /// ```should_panic + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// # use hashbrown::{HashTable, DefaultHashBuilder}; + /// # use std::hash::BuildHasher; + /// + /// let mut libraries: HashTable<(&str, u32)> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// for (k, v) in [ + /// ("Athenæum", 1807), + /// ("Library of Congress", 1800), + /// ] { + /// libraries.insert_unique(hasher(&k), (k, v), |(k, _)| hasher(&k)); + /// } + /// + /// // Duplicate keys result in a panic! + /// let keys = ["Athenæum", "Athenæum"]; + /// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test(); + /// # #[cfg(not(feature = "nightly"))] + /// # panic!(); + /// # } + /// ``` + pub fn get_many_mut( + &mut self, + hashes: [u64; N], + eq: impl FnMut(usize, &T) -> bool, + ) -> [Option<&'_ mut T>; N] { + self.raw.get_many_mut(hashes, eq) + } + + /// Attempts to get mutable references to `N` values in the map at once, without validating that + /// the values are unique. + /// + /// The `eq` argument should be a closure such that `eq(i, k)` returns true if `k` is equal to + /// the `i`th key to be looked up. + /// + /// Returns an array of length `N` with the results of each query. `None` will be returned if + /// any of the keys are missing. + /// + /// For a safe alternative see [`get_many_mut`](`HashTable::get_many_mut`). + /// + /// # Safety + /// + /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting + /// references are not used. + /// + /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut libraries: HashTable<(&str, u32)> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// for (k, v) in [ + /// ("Bodleian Library", 1602), + /// ("Athenæum", 1807), + /// ("Herzogin-Anna-Amalia-Bibliothek", 1691), + /// ("Library of Congress", 1800), + /// ] { + /// libraries.insert_unique(hasher(&k), (k, v), |(k, _)| hasher(&k)); + /// } + /// + /// let keys = ["Athenæum", "Library of Congress"]; + /// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0); + /// assert_eq!( + /// got, + /// [Some(&mut ("Athenæum", 1807)), Some(&mut ("Library of Congress", 1800))], + /// ); + /// + /// // Missing keys result in None + /// let keys = ["Athenæum", "New York Public Library"]; + /// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0); + /// assert_eq!(got, [Some(&mut ("Athenæum", 1807)), None]); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub unsafe fn get_many_unchecked_mut( + &mut self, + hashes: [u64; N], + eq: impl FnMut(usize, &T) -> bool, + ) -> [Option<&'_ mut T>; N] { + self.raw.get_many_unchecked_mut(hashes, eq) + } + + /// Returns the total amount of memory allocated internally by the hash + /// table, in bytes. + /// + /// The returned number is informational only. It is intended to be + /// primarily used for memory profiling. + #[inline] + pub fn allocation_size(&self) -> usize { + self.raw.allocation_size() + } +} + +impl IntoIterator for HashTable +where + A: Allocator, +{ + type Item = T; + type IntoIter = IntoIter; + + fn into_iter(self) -> IntoIter { + IntoIter { + inner: self.raw.into_iter(), + } + } +} + +impl<'a, T, A> IntoIterator for &'a HashTable +where + A: Allocator, +{ + type Item = &'a T; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<'a, T, A> IntoIterator for &'a mut HashTable +where + A: Allocator, +{ + type Item = &'a mut T; + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +impl Default for HashTable +where + A: Allocator + Default, +{ + fn default() -> Self { + Self { + raw: Default::default(), + } + } +} + +impl Clone for HashTable +where + T: Clone, + A: Allocator + Clone, +{ + fn clone(&self) -> Self { + Self { + raw: self.raw.clone(), + } + } +} + +impl fmt::Debug for HashTable +where + T: fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set().entries(self.iter()).finish() + } +} + +/// A view into a single entry in a table, which may either be vacant or occupied. +/// +/// This `enum` is constructed from the [`entry`] method on [`HashTable`]. +/// +/// [`HashTable`]: struct.HashTable.html +/// [`entry`]: struct.HashTable.html#method.entry +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "nightly")] +/// # fn test() { +/// use hashbrown::hash_table::{Entry, OccupiedEntry}; +/// use hashbrown::{HashTable, DefaultHashBuilder}; +/// use std::hash::BuildHasher; +/// +/// let mut table = HashTable::new(); +/// let hasher = DefaultHashBuilder::default(); +/// let hasher = |val: &_| hasher.hash_one(val); +/// for x in ["a", "b", "c"] { +/// table.insert_unique(hasher(&x), x, hasher); +/// } +/// assert_eq!(table.len(), 3); +/// +/// // Existing value (insert) +/// let entry: Entry<_> = table.entry(hasher(&"a"), |&x| x == "a", hasher); +/// let _raw_o: OccupiedEntry<_, _> = entry.insert("a"); +/// assert_eq!(table.len(), 3); +/// // Nonexistent value (insert) +/// table.entry(hasher(&"d"), |&x| x == "d", hasher).insert("d"); +/// +/// // Existing value (or_insert) +/// table +/// .entry(hasher(&"b"), |&x| x == "b", hasher) +/// .or_insert("b"); +/// // Nonexistent value (or_insert) +/// table +/// .entry(hasher(&"e"), |&x| x == "e", hasher) +/// .or_insert("e"); +/// +/// println!("Our HashTable: {:?}", table); +/// +/// let mut vec: Vec<_> = table.iter().copied().collect(); +/// // The `Iter` iterator produces items in arbitrary order, so the +/// // items must be sorted to test them against a sorted array. +/// vec.sort_unstable(); +/// assert_eq!(vec, ["a", "b", "c", "d", "e"]); +/// # } +/// # fn main() { +/// # #[cfg(feature = "nightly")] +/// # test() +/// # } +/// ``` +pub enum Entry<'a, T, A = Global> +where + A: Allocator, +{ + /// An occupied entry. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::{Entry, OccupiedEntry}; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// for x in ["a", "b"] { + /// table.insert_unique(hasher(&x), x, hasher); + /// } + /// + /// match table.entry(hasher(&"a"), |&x| x == "a", hasher) { + /// Entry::Vacant(_) => unreachable!(), + /// Entry::Occupied(_) => {} + /// } + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + Occupied(OccupiedEntry<'a, T, A>), + + /// A vacant entry. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::{Entry, OccupiedEntry}; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table = HashTable::<&str>::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// match table.entry(hasher(&"a"), |&x| x == "a", hasher) { + /// Entry::Vacant(_) => {} + /// Entry::Occupied(_) => unreachable!(), + /// } + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + Vacant(VacantEntry<'a, T, A>), +} + +impl fmt::Debug for Entry<'_, T, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(), + Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(), + } + } +} + +impl<'a, T, A> Entry<'a, T, A> +where + A: Allocator, +{ + /// Sets the value of the entry, replacing any existing value if there is + /// one, and returns an [`OccupiedEntry`]. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<&str> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// let entry = table + /// .entry(hasher(&"horseyland"), |&x| x == "horseyland", hasher) + /// .insert("horseyland"); + /// + /// assert_eq!(entry.get(), &"horseyland"); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn insert(self, value: T) -> OccupiedEntry<'a, T, A> { + match self { + Entry::Occupied(mut entry) => { + *entry.get_mut() = value; + entry + } + Entry::Vacant(entry) => entry.insert(value), + } + } + + /// Ensures a value is in the entry by inserting if it was vacant. + /// + /// Returns an [`OccupiedEntry`] pointing to the now-occupied entry. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<&str> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// // nonexistent key + /// table + /// .entry(hasher(&"poneyland"), |&x| x == "poneyland", hasher) + /// .or_insert("poneyland"); + /// assert!(table + /// .find(hasher(&"poneyland"), |&x| x == "poneyland") + /// .is_some()); + /// + /// // existing key + /// table + /// .entry(hasher(&"poneyland"), |&x| x == "poneyland", hasher) + /// .or_insert("poneyland"); + /// assert!(table + /// .find(hasher(&"poneyland"), |&x| x == "poneyland") + /// .is_some()); + /// assert_eq!(table.len(), 1); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn or_insert(self, default: T) -> OccupiedEntry<'a, T, A> { + match self { + Entry::Occupied(entry) => entry, + Entry::Vacant(entry) => entry.insert(default), + } + } + + /// Ensures a value is in the entry by inserting the result of the default function if empty.. + /// + /// Returns an [`OccupiedEntry`] pointing to the now-occupied entry. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// table + /// .entry(hasher("poneyland"), |x| x == "poneyland", |val| hasher(val)) + /// .or_insert_with(|| "poneyland".to_string()); + /// + /// assert!(table + /// .find(hasher(&"poneyland"), |x| x == "poneyland") + /// .is_some()); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn or_insert_with(self, default: impl FnOnce() -> T) -> OccupiedEntry<'a, T, A> { + match self { + Entry::Occupied(entry) => entry, + Entry::Vacant(entry) => entry.insert(default()), + } + } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the table. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<(&str, u32)> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// table + /// .entry( + /// hasher(&"poneyland"), + /// |&(x, _)| x == "poneyland", + /// |(k, _)| hasher(&k), + /// ) + /// .and_modify(|(_, v)| *v += 1) + /// .or_insert(("poneyland", 42)); + /// assert_eq!( + /// table.find(hasher(&"poneyland"), |&(k, _)| k == "poneyland"), + /// Some(&("poneyland", 42)) + /// ); + /// + /// table + /// .entry( + /// hasher(&"poneyland"), + /// |&(x, _)| x == "poneyland", + /// |(k, _)| hasher(&k), + /// ) + /// .and_modify(|(_, v)| *v += 1) + /// .or_insert(("poneyland", 42)); + /// assert_eq!( + /// table.find(hasher(&"poneyland"), |&(k, _)| k == "poneyland"), + /// Some(&("poneyland", 43)) + /// ); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn and_modify(self, f: impl FnOnce(&mut T)) -> Self { + match self { + Entry::Occupied(mut entry) => { + f(entry.get_mut()); + Entry::Occupied(entry) + } + Entry::Vacant(entry) => Entry::Vacant(entry), + } + } +} + +/// A view into an occupied entry in a `HashTable`. +/// It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "nightly")] +/// # fn test() { +/// use hashbrown::hash_table::{Entry, OccupiedEntry}; +/// use hashbrown::{HashTable, DefaultHashBuilder}; +/// use std::hash::BuildHasher; +/// +/// let mut table = HashTable::new(); +/// let hasher = DefaultHashBuilder::default(); +/// let hasher = |val: &_| hasher.hash_one(val); +/// for x in ["a", "b", "c"] { +/// table.insert_unique(hasher(&x), x, hasher); +/// } +/// assert_eq!(table.len(), 3); +/// +/// let _entry_o: OccupiedEntry<_, _> = table.find_entry(hasher(&"a"), |&x| x == "a").unwrap(); +/// assert_eq!(table.len(), 3); +/// +/// // Existing key +/// match table.entry(hasher(&"a"), |&x| x == "a", hasher) { +/// Entry::Vacant(_) => unreachable!(), +/// Entry::Occupied(view) => { +/// assert_eq!(view.get(), &"a"); +/// } +/// } +/// +/// assert_eq!(table.len(), 3); +/// +/// // Existing key (take) +/// match table.entry(hasher(&"c"), |&x| x == "c", hasher) { +/// Entry::Vacant(_) => unreachable!(), +/// Entry::Occupied(view) => { +/// assert_eq!(view.remove().0, "c"); +/// } +/// } +/// assert_eq!(table.find(hasher(&"c"), |&x| x == "c"), None); +/// assert_eq!(table.len(), 2); +/// # } +/// # fn main() { +/// # #[cfg(feature = "nightly")] +/// # test() +/// # } +/// ``` +pub struct OccupiedEntry<'a, T, A = Global> +where + A: Allocator, +{ + hash: u64, + bucket: Bucket, + table: &'a mut HashTable, +} + +unsafe impl Send for OccupiedEntry<'_, T, A> +where + T: Send, + A: Send + Allocator, +{ +} +unsafe impl Sync for OccupiedEntry<'_, T, A> +where + T: Sync, + A: Sync + Allocator, +{ +} + +impl fmt::Debug for OccupiedEntry<'_, T, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OccupiedEntry") + .field("value", self.get()) + .finish() + } +} + +impl<'a, T, A> OccupiedEntry<'a, T, A> +where + A: Allocator, +{ + /// Takes the value out of the entry, and returns it along with a + /// `VacantEntry` that can be used to insert another value with the same + /// hash as the one that was just removed. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<&str> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// // The table is empty + /// assert!(table.is_empty() && table.capacity() == 0); + /// + /// table.insert_unique(hasher(&"poneyland"), "poneyland", hasher); + /// let capacity_before_remove = table.capacity(); + /// + /// if let Entry::Occupied(o) = table.entry(hasher(&"poneyland"), |&x| x == "poneyland", hasher) { + /// assert_eq!(o.remove().0, "poneyland"); + /// } + /// + /// assert!(table + /// .find(hasher(&"poneyland"), |&x| x == "poneyland") + /// .is_none()); + /// // Now table hold none elements but capacity is equal to the old one + /// assert!(table.len() == 0 && table.capacity() == capacity_before_remove); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn remove(self) -> (T, VacantEntry<'a, T, A>) { + let (val, slot) = unsafe { self.table.raw.remove(self.bucket) }; + ( + val, + VacantEntry { + hash: self.hash, + insert_slot: slot, + table: self.table, + }, + ) + } + + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<&str> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&"poneyland"), "poneyland", hasher); + /// + /// match table.entry(hasher(&"poneyland"), |&x| x == "poneyland", hasher) { + /// Entry::Vacant(_) => panic!(), + /// Entry::Occupied(entry) => assert_eq!(entry.get(), &"poneyland"), + /// } + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + #[inline] + pub fn get(&self) -> &T { + unsafe { self.bucket.as_ref() } + } + + /// Gets a mutable reference to the value in the entry. + /// + /// If you need a reference to the `OccupiedEntry` which may outlive the + /// destruction of the `Entry` value, see [`into_mut`]. + /// + /// [`into_mut`]: #method.into_mut + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<(&str, u32)> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&"poneyland"), ("poneyland", 12), |(k, _)| hasher(&k)); + /// + /// assert_eq!( + /// table.find(hasher(&"poneyland"), |&(x, _)| x == "poneyland",), + /// Some(&("poneyland", 12)) + /// ); + /// + /// if let Entry::Occupied(mut o) = table.entry( + /// hasher(&"poneyland"), + /// |&(x, _)| x == "poneyland", + /// |(k, _)| hasher(&k), + /// ) { + /// o.get_mut().1 += 10; + /// assert_eq!(o.get().1, 22); + /// + /// // We can use the same Entry multiple times. + /// o.get_mut().1 += 2; + /// } + /// + /// assert_eq!( + /// table.find(hasher(&"poneyland"), |&(x, _)| x == "poneyland",), + /// Some(&("poneyland", 24)) + /// ); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + #[inline] + pub fn get_mut(&mut self) -> &mut T { + unsafe { self.bucket.as_mut() } + } + + /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry + /// with a lifetime bound to the table itself. + /// + /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`]. + /// + /// [`get_mut`]: #method.get_mut + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<(&str, u32)> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// table.insert_unique(hasher(&"poneyland"), ("poneyland", 12), |(k, _)| hasher(&k)); + /// + /// assert_eq!( + /// table.find(hasher(&"poneyland"), |&(x, _)| x == "poneyland",), + /// Some(&("poneyland", 12)) + /// ); + /// + /// let value: &mut (&str, u32); + /// match table.entry( + /// hasher(&"poneyland"), + /// |&(x, _)| x == "poneyland", + /// |(k, _)| hasher(&k), + /// ) { + /// Entry::Occupied(entry) => value = entry.into_mut(), + /// Entry::Vacant(_) => panic!(), + /// } + /// value.1 += 10; + /// + /// assert_eq!( + /// table.find(hasher(&"poneyland"), |&(x, _)| x == "poneyland",), + /// Some(&("poneyland", 22)) + /// ); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + pub fn into_mut(self) -> &'a mut T { + unsafe { self.bucket.as_mut() } + } + + /// Converts the `OccupiedEntry` into a mutable reference to the underlying + /// table. + pub fn into_table(self) -> &'a mut HashTable { + self.table + } +} + +/// A view into a vacant entry in a `HashTable`. +/// It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "nightly")] +/// # fn test() { +/// use hashbrown::hash_table::{Entry, VacantEntry}; +/// use hashbrown::{HashTable, DefaultHashBuilder}; +/// use std::hash::BuildHasher; +/// +/// let mut table: HashTable<&str> = HashTable::new(); +/// let hasher = DefaultHashBuilder::default(); +/// let hasher = |val: &_| hasher.hash_one(val); +/// +/// let entry_v: VacantEntry<_, _> = match table.entry(hasher(&"a"), |&x| x == "a", hasher) { +/// Entry::Vacant(view) => view, +/// Entry::Occupied(_) => unreachable!(), +/// }; +/// entry_v.insert("a"); +/// assert!(table.find(hasher(&"a"), |&x| x == "a").is_some() && table.len() == 1); +/// +/// // Nonexistent key (insert) +/// match table.entry(hasher(&"b"), |&x| x == "b", hasher) { +/// Entry::Vacant(view) => { +/// view.insert("b"); +/// } +/// Entry::Occupied(_) => unreachable!(), +/// } +/// assert!(table.find(hasher(&"b"), |&x| x == "b").is_some() && table.len() == 2); +/// # } +/// # fn main() { +/// # #[cfg(feature = "nightly")] +/// # test() +/// # } +/// ``` +pub struct VacantEntry<'a, T, A = Global> +where + A: Allocator, +{ + hash: u64, + insert_slot: InsertSlot, + table: &'a mut HashTable, +} + +impl fmt::Debug for VacantEntry<'_, T, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("VacantEntry") + } +} + +impl<'a, T, A> VacantEntry<'a, T, A> +where + A: Allocator, +{ + /// Inserts a new element into the table with the hash that was used to + /// obtain the `VacantEntry`. + /// + /// An `OccupiedEntry` is returned for the newly inserted element. + /// + /// # Examples + /// + /// ``` + /// # #[cfg(feature = "nightly")] + /// # fn test() { + /// use hashbrown::hash_table::Entry; + /// use hashbrown::{HashTable, DefaultHashBuilder}; + /// use std::hash::BuildHasher; + /// + /// let mut table: HashTable<&str> = HashTable::new(); + /// let hasher = DefaultHashBuilder::default(); + /// let hasher = |val: &_| hasher.hash_one(val); + /// + /// if let Entry::Vacant(o) = table.entry(hasher(&"poneyland"), |&x| x == "poneyland", hasher) { + /// o.insert("poneyland"); + /// } + /// assert_eq!( + /// table.find(hasher(&"poneyland"), |&x| x == "poneyland"), + /// Some(&"poneyland") + /// ); + /// # } + /// # fn main() { + /// # #[cfg(feature = "nightly")] + /// # test() + /// # } + /// ``` + #[inline] + pub fn insert(self, value: T) -> OccupiedEntry<'a, T, A> { + let bucket = unsafe { + self.table + .raw + .insert_in_slot(self.hash, self.insert_slot, value) + }; + OccupiedEntry { + hash: self.hash, + bucket, + table: self.table, + } + } + + /// Converts the `VacantEntry` into a mutable reference to the underlying + /// table. + pub fn into_table(self) -> &'a mut HashTable { + self.table + } +} + +/// Type representing the absence of an entry, as returned by [`HashTable::find_entry`]. +/// +/// This type only exists due to [limitations] in Rust's NLL borrow checker. In +/// the future, `find_entry` will return an `Option` and this +/// type will be removed. +/// +/// [limitations]: https://smallcultfollowing.com/babysteps/blog/2018/06/15/mir-based-borrow-check-nll-status-update/#polonius +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "nightly")] +/// # fn test() { +/// use hashbrown::hash_table::{AbsentEntry, Entry}; +/// use hashbrown::{HashTable, DefaultHashBuilder}; +/// use std::hash::BuildHasher; +/// +/// let mut table: HashTable<&str> = HashTable::new(); +/// let hasher = DefaultHashBuilder::default(); +/// let hasher = |val: &_| hasher.hash_one(val); +/// +/// let entry_v: AbsentEntry<_, _> = table.find_entry(hasher(&"a"), |&x| x == "a").unwrap_err(); +/// entry_v +/// .into_table() +/// .insert_unique(hasher(&"a"), "a", hasher); +/// assert!(table.find(hasher(&"a"), |&x| x == "a").is_some() && table.len() == 1); +/// +/// // Nonexistent key (insert) +/// match table.entry(hasher(&"b"), |&x| x == "b", hasher) { +/// Entry::Vacant(view) => { +/// view.insert("b"); +/// } +/// Entry::Occupied(_) => unreachable!(), +/// } +/// assert!(table.find(hasher(&"b"), |&x| x == "b").is_some() && table.len() == 2); +/// # } +/// # fn main() { +/// # #[cfg(feature = "nightly")] +/// # test() +/// # } +/// ``` +pub struct AbsentEntry<'a, T, A = Global> +where + A: Allocator, +{ + table: &'a mut HashTable, +} + +impl fmt::Debug for AbsentEntry<'_, T, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AbsentEntry") + } +} + +impl<'a, T, A> AbsentEntry<'a, T, A> +where + A: Allocator, +{ + /// Converts the `AbsentEntry` into a mutable reference to the underlying + /// table. + pub fn into_table(self) -> &'a mut HashTable { + self.table + } +} + +/// An iterator over the entries of a `HashTable` in arbitrary order. +/// The iterator element type is `&'a T`. +/// +/// This `struct` is created by the [`iter`] method on [`HashTable`]. See its +/// documentation for more. +/// +/// [`iter`]: struct.HashTable.html#method.iter +/// [`HashTable`]: struct.HashTable.html +pub struct Iter<'a, T> { + inner: RawIter, + marker: PhantomData<&'a T>, +} + +impl<'a, T> Default for Iter<'a, T> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + Iter { + inner: Default::default(), + marker: PhantomData, + } + } +} + +impl<'a, T> Iterator for Iter<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some(bucket) => Some(unsafe { bucket.as_ref() }), + None => None, + } + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner + .fold(init, |acc, bucket| unsafe { f(acc, bucket.as_ref()) }) + } +} + +impl ExactSizeIterator for Iter<'_, T> { + fn len(&self) -> usize { + self.inner.len() + } +} + +impl FusedIterator for Iter<'_, T> {} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl<'a, T> Clone for Iter<'a, T> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> Iter<'a, T> { + Iter { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +impl fmt::Debug for Iter<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A mutable iterator over the entries of a `HashTable` in arbitrary order. +/// The iterator element type is `&'a mut T`. +/// +/// This `struct` is created by the [`iter_mut`] method on [`HashTable`]. See its +/// documentation for more. +/// +/// [`iter_mut`]: struct.HashTable.html#method.iter_mut +/// [`HashTable`]: struct.HashTable.html +pub struct IterMut<'a, T> { + inner: RawIter, + marker: PhantomData<&'a mut T>, +} + +impl<'a, T> Default for IterMut<'a, T> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + IterMut { + inner: Default::default(), + marker: PhantomData, + } + } +} +impl<'a, T> Iterator for IterMut<'a, T> { + type Item = &'a mut T; + + fn next(&mut self) -> Option { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some(bucket) => Some(unsafe { bucket.as_mut() }), + None => None, + } + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner + .fold(init, |acc, bucket| unsafe { f(acc, bucket.as_mut()) }) + } +} + +impl ExactSizeIterator for IterMut<'_, T> { + fn len(&self) -> usize { + self.inner.len() + } +} + +impl FusedIterator for IterMut<'_, T> {} + +impl fmt::Debug for IterMut<'_, T> +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(Iter { + inner: self.inner.clone(), + marker: PhantomData, + }) + .finish() + } +} + +/// An iterator over the entries of a `HashTable` that could match a given hash. +/// The iterator element type is `&'a T`. +/// +/// This `struct` is created by the [`iter_hash`] method on [`HashTable`]. See its +/// documentation for more. +/// +/// [`iter_hash`]: struct.HashTable.html#method.iter_hash +/// [`HashTable`]: struct.HashTable.html +pub struct IterHash<'a, T> { + inner: RawIterHash, + marker: PhantomData<&'a T>, +} + +impl<'a, T> Default for IterHash<'a, T> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + IterHash { + inner: Default::default(), + marker: PhantomData, + } + } +} + +impl<'a, T> Iterator for IterHash<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some(bucket) => Some(unsafe { bucket.as_ref() }), + None => None, + } + } + + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner + .fold(init, |acc, bucket| unsafe { f(acc, bucket.as_ref()) }) + } +} + +impl FusedIterator for IterHash<'_, T> {} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl<'a, T> Clone for IterHash<'a, T> { + #[cfg_attr(feature = "inline-more", inline)] + fn clone(&self) -> IterHash<'a, T> { + IterHash { + inner: self.inner.clone(), + marker: PhantomData, + } + } +} + +impl fmt::Debug for IterHash<'_, T> +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A mutable iterator over the entries of a `HashTable` that could match a given hash. +/// The iterator element type is `&'a mut T`. +/// +/// This `struct` is created by the [`iter_hash_mut`] method on [`HashTable`]. See its +/// documentation for more. +/// +/// [`iter_hash_mut`]: struct.HashTable.html#method.iter_hash_mut +/// [`HashTable`]: struct.HashTable.html +pub struct IterHashMut<'a, T> { + inner: RawIterHash, + marker: PhantomData<&'a mut T>, +} + +impl<'a, T> Default for IterHashMut<'a, T> { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + IterHashMut { + inner: Default::default(), + marker: PhantomData, + } + } +} + +impl<'a, T> Iterator for IterHashMut<'a, T> { + type Item = &'a mut T; + + fn next(&mut self) -> Option { + // Avoid `Option::map` because it bloats LLVM IR. + match self.inner.next() { + Some(bucket) => Some(unsafe { bucket.as_mut() }), + None => None, + } + } + + fn fold(self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner + .fold(init, |acc, bucket| unsafe { f(acc, bucket.as_mut()) }) + } +} + +impl FusedIterator for IterHashMut<'_, T> {} + +impl fmt::Debug for IterHashMut<'_, T> +where + T: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(IterHash { + inner: self.inner.clone(), + marker: PhantomData, + }) + .finish() + } +} + +/// An owning iterator over the entries of a `HashTable` in arbitrary order. +/// The iterator element type is `T`. +/// +/// This `struct` is created by the [`into_iter`] method on [`HashTable`] +/// (provided by the [`IntoIterator`] trait). See its documentation for more. +/// The table cannot be used after calling that method. +/// +/// [`into_iter`]: struct.HashTable.html#method.into_iter +/// [`HashTable`]: struct.HashTable.html +/// [`IntoIterator`]: https://doc.rust-lang.org/core/iter/trait.IntoIterator.html +pub struct IntoIter +where + A: Allocator, +{ + inner: RawIntoIter, +} + +impl Default for IntoIter { + #[cfg_attr(feature = "inline-more", inline)] + fn default() -> Self { + IntoIter { + inner: Default::default(), + } + } +} + +impl Iterator for IntoIter +where + A: Allocator, +{ + type Item = T; + + fn next(&mut self) -> Option { + self.inner.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, f) + } +} + +impl ExactSizeIterator for IntoIter +where + A: Allocator, +{ + fn len(&self) -> usize { + self.inner.len() + } +} + +impl FusedIterator for IntoIter where A: Allocator {} + +impl fmt::Debug for IntoIter +where + T: fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(Iter { + inner: self.inner.iter(), + marker: PhantomData, + }) + .finish() + } +} + +/// A draining iterator over the items of a `HashTable`. +/// +/// This `struct` is created by the [`drain`] method on [`HashTable`]. +/// See its documentation for more. +/// +/// [`HashTable`]: struct.HashTable.html +/// [`drain`]: struct.HashTable.html#method.drain +pub struct Drain<'a, T, A: Allocator = Global> { + inner: RawDrain<'a, T, A>, +} + +impl Iterator for Drain<'_, T, A> { + type Item = T; + + fn next(&mut self) -> Option { + self.inner.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + + fn fold(self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + self.inner.fold(init, f) + } +} + +impl ExactSizeIterator for Drain<'_, T, A> { + fn len(&self) -> usize { + self.inner.len() + } +} + +impl FusedIterator for Drain<'_, T, A> {} + +impl fmt::Debug for Drain<'_, T, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(Iter { + inner: self.inner.iter(), + marker: PhantomData, + }) + .finish() + } +} + +/// A draining iterator over entries of a `HashTable` which don't satisfy the predicate `f`. +/// +/// This `struct` is created by [`HashTable::extract_if`]. See its +/// documentation for more. +#[must_use = "Iterators are lazy unless consumed"] +pub struct ExtractIf<'a, T, F, A: Allocator = Global> +where + F: FnMut(&mut T) -> bool, +{ + f: F, + inner: RawExtractIf<'a, T, A>, +} + +impl Iterator for ExtractIf<'_, T, F, A> +where + F: FnMut(&mut T) -> bool, +{ + type Item = T; + + #[inline] + fn next(&mut self) -> Option { + self.inner.next(|val| (self.f)(val)) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (0, self.inner.iter.size_hint().1) + } +} + +impl FusedIterator for ExtractIf<'_, T, F, A> where F: FnMut(&mut T) -> bool {} + +#[cfg(test)] +mod tests { + use super::HashTable; + + #[test] + fn test_allocation_info() { + assert_eq!(HashTable::<()>::new().allocation_size(), 0); + assert_eq!(HashTable::::new().allocation_size(), 0); + assert!(HashTable::::with_capacity(1).allocation_size() > core::mem::size_of::()); + } +} diff --git a/bitbox02-bt/vendor/hashbrown/tests/equivalent_trait.rs b/bitbox02-bt/vendor/hashbrown/tests/equivalent_trait.rs new file mode 100644 index 0000000..713dddd --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/tests/equivalent_trait.rs @@ -0,0 +1,53 @@ +use hashbrown::Equivalent; +use hashbrown::HashMap; + +use std::hash::Hash; + +#[derive(Debug, Hash)] +pub struct Pair(pub A, pub B); + +impl PartialEq<(A, B)> for Pair +where + C: PartialEq, + D: PartialEq, +{ + fn eq(&self, rhs: &(A, B)) -> bool { + self.0 == rhs.0 && self.1 == rhs.1 + } +} + +impl Equivalent for Pair +where + Pair: PartialEq, + A: Hash + Eq, + B: Hash + Eq, +{ + fn equivalent(&self, other: &X) -> bool { + *self == *other + } +} + +#[test] +fn test_lookup() { + let s = String::from; + let mut map = HashMap::new(); + map.insert((s("a"), s("b")), 1); + map.insert((s("a"), s("x")), 2); + + assert!(map.contains_key(&Pair("a", "b"))); + assert!(!map.contains_key(&Pair("b", "a"))); +} + +#[test] +fn test_string_str() { + let s = String::from; + let mut map = HashMap::new(); + map.insert(s("a"), 1); + map.insert(s("b"), 2); + map.insert(s("x"), 3); + map.insert(s("y"), 4); + + assert!(map.contains_key("a")); + assert!(!map.contains_key("z")); + assert_eq!(map.remove("b"), Some(2)); +} diff --git a/bitbox02-bt/vendor/hashbrown/tests/hasher.rs b/bitbox02-bt/vendor/hashbrown/tests/hasher.rs new file mode 100644 index 0000000..2237378 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/tests/hasher.rs @@ -0,0 +1,65 @@ +//! Sanity check that alternate hashers work correctly. + +#![cfg(not(miri))] // FIXME: takes too long + +use hashbrown::HashSet; +use std::hash::{BuildHasher, BuildHasherDefault, Hasher}; + +fn check() { + let range = 0..1_000; + + let mut set = HashSet::::default(); + set.extend(range.clone()); + + assert!(!set.contains(&i32::MIN)); + assert!(!set.contains(&(range.start - 1))); + for i in range.clone() { + assert!(set.contains(&i)); + } + assert!(!set.contains(&range.end)); + assert!(!set.contains(&i32::MAX)); +} + +/// Use hashbrown's default hasher. +#[test] +fn default() { + check::(); +} + +/// Use std's default hasher. +#[test] +fn random_state() { + check::(); +} + +/// Use a constant 0 hash. +#[test] +fn zero() { + #[derive(Default)] + struct ZeroHasher; + + impl Hasher for ZeroHasher { + fn finish(&self) -> u64 { + 0 + } + fn write(&mut self, _: &[u8]) {} + } + + check::>(); +} + +/// Use a constant maximum hash. +#[test] +fn max() { + #[derive(Default)] + struct MaxHasher; + + impl Hasher for MaxHasher { + fn finish(&self) -> u64 { + u64::MAX + } + fn write(&mut self, _: &[u8]) {} + } + + check::>(); +} diff --git a/bitbox02-bt/vendor/hashbrown/tests/rayon.rs b/bitbox02-bt/vendor/hashbrown/tests/rayon.rs new file mode 100644 index 0000000..d55e5a9 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/tests/rayon.rs @@ -0,0 +1,535 @@ +#![cfg(feature = "rayon")] + +#[macro_use] +extern crate lazy_static; + +use hashbrown::{HashMap, HashSet}; +use rayon::iter::{ + IntoParallelIterator, IntoParallelRefIterator, IntoParallelRefMutIterator, ParallelExtend, + ParallelIterator, +}; + +macro_rules! assert_eq3 { + ($e1:expr, $e2:expr, $e3:expr) => {{ + assert_eq!($e1, $e2); + assert_eq!($e1, $e3); + assert_eq!($e2, $e3); + }}; +} + +lazy_static! { + static ref MAP_EMPTY: HashMap = HashMap::new(); + static ref MAP: HashMap = { + let mut m = HashMap::new(); + m.insert('b', 20); + m.insert('a', 10); + m.insert('c', 30); + m.insert('e', 50); + m.insert('f', 60); + m.insert('d', 40); + m + }; +} + +#[test] +fn map_seq_par_equivalence_iter_empty() { + let vec_seq = MAP_EMPTY.iter().collect::>(); + let vec_par = MAP_EMPTY.par_iter().collect::>(); + + assert_eq3!(vec_seq, vec_par, []); +} + +#[test] +fn map_seq_par_equivalence_iter() { + let mut vec_seq = MAP.iter().collect::>(); + let mut vec_par = MAP.par_iter().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = [ + (&'a', &10), + (&'b', &20), + (&'c', &30), + (&'d', &40), + (&'e', &50), + (&'f', &60), + ]; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +#[test] +fn map_seq_par_equivalence_keys_empty() { + let vec_seq = MAP_EMPTY.keys().collect::>(); + let vec_par = MAP_EMPTY.par_keys().collect::>(); + + let expected: [&char; 0] = []; + + assert_eq3!(vec_seq, vec_par, expected); +} + +#[test] +fn map_seq_par_equivalence_keys() { + let mut vec_seq = MAP.keys().collect::>(); + let mut vec_par = MAP.par_keys().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = [&'a', &'b', &'c', &'d', &'e', &'f']; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +#[test] +fn map_seq_par_equivalence_values_empty() { + let vec_seq = MAP_EMPTY.values().collect::>(); + let vec_par = MAP_EMPTY.par_values().collect::>(); + + let expected: [&u32; 0] = []; + + assert_eq3!(vec_seq, vec_par, expected); +} + +#[test] +fn map_seq_par_equivalence_values() { + let mut vec_seq = MAP.values().collect::>(); + let mut vec_par = MAP.par_values().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = [&10, &20, &30, &40, &50, &60]; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +#[test] +fn map_seq_par_equivalence_iter_mut_empty() { + let mut map1 = MAP_EMPTY.clone(); + let mut map2 = MAP_EMPTY.clone(); + + let vec_seq = map1.iter_mut().collect::>(); + let vec_par = map2.par_iter_mut().collect::>(); + + assert_eq3!(vec_seq, vec_par, []); +} + +#[test] +fn map_seq_par_equivalence_iter_mut() { + let mut map1 = MAP.clone(); + let mut map2 = MAP.clone(); + + let mut vec_seq = map1.iter_mut().collect::>(); + let mut vec_par = map2.par_iter_mut().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = [ + (&'a', &mut 10), + (&'b', &mut 20), + (&'c', &mut 30), + (&'d', &mut 40), + (&'e', &mut 50), + (&'f', &mut 60), + ]; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +#[test] +fn map_seq_par_equivalence_values_mut_empty() { + let mut map1 = MAP_EMPTY.clone(); + let mut map2 = MAP_EMPTY.clone(); + + let vec_seq = map1.values_mut().collect::>(); + let vec_par = map2.par_values_mut().collect::>(); + + let expected: [&u32; 0] = []; + + assert_eq3!(vec_seq, vec_par, expected); +} + +#[test] +fn map_seq_par_equivalence_values_mut() { + let mut map1 = MAP.clone(); + let mut map2 = MAP.clone(); + + let mut vec_seq = map1.values_mut().collect::>(); + let mut vec_par = map2.par_values_mut().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = [&mut 10, &mut 20, &mut 30, &mut 40, &mut 50, &mut 60]; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +#[test] +fn map_seq_par_equivalence_into_iter_empty() { + let vec_seq = MAP_EMPTY.clone().into_iter().collect::>(); + let vec_par = MAP_EMPTY.clone().into_par_iter().collect::>(); + + assert_eq3!(vec_seq, vec_par, []); +} + +#[test] +fn map_seq_par_equivalence_into_iter() { + let mut vec_seq = MAP.clone().into_iter().collect::>(); + let mut vec_par = MAP.clone().into_par_iter().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = [ + ('a', 10), + ('b', 20), + ('c', 30), + ('d', 40), + ('e', 50), + ('f', 60), + ]; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +lazy_static! { + static ref MAP_VEC_EMPTY: Vec<(char, u32)> = vec![]; + static ref MAP_VEC: Vec<(char, u32)> = vec![ + ('b', 20), + ('a', 10), + ('c', 30), + ('e', 50), + ('f', 60), + ('d', 40), + ]; +} + +#[test] +fn map_seq_par_equivalence_collect_empty() { + let map_expected = MAP_EMPTY.clone(); + let map_seq = MAP_VEC_EMPTY.clone().into_iter().collect::>(); + let map_par = MAP_VEC_EMPTY + .clone() + .into_par_iter() + .collect::>(); + + assert_eq!(map_seq, map_par); + assert_eq!(map_seq, map_expected); + assert_eq!(map_par, map_expected); +} + +#[test] +fn map_seq_par_equivalence_collect() { + let map_expected = MAP.clone(); + let map_seq = MAP_VEC.clone().into_iter().collect::>(); + let map_par = MAP_VEC.clone().into_par_iter().collect::>(); + + assert_eq!(map_seq, map_par); + assert_eq!(map_seq, map_expected); + assert_eq!(map_par, map_expected); +} + +lazy_static! { + static ref MAP_EXISTING_EMPTY: HashMap = HashMap::new(); + static ref MAP_EXISTING: HashMap = { + let mut m = HashMap::new(); + m.insert('b', 20); + m.insert('a', 10); + m + }; + static ref MAP_EXTENSION_EMPTY: Vec<(char, u32)> = vec![]; + static ref MAP_EXTENSION: Vec<(char, u32)> = vec![('c', 30), ('e', 50), ('f', 60), ('d', 40),]; +} + +#[test] +fn map_seq_par_equivalence_existing_empty_extend_empty() { + let expected = HashMap::new(); + let mut map_seq = MAP_EXISTING_EMPTY.clone(); + let mut map_par = MAP_EXISTING_EMPTY.clone(); + + map_seq.extend(MAP_EXTENSION_EMPTY.iter().copied()); + map_par.par_extend(MAP_EXTENSION_EMPTY.par_iter().copied()); + + assert_eq3!(map_seq, map_par, expected); +} + +#[test] +fn map_seq_par_equivalence_existing_empty_extend() { + let expected = MAP_EXTENSION.iter().copied().collect::>(); + let mut map_seq = MAP_EXISTING_EMPTY.clone(); + let mut map_par = MAP_EXISTING_EMPTY.clone(); + + map_seq.extend(MAP_EXTENSION.iter().copied()); + map_par.par_extend(MAP_EXTENSION.par_iter().copied()); + + assert_eq3!(map_seq, map_par, expected); +} + +#[test] +fn map_seq_par_equivalence_existing_extend_empty() { + let expected = MAP_EXISTING.clone(); + let mut map_seq = MAP_EXISTING.clone(); + let mut map_par = MAP_EXISTING.clone(); + + map_seq.extend(MAP_EXTENSION_EMPTY.iter().copied()); + map_par.par_extend(MAP_EXTENSION_EMPTY.par_iter().copied()); + + assert_eq3!(map_seq, map_par, expected); +} + +#[test] +fn map_seq_par_equivalence_existing_extend() { + let expected = MAP.clone(); + let mut map_seq = MAP_EXISTING.clone(); + let mut map_par = MAP_EXISTING.clone(); + + map_seq.extend(MAP_EXTENSION.iter().copied()); + map_par.par_extend(MAP_EXTENSION.par_iter().copied()); + + assert_eq3!(map_seq, map_par, expected); +} + +lazy_static! { + static ref SET_EMPTY: HashSet = HashSet::new(); + static ref SET: HashSet = { + let mut s = HashSet::new(); + s.insert('b'); + s.insert('a'); + s.insert('c'); + s.insert('e'); + s.insert('f'); + s.insert('d'); + s + }; +} + +#[test] +fn set_seq_par_equivalence_iter_empty() { + let vec_seq = SET_EMPTY.iter().collect::>(); + let vec_par = SET_EMPTY.par_iter().collect::>(); + + let expected: [&char; 0] = []; + + assert_eq3!(vec_seq, vec_par, expected); +} + +#[test] +fn set_seq_par_equivalence_iter() { + let mut vec_seq = SET.iter().collect::>(); + let mut vec_par = SET.par_iter().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = [&'a', &'b', &'c', &'d', &'e', &'f']; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +#[test] +fn set_seq_par_equivalence_into_iter_empty() { + let vec_seq = SET_EMPTY.clone().into_iter().collect::>(); + let vec_par = SET_EMPTY.clone().into_par_iter().collect::>(); + + // Work around type inference failure introduced by rend dev-dependency. + let empty: [char; 0] = []; + assert_eq3!(vec_seq, vec_par, empty); +} + +#[test] +fn set_seq_par_equivalence_into_iter() { + let mut vec_seq = SET.clone().into_iter().collect::>(); + let mut vec_par = SET.clone().into_par_iter().collect::>(); + + assert_eq!(vec_seq, vec_par); + + // Do not depend on the exact order of values + let expected_sorted = ['a', 'b', 'c', 'd', 'e', 'f']; + + vec_seq.sort_unstable(); + vec_par.sort_unstable(); + + assert_eq3!(vec_seq, vec_par, expected_sorted); +} + +lazy_static! { + static ref SET_VEC_EMPTY: Vec = vec![]; + static ref SET_VEC: Vec = vec!['b', 'a', 'c', 'e', 'f', 'd',]; +} + +#[test] +fn set_seq_par_equivalence_collect_empty() { + let set_expected = SET_EMPTY.clone(); + let set_seq = SET_VEC_EMPTY.clone().into_iter().collect::>(); + let set_par = SET_VEC_EMPTY + .clone() + .into_par_iter() + .collect::>(); + + assert_eq!(set_seq, set_par); + assert_eq!(set_seq, set_expected); + assert_eq!(set_par, set_expected); +} + +#[test] +fn set_seq_par_equivalence_collect() { + let set_expected = SET.clone(); + let set_seq = SET_VEC.clone().into_iter().collect::>(); + let set_par = SET_VEC.clone().into_par_iter().collect::>(); + + assert_eq!(set_seq, set_par); + assert_eq!(set_seq, set_expected); + assert_eq!(set_par, set_expected); +} + +lazy_static! { + static ref SET_EXISTING_EMPTY: HashSet = HashSet::new(); + static ref SET_EXISTING: HashSet = { + let mut s = HashSet::new(); + s.insert('b'); + s.insert('a'); + s + }; + static ref SET_EXTENSION_EMPTY: Vec = vec![]; + static ref SET_EXTENSION: Vec = vec!['c', 'e', 'f', 'd',]; +} + +#[test] +fn set_seq_par_equivalence_existing_empty_extend_empty() { + let expected = HashSet::new(); + let mut set_seq = SET_EXISTING_EMPTY.clone(); + let mut set_par = SET_EXISTING_EMPTY.clone(); + + set_seq.extend(SET_EXTENSION_EMPTY.iter().copied()); + set_par.par_extend(SET_EXTENSION_EMPTY.par_iter().copied()); + + assert_eq3!(set_seq, set_par, expected); +} + +#[test] +fn set_seq_par_equivalence_existing_empty_extend() { + let expected = SET_EXTENSION.iter().copied().collect::>(); + let mut set_seq = SET_EXISTING_EMPTY.clone(); + let mut set_par = SET_EXISTING_EMPTY.clone(); + + set_seq.extend(SET_EXTENSION.iter().copied()); + set_par.par_extend(SET_EXTENSION.par_iter().copied()); + + assert_eq3!(set_seq, set_par, expected); +} + +#[test] +fn set_seq_par_equivalence_existing_extend_empty() { + let expected = SET_EXISTING.clone(); + let mut set_seq = SET_EXISTING.clone(); + let mut set_par = SET_EXISTING.clone(); + + set_seq.extend(SET_EXTENSION_EMPTY.iter().copied()); + set_par.par_extend(SET_EXTENSION_EMPTY.par_iter().copied()); + + assert_eq3!(set_seq, set_par, expected); +} + +#[test] +fn set_seq_par_equivalence_existing_extend() { + let expected = SET.clone(); + let mut set_seq = SET_EXISTING.clone(); + let mut set_par = SET_EXISTING.clone(); + + set_seq.extend(SET_EXTENSION.iter().copied()); + set_par.par_extend(SET_EXTENSION.par_iter().copied()); + + assert_eq3!(set_seq, set_par, expected); +} + +lazy_static! { + static ref SET_A: HashSet = ['a', 'b', 'c', 'd'].iter().copied().collect(); + static ref SET_B: HashSet = ['a', 'b', 'e', 'f'].iter().copied().collect(); + static ref SET_DIFF_AB: HashSet = ['c', 'd'].iter().copied().collect(); + static ref SET_DIFF_BA: HashSet = ['e', 'f'].iter().copied().collect(); + static ref SET_SYMM_DIFF_AB: HashSet = ['c', 'd', 'e', 'f'].iter().copied().collect(); + static ref SET_INTERSECTION_AB: HashSet = ['a', 'b'].iter().copied().collect(); + static ref SET_UNION_AB: HashSet = + ['a', 'b', 'c', 'd', 'e', 'f'].iter().copied().collect(); +} + +#[test] +fn set_seq_par_equivalence_difference() { + let diff_ab_seq = SET_A.difference(&*SET_B).copied().collect::>(); + let diff_ab_par = SET_A + .par_difference(&*SET_B) + .copied() + .collect::>(); + + assert_eq3!(diff_ab_seq, diff_ab_par, *SET_DIFF_AB); + + let diff_ba_seq = SET_B.difference(&*SET_A).copied().collect::>(); + let diff_ba_par = SET_B + .par_difference(&*SET_A) + .copied() + .collect::>(); + + assert_eq3!(diff_ba_seq, diff_ba_par, *SET_DIFF_BA); +} + +#[test] +fn set_seq_par_equivalence_symmetric_difference() { + let symm_diff_ab_seq = SET_A + .symmetric_difference(&*SET_B) + .copied() + .collect::>(); + let symm_diff_ab_par = SET_A + .par_symmetric_difference(&*SET_B) + .copied() + .collect::>(); + + assert_eq3!(symm_diff_ab_seq, symm_diff_ab_par, *SET_SYMM_DIFF_AB); +} + +#[test] +fn set_seq_par_equivalence_intersection() { + let intersection_ab_seq = SET_A.intersection(&*SET_B).copied().collect::>(); + let intersection_ab_par = SET_A + .par_intersection(&*SET_B) + .copied() + .collect::>(); + + assert_eq3!( + intersection_ab_seq, + intersection_ab_par, + *SET_INTERSECTION_AB + ); +} + +#[test] +fn set_seq_par_equivalence_union() { + let union_ab_seq = SET_A.union(&*SET_B).copied().collect::>(); + let union_ab_par = SET_A.par_union(&*SET_B).copied().collect::>(); + + assert_eq3!(union_ab_seq, union_ab_par, *SET_UNION_AB); +} diff --git a/bitbox02-bt/vendor/hashbrown/tests/serde.rs b/bitbox02-bt/vendor/hashbrown/tests/serde.rs new file mode 100644 index 0000000..a642348 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/tests/serde.rs @@ -0,0 +1,65 @@ +#![cfg(feature = "serde")] + +use core::hash::BuildHasherDefault; +use fnv::FnvHasher; +use hashbrown::{HashMap, HashSet}; +use serde_test::{assert_tokens, Token}; + +// We use FnvHash for this test because we rely on the ordering +type FnvHashMap = HashMap>; +type FnvHashSet = HashSet>; + +#[test] +fn map_serde_tokens_empty() { + let map = FnvHashMap::::default(); + + assert_tokens(&map, &[Token::Map { len: Some(0) }, Token::MapEnd]); +} + +#[test] +fn map_serde_tokens() { + let mut map = FnvHashMap::default(); + map.insert('b', 20); + map.insert('a', 10); + map.insert('c', 30); + + assert_tokens( + &map, + &[ + Token::Map { len: Some(3) }, + Token::Char('a'), + Token::I32(10), + Token::Char('c'), + Token::I32(30), + Token::Char('b'), + Token::I32(20), + Token::MapEnd, + ], + ); +} + +#[test] +fn set_serde_tokens_empty() { + let set = FnvHashSet::::default(); + + assert_tokens(&set, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); +} + +#[test] +fn set_serde_tokens() { + let mut set = FnvHashSet::default(); + set.insert(20); + set.insert(10); + set.insert(30); + + assert_tokens( + &set, + &[ + Token::Seq { len: Some(3) }, + Token::I32(30), + Token::I32(20), + Token::I32(10), + Token::SeqEnd, + ], + ); +} diff --git a/bitbox02-bt/vendor/hashbrown/tests/set.rs b/bitbox02-bt/vendor/hashbrown/tests/set.rs new file mode 100644 index 0000000..86ec964 --- /dev/null +++ b/bitbox02-bt/vendor/hashbrown/tests/set.rs @@ -0,0 +1,34 @@ +#![cfg(not(miri))] // FIXME: takes too long + +use hashbrown::HashSet; +use rand::{distributions::Alphanumeric, rngs::SmallRng, Rng, SeedableRng}; +use std::iter; + +#[test] +fn test_hashset_insert_remove() { + let mut m: HashSet> = HashSet::new(); + let seed = u64::from_le_bytes(*b"testseed"); + + let rng = &mut SmallRng::seed_from_u64(seed); + let tx: Vec> = iter::repeat_with(|| { + rng.sample_iter(&Alphanumeric) + .take(32) + .map(char::from) + .collect() + }) + .take(4096) + .collect(); + + // more readable with explicit `true` / `false` + #[allow(clippy::bool_assert_comparison)] + for _ in 0..32 { + for x in &tx { + assert_eq!(m.contains(x), false); + assert_eq!(m.insert(x.clone()), true); + } + for (i, x) in tx.iter().enumerate() { + println!("removing {i} {x:?}"); + assert_eq!(m.remove(x), true); + } + } +} diff --git a/bitbox02-bt/vendor/indexmap/.cargo-checksum.json b/bitbox02-bt/vendor/indexmap/.cargo-checksum.json new file mode 100644 index 0000000..64cb219 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"05f435dee0938cef91a35e33fac86aac2b816767266cfa2537d6d1abe93399ed","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"ecc269ef87fd38a1d98e30bfac9ba964a9dbd9315c3770fed98d4d7cb5882055","README.md":"68a246f0bca18cee84b30ea4188244bf4ddcb5ac5f390d0af0194ee4b63f5b19","RELEASES.md":"625dcad77103f04dd7d1479c532a050e5881226bc3a758991433fae587b3ce15","benches/bench.rs":"3b2900abbc9e8a60af78b0395222ee75e86bc68519a0f38477387d1572eed397","benches/faststring.rs":"5fdd6cdb19d0557ed58f241e809a240cf8939d9e5b87a72d5f127f81ab98380b","src/arbitrary.rs":"068713b1e8e762dbe9e4d19d555e77c17e59408335a40f4777d6100340605655","src/borsh.rs":"74121b426379d4f7365757ffd4f3dd469543fa1635193460fe268799a78a0706","src/lib.rs":"b03a354fe7c77b6970d32f10bd921a82f23798deeecbd0d8a14218209d69d058","src/macros.rs":"1493afee2db2c9744be99e5fc32d0cd3742b8a3dbb31fa786ebbe28f1387e7d6","src/map.rs":"c9cb30bba8667f39a2989889a1e2014e0a5ce0d107322bb33efe33ed990f4826","src/map/core.rs":"0355f31908fc581fa2130cd276ddb782130cb0ef1c50fac113a4a8bbea7ce351","src/map/core/entry.rs":"28e67f6a5ad58661c63b601d6efdbfdaa34fd5ac721f787302d114879a7af6d4","src/map/core/raw_entry_v1.rs":"de7dd5e7eee8ce6cfdbd153287861e248f6ce6b85295a1223ba1bb9877613c0f","src/map/iter.rs":"068be1bb8d49268c4199d1ce6a045ae4ba395c67dade65a8548006b18df959f6","src/map/mutable.rs":"36fc002d8396af4e7695d263c14d64b34234f4219440c6998910e5261bdbee05","src/map/serde_seq.rs":"ce06b5bb816c15ea8fe3d2c358baa90fe6f45ecb585623a69592d6de69319194","src/map/slice.rs":"f5ad1c6e625c39465adb4f3323faf20191749e6f20c950d6b70dd6bc82b779e2","src/map/tests.rs":"154e94016f3c62d58eaf70fb605dc812f4929e64dfc4a2ed1210a2ea145be8d9","src/rayon/map.rs":"0fad36851fdf6894695e526c684c9b3afeac82e29016e6a523eea68cc3b2d19d","src/rayon/mod.rs":"1c9c13b5cf6974f652ded53b014774944c761f079a77a61b3bc52eaa3d4b972b","src/rayon/set.rs":"4b076dbfd9a7eb2fd65783f1c8a5acabe075403f3d05e30c337676acec25d8ee","src/rustc.rs":"fe7a348c5a10a66880cb6c737593fe79d3b6de40f44ba0d7b89204aa95e14a3a","src/serde.rs":"23fd6b5e8f6795e4121693ac16dab61e76c4d8c83e6da1b3ef26d081fae28e79","src/set.rs":"ec1dd32b18dbb824f063d8a1a93bf80841d315a81a5a88ac0c3f80f51bc88874","src/set/iter.rs":"b4554473c82cd032e7881dc3959fa59a84856436ce0b6f94415a18a7abd5bcd7","src/set/mutable.rs":"42a4118b123b9bc8385e2023d9f1d48230e61b8fec2cfa60782836949b639aac","src/set/slice.rs":"fd7ad83fb5b4ad593a81f6e5a795fdc40a97b7215325d76ccef3c4ea9c9a5507","src/set/tests.rs":"d9c182cd776ca9182b5284f06eacc70c5f33a66aff3021c35134ffd1d7630c05","src/util.rs":"dbd57cfdac2a72db8c5ce83bf288bcaf33b5ae59adddcd088792a624c4c0e909","tests/equivalent_trait.rs":"efe9393069e3cfc893d2c9c0343679979578e437fdb98a10baefeced027ba310","tests/macros_full_path.rs":"c33c86d7341581fdd08e2e6375a4afca507fa603540c54a3b9e51c4cd011cd71","tests/quick.rs":"9759dcc34d86d9635d9d18be6358f5f3e3c0f995874b64b5a7ca4b582f4acedb","tests/tests.rs":"f6dbeeb0e2950402b0e66ac52bf74c9e4197d3c5d9c0dde64a7998a2ef74d327"},"package":"707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/indexmap/Cargo.toml b/bitbox02-bt/vendor/indexmap/Cargo.toml new file mode 100644 index 0000000..5104c93 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/Cargo.toml @@ -0,0 +1,152 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.63" +name = "indexmap" +version = "2.6.0" +build = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A hash table with consistent order and fast iteration." +documentation = "https://docs.rs/indexmap/" +readme = "README.md" +keywords = [ + "hashmap", + "no_std", +] +categories = [ + "data-structures", + "no-std", +] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/indexmap-rs/indexmap" + +[package.metadata.docs.rs] +features = [ + "arbitrary", + "quickcheck", + "serde", + "borsh", + "rayon", +] +rustdoc-args = [ + "--cfg", + "docsrs", +] + +[package.metadata.release] +allow-branch = ["master"] +sign-tag = true +tag-name = "{{version}}" + +[profile.bench] +debug = 2 + +[lib] +name = "indexmap" +path = "src/lib.rs" +bench = false + +[[test]] +name = "equivalent_trait" +path = "tests/equivalent_trait.rs" + +[[test]] +name = "macros_full_path" +path = "tests/macros_full_path.rs" + +[[test]] +name = "quick" +path = "tests/quick.rs" + +[[test]] +name = "tests" +path = "tests/tests.rs" + +[[bench]] +name = "bench" +path = "benches/bench.rs" + +[[bench]] +name = "faststring" +path = "benches/faststring.rs" + +[dependencies.arbitrary] +version = "1.0" +optional = true +default-features = false + +[dependencies.borsh] +version = "1.2" +optional = true +default-features = false + +[dependencies.equivalent] +version = "1.0" +default-features = false + +[dependencies.hashbrown] +version = "0.15.0" +default-features = false + +[dependencies.quickcheck] +version = "1.0" +optional = true +default-features = false + +[dependencies.rayon] +version = "1.5.3" +optional = true + +[dependencies.rustc-rayon] +version = "0.5" +optional = true +package = "rustc-rayon" + +[dependencies.serde] +version = "1.0" +optional = true +default-features = false + +[dev-dependencies.fnv] +version = "1.0" + +[dev-dependencies.fxhash] +version = "0.2.1" + +[dev-dependencies.itertools] +version = "0.13" + +[dev-dependencies.lazy_static] +version = "1.3" + +[dev-dependencies.quickcheck] +version = "1.0" +default-features = false + +[dev-dependencies.rand] +version = "0.8" +features = ["small_rng"] + +[dev-dependencies.serde_derive] +version = "1.0" + +[features] +default = ["std"] +std = [] +test_debug = [] + +[lints.clippy] +style = "allow" diff --git a/bitbox02-bt/vendor/indexmap/LICENSE-APACHE b/bitbox02-bt/vendor/indexmap/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/indexmap/LICENSE-MIT b/bitbox02-bt/vendor/indexmap/LICENSE-MIT new file mode 100644 index 0000000..8b81810 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016--2017 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/indexmap/README.md b/bitbox02-bt/vendor/indexmap/README.md new file mode 100644 index 0000000..2585b23 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/README.md @@ -0,0 +1,59 @@ +# indexmap + +[![build status](https://github.com/indexmap-rs/indexmap/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/indexmap-rs/indexmap/actions) +[![crates.io](https://img.shields.io/crates/v/indexmap.svg)](https://crates.io/crates/indexmap) +[![docs](https://docs.rs/indexmap/badge.svg)](https://docs.rs/indexmap) +[![rustc](https://img.shields.io/badge/rust-1.63%2B-orange.svg)](https://img.shields.io/badge/rust-1.63%2B-orange.svg) + +A pure-Rust hash table which preserves (in a limited sense) insertion order. + +This crate implements compact map and set data-structures, +where the iteration order of the keys is independent from their hash or +value. It preserves insertion order (except after removals), and it +allows lookup of entries by either hash table key or numerical index. + +Note: this crate was originally released under the name `ordermap`, +but it was renamed to `indexmap` to better reflect its features. +The [`ordermap`](https://crates.io/crates/ordermap) crate now exists +as a wrapper over `indexmap` with stronger ordering properties. + +# Background + +This was inspired by Python 3.6's new dict implementation (which remembers +the insertion order and is fast to iterate, and is compact in memory). + +Some of those features were translated to Rust, and some were not. The result +was indexmap, a hash table that has following properties: + +- Order is **independent of hash function** and hash values of keys. +- Fast to iterate. +- Indexed in compact space. +- Preserves insertion order **as long** as you don't call `.remove()`, + `.swap_remove()`, or other methods that explicitly change order. + The alternate `.shift_remove()` does preserve relative order. +- Uses hashbrown for the inner table, just like Rust's libstd `HashMap` does. + +## Performance + +`IndexMap` derives a couple of performance facts directly from how it is constructed, +which is roughly: + +> A raw hash table of key-value indices, and a vector of key-value pairs. + +- Iteration is very fast since it is on the dense key-values. +- Removal is fast since it moves memory areas only in the table, + and uses a single swap in the vector. +- Lookup is fast-ish because the initial 7-bit hash lookup uses SIMD, and indices are + densely stored. Lookup also is slow-ish since the actual key-value pairs are stored + separately. (Visible when cpu caches size is limiting.) + +- In practice, `IndexMap` has been tested out as the hashmap in rustc in [PR45282] and + the performance was roughly on par across the whole workload. +- If you want the properties of `IndexMap`, or its strongest performance points + fits your workload, it might be the best hash table implementation. + +[PR45282]: https://github.com/rust-lang/rust/pull/45282 + +# Recent Changes + +See [RELEASES.md](https://github.com/indexmap-rs/indexmap/blob/master/RELEASES.md). diff --git a/bitbox02-bt/vendor/indexmap/RELEASES.md b/bitbox02-bt/vendor/indexmap/RELEASES.md new file mode 100644 index 0000000..b1f7a51 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/RELEASES.md @@ -0,0 +1,531 @@ +# Releases + +## 2.6.0 (2024-10-01) + +- Implemented `Clone` for `map::IntoIter` and `set::IntoIter`. +- Updated the `hashbrown` dependency to version 0.15. + +## 2.5.0 (2024-08-30) + +- Added an `insert_before` method to `IndexMap` and `IndexSet`, as an + alternative to `shift_insert` with different behavior on existing entries. +- Added `first_entry` and `last_entry` methods to `IndexMap`. +- Added `From` implementations between `IndexedEntry` and `OccupiedEntry`. + +## 2.4.0 (2024-08-13) + +- Added methods `IndexMap::append` and `IndexSet::append`, moving all items from + one map or set into another, and leaving the original capacity for reuse. + +## 2.3.0 (2024-07-31) + +- Added trait `MutableEntryKey` for opt-in mutable access to map entry keys. +- Added method `MutableKeys::iter_mut2` for opt-in mutable iteration of map + keys and values. + +## 2.2.6 (2024-03-22) + +- Added trait `MutableValues` for opt-in mutable access to set values. + +## 2.2.5 (2024-02-29) + +- Added optional `borsh` serialization support. + +## 2.2.4 (2024-02-28) + +- Added an `insert_sorted` method on `IndexMap`, `IndexSet`, and `VacantEntry`. +- Avoid hashing for lookups in single-entry maps. +- Limit preallocated memory in `serde` deserializers. + +## 2.2.3 (2024-02-11) + +- Added `move_index` and `swap_indices` methods to `IndexedEntry`, + `OccupiedEntry`, and `RawOccupiedEntryMut`, functioning like the existing + methods on `IndexMap`. +- Added `shift_insert` methods on `VacantEntry` and `RawVacantEntryMut`, as + well as `shift_insert_hashed_nocheck` on the latter, to insert the new entry + at a particular index. +- Added `shift_insert` methods on `IndexMap` and `IndexSet` to insert a new + entry at a particular index, or else move an existing entry there. + +## 2.2.2 (2024-01-31) + +- Added indexing methods to raw entries: `RawEntryBuilder::from_hash_full`, + `RawEntryBuilder::index_from_hash`, and `RawEntryMut::index`. + +## 2.2.1 (2024-01-28) + +- Corrected the signature of `RawOccupiedEntryMut::into_key(self) -> &'a mut K`, + This a breaking change from 2.2.0, but that version was published for less + than a day and has now been yanked. + +## 2.2.0 (2024-01-28) + +- The new `IndexMap::get_index_entry` method finds an entry by its index for + in-place manipulation. + +- The `Keys` iterator now implements `Index` for quick access to the + entry's key, compared to indexing the map to get the value. + +- The new `IndexMap::splice` and `IndexSet::splice` methods will drain the + given range as an iterator, and then replace that range with entries from + an input iterator. + +- The new trait `RawEntryApiV1` offers opt-in access to a raw entry API for + `IndexMap`, corresponding to the unstable API on `HashSet` as of Rust 1.75. + +- Many `IndexMap` and `IndexSet` methods have relaxed their type constraints, + e.g. removing `K: Hash` on methods that don't actually need to hash. + +- Removal methods `remove`, `remove_entry`, and `take` are now deprecated + in favor of their `shift_` or `swap_` prefixed variants, which are more + explicit about their effect on the index and order of remaining items. + The deprecated methods will remain to guide drop-in replacements from + `HashMap` and `HashSet` toward the prefixed methods. + +## 2.1.0 (2023-10-31) + +- Empty slices can now be created with `map::Slice::{new, new_mut}` and + `set::Slice::new`. In addition, `Slice::new`, `len`, and `is_empty` are + now `const` functions on both types. + +- `IndexMap`, `IndexSet`, and their respective `Slice`s all have binary + search methods for sorted data: map `binary_search_keys` and set + `binary_search` for plain comparison, `binary_search_by` for custom + comparators, `binary_search_by_key` for key extraction, and + `partition_point` for boolean conditions. + +## 2.0.2 (2023-09-29) + +- The `hashbrown` dependency has been updated to version 0.14.1 to + complete the support for Rust 1.63. + +## 2.0.1 (2023-09-27) + +- **MSRV**: Rust 1.63.0 is now supported as well, pending publication of + `hashbrown`'s relaxed MSRV (or use cargo `--ignore-rust-version`). + +## 2.0.0 (2023-06-23) + +- **MSRV**: Rust 1.64.0 or later is now required. + +- The `"std"` feature is no longer auto-detected. It is included in the + default feature set, or else can be enabled like any other Cargo feature. + +- The `"serde-1"` feature has been removed, leaving just the optional + `"serde"` dependency to be enabled like a feature itself. + +- `IndexMap::get_index_mut` now returns `Option<(&K, &mut V)>`, changing + the key part from `&mut K` to `&K`. There is also a new alternative + `MutableKeys::get_index_mut2` to access the former behavior. + +- The new `map::Slice` and `set::Slice` offer a linear view of maps + and sets, behaving a lot like normal `[(K, V)]` and `[T]` slices. Notably, + comparison traits like `Eq` only consider items in order, rather than hash + lookups, and slices even implement `Hash`. + +- `IndexMap` and `IndexSet` now have `sort_by_cached_key` and + `par_sort_by_cached_key` methods which perform stable sorts in place + using a key extraction function. + +- `IndexMap` and `IndexSet` now have `reserve_exact`, `try_reserve`, and + `try_reserve_exact` methods that correspond to the same methods on `Vec`. + However, exactness only applies to the direct capacity for items, while the + raw hash table still follows its own rules for capacity and load factor. + +- The `Equivalent` trait is now re-exported from the `equivalent` crate, + intended as a common base to allow types to work with multiple map types. + +- The `hashbrown` dependency has been updated to version 0.14. + +- The `serde_seq` module has been moved from the crate root to below the + `map` module. + +## 1.9.3 (2023-03-24) + +- Bump the `rustc-rayon` dependency, for compiler use only. + +## 1.9.2 (2022-11-17) + +- `IndexMap` and `IndexSet` both implement `arbitrary::Arbitrary<'_>` and + `quickcheck::Arbitrary` if those optional dependency features are enabled. + +## 1.9.1 (2022-06-21) + +- The MSRV now allows Rust 1.56.0 as well. However, currently `hashbrown` + 0.12.1 requires 1.56.1, so users on 1.56.0 should downgrade that to 0.12.0 + until there is a later published version relaxing its requirement. + +## 1.9.0 (2022-06-16) + +- **MSRV**: Rust 1.56.1 or later is now required. + +- The `hashbrown` dependency has been updated to version 0.12. + +- `IterMut` and `ValuesMut` now implement `Debug`. + +- The new `IndexMap::shrink_to` and `IndexSet::shrink_to` methods shrink + the capacity with a lower bound. + +- The new `IndexMap::move_index` and `IndexSet::move_index` methods change + the position of an item from one index to another, shifting the items + between to accommodate the move. + +## 1.8.2 (2022-05-27) + +- Bump the `rustc-rayon` dependency, for compiler use only. + +## 1.8.1 (2022-03-29) + +- The new `IndexSet::replace_full` will return the index of the item along + with the replaced value, if any, by @zakcutner in PR [222]. + +[222]: https://github.com/indexmap-rs/indexmap/pull/222 + +## 1.8.0 (2022-01-07) + +- The new `IndexMap::into_keys` and `IndexMap::into_values` will consume + the map into keys or values, respectively, matching Rust 1.54's `HashMap` + methods, by @taiki-e in PR [195]. + +- More of the iterator types implement `Debug`, `ExactSizeIterator`, and + `FusedIterator`, by @cuviper in PR [196]. + +- `IndexMap` and `IndexSet` now implement rayon's `ParallelDrainRange`, + by @cuviper in PR [197]. + +- `IndexMap::with_hasher` and `IndexSet::with_hasher` are now `const` + functions, allowing static maps and sets, by @mwillsey in PR [203]. + +- `IndexMap` and `IndexSet` now implement `From` for arrays, matching + Rust 1.56's implementation for `HashMap`, by @rouge8 in PR [205]. + +- `IndexMap` and `IndexSet` now have methods `sort_unstable_keys`, + `sort_unstable_by`, `sorted_unstable_by`, and `par_*` equivalents, + which sort in-place without preserving the order of equal items, by + @bhgomes in PR [211]. + +[195]: https://github.com/indexmap-rs/indexmap/pull/195 +[196]: https://github.com/indexmap-rs/indexmap/pull/196 +[197]: https://github.com/indexmap-rs/indexmap/pull/197 +[203]: https://github.com/indexmap-rs/indexmap/pull/203 +[205]: https://github.com/indexmap-rs/indexmap/pull/205 +[211]: https://github.com/indexmap-rs/indexmap/pull/211 + +## 1.7.0 (2021-06-29) + +- **MSRV**: Rust 1.49 or later is now required. + +- The `hashbrown` dependency has been updated to version 0.11. + +## 1.6.2 (2021-03-05) + +- Fixed to match `std` behavior, `OccupiedEntry::key` now references the + existing key in the map instead of the lookup key, by @cuviper in PR [170]. + +- The new `Entry::or_insert_with_key` matches Rust 1.50's `Entry` method, + passing `&K` to the callback to create a value, by @cuviper in PR [175]. + +[170]: https://github.com/indexmap-rs/indexmap/pull/170 +[175]: https://github.com/indexmap-rs/indexmap/pull/175 + +## 1.6.1 (2020-12-14) + +- The new `serde_seq` module implements `IndexMap` serialization as a + sequence to ensure order is preserved, by @cuviper in PR [158]. + +- New methods on maps and sets work like the `Vec`/slice methods by the same name: + `truncate`, `split_off`, `first`, `first_mut`, `last`, `last_mut`, and + `swap_indices`, by @cuviper in PR [160]. + +[158]: https://github.com/indexmap-rs/indexmap/pull/158 +[160]: https://github.com/indexmap-rs/indexmap/pull/160 + +## 1.6.0 (2020-09-05) + +- **MSRV**: Rust 1.36 or later is now required. + +- The `hashbrown` dependency has been updated to version 0.9. + +## 1.5.2 (2020-09-01) + +- The new "std" feature will force the use of `std` for users that explicitly + want the default `S = RandomState`, bypassing the autodetection added in 1.3.0, + by @cuviper in PR [145]. + +[145]: https://github.com/indexmap-rs/indexmap/pull/145 + +## 1.5.1 (2020-08-07) + +- Values can now be indexed by their `usize` position by @cuviper in PR [132]. + +- Some of the generic bounds have been relaxed to match `std` by @cuviper in PR [141]. + +- `drain` now accepts any `R: RangeBounds` by @cuviper in PR [142]. + +[132]: https://github.com/indexmap-rs/indexmap/pull/132 +[141]: https://github.com/indexmap-rs/indexmap/pull/141 +[142]: https://github.com/indexmap-rs/indexmap/pull/142 + +## 1.5.0 (2020-07-17) + +- **MSRV**: Rust 1.32 or later is now required. + +- The inner hash table is now based on `hashbrown` by @cuviper in PR [131]. + This also completes the method `reserve` and adds `shrink_to_fit`. + +- Add new methods `get_key_value`, `remove_entry`, `swap_remove_entry`, + and `shift_remove_entry`, by @cuviper in PR [136] + +- `Clone::clone_from` reuses allocations by @cuviper in PR [125] + +- Add new method `reverse` by @linclelinkpart5 in PR [128] + +[125]: https://github.com/indexmap-rs/indexmap/pull/125 +[128]: https://github.com/indexmap-rs/indexmap/pull/128 +[131]: https://github.com/indexmap-rs/indexmap/pull/131 +[136]: https://github.com/indexmap-rs/indexmap/pull/136 + +## 1.4.0 (2020-06-01) + +- Add new method `get_index_of` by @Thermatrix in PR [115] and [120] + +- Fix build script rebuild-if-changed configuration to use "build.rs"; + fixes issue [123]. Fix by @cuviper. + +- Dev-dependencies (rand and quickcheck) have been updated. The crate's tests + now run using Rust 1.32 or later (MSRV for building the crate has not changed). + by @kjeremy and @bluss + +[123]: https://github.com/indexmap-rs/indexmap/issues/123 +[115]: https://github.com/indexmap-rs/indexmap/pull/115 +[120]: https://github.com/indexmap-rs/indexmap/pull/120 + +## 1.3.2 (2020-02-05) + +- Maintenance update to regenerate the published `Cargo.toml`. + +## 1.3.1 (2020-01-15) + +- Maintenance update for formatting and `autocfg` 1.0. + +## 1.3.0 (2019-10-18) + +- The deprecation messages in the previous version have been removed. + (The methods have not otherwise changed.) Docs for removal methods have been + improved. +- From Rust 1.36, this crate supports being built **without std**, requiring + `alloc` instead. This is enabled automatically when it is detected that + `std` is not available. There is no crate feature to enable/disable to + trigger this. The new build-dep `autocfg` enables this. + +## 1.2.0 (2019-09-08) + +- Plain `.remove()` now has a deprecation message, it informs the user + about picking one of the removal functions `swap_remove` and `shift_remove` + which have different performance and order semantics. + Plain `.remove()` will not be removed, the warning message and method + will remain until further. + +- Add new method `shift_remove` for order preserving removal on the map, + and `shift_take` for the corresponding operation on the set. + +- Add methods `swap_remove`, `swap_remove_entry` to `Entry`. + +- Fix indexset/indexmap to support full paths, like `indexmap::indexmap!()` + +- Internal improvements: fix warnings, deprecations and style lints + +## 1.1.0 (2019-08-20) + +- Added optional feature `"rayon"` that adds parallel iterator support + to `IndexMap` and `IndexSet` using Rayon. This includes all the regular + iterators in parallel versions, and parallel sort. + +- Implemented `Clone` for `map::{Iter, Keys, Values}` and + `set::{Difference, Intersection, Iter, SymmetricDifference, Union}` + +- Implemented `Debug` for `map::{Entry, IntoIter, Iter, Keys, Values}` and + `set::{Difference, Intersection, IntoIter, Iter, SymmetricDifference, Union}` + +- Serde trait `IntoDeserializer` are implemented for `IndexMap` and `IndexSet`. + +- Minimum Rust version requirement increased to Rust 1.30 for development builds. + +## 1.0.2 (2018-10-22) + +- The new methods `IndexMap::insert_full` and `IndexSet::insert_full` are + both like `insert` with the index included in the return value. + +- The new method `Entry::and_modify` can be used to modify occupied + entries, matching the new methods of `std` maps in Rust 1.26. + +- The new method `Entry::or_default` inserts a default value in unoccupied + entries, matching the new methods of `std` maps in Rust 1.28. + +## 1.0.1 (2018-03-24) + +- Document Rust version policy for the crate (see rustdoc) + +## 1.0.0 (2018-03-11) + +- This is the 1.0 release for `indexmap`! (the crate and datastructure + formerly known as “ordermap”) +- `OccupiedEntry::insert` changed its signature, to use `&mut self` for + the method receiver, matching the equivalent method for a standard + `HashMap`. Thanks to @dtolnay for finding this bug. +- The deprecated old names from ordermap were removed: `OrderMap`, + `OrderSet`, `ordermap!{}`, `orderset!{}`. Use the new `IndexMap` + etc names instead. + +## 0.4.1 (2018-02-14) + +- Renamed crate to `indexmap`; the `ordermap` crate is now deprecated + and the types `OrderMap/Set` now have a deprecation notice. + +## 0.4.0 (2018-02-02) + +- This is the last release series for this `ordermap` under that name, + because the crate is **going to be renamed** to `indexmap` (with types + `IndexMap`, `IndexSet`) and no change in functionality! +- The map and its associated structs moved into the `map` submodule of the + crate, so that the map and set are symmetric + + + The iterators, `Entry` and other structs are now under `ordermap::map::` + +- Internally refactored `OrderMap` so that all the main algorithms + (insertion, lookup, removal etc) that don't use the `S` parameter (the + hasher) are compiled without depending on `S`, which reduces generics bloat. + +- `Entry` no longer has a type parameter `S`, which is just like + the standard `HashMap`'s entry. + +- Minimum Rust version requirement increased to Rust 1.18 + +## 0.3.5 (2018-01-14) + +- Documentation improvements + +## 0.3.4 (2018-01-04) + +- The `.retain()` methods for `OrderMap` and `OrderSet` now + traverse the elements in order, and the retained elements **keep their order** +- Added new methods `.sort_by()`, `.sort_keys()` to `OrderMap` and + `.sort_by()`, `.sort()` to `OrderSet`. These methods allow you to + sort the maps in place efficiently. + +## 0.3.3 (2017-12-28) + +- Document insertion behaviour better by @lucab +- Updated dependences (no feature changes) by @ignatenkobrain + +## 0.3.2 (2017-11-25) + +- Add `OrderSet` by @cuviper! +- `OrderMap::drain` is now (too) a double ended iterator. + +## 0.3.1 (2017-11-19) + +- In all ordermap iterators, forward the `collect` method to the underlying + iterator as well. +- Add crates.io categories. + +## 0.3.0 (2017-10-07) + +- The methods `get_pair`, `get_pair_index` were both replaced by + `get_full` (and the same for the mutable case). +- Method `swap_remove_pair` replaced by `swap_remove_full`. +- Add trait `MutableKeys` for opt-in mutable key access. Mutable key access + is only possible through the methods of this extension trait. +- Add new trait `Equivalent` for key equivalence. This extends the + `Borrow` trait mechanism for `OrderMap::get` in a backwards compatible + way, just some minor type inference related issues may become apparent. + See [#10] for more information. +- Implement `Extend<(&K, &V)>` by @xfix. + +[#10]: https://github.com/indexmap-rs/indexmap/pull/10 + +## 0.2.13 (2017-09-30) + +- Fix deserialization to support custom hashers by @Techcable. +- Add methods `.index()` on the entry types by @garro95. + +## 0.2.12 (2017-09-11) + +- Add methods `.with_hasher()`, `.hasher()`. + +## 0.2.11 (2017-08-29) + +- Support `ExactSizeIterator` for the iterators. By @Binero. +- Use `Box<[Pos]>` internally, saving a word in the `OrderMap` struct. +- Serde support, with crate feature `"serde-1"`. By @xfix. + +## 0.2.10 (2017-04-29) + +- Add iterator `.drain(..)` by @stevej. + +## 0.2.9 (2017-03-26) + +- Add method `.is_empty()` by @overvenus. +- Implement `PartialEq, Eq` by @overvenus. +- Add method `.sorted_by()`. + +## 0.2.8 (2017-03-01) + +- Add iterators `.values()` and `.values_mut()`. +- Fix compatibility with 32-bit platforms. + +## 0.2.7 (2016-11-02) + +- Add `.retain()`. + +## 0.2.6 (2016-11-02) + +- Add `OccupiedEntry::remove_entry` and other minor entry methods, + so that it now has all the features of `HashMap`'s entries. + +## 0.2.5 (2016-10-31) + +- Improved `.pop()` slightly. + +## 0.2.4 (2016-10-22) + +- Improved performance of `.insert()` ([#3]) by @pczarn. + +[#3]: https://github.com/indexmap-rs/indexmap/pull/3 + +## 0.2.3 (2016-10-11) + +- Generalize `Entry` for now, so that it works on hashmaps with non-default + hasher. However, there's a lingering compat issue since libstd `HashMap` + does not parameterize its entries by the hasher (`S` typarm). +- Special case some iterator methods like `.nth()`. + +## 0.2.2 (2016-10-02) + +- Disable the verbose `Debug` impl by default. + +## 0.2.1 (2016-10-02) + +- Fix doc links and clarify docs. + +## 0.2.0 (2016-10-01) + +- Add more `HashMap` methods & compat with its API. +- Experimental support for `.entry()` (the simplest parts of the API). +- Add `.reserve()` (placeholder impl). +- Add `.remove()` as synonym for `.swap_remove()`. +- Changed `.insert()` to swap value if the entry already exists, and + return `Option`. +- Experimental support as an *indexed* hash map! Added methods + `.get_index()`, `.get_index_mut()`, `.swap_remove_index()`, + `.get_pair_index()`, `.get_pair_index_mut()`. + +## 0.1.2 (2016-09-19) + +- Implement the 32/32 split idea for `Pos` which improves cache utilization + and lookup performance. + +## 0.1.1 (2016-09-16) + +- Initial release. diff --git a/bitbox02-bt/vendor/indexmap/benches/bench.rs b/bitbox02-bt/vendor/indexmap/benches/bench.rs new file mode 100644 index 0000000..a4e8e21 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/benches/bench.rs @@ -0,0 +1,763 @@ +#![feature(test)] + +extern crate test; +#[macro_use] +extern crate lazy_static; + +use fnv::FnvHasher; +use std::hash::BuildHasherDefault; +use std::hash::Hash; +type FnvBuilder = BuildHasherDefault; + +use test::black_box; +use test::Bencher; + +use indexmap::IndexMap; + +use std::collections::HashMap; + +use rand::rngs::SmallRng; +use rand::seq::SliceRandom; +use rand::SeedableRng; + +/// Use a consistently seeded Rng for benchmark stability +fn small_rng() -> SmallRng { + let seed = u64::from_le_bytes(*b"indexmap"); + SmallRng::seed_from_u64(seed) +} + +#[bench] +fn new_hashmap(b: &mut Bencher) { + b.iter(|| HashMap::::new()); +} + +#[bench] +fn new_indexmap(b: &mut Bencher) { + b.iter(|| IndexMap::::new()); +} + +#[bench] +fn with_capacity_10e5_hashmap(b: &mut Bencher) { + b.iter(|| HashMap::::with_capacity(10_000)); +} + +#[bench] +fn with_capacity_10e5_indexmap(b: &mut Bencher) { + b.iter(|| IndexMap::::with_capacity(10_000)); +} + +#[bench] +fn insert_hashmap_10_000(b: &mut Bencher) { + let c = 10_000; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for x in 0..c { + map.insert(x, ()); + } + map + }); +} + +#[bench] +fn insert_indexmap_10_000(b: &mut Bencher) { + let c = 10_000; + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for x in 0..c { + map.insert(x, ()); + } + map + }); +} + +#[bench] +fn insert_hashmap_string_10_000(b: &mut Bencher) { + let c = 10_000; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for x in 0..c { + map.insert(x.to_string(), ()); + } + map + }); +} + +#[bench] +fn insert_indexmap_string_10_000(b: &mut Bencher) { + let c = 10_000; + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for x in 0..c { + map.insert(x.to_string(), ()); + } + map + }); +} + +#[bench] +fn insert_hashmap_str_10_000(b: &mut Bencher) { + let c = 10_000; + let ss = Vec::from_iter((0..c).map(|x| x.to_string())); + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for key in &ss { + map.insert(&key[..], ()); + } + map + }); +} + +#[bench] +fn insert_indexmap_str_10_000(b: &mut Bencher) { + let c = 10_000; + let ss = Vec::from_iter((0..c).map(|x| x.to_string())); + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for key in &ss { + map.insert(&key[..], ()); + } + map + }); +} + +#[bench] +fn insert_hashmap_int_bigvalue_10_000(b: &mut Bencher) { + let c = 10_000; + let value = [0u64; 10]; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for i in 0..c { + map.insert(i, value); + } + map + }); +} + +#[bench] +fn insert_indexmap_int_bigvalue_10_000(b: &mut Bencher) { + let c = 10_000; + let value = [0u64; 10]; + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for i in 0..c { + map.insert(i, value); + } + map + }); +} + +#[bench] +fn insert_hashmap_100_000(b: &mut Bencher) { + let c = 100_000; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for x in 0..c { + map.insert(x, ()); + } + map + }); +} + +#[bench] +fn insert_indexmap_100_000(b: &mut Bencher) { + let c = 100_000; + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for x in 0..c { + map.insert(x, ()); + } + map + }); +} + +#[bench] +fn insert_hashmap_150(b: &mut Bencher) { + let c = 150; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for x in 0..c { + map.insert(x, ()); + } + map + }); +} + +#[bench] +fn insert_indexmap_150(b: &mut Bencher) { + let c = 150; + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for x in 0..c { + map.insert(x, ()); + } + map + }); +} + +#[bench] +fn entry_hashmap_150(b: &mut Bencher) { + let c = 150; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for x in 0..c { + map.entry(x).or_insert(()); + } + map + }); +} + +#[bench] +fn entry_indexmap_150(b: &mut Bencher) { + let c = 150; + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for x in 0..c { + map.entry(x).or_insert(()); + } + map + }); +} + +#[bench] +fn iter_sum_hashmap_10_000(b: &mut Bencher) { + let c = 10_000; + let mut map = HashMap::with_capacity(c); + let len = c - c / 10; + for x in 0..len { + map.insert(x, ()); + } + assert_eq!(map.len(), len); + b.iter(|| map.keys().sum::()); +} + +#[bench] +fn iter_sum_indexmap_10_000(b: &mut Bencher) { + let c = 10_000; + let mut map = IndexMap::with_capacity(c); + let len = c - c / 10; + for x in 0..len { + map.insert(x, ()); + } + assert_eq!(map.len(), len); + b.iter(|| map.keys().sum::()); +} + +#[bench] +fn iter_black_box_hashmap_10_000(b: &mut Bencher) { + let c = 10_000; + let mut map = HashMap::with_capacity(c); + let len = c - c / 10; + for x in 0..len { + map.insert(x, ()); + } + assert_eq!(map.len(), len); + b.iter(|| { + for &key in map.keys() { + black_box(key); + } + }); +} + +#[bench] +fn iter_black_box_indexmap_10_000(b: &mut Bencher) { + let c = 10_000; + let mut map = IndexMap::with_capacity(c); + let len = c - c / 10; + for x in 0..len { + map.insert(x, ()); + } + assert_eq!(map.len(), len); + b.iter(|| { + for &key in map.keys() { + black_box(key); + } + }); +} + +fn shuffled_keys(iter: I) -> Vec +where + I: IntoIterator, +{ + let mut v = Vec::from_iter(iter); + let mut rng = small_rng(); + v.shuffle(&mut rng); + v +} + +#[bench] +fn lookup_hashmap_10_000_exist(b: &mut Bencher) { + let c = 10_000; + let mut map = HashMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(key, 1); + } + b.iter(|| { + let mut found = 0; + for key in 5000..c { + found += map.get(&key).is_some() as i32; + } + found + }); +} + +#[bench] +fn lookup_hashmap_10_000_noexist(b: &mut Bencher) { + let c = 10_000; + let mut map = HashMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(key, 1); + } + b.iter(|| { + let mut found = 0; + for key in c..15000 { + found += map.get(&key).is_some() as i32; + } + found + }); +} + +#[bench] +fn lookup_indexmap_10_000_exist(b: &mut Bencher) { + let c = 10_000; + let mut map = IndexMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(key, 1); + } + b.iter(|| { + let mut found = 0; + for key in 5000..c { + found += map.get(&key).is_some() as i32; + } + found + }); +} + +#[bench] +fn lookup_indexmap_10_000_noexist(b: &mut Bencher) { + let c = 10_000; + let mut map = IndexMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(key, 1); + } + b.iter(|| { + let mut found = 0; + for key in c..15000 { + found += map.get(&key).is_some() as i32; + } + found + }); +} + +// number of items to look up +const LOOKUP_MAP_SIZE: u32 = 100_000_u32; +const LOOKUP_SAMPLE_SIZE: u32 = 5000; +const SORT_MAP_SIZE: usize = 10_000; + +// use lazy_static so that comparison benchmarks use the exact same inputs +lazy_static! { + static ref KEYS: Vec = shuffled_keys(0..LOOKUP_MAP_SIZE); +} + +lazy_static! { + static ref HMAP_100K: HashMap = { + let c = LOOKUP_MAP_SIZE; + let mut map = HashMap::with_capacity(c as usize); + let keys = &*KEYS; + for &key in keys { + map.insert(key, key); + } + map + }; +} + +lazy_static! { + static ref IMAP_100K: IndexMap = { + let c = LOOKUP_MAP_SIZE; + let mut map = IndexMap::with_capacity(c as usize); + let keys = &*KEYS; + for &key in keys { + map.insert(key, key); + } + map + }; +} + +lazy_static! { + static ref IMAP_SORT_U32: IndexMap = { + let mut map = IndexMap::with_capacity(SORT_MAP_SIZE); + for &key in &KEYS[..SORT_MAP_SIZE] { + map.insert(key, key); + } + map + }; +} +lazy_static! { + static ref IMAP_SORT_S: IndexMap = { + let mut map = IndexMap::with_capacity(SORT_MAP_SIZE); + for &key in &KEYS[..SORT_MAP_SIZE] { + map.insert(format!("{:^16x}", &key), String::new()); + } + map + }; +} + +#[bench] +fn lookup_hashmap_100_000_multi(b: &mut Bencher) { + let map = &*HMAP_100K; + b.iter(|| { + let mut found = 0; + for key in 0..LOOKUP_SAMPLE_SIZE { + found += map.get(&key).is_some() as u32; + } + found + }); +} + +#[bench] +fn lookup_indexmap_100_000_multi(b: &mut Bencher) { + let map = &*IMAP_100K; + b.iter(|| { + let mut found = 0; + for key in 0..LOOKUP_SAMPLE_SIZE { + found += map.get(&key).is_some() as u32; + } + found + }); +} + +// inorder: Test looking up keys in the same order as they were inserted +#[bench] +fn lookup_hashmap_100_000_inorder_multi(b: &mut Bencher) { + let map = &*HMAP_100K; + let keys = &*KEYS; + b.iter(|| { + let mut found = 0; + for key in &keys[0..LOOKUP_SAMPLE_SIZE as usize] { + found += map.get(key).is_some() as u32; + } + found + }); +} + +#[bench] +fn lookup_indexmap_100_000_inorder_multi(b: &mut Bencher) { + let map = &*IMAP_100K; + let keys = &*KEYS; + b.iter(|| { + let mut found = 0; + for key in &keys[0..LOOKUP_SAMPLE_SIZE as usize] { + found += map.get(key).is_some() as u32; + } + found + }); +} + +#[bench] +fn lookup_hashmap_100_000_single(b: &mut Bencher) { + let map = &*HMAP_100K; + let mut iter = (0..LOOKUP_MAP_SIZE + LOOKUP_SAMPLE_SIZE).cycle(); + b.iter(|| { + let key = iter.next().unwrap(); + map.get(&key).is_some() + }); +} + +#[bench] +fn lookup_indexmap_100_000_single(b: &mut Bencher) { + let map = &*IMAP_100K; + let mut iter = (0..LOOKUP_MAP_SIZE + LOOKUP_SAMPLE_SIZE).cycle(); + b.iter(|| { + let key = iter.next().unwrap(); + map.get(&key).is_some() + }); +} + +const GROW_SIZE: usize = 100_000; +type GrowKey = u32; + +// Test grow/resize without preallocation +#[bench] +fn grow_fnv_hashmap_100_000(b: &mut Bencher) { + b.iter(|| { + let mut map: HashMap<_, _, FnvBuilder> = HashMap::default(); + for x in 0..GROW_SIZE { + map.insert(x as GrowKey, x as GrowKey); + } + map + }); +} + +#[bench] +fn grow_fnv_indexmap_100_000(b: &mut Bencher) { + b.iter(|| { + let mut map: IndexMap<_, _, FnvBuilder> = IndexMap::default(); + for x in 0..GROW_SIZE { + map.insert(x as GrowKey, x as GrowKey); + } + map + }); +} + +const MERGE: u64 = 10_000; +#[bench] +fn hashmap_merge_simple(b: &mut Bencher) { + let first_map: HashMap = (0..MERGE).map(|i| (i, ())).collect(); + let second_map: HashMap = (MERGE..MERGE * 2).map(|i| (i, ())).collect(); + b.iter(|| { + let mut merged = first_map.clone(); + merged.extend(second_map.iter().map(|(&k, &v)| (k, v))); + merged + }); +} + +#[bench] +fn hashmap_merge_shuffle(b: &mut Bencher) { + let first_map: HashMap = (0..MERGE).map(|i| (i, ())).collect(); + let second_map: HashMap = (MERGE..MERGE * 2).map(|i| (i, ())).collect(); + let mut v = Vec::new(); + let mut rng = small_rng(); + b.iter(|| { + let mut merged = first_map.clone(); + v.extend(second_map.iter().map(|(&k, &v)| (k, v))); + v.shuffle(&mut rng); + merged.extend(v.drain(..)); + + merged + }); +} + +#[bench] +fn indexmap_merge_simple(b: &mut Bencher) { + let first_map: IndexMap = (0..MERGE).map(|i| (i, ())).collect(); + let second_map: IndexMap = (MERGE..MERGE * 2).map(|i| (i, ())).collect(); + b.iter(|| { + let mut merged = first_map.clone(); + merged.extend(second_map.iter().map(|(&k, &v)| (k, v))); + merged + }); +} + +#[bench] +fn indexmap_merge_shuffle(b: &mut Bencher) { + let first_map: IndexMap = (0..MERGE).map(|i| (i, ())).collect(); + let second_map: IndexMap = (MERGE..MERGE * 2).map(|i| (i, ())).collect(); + let mut v = Vec::new(); + let mut rng = small_rng(); + b.iter(|| { + let mut merged = first_map.clone(); + v.extend(second_map.iter().map(|(&k, &v)| (k, v))); + v.shuffle(&mut rng); + merged.extend(v.drain(..)); + + merged + }); +} + +#[bench] +fn swap_remove_indexmap_100_000(b: &mut Bencher) { + let map = IMAP_100K.clone(); + let mut keys = Vec::from_iter(map.keys().copied()); + let mut rng = small_rng(); + keys.shuffle(&mut rng); + + b.iter(|| { + let mut map = map.clone(); + for key in &keys { + map.swap_remove(key); + } + assert_eq!(map.len(), 0); + map + }); +} + +#[bench] +fn shift_remove_indexmap_100_000_few(b: &mut Bencher) { + let map = IMAP_100K.clone(); + let mut keys = Vec::from_iter(map.keys().copied()); + let mut rng = small_rng(); + keys.shuffle(&mut rng); + keys.truncate(50); + + b.iter(|| { + let mut map = map.clone(); + for key in &keys { + map.shift_remove(key); + } + assert_eq!(map.len(), IMAP_100K.len() - keys.len()); + map + }); +} + +#[bench] +fn shift_remove_indexmap_2_000_full(b: &mut Bencher) { + let mut keys = KEYS[..2_000].to_vec(); + let mut map = IndexMap::with_capacity(keys.len()); + for &key in &keys { + map.insert(key, key); + } + let mut rng = small_rng(); + keys.shuffle(&mut rng); + + b.iter(|| { + let mut map = map.clone(); + for key in &keys { + map.shift_remove(key); + } + assert_eq!(map.len(), 0); + map + }); +} + +#[bench] +fn pop_indexmap_100_000(b: &mut Bencher) { + let map = IMAP_100K.clone(); + + b.iter(|| { + let mut map = map.clone(); + while !map.is_empty() { + map.pop(); + } + assert_eq!(map.len(), 0); + map + }); +} + +#[bench] +fn few_retain_indexmap_100_000(b: &mut Bencher) { + let map = IMAP_100K.clone(); + + b.iter(|| { + let mut map = map.clone(); + map.retain(|k, _| *k % 7 == 0); + map + }); +} + +#[bench] +fn few_retain_hashmap_100_000(b: &mut Bencher) { + let map = HMAP_100K.clone(); + + b.iter(|| { + let mut map = map.clone(); + map.retain(|k, _| *k % 7 == 0); + map + }); +} + +#[bench] +fn half_retain_indexmap_100_000(b: &mut Bencher) { + let map = IMAP_100K.clone(); + + b.iter(|| { + let mut map = map.clone(); + map.retain(|k, _| *k % 2 == 0); + map + }); +} + +#[bench] +fn half_retain_hashmap_100_000(b: &mut Bencher) { + let map = HMAP_100K.clone(); + + b.iter(|| { + let mut map = map.clone(); + map.retain(|k, _| *k % 2 == 0); + map + }); +} + +#[bench] +fn many_retain_indexmap_100_000(b: &mut Bencher) { + let map = IMAP_100K.clone(); + + b.iter(|| { + let mut map = map.clone(); + map.retain(|k, _| *k % 100 != 0); + map + }); +} + +#[bench] +fn many_retain_hashmap_100_000(b: &mut Bencher) { + let map = HMAP_100K.clone(); + + b.iter(|| { + let mut map = map.clone(); + map.retain(|k, _| *k % 100 != 0); + map + }); +} + +// simple sort impl for comparison +pub fn simple_sort(m: &mut IndexMap) { + let mut ordered: Vec<_> = m.drain(..).collect(); + ordered.sort_by(|left, right| left.0.cmp(&right.0)); + m.extend(ordered); +} + +#[bench] +fn indexmap_sort_s(b: &mut Bencher) { + let map = IMAP_SORT_S.clone(); + + // there's a map clone there, but it's still useful to profile this + b.iter(|| { + let mut map = map.clone(); + map.sort_keys(); + map + }); +} + +#[bench] +fn indexmap_simple_sort_s(b: &mut Bencher) { + let map = IMAP_SORT_S.clone(); + + // there's a map clone there, but it's still useful to profile this + b.iter(|| { + let mut map = map.clone(); + simple_sort(&mut map); + map + }); +} + +#[bench] +fn indexmap_sort_u32(b: &mut Bencher) { + let map = IMAP_SORT_U32.clone(); + + // there's a map clone there, but it's still useful to profile this + b.iter(|| { + let mut map = map.clone(); + map.sort_keys(); + map + }); +} + +#[bench] +fn indexmap_simple_sort_u32(b: &mut Bencher) { + let map = IMAP_SORT_U32.clone(); + + // there's a map clone there, but it's still useful to profile this + b.iter(|| { + let mut map = map.clone(); + simple_sort(&mut map); + map + }); +} + +// measure the fixed overhead of cloning in sort benchmarks +#[bench] +fn indexmap_clone_for_sort_s(b: &mut Bencher) { + let map = IMAP_SORT_S.clone(); + + b.iter(|| map.clone()); +} + +#[bench] +fn indexmap_clone_for_sort_u32(b: &mut Bencher) { + let map = IMAP_SORT_U32.clone(); + + b.iter(|| map.clone()); +} diff --git a/bitbox02-bt/vendor/indexmap/benches/faststring.rs b/bitbox02-bt/vendor/indexmap/benches/faststring.rs new file mode 100644 index 0000000..ecc28b4 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/benches/faststring.rs @@ -0,0 +1,185 @@ +#![feature(test)] + +extern crate test; + +use test::Bencher; + +use indexmap::IndexMap; + +use std::collections::HashMap; + +use rand::rngs::SmallRng; +use rand::seq::SliceRandom; +use rand::SeedableRng; + +use std::hash::{Hash, Hasher}; + +use std::borrow::Borrow; +use std::ops::Deref; + +/// Use a consistently seeded Rng for benchmark stability +fn small_rng() -> SmallRng { + let seed = u64::from_le_bytes(*b"indexmap"); + SmallRng::seed_from_u64(seed) +} + +#[derive(PartialEq, Eq, Copy, Clone)] +#[repr(transparent)] +pub struct OneShot(pub T); + +impl Hash for OneShot { + fn hash(&self, h: &mut H) { + h.write(self.0.as_bytes()) + } +} + +impl<'a, S> From<&'a S> for &'a OneShot +where + S: AsRef, +{ + fn from(s: &'a S) -> Self { + let s: &str = s.as_ref(); + unsafe { &*(s as *const str as *const OneShot) } + } +} + +impl Hash for OneShot { + fn hash(&self, h: &mut H) { + h.write(self.0.as_bytes()) + } +} + +impl Borrow> for OneShot { + fn borrow(&self) -> &OneShot { + <&OneShot>::from(&self.0) + } +} + +impl Deref for OneShot { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +fn shuffled_keys(iter: I) -> Vec +where + I: IntoIterator, +{ + let mut v = Vec::from_iter(iter); + let mut rng = small_rng(); + v.shuffle(&mut rng); + v +} + +#[bench] +fn insert_hashmap_string_10_000(b: &mut Bencher) { + let c = 10_000; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for x in 0..c { + map.insert(x.to_string(), ()); + } + map + }); +} + +#[bench] +fn insert_hashmap_string_oneshot_10_000(b: &mut Bencher) { + let c = 10_000; + b.iter(|| { + let mut map = HashMap::with_capacity(c); + for x in 0..c { + map.insert(OneShot(x.to_string()), ()); + } + map + }); +} + +#[bench] +fn insert_indexmap_string_10_000(b: &mut Bencher) { + let c = 10_000; + b.iter(|| { + let mut map = IndexMap::with_capacity(c); + for x in 0..c { + map.insert(x.to_string(), ()); + } + map + }); +} + +#[bench] +fn lookup_hashmap_10_000_exist_string(b: &mut Bencher) { + let c = 10_000; + let mut map = HashMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(key.to_string(), 1); + } + let lookups = (5000..c).map(|x| x.to_string()).collect::>(); + b.iter(|| { + let mut found = 0; + for key in &lookups { + found += map.get(key).is_some() as i32; + } + found + }); +} + +#[bench] +fn lookup_hashmap_10_000_exist_string_oneshot(b: &mut Bencher) { + let c = 10_000; + let mut map = HashMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(OneShot(key.to_string()), 1); + } + let lookups = (5000..c) + .map(|x| OneShot(x.to_string())) + .collect::>(); + b.iter(|| { + let mut found = 0; + for key in &lookups { + found += map.get(key).is_some() as i32; + } + found + }); +} + +#[bench] +fn lookup_indexmap_10_000_exist_string(b: &mut Bencher) { + let c = 10_000; + let mut map = IndexMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(key.to_string(), 1); + } + let lookups = (5000..c).map(|x| x.to_string()).collect::>(); + b.iter(|| { + let mut found = 0; + for key in &lookups { + found += map.get(key).is_some() as i32; + } + found + }); +} + +#[bench] +fn lookup_indexmap_10_000_exist_string_oneshot(b: &mut Bencher) { + let c = 10_000; + let mut map = IndexMap::with_capacity(c); + let keys = shuffled_keys(0..c); + for &key in &keys { + map.insert(OneShot(key.to_string()), 1); + } + let lookups = (5000..c) + .map(|x| OneShot(x.to_string())) + .collect::>(); + b.iter(|| { + let mut found = 0; + for key in &lookups { + found += map.get(key).is_some() as i32; + } + found + }); +} diff --git a/bitbox02-bt/vendor/indexmap/src/arbitrary.rs b/bitbox02-bt/vendor/indexmap/src/arbitrary.rs new file mode 100644 index 0000000..7798438 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/arbitrary.rs @@ -0,0 +1,77 @@ +#[cfg(feature = "arbitrary")] +#[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))] +mod impl_arbitrary { + use crate::{IndexMap, IndexSet}; + use arbitrary::{Arbitrary, Result, Unstructured}; + use core::hash::{BuildHasher, Hash}; + + impl<'a, K, V, S> Arbitrary<'a> for IndexMap + where + K: Arbitrary<'a> + Hash + Eq, + V: Arbitrary<'a>, + S: BuildHasher + Default, + { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + u.arbitrary_iter()?.collect() + } + + fn arbitrary_take_rest(u: Unstructured<'a>) -> Result { + u.arbitrary_take_rest_iter()?.collect() + } + } + + impl<'a, T, S> Arbitrary<'a> for IndexSet + where + T: Arbitrary<'a> + Hash + Eq, + S: BuildHasher + Default, + { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + u.arbitrary_iter()?.collect() + } + + fn arbitrary_take_rest(u: Unstructured<'a>) -> Result { + u.arbitrary_take_rest_iter()?.collect() + } + } +} + +#[cfg(feature = "quickcheck")] +#[cfg_attr(docsrs, doc(cfg(feature = "quickcheck")))] +mod impl_quickcheck { + use crate::{IndexMap, IndexSet}; + use alloc::boxed::Box; + use alloc::vec::Vec; + use core::hash::{BuildHasher, Hash}; + use quickcheck::{Arbitrary, Gen}; + + impl Arbitrary for IndexMap + where + K: Arbitrary + Hash + Eq, + V: Arbitrary, + S: BuildHasher + Default + Clone + 'static, + { + fn arbitrary(g: &mut Gen) -> Self { + Self::from_iter(Vec::arbitrary(g)) + } + + fn shrink(&self) -> Box> { + let vec = Vec::from_iter(self.clone()); + Box::new(vec.shrink().map(Self::from_iter)) + } + } + + impl Arbitrary for IndexSet + where + T: Arbitrary + Hash + Eq, + S: BuildHasher + Default + Clone + 'static, + { + fn arbitrary(g: &mut Gen) -> Self { + Self::from_iter(Vec::arbitrary(g)) + } + + fn shrink(&self) -> Box> { + let vec = Vec::from_iter(self.clone()); + Box::new(vec.shrink().map(Self::from_iter)) + } + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/borsh.rs b/bitbox02-bt/vendor/indexmap/src/borsh.rs new file mode 100644 index 0000000..c485bd5 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/borsh.rs @@ -0,0 +1,122 @@ +#![cfg_attr(docsrs, doc(cfg(feature = "borsh")))] + +use alloc::vec::Vec; +use core::hash::BuildHasher; +use core::hash::Hash; +use core::mem::size_of; + +use borsh::error::ERROR_ZST_FORBIDDEN; +use borsh::io::{Error, ErrorKind, Read, Result, Write}; +use borsh::{BorshDeserialize, BorshSerialize}; + +use crate::map::IndexMap; +use crate::set::IndexSet; + +impl BorshSerialize for IndexMap +where + K: BorshSerialize, + V: BorshSerialize, +{ + #[inline] + fn serialize(&self, writer: &mut W) -> Result<()> { + check_zst::()?; + + let iterator = self.iter(); + + u32::try_from(iterator.len()) + .map_err(|_| ErrorKind::InvalidData)? + .serialize(writer)?; + + for (key, value) in iterator { + key.serialize(writer)?; + value.serialize(writer)?; + } + + Ok(()) + } +} + +impl BorshDeserialize for IndexMap +where + K: BorshDeserialize + Eq + Hash, + V: BorshDeserialize, + S: BuildHasher + Default, +{ + #[inline] + fn deserialize_reader(reader: &mut R) -> Result { + check_zst::()?; + let vec = >::deserialize_reader(reader)?; + Ok(vec.into_iter().collect::>()) + } +} + +impl BorshSerialize for IndexSet +where + T: BorshSerialize, +{ + #[inline] + fn serialize(&self, writer: &mut W) -> Result<()> { + check_zst::()?; + + let iterator = self.iter(); + + u32::try_from(iterator.len()) + .map_err(|_| ErrorKind::InvalidData)? + .serialize(writer)?; + + for item in iterator { + item.serialize(writer)?; + } + + Ok(()) + } +} + +impl BorshDeserialize for IndexSet +where + T: BorshDeserialize + Eq + Hash, + S: BuildHasher + Default, +{ + #[inline] + fn deserialize_reader(reader: &mut R) -> Result { + check_zst::()?; + let vec = >::deserialize_reader(reader)?; + Ok(vec.into_iter().collect::>()) + } +} + +fn check_zst() -> Result<()> { + if size_of::() == 0 { + return Err(Error::new(ErrorKind::InvalidData, ERROR_ZST_FORBIDDEN)); + } + Ok(()) +} + +#[cfg(test)] +mod borsh_tests { + use super::*; + + #[test] + fn map_borsh_roundtrip() { + let original_map: IndexMap = { + let mut map = IndexMap::new(); + map.insert(1, 2); + map.insert(3, 4); + map.insert(5, 6); + map + }; + let serialized_map = borsh::to_vec(&original_map).unwrap(); + let deserialized_map: IndexMap = + BorshDeserialize::try_from_slice(&serialized_map).unwrap(); + assert_eq!(original_map, deserialized_map); + } + + #[test] + fn set_borsh_roundtrip() { + let original_map: IndexSet = [1, 2, 3, 4, 5, 6].into_iter().collect(); + let serialized_map = borsh::to_vec(&original_map).unwrap(); + let deserialized_map: IndexSet = + BorshDeserialize::try_from_slice(&serialized_map).unwrap(); + assert_eq!(original_map, deserialized_map); + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/lib.rs b/bitbox02-bt/vendor/indexmap/src/lib.rs new file mode 100644 index 0000000..3e16bc6 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/lib.rs @@ -0,0 +1,274 @@ +// We *mostly* avoid unsafe code, but `Slice` allows it for DST casting. +#![deny(unsafe_code)] +#![warn(rust_2018_idioms)] +#![no_std] + +//! [`IndexMap`] is a hash table where the iteration order of the key-value +//! pairs is independent of the hash values of the keys. +//! +//! [`IndexSet`] is a corresponding hash set using the same implementation and +//! with similar properties. +//! +//! ### Highlights +//! +//! [`IndexMap`] and [`IndexSet`] are drop-in compatible with the std `HashMap` +//! and `HashSet`, but they also have some features of note: +//! +//! - The ordering semantics (see their documentation for details) +//! - Sorting methods and the [`.pop()`][IndexMap::pop] methods. +//! - The [`Equivalent`] trait, which offers more flexible equality definitions +//! between borrowed and owned versions of keys. +//! - The [`MutableKeys`][map::MutableKeys] trait, which gives opt-in mutable +//! access to map keys, and [`MutableValues`][set::MutableValues] for sets. +//! +//! ### Feature Flags +//! +//! To reduce the amount of compiled code in the crate by default, certain +//! features are gated behind [feature flags]. These allow you to opt in to (or +//! out of) functionality. Below is a list of the features available in this +//! crate. +//! +//! * `std`: Enables features which require the Rust standard library. For more +//! information see the section on [`no_std`]. +//! * `rayon`: Enables parallel iteration and other parallel methods. +//! * `serde`: Adds implementations for [`Serialize`] and [`Deserialize`] +//! to [`IndexMap`] and [`IndexSet`]. Alternative implementations for +//! (de)serializing [`IndexMap`] as an ordered sequence are available in the +//! [`map::serde_seq`] module. +//! * `borsh`: Adds implementations for [`BorshSerialize`] and [`BorshDeserialize`] +//! to [`IndexMap`] and [`IndexSet`]. +//! * `arbitrary`: Adds implementations for the [`arbitrary::Arbitrary`] trait +//! to [`IndexMap`] and [`IndexSet`]. +//! * `quickcheck`: Adds implementations for the [`quickcheck::Arbitrary`] trait +//! to [`IndexMap`] and [`IndexSet`]. +//! +//! _Note: only the `std` feature is enabled by default._ +//! +//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section +//! [`no_std`]: #no-standard-library-targets +//! [`Serialize`]: `::serde::Serialize` +//! [`Deserialize`]: `::serde::Deserialize` +//! [`BorshSerialize`]: `::borsh::BorshSerialize` +//! [`BorshDeserialize`]: `::borsh::BorshDeserialize` +//! [`arbitrary::Arbitrary`]: `::arbitrary::Arbitrary` +//! [`quickcheck::Arbitrary`]: `::quickcheck::Arbitrary` +//! +//! ### Alternate Hashers +//! +//! [`IndexMap`] and [`IndexSet`] have a default hasher type +//! [`S = RandomState`][std::collections::hash_map::RandomState], +//! just like the standard `HashMap` and `HashSet`, which is resistant to +//! HashDoS attacks but not the most performant. Type aliases can make it easier +//! to use alternate hashers: +//! +//! ``` +//! use fnv::FnvBuildHasher; +//! use fxhash::FxBuildHasher; +//! use indexmap::{IndexMap, IndexSet}; +//! +//! type FnvIndexMap = IndexMap; +//! type FnvIndexSet = IndexSet; +//! +//! type FxIndexMap = IndexMap; +//! type FxIndexSet = IndexSet; +//! +//! let std: IndexSet = (0..100).collect(); +//! let fnv: FnvIndexSet = (0..100).collect(); +//! let fx: FxIndexSet = (0..100).collect(); +//! assert_eq!(std, fnv); +//! assert_eq!(std, fx); +//! ``` +//! +//! ### Rust Version +//! +//! This version of indexmap requires Rust 1.63 or later. +//! +//! The indexmap 2.x release series will use a carefully considered version +//! upgrade policy, where in a later 2.x version, we will raise the minimum +//! required Rust version. +//! +//! ## No Standard Library Targets +//! +//! This crate supports being built without `std`, requiring `alloc` instead. +//! This is chosen by disabling the default "std" cargo feature, by adding +//! `default-features = false` to your dependency specification. +//! +//! - Creating maps and sets using [`new`][IndexMap::new] and +//! [`with_capacity`][IndexMap::with_capacity] is unavailable without `std`. +//! Use methods [`IndexMap::default`], [`with_hasher`][IndexMap::with_hasher], +//! [`with_capacity_and_hasher`][IndexMap::with_capacity_and_hasher] instead. +//! A no-std compatible hasher will be needed as well, for example +//! from the crate `twox-hash`. +//! - Macros [`indexmap!`] and [`indexset!`] are unavailable without `std`. + +#![cfg_attr(docsrs, feature(doc_cfg))] + +extern crate alloc; + +#[cfg(feature = "std")] +#[macro_use] +extern crate std; + +use alloc::vec::{self, Vec}; + +mod arbitrary; +#[macro_use] +mod macros; +#[cfg(feature = "borsh")] +mod borsh; +#[cfg(feature = "serde")] +mod serde; +mod util; + +pub mod map; +pub mod set; + +// Placed after `map` and `set` so new `rayon` methods on the types +// are documented after the "normal" methods. +#[cfg(feature = "rayon")] +mod rayon; + +#[cfg(feature = "rustc-rayon")] +mod rustc; + +pub use crate::map::IndexMap; +pub use crate::set::IndexSet; +pub use equivalent::Equivalent; + +// shared private items + +/// Hash value newtype. Not larger than usize, since anything larger +/// isn't used for selecting position anyway. +#[derive(Clone, Copy, Debug, PartialEq)] +struct HashValue(usize); + +impl HashValue { + #[inline(always)] + fn get(self) -> u64 { + self.0 as u64 + } +} + +#[derive(Copy, Debug)] +struct Bucket { + hash: HashValue, + key: K, + value: V, +} + +impl Clone for Bucket +where + K: Clone, + V: Clone, +{ + fn clone(&self) -> Self { + Bucket { + hash: self.hash, + key: self.key.clone(), + value: self.value.clone(), + } + } + + fn clone_from(&mut self, other: &Self) { + self.hash = other.hash; + self.key.clone_from(&other.key); + self.value.clone_from(&other.value); + } +} + +impl Bucket { + // field accessors -- used for `f` instead of closures in `.map(f)` + fn key_ref(&self) -> &K { + &self.key + } + fn value_ref(&self) -> &V { + &self.value + } + fn value_mut(&mut self) -> &mut V { + &mut self.value + } + fn key(self) -> K { + self.key + } + fn value(self) -> V { + self.value + } + fn key_value(self) -> (K, V) { + (self.key, self.value) + } + fn refs(&self) -> (&K, &V) { + (&self.key, &self.value) + } + fn ref_mut(&mut self) -> (&K, &mut V) { + (&self.key, &mut self.value) + } + fn muts(&mut self) -> (&mut K, &mut V) { + (&mut self.key, &mut self.value) + } +} + +trait Entries { + type Entry; + fn into_entries(self) -> Vec; + fn as_entries(&self) -> &[Self::Entry]; + fn as_entries_mut(&mut self) -> &mut [Self::Entry]; + fn with_entries(&mut self, f: F) + where + F: FnOnce(&mut [Self::Entry]); +} + +/// The error type for [`try_reserve`][IndexMap::try_reserve] methods. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct TryReserveError { + kind: TryReserveErrorKind, +} + +#[derive(Clone, PartialEq, Eq, Debug)] +enum TryReserveErrorKind { + // The standard library's kind is currently opaque to us, otherwise we could unify this. + Std(alloc::collections::TryReserveError), + CapacityOverflow, + AllocError { layout: alloc::alloc::Layout }, +} + +// These are not `From` so we don't expose them in our public API. +impl TryReserveError { + fn from_alloc(error: alloc::collections::TryReserveError) -> Self { + Self { + kind: TryReserveErrorKind::Std(error), + } + } + + fn from_hashbrown(error: hashbrown::TryReserveError) -> Self { + Self { + kind: match error { + hashbrown::TryReserveError::CapacityOverflow => { + TryReserveErrorKind::CapacityOverflow + } + hashbrown::TryReserveError::AllocError { layout } => { + TryReserveErrorKind::AllocError { layout } + } + }, + } + } +} + +impl core::fmt::Display for TryReserveError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let reason = match &self.kind { + TryReserveErrorKind::Std(e) => return core::fmt::Display::fmt(e, f), + TryReserveErrorKind::CapacityOverflow => { + " because the computed capacity exceeded the collection's maximum" + } + TryReserveErrorKind::AllocError { .. } => { + " because the memory allocator returned an error" + } + }; + f.write_str("memory allocation failed")?; + f.write_str(reason) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl std::error::Error for TryReserveError {} diff --git a/bitbox02-bt/vendor/indexmap/src/macros.rs b/bitbox02-bt/vendor/indexmap/src/macros.rs new file mode 100644 index 0000000..b347de2 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/macros.rs @@ -0,0 +1,178 @@ +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[macro_export] +/// Create an [`IndexMap`][crate::IndexMap] from a list of key-value pairs +/// +/// ## Example +/// +/// ``` +/// use indexmap::indexmap; +/// +/// let map = indexmap!{ +/// "a" => 1, +/// "b" => 2, +/// }; +/// assert_eq!(map["a"], 1); +/// assert_eq!(map["b"], 2); +/// assert_eq!(map.get("c"), None); +/// +/// // "a" is the first key +/// assert_eq!(map.keys().next(), Some(&"a")); +/// ``` +macro_rules! indexmap { + ($($key:expr => $value:expr,)+) => { $crate::indexmap!($($key => $value),+) }; + ($($key:expr => $value:expr),*) => { + { + // Note: `stringify!($key)` is just here to consume the repetition, + // but we throw away that string literal during constant evaluation. + const CAP: usize = <[()]>::len(&[$({ stringify!($key); }),*]); + let mut map = $crate::IndexMap::with_capacity(CAP); + $( + map.insert($key, $value); + )* + map + } + }; +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[macro_export] +/// Create an [`IndexSet`][crate::IndexSet] from a list of values +/// +/// ## Example +/// +/// ``` +/// use indexmap::indexset; +/// +/// let set = indexset!{ +/// "a", +/// "b", +/// }; +/// assert!(set.contains("a")); +/// assert!(set.contains("b")); +/// assert!(!set.contains("c")); +/// +/// // "a" is the first value +/// assert_eq!(set.iter().next(), Some(&"a")); +/// ``` +macro_rules! indexset { + ($($value:expr,)+) => { $crate::indexset!($($value),+) }; + ($($value:expr),*) => { + { + // Note: `stringify!($value)` is just here to consume the repetition, + // but we throw away that string literal during constant evaluation. + const CAP: usize = <[()]>::len(&[$({ stringify!($value); }),*]); + let mut set = $crate::IndexSet::with_capacity(CAP); + $( + set.insert($value); + )* + set + } + }; +} + +// generate all the Iterator methods by just forwarding to the underlying +// self.iter and mapping its element. +macro_rules! iterator_methods { + // $map_elt is the mapping function from the underlying iterator's element + // same mapping function for both options and iterators + ($map_elt:expr) => { + fn next(&mut self) -> Option { + self.iter.next().map($map_elt) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + fn count(self) -> usize { + self.iter.len() + } + + fn nth(&mut self, n: usize) -> Option { + self.iter.nth(n).map($map_elt) + } + + fn last(mut self) -> Option { + self.next_back() + } + + fn collect(self) -> C + where + C: FromIterator, + { + // NB: forwarding this directly to standard iterators will + // allow it to leverage unstable traits like `TrustedLen`. + self.iter.map($map_elt).collect() + } + }; +} + +macro_rules! double_ended_iterator_methods { + // $map_elt is the mapping function from the underlying iterator's element + // same mapping function for both options and iterators + ($map_elt:expr) => { + fn next_back(&mut self) -> Option { + self.iter.next_back().map($map_elt) + } + + fn nth_back(&mut self, n: usize) -> Option { + self.iter.nth_back(n).map($map_elt) + } + }; +} + +// generate `ParallelIterator` methods by just forwarding to the underlying +// self.entries and mapping its elements. +#[cfg(any(feature = "rayon", feature = "rustc-rayon"))] +macro_rules! parallel_iterator_methods { + // $map_elt is the mapping function from the underlying iterator's element + ($map_elt:expr) => { + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + self.entries + .into_par_iter() + .map($map_elt) + .drive_unindexed(consumer) + } + + // NB: This allows indexed collection, e.g. directly into a `Vec`, but the + // underlying iterator must really be indexed. We should remove this if we + // start having tombstones that must be filtered out. + fn opt_len(&self) -> Option { + Some(self.entries.len()) + } + }; +} + +// generate `IndexedParallelIterator` methods by just forwarding to the underlying +// self.entries and mapping its elements. +#[cfg(any(feature = "rayon", feature = "rustc-rayon"))] +macro_rules! indexed_parallel_iterator_methods { + // $map_elt is the mapping function from the underlying iterator's element + ($map_elt:expr) => { + fn drive(self, consumer: C) -> C::Result + where + C: Consumer, + { + self.entries.into_par_iter().map($map_elt).drive(consumer) + } + + fn len(&self) -> usize { + self.entries.len() + } + + fn with_producer(self, callback: CB) -> CB::Output + where + CB: ProducerCallback, + { + self.entries + .into_par_iter() + .map($map_elt) + .with_producer(callback) + } + }; +} diff --git a/bitbox02-bt/vendor/indexmap/src/map.rs b/bitbox02-bt/vendor/indexmap/src/map.rs new file mode 100644 index 0000000..946cb6f --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map.rs @@ -0,0 +1,1578 @@ +//! [`IndexMap`] is a hash table where the iteration order of the key-value +//! pairs is independent of the hash values of the keys. + +mod core; +mod iter; +mod mutable; +mod slice; + +#[cfg(feature = "serde")] +#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] +pub mod serde_seq; + +#[cfg(test)] +mod tests; + +pub use self::core::raw_entry_v1::{self, RawEntryApiV1}; +pub use self::core::{Entry, IndexedEntry, OccupiedEntry, VacantEntry}; +pub use self::iter::{ + Drain, IntoIter, IntoKeys, IntoValues, Iter, IterMut, IterMut2, Keys, Splice, Values, ValuesMut, +}; +pub use self::mutable::MutableEntryKey; +pub use self::mutable::MutableKeys; +pub use self::slice::Slice; + +#[cfg(feature = "rayon")] +pub use crate::rayon::map as rayon; + +use ::core::cmp::Ordering; +use ::core::fmt; +use ::core::hash::{BuildHasher, Hash, Hasher}; +use ::core::mem; +use ::core::ops::{Index, IndexMut, RangeBounds}; +use alloc::boxed::Box; +use alloc::vec::Vec; + +#[cfg(feature = "std")] +use std::collections::hash_map::RandomState; + +use self::core::IndexMapCore; +use crate::util::{third, try_simplify_range}; +use crate::{Bucket, Entries, Equivalent, HashValue, TryReserveError}; + +/// A hash table where the iteration order of the key-value pairs is independent +/// of the hash values of the keys. +/// +/// The interface is closely compatible with the standard +/// [`HashMap`][std::collections::HashMap], +/// but also has additional features. +/// +/// # Order +/// +/// The key-value pairs have a consistent order that is determined by +/// the sequence of insertion and removal calls on the map. The order does +/// not depend on the keys or the hash function at all. +/// +/// All iterators traverse the map in *the order*. +/// +/// The insertion order is preserved, with **notable exceptions** like the +/// [`.remove()`][Self::remove] or [`.swap_remove()`][Self::swap_remove] methods. +/// Methods such as [`.sort_by()`][Self::sort_by] of +/// course result in a new order, depending on the sorting order. +/// +/// # Indices +/// +/// The key-value pairs are indexed in a compact range without holes in the +/// range `0..self.len()`. For example, the method `.get_full` looks up the +/// index for a key, and the method `.get_index` looks up the key-value pair by +/// index. +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexMap; +/// +/// // count the frequency of each letter in a sentence. +/// let mut letters = IndexMap::new(); +/// for ch in "a short treatise on fungi".chars() { +/// *letters.entry(ch).or_insert(0) += 1; +/// } +/// +/// assert_eq!(letters[&'s'], 2); +/// assert_eq!(letters[&'t'], 3); +/// assert_eq!(letters[&'u'], 1); +/// assert_eq!(letters.get(&'y'), None); +/// ``` +#[cfg(feature = "std")] +pub struct IndexMap { + pub(crate) core: IndexMapCore, + hash_builder: S, +} +#[cfg(not(feature = "std"))] +pub struct IndexMap { + pub(crate) core: IndexMapCore, + hash_builder: S, +} + +impl Clone for IndexMap +where + K: Clone, + V: Clone, + S: Clone, +{ + fn clone(&self) -> Self { + IndexMap { + core: self.core.clone(), + hash_builder: self.hash_builder.clone(), + } + } + + fn clone_from(&mut self, other: &Self) { + self.core.clone_from(&other.core); + self.hash_builder.clone_from(&other.hash_builder); + } +} + +impl Entries for IndexMap { + type Entry = Bucket; + + #[inline] + fn into_entries(self) -> Vec { + self.core.into_entries() + } + + #[inline] + fn as_entries(&self) -> &[Self::Entry] { + self.core.as_entries() + } + + #[inline] + fn as_entries_mut(&mut self) -> &mut [Self::Entry] { + self.core.as_entries_mut() + } + + fn with_entries(&mut self, f: F) + where + F: FnOnce(&mut [Self::Entry]), + { + self.core.with_entries(f); + } +} + +impl fmt::Debug for IndexMap +where + K: fmt::Debug, + V: fmt::Debug, +{ + #[cfg(not(feature = "test_debug"))] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_map().entries(self.iter()).finish() + } + + #[cfg(feature = "test_debug")] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Let the inner `IndexMapCore` print all of its details + f.debug_struct("IndexMap") + .field("core", &self.core) + .finish() + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl IndexMap { + /// Create a new map. (Does not allocate.) + #[inline] + pub fn new() -> Self { + Self::with_capacity(0) + } + + /// Create a new map with capacity for `n` key-value pairs. (Does not + /// allocate if `n` is zero.) + /// + /// Computes in **O(n)** time. + #[inline] + pub fn with_capacity(n: usize) -> Self { + Self::with_capacity_and_hasher(n, <_>::default()) + } +} + +impl IndexMap { + /// Create a new map with capacity for `n` key-value pairs. (Does not + /// allocate if `n` is zero.) + /// + /// Computes in **O(n)** time. + #[inline] + pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self { + if n == 0 { + Self::with_hasher(hash_builder) + } else { + IndexMap { + core: IndexMapCore::with_capacity(n), + hash_builder, + } + } + } + + /// Create a new map with `hash_builder`. + /// + /// This function is `const`, so it + /// can be called in `static` contexts. + pub const fn with_hasher(hash_builder: S) -> Self { + IndexMap { + core: IndexMapCore::new(), + hash_builder, + } + } + + /// Return the number of elements the map can hold without reallocating. + /// + /// This number is a lower bound; the map might be able to hold more, + /// but is guaranteed to be able to hold at least this many. + /// + /// Computes in **O(1)** time. + pub fn capacity(&self) -> usize { + self.core.capacity() + } + + /// Return a reference to the map's `BuildHasher`. + pub fn hasher(&self) -> &S { + &self.hash_builder + } + + /// Return the number of key-value pairs in the map. + /// + /// Computes in **O(1)** time. + #[inline] + pub fn len(&self) -> usize { + self.core.len() + } + + /// Returns true if the map contains no elements. + /// + /// Computes in **O(1)** time. + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Return an iterator over the key-value pairs of the map, in their order + pub fn iter(&self) -> Iter<'_, K, V> { + Iter::new(self.as_entries()) + } + + /// Return an iterator over the key-value pairs of the map, in their order + pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { + IterMut::new(self.as_entries_mut()) + } + + /// Return an iterator over the keys of the map, in their order + pub fn keys(&self) -> Keys<'_, K, V> { + Keys::new(self.as_entries()) + } + + /// Return an owning iterator over the keys of the map, in their order + pub fn into_keys(self) -> IntoKeys { + IntoKeys::new(self.into_entries()) + } + + /// Return an iterator over the values of the map, in their order + pub fn values(&self) -> Values<'_, K, V> { + Values::new(self.as_entries()) + } + + /// Return an iterator over mutable references to the values of the map, + /// in their order + pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> { + ValuesMut::new(self.as_entries_mut()) + } + + /// Return an owning iterator over the values of the map, in their order + pub fn into_values(self) -> IntoValues { + IntoValues::new(self.into_entries()) + } + + /// Remove all key-value pairs in the map, while preserving its capacity. + /// + /// Computes in **O(n)** time. + pub fn clear(&mut self) { + self.core.clear(); + } + + /// Shortens the map, keeping the first `len` elements and dropping the rest. + /// + /// If `len` is greater than the map's current length, this has no effect. + pub fn truncate(&mut self, len: usize) { + self.core.truncate(len); + } + + /// Clears the `IndexMap` in the given index range, returning those + /// key-value pairs as a drain iterator. + /// + /// The range may be any type that implements [`RangeBounds`], + /// including all of the `std::ops::Range*` types, or even a tuple pair of + /// `Bound` start and end values. To drain the map entirely, use `RangeFull` + /// like `map.drain(..)`. + /// + /// This shifts down all entries following the drained range to fill the + /// gap, and keeps the allocated memory for reuse. + /// + /// ***Panics*** if the starting point is greater than the end point or if + /// the end point is greater than the length of the map. + pub fn drain(&mut self, range: R) -> Drain<'_, K, V> + where + R: RangeBounds, + { + Drain::new(self.core.drain(range)) + } + + /// Splits the collection into two at the given index. + /// + /// Returns a newly allocated map containing the elements in the range + /// `[at, len)`. After the call, the original map will be left containing + /// the elements `[0, at)` with its previous capacity unchanged. + /// + /// ***Panics*** if `at > len`. + pub fn split_off(&mut self, at: usize) -> Self + where + S: Clone, + { + Self { + core: self.core.split_off(at), + hash_builder: self.hash_builder.clone(), + } + } + + /// Reserve capacity for `additional` more key-value pairs. + /// + /// Computes in **O(n)** time. + pub fn reserve(&mut self, additional: usize) { + self.core.reserve(additional); + } + + /// Reserve capacity for `additional` more key-value pairs, without over-allocating. + /// + /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid + /// frequent re-allocations. However, the underlying data structures may still have internal + /// capacity requirements, and the allocator itself may give more space than requested, so this + /// cannot be relied upon to be precisely minimal. + /// + /// Computes in **O(n)** time. + pub fn reserve_exact(&mut self, additional: usize) { + self.core.reserve_exact(additional); + } + + /// Try to reserve capacity for `additional` more key-value pairs. + /// + /// Computes in **O(n)** time. + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.core.try_reserve(additional) + } + + /// Try to reserve capacity for `additional` more key-value pairs, without over-allocating. + /// + /// Unlike `try_reserve`, this does not deliberately over-allocate the entry capacity to avoid + /// frequent re-allocations. However, the underlying data structures may still have internal + /// capacity requirements, and the allocator itself may give more space than requested, so this + /// cannot be relied upon to be precisely minimal. + /// + /// Computes in **O(n)** time. + pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.core.try_reserve_exact(additional) + } + + /// Shrink the capacity of the map as much as possible. + /// + /// Computes in **O(n)** time. + pub fn shrink_to_fit(&mut self) { + self.core.shrink_to(0); + } + + /// Shrink the capacity of the map with a lower limit. + /// + /// Computes in **O(n)** time. + pub fn shrink_to(&mut self, min_capacity: usize) { + self.core.shrink_to(min_capacity); + } +} + +impl IndexMap +where + K: Hash + Eq, + S: BuildHasher, +{ + /// Insert a key-value pair in the map. + /// + /// If an equivalent key already exists in the map: the key remains and + /// retains in its place in the order, its corresponding value is updated + /// with `value`, and the older value is returned inside `Some(_)`. + /// + /// If no equivalent key existed in the map: the new key-value pair is + /// inserted, last in order, and `None` is returned. + /// + /// Computes in **O(1)** time (amortized average). + /// + /// See also [`entry`][Self::entry] if you want to insert *or* modify, + /// or [`insert_full`][Self::insert_full] if you need to get the index of + /// the corresponding key-value pair. + pub fn insert(&mut self, key: K, value: V) -> Option { + self.insert_full(key, value).1 + } + + /// Insert a key-value pair in the map, and get their index. + /// + /// If an equivalent key already exists in the map: the key remains and + /// retains in its place in the order, its corresponding value is updated + /// with `value`, and the older value is returned inside `(index, Some(_))`. + /// + /// If no equivalent key existed in the map: the new key-value pair is + /// inserted, last in order, and `(index, None)` is returned. + /// + /// Computes in **O(1)** time (amortized average). + /// + /// See also [`entry`][Self::entry] if you want to insert *or* modify. + pub fn insert_full(&mut self, key: K, value: V) -> (usize, Option) { + let hash = self.hash(&key); + self.core.insert_full(hash, key, value) + } + + /// Insert a key-value pair in the map at its ordered position among sorted keys. + /// + /// This is equivalent to finding the position with + /// [`binary_search_keys`][Self::binary_search_keys], then either updating + /// it or calling [`insert_before`][Self::insert_before] for a new key. + /// + /// If the sorted key is found in the map, its corresponding value is + /// updated with `value`, and the older value is returned inside + /// `(index, Some(_))`. Otherwise, the new key-value pair is inserted at + /// the sorted position, and `(index, None)` is returned. + /// + /// If the existing keys are **not** already sorted, then the insertion + /// index is unspecified (like [`slice::binary_search`]), but the key-value + /// pair is moved to or inserted at that position regardless. + /// + /// Computes in **O(n)** time (average). Instead of repeating calls to + /// `insert_sorted`, it may be faster to call batched [`insert`][Self::insert] + /// or [`extend`][Self::extend] and only call [`sort_keys`][Self::sort_keys] + /// or [`sort_unstable_keys`][Self::sort_unstable_keys] once. + pub fn insert_sorted(&mut self, key: K, value: V) -> (usize, Option) + where + K: Ord, + { + match self.binary_search_keys(&key) { + Ok(i) => (i, Some(mem::replace(&mut self[i], value))), + Err(i) => self.insert_before(i, key, value), + } + } + + /// Insert a key-value pair in the map before the entry at the given index, or at the end. + /// + /// If an equivalent key already exists in the map: the key remains and + /// is moved to the new position in the map, its corresponding value is updated + /// with `value`, and the older value is returned inside `Some(_)`. The returned index + /// will either be the given index or one less, depending on how the entry moved. + /// (See [`shift_insert`](Self::shift_insert) for different behavior here.) + /// + /// If no equivalent key existed in the map: the new key-value pair is + /// inserted exactly at the given index, and `None` is returned. + /// + /// ***Panics*** if `index` is out of bounds. + /// Valid indices are `0..=map.len()` (inclusive). + /// + /// Computes in **O(n)** time (average). + /// + /// See also [`entry`][Self::entry] if you want to insert *or* modify, + /// perhaps only using the index for new entries with [`VacantEntry::shift_insert`]. + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexMap; + /// let mut map: IndexMap = ('a'..='z').map(|c| (c, ())).collect(); + /// + /// // The new key '*' goes exactly at the given index. + /// assert_eq!(map.get_index_of(&'*'), None); + /// assert_eq!(map.insert_before(10, '*', ()), (10, None)); + /// assert_eq!(map.get_index_of(&'*'), Some(10)); + /// + /// // Moving the key 'a' up will shift others down, so this moves *before* 10 to index 9. + /// assert_eq!(map.insert_before(10, 'a', ()), (9, Some(()))); + /// assert_eq!(map.get_index_of(&'a'), Some(9)); + /// assert_eq!(map.get_index_of(&'*'), Some(10)); + /// + /// // Moving the key 'z' down will shift others up, so this moves to exactly 10. + /// assert_eq!(map.insert_before(10, 'z', ()), (10, Some(()))); + /// assert_eq!(map.get_index_of(&'z'), Some(10)); + /// assert_eq!(map.get_index_of(&'*'), Some(11)); + /// + /// // Moving or inserting before the endpoint is also valid. + /// assert_eq!(map.len(), 27); + /// assert_eq!(map.insert_before(map.len(), '*', ()), (26, Some(()))); + /// assert_eq!(map.get_index_of(&'*'), Some(26)); + /// assert_eq!(map.insert_before(map.len(), '+', ()), (27, None)); + /// assert_eq!(map.get_index_of(&'+'), Some(27)); + /// assert_eq!(map.len(), 28); + /// ``` + pub fn insert_before(&mut self, mut index: usize, key: K, value: V) -> (usize, Option) { + assert!(index <= self.len(), "index out of bounds"); + match self.entry(key) { + Entry::Occupied(mut entry) => { + if index > entry.index() { + // Some entries will shift down when this one moves up, + // so "insert before index" becomes "move to index - 1", + // keeping the entry at the original index unmoved. + index -= 1; + } + let old = mem::replace(entry.get_mut(), value); + entry.move_index(index); + (index, Some(old)) + } + Entry::Vacant(entry) => { + entry.shift_insert(index, value); + (index, None) + } + } + } + + /// Insert a key-value pair in the map at the given index. + /// + /// If an equivalent key already exists in the map: the key remains and + /// is moved to the given index in the map, its corresponding value is updated + /// with `value`, and the older value is returned inside `Some(_)`. + /// Note that existing entries **cannot** be moved to `index == map.len()`! + /// (See [`insert_before`](Self::insert_before) for different behavior here.) + /// + /// If no equivalent key existed in the map: the new key-value pair is + /// inserted at the given index, and `None` is returned. + /// + /// ***Panics*** if `index` is out of bounds. + /// Valid indices are `0..map.len()` (exclusive) when moving an existing entry, or + /// `0..=map.len()` (inclusive) when inserting a new key. + /// + /// Computes in **O(n)** time (average). + /// + /// See also [`entry`][Self::entry] if you want to insert *or* modify, + /// perhaps only using the index for new entries with [`VacantEntry::shift_insert`]. + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexMap; + /// let mut map: IndexMap = ('a'..='z').map(|c| (c, ())).collect(); + /// + /// // The new key '*' goes exactly at the given index. + /// assert_eq!(map.get_index_of(&'*'), None); + /// assert_eq!(map.shift_insert(10, '*', ()), None); + /// assert_eq!(map.get_index_of(&'*'), Some(10)); + /// + /// // Moving the key 'a' up to 10 will shift others down, including the '*' that was at 10. + /// assert_eq!(map.shift_insert(10, 'a', ()), Some(())); + /// assert_eq!(map.get_index_of(&'a'), Some(10)); + /// assert_eq!(map.get_index_of(&'*'), Some(9)); + /// + /// // Moving the key 'z' down to 9 will shift others up, including the '*' that was at 9. + /// assert_eq!(map.shift_insert(9, 'z', ()), Some(())); + /// assert_eq!(map.get_index_of(&'z'), Some(9)); + /// assert_eq!(map.get_index_of(&'*'), Some(10)); + /// + /// // Existing keys can move to len-1 at most, but new keys can insert at the endpoint. + /// assert_eq!(map.len(), 27); + /// assert_eq!(map.shift_insert(map.len() - 1, '*', ()), Some(())); + /// assert_eq!(map.get_index_of(&'*'), Some(26)); + /// assert_eq!(map.shift_insert(map.len(), '+', ()), None); + /// assert_eq!(map.get_index_of(&'+'), Some(27)); + /// assert_eq!(map.len(), 28); + /// ``` + /// + /// ```should_panic + /// use indexmap::IndexMap; + /// let mut map: IndexMap = ('a'..='z').map(|c| (c, ())).collect(); + /// + /// // This is an invalid index for moving an existing key! + /// map.shift_insert(map.len(), 'a', ()); + /// ``` + pub fn shift_insert(&mut self, index: usize, key: K, value: V) -> Option { + let len = self.len(); + match self.entry(key) { + Entry::Occupied(mut entry) => { + assert!(index < len, "index out of bounds"); + let old = mem::replace(entry.get_mut(), value); + entry.move_index(index); + Some(old) + } + Entry::Vacant(entry) => { + assert!(index <= len, "index out of bounds"); + entry.shift_insert(index, value); + None + } + } + } + + /// Get the given key’s corresponding entry in the map for insertion and/or + /// in-place manipulation. + /// + /// Computes in **O(1)** time (amortized average). + pub fn entry(&mut self, key: K) -> Entry<'_, K, V> { + let hash = self.hash(&key); + self.core.entry(hash, key) + } + + /// Creates a splicing iterator that replaces the specified range in the map + /// with the given `replace_with` key-value iterator and yields the removed + /// items. `replace_with` does not need to be the same length as `range`. + /// + /// The `range` is removed even if the iterator is not consumed until the + /// end. It is unspecified how many elements are removed from the map if the + /// `Splice` value is leaked. + /// + /// The input iterator `replace_with` is only consumed when the `Splice` + /// value is dropped. If a key from the iterator matches an existing entry + /// in the map (outside of `range`), then the value will be updated in that + /// position. Otherwise, the new key-value pair will be inserted in the + /// replaced `range`. + /// + /// ***Panics*** if the starting point is greater than the end point or if + /// the end point is greater than the length of the map. + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexMap; + /// + /// let mut map = IndexMap::from([(0, '_'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]); + /// let new = [(5, 'E'), (4, 'D'), (3, 'C'), (2, 'B'), (1, 'A')]; + /// let removed: Vec<_> = map.splice(2..4, new).collect(); + /// + /// // 1 and 4 got new values, while 5, 3, and 2 were newly inserted. + /// assert!(map.into_iter().eq([(0, '_'), (1, 'A'), (5, 'E'), (3, 'C'), (2, 'B'), (4, 'D')])); + /// assert_eq!(removed, &[(2, 'b'), (3, 'c')]); + /// ``` + pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, K, V, S> + where + R: RangeBounds, + I: IntoIterator, + { + Splice::new(self, range, replace_with.into_iter()) + } + + /// Moves all key-value pairs from `other` into `self`, leaving `other` empty. + /// + /// This is equivalent to calling [`insert`][Self::insert] for each + /// key-value pair from `other` in order, which means that for keys that + /// already exist in `self`, their value is updated in the current position. + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexMap; + /// + /// // Note: Key (3) is present in both maps. + /// let mut a = IndexMap::from([(3, "c"), (2, "b"), (1, "a")]); + /// let mut b = IndexMap::from([(3, "d"), (4, "e"), (5, "f")]); + /// let old_capacity = b.capacity(); + /// + /// a.append(&mut b); + /// + /// assert_eq!(a.len(), 5); + /// assert_eq!(b.len(), 0); + /// assert_eq!(b.capacity(), old_capacity); + /// + /// assert!(a.keys().eq(&[3, 2, 1, 4, 5])); + /// assert_eq!(a[&3], "d"); // "c" was overwritten. + /// ``` + pub fn append(&mut self, other: &mut IndexMap) { + self.extend(other.drain(..)); + } +} + +impl IndexMap +where + S: BuildHasher, +{ + pub(crate) fn hash(&self, key: &Q) -> HashValue { + let mut h = self.hash_builder.build_hasher(); + key.hash(&mut h); + HashValue(h.finish() as usize) + } + + /// Return `true` if an equivalent to `key` exists in the map. + /// + /// Computes in **O(1)** time (average). + pub fn contains_key(&self, key: &Q) -> bool + where + Q: ?Sized + Hash + Equivalent, + { + self.get_index_of(key).is_some() + } + + /// Return a reference to the value stored for `key`, if it is present, + /// else `None`. + /// + /// Computes in **O(1)** time (average). + pub fn get(&self, key: &Q) -> Option<&V> + where + Q: ?Sized + Hash + Equivalent, + { + if let Some(i) = self.get_index_of(key) { + let entry = &self.as_entries()[i]; + Some(&entry.value) + } else { + None + } + } + + /// Return references to the key-value pair stored for `key`, + /// if it is present, else `None`. + /// + /// Computes in **O(1)** time (average). + pub fn get_key_value(&self, key: &Q) -> Option<(&K, &V)> + where + Q: ?Sized + Hash + Equivalent, + { + if let Some(i) = self.get_index_of(key) { + let entry = &self.as_entries()[i]; + Some((&entry.key, &entry.value)) + } else { + None + } + } + + /// Return item index, key and value + pub fn get_full(&self, key: &Q) -> Option<(usize, &K, &V)> + where + Q: ?Sized + Hash + Equivalent, + { + if let Some(i) = self.get_index_of(key) { + let entry = &self.as_entries()[i]; + Some((i, &entry.key, &entry.value)) + } else { + None + } + } + + /// Return item index, if it exists in the map + /// + /// Computes in **O(1)** time (average). + pub fn get_index_of(&self, key: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + match self.as_entries() { + [] => None, + [x] => key.equivalent(&x.key).then_some(0), + _ => { + let hash = self.hash(key); + self.core.get_index_of(hash, key) + } + } + } + + pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> + where + Q: ?Sized + Hash + Equivalent, + { + if let Some(i) = self.get_index_of(key) { + let entry = &mut self.as_entries_mut()[i]; + Some(&mut entry.value) + } else { + None + } + } + + pub fn get_full_mut(&mut self, key: &Q) -> Option<(usize, &K, &mut V)> + where + Q: ?Sized + Hash + Equivalent, + { + if let Some(i) = self.get_index_of(key) { + let entry = &mut self.as_entries_mut()[i]; + Some((i, &entry.key, &mut entry.value)) + } else { + None + } + } + + /// Remove the key-value pair equivalent to `key` and return + /// its value. + /// + /// **NOTE:** This is equivalent to [`.swap_remove(key)`][Self::swap_remove], replacing this + /// entry's position with the last element, and it is deprecated in favor of calling that + /// explicitly. If you need to preserve the relative order of the keys in the map, use + /// [`.shift_remove(key)`][Self::shift_remove] instead. + #[deprecated(note = "`remove` disrupts the map order -- \ + use `swap_remove` or `shift_remove` for explicit behavior.")] + pub fn remove(&mut self, key: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + self.swap_remove(key) + } + + /// Remove and return the key-value pair equivalent to `key`. + /// + /// **NOTE:** This is equivalent to [`.swap_remove_entry(key)`][Self::swap_remove_entry], + /// replacing this entry's position with the last element, and it is deprecated in favor of + /// calling that explicitly. If you need to preserve the relative order of the keys in the map, + /// use [`.shift_remove_entry(key)`][Self::shift_remove_entry] instead. + #[deprecated(note = "`remove_entry` disrupts the map order -- \ + use `swap_remove_entry` or `shift_remove_entry` for explicit behavior.")] + pub fn remove_entry(&mut self, key: &Q) -> Option<(K, V)> + where + Q: ?Sized + Hash + Equivalent, + { + self.swap_remove_entry(key) + } + + /// Remove the key-value pair equivalent to `key` and return + /// its value. + /// + /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the + /// last element of the map and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Return `None` if `key` is not in map. + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove(&mut self, key: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + self.swap_remove_full(key).map(third) + } + + /// Remove and return the key-value pair equivalent to `key`. + /// + /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the + /// last element of the map and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Return `None` if `key` is not in map. + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove_entry(&mut self, key: &Q) -> Option<(K, V)> + where + Q: ?Sized + Hash + Equivalent, + { + match self.swap_remove_full(key) { + Some((_, key, value)) => Some((key, value)), + None => None, + } + } + + /// Remove the key-value pair equivalent to `key` and return it and + /// the index it had. + /// + /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the + /// last element of the map and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Return `None` if `key` is not in map. + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove_full(&mut self, key: &Q) -> Option<(usize, K, V)> + where + Q: ?Sized + Hash + Equivalent, + { + match self.as_entries() { + [x] if key.equivalent(&x.key) => { + let (k, v) = self.core.pop()?; + Some((0, k, v)) + } + [_] | [] => None, + _ => { + let hash = self.hash(key); + self.core.swap_remove_full(hash, key) + } + } + } + + /// Remove the key-value pair equivalent to `key` and return + /// its value. + /// + /// Like [`Vec::remove`], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Return `None` if `key` is not in map. + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove(&mut self, key: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + self.shift_remove_full(key).map(third) + } + + /// Remove and return the key-value pair equivalent to `key`. + /// + /// Like [`Vec::remove`], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Return `None` if `key` is not in map. + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove_entry(&mut self, key: &Q) -> Option<(K, V)> + where + Q: ?Sized + Hash + Equivalent, + { + match self.shift_remove_full(key) { + Some((_, key, value)) => Some((key, value)), + None => None, + } + } + + /// Remove the key-value pair equivalent to `key` and return it and + /// the index it had. + /// + /// Like [`Vec::remove`], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Return `None` if `key` is not in map. + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove_full(&mut self, key: &Q) -> Option<(usize, K, V)> + where + Q: ?Sized + Hash + Equivalent, + { + match self.as_entries() { + [x] if key.equivalent(&x.key) => { + let (k, v) = self.core.pop()?; + Some((0, k, v)) + } + [_] | [] => None, + _ => { + let hash = self.hash(key); + self.core.shift_remove_full(hash, key) + } + } + } +} + +impl IndexMap { + /// Remove the last key-value pair + /// + /// This preserves the order of the remaining elements. + /// + /// Computes in **O(1)** time (average). + #[doc(alias = "pop_last")] // like `BTreeMap` + pub fn pop(&mut self) -> Option<(K, V)> { + self.core.pop() + } + + /// Scan through each key-value pair in the map and keep those where the + /// closure `keep` returns `true`. + /// + /// The elements are visited in order, and remaining elements keep their + /// order. + /// + /// Computes in **O(n)** time (average). + pub fn retain(&mut self, mut keep: F) + where + F: FnMut(&K, &mut V) -> bool, + { + self.core.retain_in_order(move |k, v| keep(k, v)); + } + + /// Sort the map’s key-value pairs by the default ordering of the keys. + /// + /// This is a stable sort -- but equivalent keys should not normally coexist in + /// a map at all, so [`sort_unstable_keys`][Self::sort_unstable_keys] is preferred + /// because it is generally faster and doesn't allocate auxiliary memory. + /// + /// See [`sort_by`](Self::sort_by) for details. + pub fn sort_keys(&mut self) + where + K: Ord, + { + self.with_entries(move |entries| { + entries.sort_by(move |a, b| K::cmp(&a.key, &b.key)); + }); + } + + /// Sort the map’s key-value pairs in place using the comparison + /// function `cmp`. + /// + /// The comparison function receives two key and value pairs to compare (you + /// can sort by keys or values or their combination as needed). + /// + /// Computes in **O(n log n + c)** time and **O(n)** space where *n* is + /// the length of the map and *c* the capacity. The sort is stable. + pub fn sort_by(&mut self, mut cmp: F) + where + F: FnMut(&K, &V, &K, &V) -> Ordering, + { + self.with_entries(move |entries| { + entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + }); + } + + /// Sort the key-value pairs of the map and return a by-value iterator of + /// the key-value pairs with the result. + /// + /// The sort is stable. + pub fn sorted_by(self, mut cmp: F) -> IntoIter + where + F: FnMut(&K, &V, &K, &V) -> Ordering, + { + let mut entries = self.into_entries(); + entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + IntoIter::new(entries) + } + + /// Sort the map's key-value pairs by the default ordering of the keys, but + /// may not preserve the order of equal elements. + /// + /// See [`sort_unstable_by`](Self::sort_unstable_by) for details. + pub fn sort_unstable_keys(&mut self) + where + K: Ord, + { + self.with_entries(move |entries| { + entries.sort_unstable_by(move |a, b| K::cmp(&a.key, &b.key)); + }); + } + + /// Sort the map's key-value pairs in place using the comparison function `cmp`, but + /// may not preserve the order of equal elements. + /// + /// The comparison function receives two key and value pairs to compare (you + /// can sort by keys or values or their combination as needed). + /// + /// Computes in **O(n log n + c)** time where *n* is + /// the length of the map and *c* is the capacity. The sort is unstable. + pub fn sort_unstable_by(&mut self, mut cmp: F) + where + F: FnMut(&K, &V, &K, &V) -> Ordering, + { + self.with_entries(move |entries| { + entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + }); + } + + /// Sort the key-value pairs of the map and return a by-value iterator of + /// the key-value pairs with the result. + /// + /// The sort is unstable. + #[inline] + pub fn sorted_unstable_by(self, mut cmp: F) -> IntoIter + where + F: FnMut(&K, &V, &K, &V) -> Ordering, + { + let mut entries = self.into_entries(); + entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + IntoIter::new(entries) + } + + /// Sort the map’s key-value pairs in place using a sort-key extraction function. + /// + /// During sorting, the function is called at most once per entry, by using temporary storage + /// to remember the results of its evaluation. The order of calls to the function is + /// unspecified and may change between versions of `indexmap` or the standard library. + /// + /// Computes in **O(m n + n log n + c)** time () and **O(n)** space, where the function is + /// **O(m)**, *n* is the length of the map, and *c* the capacity. The sort is stable. + pub fn sort_by_cached_key(&mut self, mut sort_key: F) + where + T: Ord, + F: FnMut(&K, &V) -> T, + { + self.with_entries(move |entries| { + entries.sort_by_cached_key(move |a| sort_key(&a.key, &a.value)); + }); + } + + /// Search over a sorted map for a key. + /// + /// Returns the position where that key is present, or the position where it can be inserted to + /// maintain the sort. See [`slice::binary_search`] for more details. + /// + /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up + /// using [`get_index_of`][IndexMap::get_index_of], but this can also position missing keys. + pub fn binary_search_keys(&self, x: &K) -> Result + where + K: Ord, + { + self.as_slice().binary_search_keys(x) + } + + /// Search over a sorted map with a comparator function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result + where + F: FnMut(&'a K, &'a V) -> Ordering, + { + self.as_slice().binary_search_by(f) + } + + /// Search over a sorted map with an extraction function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by_key`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result + where + F: FnMut(&'a K, &'a V) -> B, + B: Ord, + { + self.as_slice().binary_search_by_key(b, f) + } + + /// Returns the index of the partition point of a sorted map according to the given predicate + /// (the index of the first element of the second partition). + /// + /// See [`slice::partition_point`] for more details. + /// + /// Computes in **O(log(n))** time. + #[must_use] + pub fn partition_point

(&self, pred: P) -> usize + where + P: FnMut(&K, &V) -> bool, + { + self.as_slice().partition_point(pred) + } + + /// Reverses the order of the map’s key-value pairs in place. + /// + /// Computes in **O(n)** time and **O(1)** space. + pub fn reverse(&mut self) { + self.core.reverse() + } + + /// Returns a slice of all the key-value pairs in the map. + /// + /// Computes in **O(1)** time. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.as_entries()) + } + + /// Returns a mutable slice of all the key-value pairs in the map. + /// + /// Computes in **O(1)** time. + pub fn as_mut_slice(&mut self) -> &mut Slice { + Slice::from_mut_slice(self.as_entries_mut()) + } + + /// Converts into a boxed slice of all the key-value pairs in the map. + /// + /// Note that this will drop the inner hash table and any excess capacity. + pub fn into_boxed_slice(self) -> Box> { + Slice::from_boxed(self.into_entries().into_boxed_slice()) + } + + /// Get a key-value pair by index + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + pub fn get_index(&self, index: usize) -> Option<(&K, &V)> { + self.as_entries().get(index).map(Bucket::refs) + } + + /// Get a key-value pair by index + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> { + self.as_entries_mut().get_mut(index).map(Bucket::ref_mut) + } + + /// Get an entry in the map by index for in-place manipulation. + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + pub fn get_index_entry(&mut self, index: usize) -> Option> { + if index >= self.len() { + return None; + } + Some(IndexedEntry::new(&mut self.core, index)) + } + + /// Returns a slice of key-value pairs in the given range of indices. + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + pub fn get_range>(&self, range: R) -> Option<&Slice> { + let entries = self.as_entries(); + let range = try_simplify_range(range, entries.len())?; + entries.get(range).map(Slice::from_slice) + } + + /// Returns a mutable slice of key-value pairs in the given range of indices. + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + pub fn get_range_mut>(&mut self, range: R) -> Option<&mut Slice> { + let entries = self.as_entries_mut(); + let range = try_simplify_range(range, entries.len())?; + entries.get_mut(range).map(Slice::from_mut_slice) + } + + /// Get the first key-value pair + /// + /// Computes in **O(1)** time. + #[doc(alias = "first_key_value")] // like `BTreeMap` + pub fn first(&self) -> Option<(&K, &V)> { + self.as_entries().first().map(Bucket::refs) + } + + /// Get the first key-value pair, with mutable access to the value + /// + /// Computes in **O(1)** time. + pub fn first_mut(&mut self) -> Option<(&K, &mut V)> { + self.as_entries_mut().first_mut().map(Bucket::ref_mut) + } + + /// Get the first entry in the map for in-place manipulation. + /// + /// Computes in **O(1)** time. + pub fn first_entry(&mut self) -> Option> { + self.get_index_entry(0) + } + + /// Get the last key-value pair + /// + /// Computes in **O(1)** time. + #[doc(alias = "last_key_value")] // like `BTreeMap` + pub fn last(&self) -> Option<(&K, &V)> { + self.as_entries().last().map(Bucket::refs) + } + + /// Get the last key-value pair, with mutable access to the value + /// + /// Computes in **O(1)** time. + pub fn last_mut(&mut self) -> Option<(&K, &mut V)> { + self.as_entries_mut().last_mut().map(Bucket::ref_mut) + } + + /// Get the last entry in the map for in-place manipulation. + /// + /// Computes in **O(1)** time. + pub fn last_entry(&mut self) -> Option> { + self.get_index_entry(self.len().checked_sub(1)?) + } + + /// Remove the key-value pair by index + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the + /// last element of the map and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> { + self.core.swap_remove_index(index) + } + + /// Remove the key-value pair by index + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Like [`Vec::remove`], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove_index(&mut self, index: usize) -> Option<(K, V)> { + self.core.shift_remove_index(index) + } + + /// Moves the position of a key-value pair from one index to another + /// by shifting all other pairs in-between. + /// + /// * If `from < to`, the other pairs will shift down while the targeted pair moves up. + /// * If `from > to`, the other pairs will shift up while the targeted pair moves down. + /// + /// ***Panics*** if `from` or `to` are out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn move_index(&mut self, from: usize, to: usize) { + self.core.move_index(from, to) + } + + /// Swaps the position of two key-value pairs in the map. + /// + /// ***Panics*** if `a` or `b` are out of bounds. + /// + /// Computes in **O(1)** time (average). + pub fn swap_indices(&mut self, a: usize, b: usize) { + self.core.swap_indices(a, b) + } +} + +/// Access [`IndexMap`] values corresponding to a key. +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// for word in "Lorem ipsum dolor sit amet".split_whitespace() { +/// map.insert(word.to_lowercase(), word.to_uppercase()); +/// } +/// assert_eq!(map["lorem"], "LOREM"); +/// assert_eq!(map["ipsum"], "IPSUM"); +/// ``` +/// +/// ```should_panic +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// map.insert("foo", 1); +/// println!("{:?}", map["bar"]); // panics! +/// ``` +impl Index<&Q> for IndexMap +where + Q: Hash + Equivalent, + S: BuildHasher, +{ + type Output = V; + + /// Returns a reference to the value corresponding to the supplied `key`. + /// + /// ***Panics*** if `key` is not present in the map. + fn index(&self, key: &Q) -> &V { + self.get(key).expect("IndexMap: key not found") + } +} + +/// Access [`IndexMap`] values corresponding to a key. +/// +/// Mutable indexing allows changing / updating values of key-value +/// pairs that are already present. +/// +/// You can **not** insert new pairs with index syntax, use `.insert()`. +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// for word in "Lorem ipsum dolor sit amet".split_whitespace() { +/// map.insert(word.to_lowercase(), word.to_string()); +/// } +/// let lorem = &mut map["lorem"]; +/// assert_eq!(lorem, "Lorem"); +/// lorem.retain(char::is_lowercase); +/// assert_eq!(map["lorem"], "orem"); +/// ``` +/// +/// ```should_panic +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// map.insert("foo", 1); +/// map["bar"] = 1; // panics! +/// ``` +impl IndexMut<&Q> for IndexMap +where + Q: Hash + Equivalent, + S: BuildHasher, +{ + /// Returns a mutable reference to the value corresponding to the supplied `key`. + /// + /// ***Panics*** if `key` is not present in the map. + fn index_mut(&mut self, key: &Q) -> &mut V { + self.get_mut(key).expect("IndexMap: key not found") + } +} + +/// Access [`IndexMap`] values at indexed positions. +/// +/// See [`Index for Keys`][keys] to access a map's keys instead. +/// +/// [keys]: Keys#impl-Index-for-Keys<'a,+K,+V> +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// for word in "Lorem ipsum dolor sit amet".split_whitespace() { +/// map.insert(word.to_lowercase(), word.to_uppercase()); +/// } +/// assert_eq!(map[0], "LOREM"); +/// assert_eq!(map[1], "IPSUM"); +/// map.reverse(); +/// assert_eq!(map[0], "AMET"); +/// assert_eq!(map[1], "SIT"); +/// map.sort_keys(); +/// assert_eq!(map[0], "AMET"); +/// assert_eq!(map[1], "DOLOR"); +/// ``` +/// +/// ```should_panic +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// map.insert("foo", 1); +/// println!("{:?}", map[10]); // panics! +/// ``` +impl Index for IndexMap { + type Output = V; + + /// Returns a reference to the value at the supplied `index`. + /// + /// ***Panics*** if `index` is out of bounds. + fn index(&self, index: usize) -> &V { + self.get_index(index) + .expect("IndexMap: index out of bounds") + .1 + } +} + +/// Access [`IndexMap`] values at indexed positions. +/// +/// Mutable indexing allows changing / updating indexed values +/// that are already present. +/// +/// You can **not** insert new values with index syntax -- use [`.insert()`][IndexMap::insert]. +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// for word in "Lorem ipsum dolor sit amet".split_whitespace() { +/// map.insert(word.to_lowercase(), word.to_string()); +/// } +/// let lorem = &mut map[0]; +/// assert_eq!(lorem, "Lorem"); +/// lorem.retain(char::is_lowercase); +/// assert_eq!(map["lorem"], "orem"); +/// ``` +/// +/// ```should_panic +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// map.insert("foo", 1); +/// map[10] = 1; // panics! +/// ``` +impl IndexMut for IndexMap { + /// Returns a mutable reference to the value at the supplied `index`. + /// + /// ***Panics*** if `index` is out of bounds. + fn index_mut(&mut self, index: usize) -> &mut V { + self.get_index_mut(index) + .expect("IndexMap: index out of bounds") + .1 + } +} + +impl FromIterator<(K, V)> for IndexMap +where + K: Hash + Eq, + S: BuildHasher + Default, +{ + /// Create an `IndexMap` from the sequence of key-value pairs in the + /// iterable. + /// + /// `from_iter` uses the same logic as `extend`. See + /// [`extend`][IndexMap::extend] for more details. + fn from_iter>(iterable: I) -> Self { + let iter = iterable.into_iter(); + let (low, _) = iter.size_hint(); + let mut map = Self::with_capacity_and_hasher(low, <_>::default()); + map.extend(iter); + map + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl From<[(K, V); N]> for IndexMap +where + K: Hash + Eq, +{ + /// # Examples + /// + /// ``` + /// use indexmap::IndexMap; + /// + /// let map1 = IndexMap::from([(1, 2), (3, 4)]); + /// let map2: IndexMap<_, _> = [(1, 2), (3, 4)].into(); + /// assert_eq!(map1, map2); + /// ``` + fn from(arr: [(K, V); N]) -> Self { + Self::from_iter(arr) + } +} + +impl Extend<(K, V)> for IndexMap +where + K: Hash + Eq, + S: BuildHasher, +{ + /// Extend the map with all key-value pairs in the iterable. + /// + /// This is equivalent to calling [`insert`][IndexMap::insert] for each of + /// them in order, which means that for keys that already existed + /// in the map, their value is updated but it keeps the existing order. + /// + /// New keys are inserted in the order they appear in the sequence. If + /// equivalents of a key occur more than once, the last corresponding value + /// prevails. + fn extend>(&mut self, iterable: I) { + // (Note: this is a copy of `std`/`hashbrown`'s reservation logic.) + // Keys may be already present or show multiple times in the iterator. + // Reserve the entire hint lower bound if the map is empty. + // Otherwise reserve half the hint (rounded up), so the map + // will only resize twice in the worst case. + let iter = iterable.into_iter(); + let reserve = if self.is_empty() { + iter.size_hint().0 + } else { + (iter.size_hint().0 + 1) / 2 + }; + self.reserve(reserve); + iter.for_each(move |(k, v)| { + self.insert(k, v); + }); + } +} + +impl<'a, K, V, S> Extend<(&'a K, &'a V)> for IndexMap +where + K: Hash + Eq + Copy, + V: Copy, + S: BuildHasher, +{ + /// Extend the map with all key-value pairs in the iterable. + /// + /// See the first extend method for more details. + fn extend>(&mut self, iterable: I) { + self.extend(iterable.into_iter().map(|(&key, &value)| (key, value))); + } +} + +impl Default for IndexMap +where + S: Default, +{ + /// Return an empty [`IndexMap`] + fn default() -> Self { + Self::with_capacity_and_hasher(0, S::default()) + } +} + +impl PartialEq> for IndexMap +where + K: Hash + Eq, + V1: PartialEq, + S1: BuildHasher, + S2: BuildHasher, +{ + fn eq(&self, other: &IndexMap) -> bool { + if self.len() != other.len() { + return false; + } + + self.iter() + .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v)) + } +} + +impl Eq for IndexMap +where + K: Eq + Hash, + V: Eq, + S: BuildHasher, +{ +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/core.rs b/bitbox02-bt/vendor/indexmap/src/map/core.rs new file mode 100644 index 0000000..f42cccb --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/core.rs @@ -0,0 +1,718 @@ +//! This is the core implementation that doesn't depend on the hasher at all. +//! +//! The methods of `IndexMapCore` don't use any Hash properties of K. +//! +//! It's cleaner to separate them out, then the compiler checks that we are not +//! using Hash at all in these methods. +//! +//! However, we should probably not let this show in the public API or docs. + +mod entry; + +pub mod raw_entry_v1; + +use hashbrown::hash_table; + +use crate::vec::{self, Vec}; +use crate::TryReserveError; +use core::mem; +use core::ops::RangeBounds; + +use crate::util::simplify_range; +use crate::{Bucket, Equivalent, HashValue}; + +type Indices = hash_table::HashTable; +type Entries = Vec>; + +pub use entry::{Entry, IndexedEntry, OccupiedEntry, VacantEntry}; + +/// Core of the map that does not depend on S +#[derive(Debug)] +pub(crate) struct IndexMapCore { + /// indices mapping from the entry hash to its index. + indices: Indices, + /// entries is a dense vec maintaining entry order. + entries: Entries, +} + +/// Mutable references to the parts of an `IndexMapCore`. +/// +/// When using `HashTable::find_entry`, that takes hold of `&mut indices`, so we have to borrow our +/// `&mut entries` separately, and there's no way to go back to a `&mut IndexMapCore`. So this type +/// is used to implement methods on the split references, and `IndexMapCore` can also call those to +/// avoid duplication. +struct RefMut<'a, K, V> { + indices: &'a mut Indices, + entries: &'a mut Entries, +} + +#[inline(always)] +fn get_hash(entries: &[Bucket]) -> impl Fn(&usize) -> u64 + '_ { + move |&i| entries[i].hash.get() +} + +#[inline] +fn equivalent<'a, K, V, Q: ?Sized + Equivalent>( + key: &'a Q, + entries: &'a [Bucket], +) -> impl Fn(&usize) -> bool + 'a { + move |&i| Q::equivalent(key, &entries[i].key) +} + +#[inline] +fn erase_index(table: &mut Indices, hash: HashValue, index: usize) { + if let Ok(entry) = table.find_entry(hash.get(), move |&i| i == index) { + entry.remove(); + } else if cfg!(debug_assertions) { + panic!("index not found"); + } +} + +#[inline] +fn update_index(table: &mut Indices, hash: HashValue, old: usize, new: usize) { + let index = table + .find_mut(hash.get(), move |&i| i == old) + .expect("index not found"); + *index = new; +} + +/// Inserts many entries into the indices table without reallocating, +/// and without regard for duplication. +/// +/// ***Panics*** if there is not sufficient capacity already. +fn insert_bulk_no_grow(indices: &mut Indices, entries: &[Bucket]) { + assert!(indices.capacity() - indices.len() >= entries.len()); + for entry in entries { + indices.insert_unique(entry.hash.get(), indices.len(), |_| unreachable!()); + } +} + +impl Clone for IndexMapCore +where + K: Clone, + V: Clone, +{ + fn clone(&self) -> Self { + let mut new = Self::new(); + new.clone_from(self); + new + } + + fn clone_from(&mut self, other: &Self) { + self.indices.clone_from(&other.indices); + if self.entries.capacity() < other.entries.len() { + // If we must resize, match the indices capacity. + let additional = other.entries.len() - self.entries.len(); + self.borrow_mut().reserve_entries(additional); + } + self.entries.clone_from(&other.entries); + } +} + +impl crate::Entries for IndexMapCore { + type Entry = Bucket; + + #[inline] + fn into_entries(self) -> Vec { + self.entries + } + + #[inline] + fn as_entries(&self) -> &[Self::Entry] { + &self.entries + } + + #[inline] + fn as_entries_mut(&mut self) -> &mut [Self::Entry] { + &mut self.entries + } + + fn with_entries(&mut self, f: F) + where + F: FnOnce(&mut [Self::Entry]), + { + f(&mut self.entries); + self.rebuild_hash_table(); + } +} + +impl IndexMapCore { + /// The maximum capacity before the `entries` allocation would exceed `isize::MAX`. + const MAX_ENTRIES_CAPACITY: usize = (isize::MAX as usize) / mem::size_of::>(); + + #[inline] + pub(crate) const fn new() -> Self { + IndexMapCore { + indices: Indices::new(), + entries: Vec::new(), + } + } + + #[inline] + fn borrow_mut(&mut self) -> RefMut<'_, K, V> { + RefMut::new(&mut self.indices, &mut self.entries) + } + + #[inline] + pub(crate) fn with_capacity(n: usize) -> Self { + IndexMapCore { + indices: Indices::with_capacity(n), + entries: Vec::with_capacity(n), + } + } + + #[inline] + pub(crate) fn len(&self) -> usize { + self.indices.len() + } + + #[inline] + pub(crate) fn capacity(&self) -> usize { + Ord::min(self.indices.capacity(), self.entries.capacity()) + } + + pub(crate) fn clear(&mut self) { + self.indices.clear(); + self.entries.clear(); + } + + pub(crate) fn truncate(&mut self, len: usize) { + if len < self.len() { + self.erase_indices(len, self.entries.len()); + self.entries.truncate(len); + } + } + + pub(crate) fn drain(&mut self, range: R) -> vec::Drain<'_, Bucket> + where + R: RangeBounds, + { + let range = simplify_range(range, self.entries.len()); + self.erase_indices(range.start, range.end); + self.entries.drain(range) + } + + #[cfg(feature = "rayon")] + pub(crate) fn par_drain(&mut self, range: R) -> rayon::vec::Drain<'_, Bucket> + where + K: Send, + V: Send, + R: RangeBounds, + { + use rayon::iter::ParallelDrainRange; + let range = simplify_range(range, self.entries.len()); + self.erase_indices(range.start, range.end); + self.entries.par_drain(range) + } + + pub(crate) fn split_off(&mut self, at: usize) -> Self { + assert!(at <= self.entries.len()); + self.erase_indices(at, self.entries.len()); + let entries = self.entries.split_off(at); + + let mut indices = Indices::with_capacity(entries.len()); + insert_bulk_no_grow(&mut indices, &entries); + Self { indices, entries } + } + + pub(crate) fn split_splice(&mut self, range: R) -> (Self, vec::IntoIter>) + where + R: RangeBounds, + { + let range = simplify_range(range, self.len()); + self.erase_indices(range.start, self.entries.len()); + let entries = self.entries.split_off(range.end); + let drained = self.entries.split_off(range.start); + + let mut indices = Indices::with_capacity(entries.len()); + insert_bulk_no_grow(&mut indices, &entries); + (Self { indices, entries }, drained.into_iter()) + } + + /// Append from another map without checking whether items already exist. + pub(crate) fn append_unchecked(&mut self, other: &mut Self) { + self.reserve(other.len()); + insert_bulk_no_grow(&mut self.indices, &other.entries); + self.entries.append(&mut other.entries); + other.indices.clear(); + } + + /// Reserve capacity for `additional` more key-value pairs. + pub(crate) fn reserve(&mut self, additional: usize) { + self.indices.reserve(additional, get_hash(&self.entries)); + // Only grow entries if necessary, since we also round up capacity. + if additional > self.entries.capacity() - self.entries.len() { + self.borrow_mut().reserve_entries(additional); + } + } + + /// Reserve capacity for `additional` more key-value pairs, without over-allocating. + pub(crate) fn reserve_exact(&mut self, additional: usize) { + self.indices.reserve(additional, get_hash(&self.entries)); + self.entries.reserve_exact(additional); + } + + /// Try to reserve capacity for `additional` more key-value pairs. + pub(crate) fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.indices + .try_reserve(additional, get_hash(&self.entries)) + .map_err(TryReserveError::from_hashbrown)?; + // Only grow entries if necessary, since we also round up capacity. + if additional > self.entries.capacity() - self.entries.len() { + self.try_reserve_entries(additional) + } else { + Ok(()) + } + } + + /// Try to reserve entries capacity, rounded up to match the indices + fn try_reserve_entries(&mut self, additional: usize) -> Result<(), TryReserveError> { + // Use a soft-limit on the maximum capacity, but if the caller explicitly + // requested more, do it and let them have the resulting error. + let new_capacity = Ord::min(self.indices.capacity(), Self::MAX_ENTRIES_CAPACITY); + let try_add = new_capacity - self.entries.len(); + if try_add > additional && self.entries.try_reserve_exact(try_add).is_ok() { + return Ok(()); + } + self.entries + .try_reserve_exact(additional) + .map_err(TryReserveError::from_alloc) + } + + /// Try to reserve capacity for `additional` more key-value pairs, without over-allocating. + pub(crate) fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.indices + .try_reserve(additional, get_hash(&self.entries)) + .map_err(TryReserveError::from_hashbrown)?; + self.entries + .try_reserve_exact(additional) + .map_err(TryReserveError::from_alloc) + } + + /// Shrink the capacity of the map with a lower bound + pub(crate) fn shrink_to(&mut self, min_capacity: usize) { + self.indices + .shrink_to(min_capacity, get_hash(&self.entries)); + self.entries.shrink_to(min_capacity); + } + + /// Remove the last key-value pair + pub(crate) fn pop(&mut self) -> Option<(K, V)> { + if let Some(entry) = self.entries.pop() { + let last = self.entries.len(); + erase_index(&mut self.indices, entry.hash, last); + Some((entry.key, entry.value)) + } else { + None + } + } + + /// Return the index in `entries` where an equivalent key can be found + pub(crate) fn get_index_of(&self, hash: HashValue, key: &Q) -> Option + where + Q: ?Sized + Equivalent, + { + let eq = equivalent(key, &self.entries); + self.indices.find(hash.get(), eq).copied() + } + + pub(crate) fn insert_full(&mut self, hash: HashValue, key: K, value: V) -> (usize, Option) + where + K: Eq, + { + let eq = equivalent(&key, &self.entries); + let hasher = get_hash(&self.entries); + match self.indices.entry(hash.get(), eq, hasher) { + hash_table::Entry::Occupied(entry) => { + let i = *entry.get(); + (i, Some(mem::replace(&mut self.entries[i].value, value))) + } + hash_table::Entry::Vacant(entry) => { + let i = self.entries.len(); + entry.insert(i); + self.borrow_mut().push_entry(hash, key, value); + debug_assert_eq!(self.indices.len(), self.entries.len()); + (i, None) + } + } + } + + /// Same as `insert_full`, except it also replaces the key + pub(crate) fn replace_full( + &mut self, + hash: HashValue, + key: K, + value: V, + ) -> (usize, Option<(K, V)>) + where + K: Eq, + { + let eq = equivalent(&key, &self.entries); + let hasher = get_hash(&self.entries); + match self.indices.entry(hash.get(), eq, hasher) { + hash_table::Entry::Occupied(entry) => { + let i = *entry.get(); + let entry = &mut self.entries[i]; + let kv = ( + mem::replace(&mut entry.key, key), + mem::replace(&mut entry.value, value), + ); + (i, Some(kv)) + } + hash_table::Entry::Vacant(entry) => { + let i = self.entries.len(); + entry.insert(i); + self.borrow_mut().push_entry(hash, key, value); + debug_assert_eq!(self.indices.len(), self.entries.len()); + (i, None) + } + } + } + + /// Remove an entry by shifting all entries that follow it + pub(crate) fn shift_remove_full(&mut self, hash: HashValue, key: &Q) -> Option<(usize, K, V)> + where + Q: ?Sized + Equivalent, + { + let eq = equivalent(key, &self.entries); + match self.indices.find_entry(hash.get(), eq) { + Ok(entry) => { + let (index, _) = entry.remove(); + let (key, value) = self.borrow_mut().shift_remove_finish(index); + Some((index, key, value)) + } + Err(_) => None, + } + } + + /// Remove an entry by shifting all entries that follow it + #[inline] + pub(crate) fn shift_remove_index(&mut self, index: usize) -> Option<(K, V)> { + self.borrow_mut().shift_remove_index(index) + } + + #[inline] + pub(super) fn move_index(&mut self, from: usize, to: usize) { + self.borrow_mut().move_index(from, to); + } + + #[inline] + pub(crate) fn swap_indices(&mut self, a: usize, b: usize) { + self.borrow_mut().swap_indices(a, b); + } + + /// Remove an entry by swapping it with the last + pub(crate) fn swap_remove_full(&mut self, hash: HashValue, key: &Q) -> Option<(usize, K, V)> + where + Q: ?Sized + Equivalent, + { + let eq = equivalent(key, &self.entries); + match self.indices.find_entry(hash.get(), eq) { + Ok(entry) => { + let (index, _) = entry.remove(); + let (key, value) = self.borrow_mut().swap_remove_finish(index); + Some((index, key, value)) + } + Err(_) => None, + } + } + + /// Remove an entry by swapping it with the last + #[inline] + pub(crate) fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> { + self.borrow_mut().swap_remove_index(index) + } + + /// Erase `start..end` from `indices`, and shift `end..` indices down to `start..` + /// + /// All of these items should still be at their original location in `entries`. + /// This is used by `drain`, which will let `Vec::drain` do the work on `entries`. + fn erase_indices(&mut self, start: usize, end: usize) { + let (init, shifted_entries) = self.entries.split_at(end); + let (start_entries, erased_entries) = init.split_at(start); + + let erased = erased_entries.len(); + let shifted = shifted_entries.len(); + let half_capacity = self.indices.capacity() / 2; + + // Use a heuristic between different strategies + if erased == 0 { + // Degenerate case, nothing to do + } else if start + shifted < half_capacity && start < erased { + // Reinsert everything, as there are few kept indices + self.indices.clear(); + + // Reinsert stable indices, then shifted indices + insert_bulk_no_grow(&mut self.indices, start_entries); + insert_bulk_no_grow(&mut self.indices, shifted_entries); + } else if erased + shifted < half_capacity { + // Find each affected index, as there are few to adjust + + // Find erased indices + for (i, entry) in (start..).zip(erased_entries) { + erase_index(&mut self.indices, entry.hash, i); + } + + // Find shifted indices + for ((new, old), entry) in (start..).zip(end..).zip(shifted_entries) { + update_index(&mut self.indices, entry.hash, old, new); + } + } else { + // Sweep the whole table for adjustments + let offset = end - start; + self.indices.retain(move |i| { + if *i >= end { + *i -= offset; + true + } else { + *i < start + } + }); + } + + debug_assert_eq!(self.indices.len(), start + shifted); + } + + pub(crate) fn retain_in_order(&mut self, mut keep: F) + where + F: FnMut(&mut K, &mut V) -> bool, + { + self.entries + .retain_mut(|entry| keep(&mut entry.key, &mut entry.value)); + if self.entries.len() < self.indices.len() { + self.rebuild_hash_table(); + } + } + + fn rebuild_hash_table(&mut self) { + self.indices.clear(); + insert_bulk_no_grow(&mut self.indices, &self.entries); + } + + pub(crate) fn reverse(&mut self) { + self.entries.reverse(); + + // No need to save hash indices, can easily calculate what they should + // be, given that this is an in-place reversal. + let len = self.entries.len(); + for i in &mut self.indices { + *i = len - *i - 1; + } + } +} + +impl<'a, K, V> RefMut<'a, K, V> { + #[inline] + fn new(indices: &'a mut Indices, entries: &'a mut Entries) -> Self { + Self { indices, entries } + } + + /// Reserve entries capacity, rounded up to match the indices + fn reserve_entries(&mut self, additional: usize) { + // Use a soft-limit on the maximum capacity, but if the caller explicitly + // requested more, do it and let them have the resulting panic. + let new_capacity = Ord::min( + self.indices.capacity(), + IndexMapCore::::MAX_ENTRIES_CAPACITY, + ); + let try_add = new_capacity - self.entries.len(); + if try_add > additional && self.entries.try_reserve_exact(try_add).is_ok() { + return; + } + self.entries.reserve_exact(additional); + } + + /// Append a key-value pair to `entries`, + /// *without* checking whether it already exists. + fn push_entry(&mut self, hash: HashValue, key: K, value: V) { + if self.entries.len() == self.entries.capacity() { + // Reserve our own capacity synced to the indices, + // rather than letting `Vec::push` just double it. + self.reserve_entries(1); + } + self.entries.push(Bucket { hash, key, value }); + } + + /// Insert a key-value pair in `entries` at a particular index, + /// *without* checking whether it already exists. + fn insert_entry(&mut self, index: usize, hash: HashValue, key: K, value: V) { + if self.entries.len() == self.entries.capacity() { + // Reserve our own capacity synced to the indices, + // rather than letting `Vec::insert` just double it. + self.reserve_entries(1); + } + self.entries.insert(index, Bucket { hash, key, value }); + } + + fn insert_unique(&mut self, hash: HashValue, key: K, value: V) -> usize { + let i = self.indices.len(); + self.indices + .insert_unique(hash.get(), i, get_hash(self.entries)); + debug_assert_eq!(i, self.entries.len()); + self.push_entry(hash, key, value); + i + } + + fn shift_insert_unique(&mut self, index: usize, hash: HashValue, key: K, value: V) { + let end = self.indices.len(); + assert!(index <= end); + // Increment others first so we don't have duplicate indices. + self.increment_indices(index, end); + let entries = &*self.entries; + self.indices.insert_unique(hash.get(), index, move |&i| { + // Adjust for the incremented indices to find hashes. + debug_assert_ne!(i, index); + let i = if i < index { i } else { i - 1 }; + entries[i].hash.get() + }); + self.insert_entry(index, hash, key, value); + } + + /// Remove an entry by shifting all entries that follow it + fn shift_remove_index(&mut self, index: usize) -> Option<(K, V)> { + match self.entries.get(index) { + Some(entry) => { + erase_index(self.indices, entry.hash, index); + Some(self.shift_remove_finish(index)) + } + None => None, + } + } + + /// Remove an entry by shifting all entries that follow it + /// + /// The index should already be removed from `self.indices`. + fn shift_remove_finish(&mut self, index: usize) -> (K, V) { + // Correct indices that point to the entries that followed the removed entry. + self.decrement_indices(index + 1, self.entries.len()); + + // Use Vec::remove to actually remove the entry. + let entry = self.entries.remove(index); + (entry.key, entry.value) + } + + /// Remove an entry by swapping it with the last + fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> { + match self.entries.get(index) { + Some(entry) => { + erase_index(self.indices, entry.hash, index); + Some(self.swap_remove_finish(index)) + } + None => None, + } + } + + /// Finish removing an entry by swapping it with the last + /// + /// The index should already be removed from `self.indices`. + fn swap_remove_finish(&mut self, index: usize) -> (K, V) { + // use swap_remove, but then we need to update the index that points + // to the other entry that has to move + let entry = self.entries.swap_remove(index); + + // correct index that points to the entry that had to swap places + if let Some(entry) = self.entries.get(index) { + // was not last element + // examine new element in `index` and find it in indices + let last = self.entries.len(); + update_index(self.indices, entry.hash, last, index); + } + + (entry.key, entry.value) + } + + /// Decrement all indices in the range `start..end`. + /// + /// The index `start - 1` should not exist in `self.indices`. + /// All entries should still be in their original positions. + fn decrement_indices(&mut self, start: usize, end: usize) { + // Use a heuristic between a full sweep vs. a `find()` for every shifted item. + let shifted_entries = &self.entries[start..end]; + if shifted_entries.len() > self.indices.capacity() / 2 { + // Shift all indices in range. + for i in &mut *self.indices { + if start <= *i && *i < end { + *i -= 1; + } + } + } else { + // Find each entry in range to shift its index. + for (i, entry) in (start..end).zip(shifted_entries) { + update_index(self.indices, entry.hash, i, i - 1); + } + } + } + + /// Increment all indices in the range `start..end`. + /// + /// The index `end` should not exist in `self.indices`. + /// All entries should still be in their original positions. + fn increment_indices(&mut self, start: usize, end: usize) { + // Use a heuristic between a full sweep vs. a `find()` for every shifted item. + let shifted_entries = &self.entries[start..end]; + if shifted_entries.len() > self.indices.capacity() / 2 { + // Shift all indices in range. + for i in &mut *self.indices { + if start <= *i && *i < end { + *i += 1; + } + } + } else { + // Find each entry in range to shift its index, updated in reverse so + // we never have duplicated indices that might have a hash collision. + for (i, entry) in (start..end).zip(shifted_entries).rev() { + update_index(self.indices, entry.hash, i, i + 1); + } + } + } + + fn move_index(&mut self, from: usize, to: usize) { + let from_hash = self.entries[from].hash; + let _ = self.entries[to]; // explicit bounds check + if from != to { + // Use a sentinel index so other indices don't collide. + update_index(self.indices, from_hash, from, usize::MAX); + + // Update all other indices and rotate the entry positions. + if from < to { + self.decrement_indices(from + 1, to + 1); + self.entries[from..=to].rotate_left(1); + } else if to < from { + self.increment_indices(to, from); + self.entries[to..=from].rotate_right(1); + } + + // Change the sentinel index to its final position. + update_index(self.indices, from_hash, usize::MAX, to); + } + } + + fn swap_indices(&mut self, a: usize, b: usize) { + // If they're equal and in-bounds, there's nothing to do. + if a == b && a < self.entries.len() { + return; + } + + // We'll get a "nice" bounds-check from indexing `entries`, + // and then we expect to find it in the table as well. + match self.indices.get_many_mut( + [self.entries[a].hash.get(), self.entries[b].hash.get()], + move |i, &x| if i == 0 { x == a } else { x == b }, + ) { + [Some(ref_a), Some(ref_b)] => { + mem::swap(ref_a, ref_b); + self.entries.swap(a, b); + } + _ => panic!("indices not found"), + } + } +} + +#[test] +fn assert_send_sync() { + fn assert_send_sync() {} + assert_send_sync::>(); + assert_send_sync::>(); + assert_send_sync::>(); + assert_send_sync::>(); +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/core/entry.rs b/bitbox02-bt/vendor/indexmap/src/map/core/entry.rs new file mode 100644 index 0000000..f8a8136 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/core/entry.rs @@ -0,0 +1,535 @@ +use super::{equivalent, Entries, IndexMapCore, RefMut}; +use crate::HashValue; +use core::{fmt, mem}; +use hashbrown::hash_table; + +impl IndexMapCore { + pub(crate) fn entry(&mut self, hash: HashValue, key: K) -> Entry<'_, K, V> + where + K: Eq, + { + let entries = &mut self.entries; + let eq = equivalent(&key, entries); + match self.indices.find_entry(hash.get(), eq) { + Ok(index) => Entry::Occupied(OccupiedEntry { entries, index }), + Err(absent) => Entry::Vacant(VacantEntry { + map: RefMut::new(absent.into_table(), entries), + hash, + key, + }), + } + } +} + +/// Entry for an existing key-value pair in an [`IndexMap`][crate::IndexMap] +/// or a vacant location to insert one. +pub enum Entry<'a, K, V> { + /// Existing slot with equivalent key. + Occupied(OccupiedEntry<'a, K, V>), + /// Vacant slot (no equivalent key in the map). + Vacant(VacantEntry<'a, K, V>), +} + +impl<'a, K, V> Entry<'a, K, V> { + /// Return the index where the key-value pair exists or will be inserted. + pub fn index(&self) -> usize { + match *self { + Entry::Occupied(ref entry) => entry.index(), + Entry::Vacant(ref entry) => entry.index(), + } + } + + /// Inserts the given default value in the entry if it is vacant and returns a mutable + /// reference to it. Otherwise a mutable reference to an already existent value is returned. + /// + /// Computes in **O(1)** time (amortized average). + pub fn or_insert(self, default: V) -> &'a mut V { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => entry.insert(default), + } + } + + /// Inserts the result of the `call` function in the entry if it is vacant and returns a mutable + /// reference to it. Otherwise a mutable reference to an already existent value is returned. + /// + /// Computes in **O(1)** time (amortized average). + pub fn or_insert_with(self, call: F) -> &'a mut V + where + F: FnOnce() -> V, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => entry.insert(call()), + } + } + + /// Inserts the result of the `call` function with a reference to the entry's key if it is + /// vacant, and returns a mutable reference to the new value. Otherwise a mutable reference to + /// an already existent value is returned. + /// + /// Computes in **O(1)** time (amortized average). + pub fn or_insert_with_key(self, call: F) -> &'a mut V + where + F: FnOnce(&K) -> V, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + let value = call(&entry.key); + entry.insert(value) + } + } + } + + /// Gets a reference to the entry's key, either within the map if occupied, + /// or else the new key that was used to find the entry. + pub fn key(&self) -> &K { + match *self { + Entry::Occupied(ref entry) => entry.key(), + Entry::Vacant(ref entry) => entry.key(), + } + } + + /// Modifies the entry if it is occupied. + pub fn and_modify(mut self, f: F) -> Self + where + F: FnOnce(&mut V), + { + if let Entry::Occupied(entry) = &mut self { + f(entry.get_mut()); + } + self + } + + /// Inserts a default-constructed value in the entry if it is vacant and returns a mutable + /// reference to it. Otherwise a mutable reference to an already existent value is returned. + /// + /// Computes in **O(1)** time (amortized average). + pub fn or_default(self) -> &'a mut V + where + V: Default, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => entry.insert(V::default()), + } + } +} + +impl fmt::Debug for Entry<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut tuple = f.debug_tuple("Entry"); + match self { + Entry::Vacant(v) => tuple.field(v), + Entry::Occupied(o) => tuple.field(o), + }; + tuple.finish() + } +} + +/// A view into an occupied entry in an [`IndexMap`][crate::IndexMap]. +/// It is part of the [`Entry`] enum. +pub struct OccupiedEntry<'a, K, V> { + entries: &'a mut Entries, + index: hash_table::OccupiedEntry<'a, usize>, +} + +impl<'a, K, V> OccupiedEntry<'a, K, V> { + /// Return the index of the key-value pair + #[inline] + pub fn index(&self) -> usize { + *self.index.get() + } + + #[inline] + fn into_ref_mut(self) -> RefMut<'a, K, V> { + RefMut::new(self.index.into_table(), self.entries) + } + + /// Gets a reference to the entry's key in the map. + /// + /// Note that this is not the key that was used to find the entry. There may be an observable + /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like + /// extra fields or the memory address of an allocation. + pub fn key(&self) -> &K { + &self.entries[self.index()].key + } + + pub(crate) fn key_mut(&mut self) -> &mut K { + let index = self.index(); + &mut self.entries[index].key + } + + /// Gets a reference to the entry's value in the map. + pub fn get(&self) -> &V { + &self.entries[self.index()].value + } + + /// Gets a mutable reference to the entry's value in the map. + /// + /// If you need a reference which may outlive the destruction of the + /// [`Entry`] value, see [`into_mut`][Self::into_mut]. + pub fn get_mut(&mut self) -> &mut V { + let index = self.index(); + &mut self.entries[index].value + } + + /// Converts into a mutable reference to the entry's value in the map, + /// with a lifetime bound to the map itself. + pub fn into_mut(self) -> &'a mut V { + let index = self.index(); + &mut self.entries[index].value + } + + /// Sets the value of the entry to `value`, and returns the entry's old value. + pub fn insert(&mut self, value: V) -> V { + mem::replace(self.get_mut(), value) + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// **NOTE:** This is equivalent to [`.swap_remove()`][Self::swap_remove], replacing this + /// entry's position with the last element, and it is deprecated in favor of calling that + /// explicitly. If you need to preserve the relative order of the keys in the map, use + /// [`.shift_remove()`][Self::shift_remove] instead. + #[deprecated(note = "`remove` disrupts the map order -- \ + use `swap_remove` or `shift_remove` for explicit behavior.")] + pub fn remove(self) -> V { + self.swap_remove() + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// Like [`Vec::swap_remove`][crate::Vec::swap_remove], the pair is removed by swapping it with + /// the last element of the map and popping it off. + /// **This perturbs the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove(self) -> V { + self.swap_remove_entry().1 + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// Like [`Vec::remove`][crate::Vec::remove], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove(self) -> V { + self.shift_remove_entry().1 + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// **NOTE:** This is equivalent to [`.swap_remove_entry()`][Self::swap_remove_entry], + /// replacing this entry's position with the last element, and it is deprecated in favor of + /// calling that explicitly. If you need to preserve the relative order of the keys in the map, + /// use [`.shift_remove_entry()`][Self::shift_remove_entry] instead. + #[deprecated(note = "`remove_entry` disrupts the map order -- \ + use `swap_remove_entry` or `shift_remove_entry` for explicit behavior.")] + pub fn remove_entry(self) -> (K, V) { + self.swap_remove_entry() + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// Like [`Vec::swap_remove`][crate::Vec::swap_remove], the pair is removed by swapping it with + /// the last element of the map and popping it off. + /// **This perturbs the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove_entry(self) -> (K, V) { + let (index, entry) = self.index.remove(); + RefMut::new(entry.into_table(), self.entries).swap_remove_finish(index) + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// Like [`Vec::remove`][crate::Vec::remove], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove_entry(self) -> (K, V) { + let (index, entry) = self.index.remove(); + RefMut::new(entry.into_table(), self.entries).shift_remove_finish(index) + } + + /// Moves the position of the entry to a new index + /// by shifting all other entries in-between. + /// + /// This is equivalent to [`IndexMap::move_index`][`crate::IndexMap::move_index`] + /// coming `from` the current [`.index()`][Self::index]. + /// + /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up. + /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down. + /// + /// ***Panics*** if `to` is out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn move_index(self, to: usize) { + let index = self.index(); + self.into_ref_mut().move_index(index, to); + } + + /// Swaps the position of entry with another. + /// + /// This is equivalent to [`IndexMap::swap_indices`][`crate::IndexMap::swap_indices`] + /// with the current [`.index()`][Self::index] as one of the two being swapped. + /// + /// ***Panics*** if the `other` index is out of bounds. + /// + /// Computes in **O(1)** time (average). + pub fn swap_indices(self, other: usize) { + let index = self.index(); + self.into_ref_mut().swap_indices(index, other); + } +} + +impl fmt::Debug for OccupiedEntry<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OccupiedEntry") + .field("key", self.key()) + .field("value", self.get()) + .finish() + } +} + +impl<'a, K, V> From> for OccupiedEntry<'a, K, V> { + fn from(other: IndexedEntry<'a, K, V>) -> Self { + let IndexedEntry { + map: RefMut { indices, entries }, + index, + } = other; + let hash = entries[index].hash; + Self { + entries, + index: indices + .find_entry(hash.get(), move |&i| i == index) + .expect("index not found"), + } + } +} + +/// A view into a vacant entry in an [`IndexMap`][crate::IndexMap]. +/// It is part of the [`Entry`] enum. +pub struct VacantEntry<'a, K, V> { + map: RefMut<'a, K, V>, + hash: HashValue, + key: K, +} + +impl<'a, K, V> VacantEntry<'a, K, V> { + /// Return the index where a key-value pair may be inserted. + pub fn index(&self) -> usize { + self.map.indices.len() + } + + /// Gets a reference to the key that was used to find the entry. + pub fn key(&self) -> &K { + &self.key + } + + pub(crate) fn key_mut(&mut self) -> &mut K { + &mut self.key + } + + /// Takes ownership of the key, leaving the entry vacant. + pub fn into_key(self) -> K { + self.key + } + + /// Inserts the entry's key and the given value into the map, and returns a mutable reference + /// to the value. + pub fn insert(mut self, value: V) -> &'a mut V { + let i = self.map.insert_unique(self.hash, self.key, value); + &mut self.map.entries[i].value + } + + /// Inserts the entry's key and the given value into the map at its ordered + /// position among sorted keys, and returns the new index and a mutable + /// reference to the value. + /// + /// If the existing keys are **not** already sorted, then the insertion + /// index is unspecified (like [`slice::binary_search`]), but the key-value + /// pair is inserted at that position regardless. + /// + /// Computes in **O(n)** time (average). + pub fn insert_sorted(self, value: V) -> (usize, &'a mut V) + where + K: Ord, + { + let slice = crate::map::Slice::from_slice(self.map.entries); + let i = slice.binary_search_keys(&self.key).unwrap_err(); + (i, self.shift_insert(i, value)) + } + + /// Inserts the entry's key and the given value into the map at the given index, + /// shifting others to the right, and returns a mutable reference to the value. + /// + /// ***Panics*** if `index` is out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn shift_insert(mut self, index: usize, value: V) -> &'a mut V { + self.map + .shift_insert_unique(index, self.hash, self.key, value); + &mut self.map.entries[index].value + } +} + +impl fmt::Debug for VacantEntry<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("VacantEntry").field(self.key()).finish() + } +} + +/// A view into an occupied entry in an [`IndexMap`][crate::IndexMap] obtained by index. +/// +/// This `struct` is created from the [`get_index_entry`][crate::IndexMap::get_index_entry] method. +pub struct IndexedEntry<'a, K, V> { + map: RefMut<'a, K, V>, + // We have a mutable reference to the map, which keeps the index + // valid and pointing to the correct entry. + index: usize, +} + +impl<'a, K, V> IndexedEntry<'a, K, V> { + pub(crate) fn new(map: &'a mut IndexMapCore, index: usize) -> Self { + Self { + map: map.borrow_mut(), + index, + } + } + + /// Return the index of the key-value pair + #[inline] + pub fn index(&self) -> usize { + self.index + } + + /// Gets a reference to the entry's key in the map. + pub fn key(&self) -> &K { + &self.map.entries[self.index].key + } + + pub(crate) fn key_mut(&mut self) -> &mut K { + &mut self.map.entries[self.index].key + } + + /// Gets a reference to the entry's value in the map. + pub fn get(&self) -> &V { + &self.map.entries[self.index].value + } + + /// Gets a mutable reference to the entry's value in the map. + /// + /// If you need a reference which may outlive the destruction of the + /// `IndexedEntry` value, see [`into_mut`][Self::into_mut]. + pub fn get_mut(&mut self) -> &mut V { + &mut self.map.entries[self.index].value + } + + /// Sets the value of the entry to `value`, and returns the entry's old value. + pub fn insert(&mut self, value: V) -> V { + mem::replace(self.get_mut(), value) + } + + /// Converts into a mutable reference to the entry's value in the map, + /// with a lifetime bound to the map itself. + pub fn into_mut(self) -> &'a mut V { + &mut self.map.entries[self.index].value + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// Like [`Vec::swap_remove`][crate::Vec::swap_remove], the pair is removed by swapping it with + /// the last element of the map and popping it off. + /// **This perturbs the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove_entry(mut self) -> (K, V) { + self.map.swap_remove_index(self.index).unwrap() + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// Like [`Vec::remove`][crate::Vec::remove], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove_entry(mut self) -> (K, V) { + self.map.shift_remove_index(self.index).unwrap() + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// Like [`Vec::swap_remove`][crate::Vec::swap_remove], the pair is removed by swapping it with + /// the last element of the map and popping it off. + /// **This perturbs the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove(self) -> V { + self.swap_remove_entry().1 + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// Like [`Vec::remove`][crate::Vec::remove], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove(self) -> V { + self.shift_remove_entry().1 + } + + /// Moves the position of the entry to a new index + /// by shifting all other entries in-between. + /// + /// This is equivalent to [`IndexMap::move_index`][`crate::IndexMap::move_index`] + /// coming `from` the current [`.index()`][Self::index]. + /// + /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up. + /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down. + /// + /// ***Panics*** if `to` is out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn move_index(mut self, to: usize) { + self.map.move_index(self.index, to); + } + + /// Swaps the position of entry with another. + /// + /// This is equivalent to [`IndexMap::swap_indices`][`crate::IndexMap::swap_indices`] + /// with the current [`.index()`][Self::index] as one of the two being swapped. + /// + /// ***Panics*** if the `other` index is out of bounds. + /// + /// Computes in **O(1)** time (average). + pub fn swap_indices(mut self, other: usize) { + self.map.swap_indices(self.index, other); + } +} + +impl fmt::Debug for IndexedEntry<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("IndexedEntry") + .field("index", &self.index) + .field("key", self.key()) + .field("value", self.get()) + .finish() + } +} + +impl<'a, K, V> From> for IndexedEntry<'a, K, V> { + fn from(other: OccupiedEntry<'a, K, V>) -> Self { + Self { + index: other.index(), + map: other.into_ref_mut(), + } + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/core/raw_entry_v1.rs b/bitbox02-bt/vendor/indexmap/src/map/core/raw_entry_v1.rs new file mode 100644 index 0000000..5d73469 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/core/raw_entry_v1.rs @@ -0,0 +1,666 @@ +//! Opt-in access to the experimental raw entry API. +//! +//! This module is designed to mimic the raw entry API of [`HashMap`][std::collections::hash_map], +//! matching its unstable state as of Rust 1.75. See the tracking issue +//! [rust#56167](https://github.com/rust-lang/rust/issues/56167) for more details. +//! +//! The trait [`RawEntryApiV1`] and the `_v1` suffix on its methods are meant to insulate this for +//! the future, in case later breaking changes are needed. If the standard library stabilizes its +//! `hash_raw_entry` feature (or some replacement), matching *inherent* methods will be added to +//! `IndexMap` without such an opt-in trait. + +use super::{Entries, RefMut}; +use crate::{Equivalent, HashValue, IndexMap}; +use core::fmt; +use core::hash::{BuildHasher, Hash, Hasher}; +use core::marker::PhantomData; +use core::mem; +use hashbrown::hash_table; + +/// Opt-in access to the experimental raw entry API. +/// +/// See the [`raw_entry_v1`][self] module documentation for more information. +pub trait RawEntryApiV1: private::Sealed { + /// Creates a raw immutable entry builder for the [`IndexMap`]. + /// + /// Raw entries provide the lowest level of control for searching and + /// manipulating a map. They must be manually initialized with a hash and + /// then manually searched. + /// + /// This is useful for + /// * Hash memoization + /// * Using a search key that doesn't work with the [`Equivalent`] trait + /// * Using custom comparison logic without newtype wrappers + /// + /// Unless you are in such a situation, higher-level and more foolproof APIs like + /// [`get`][IndexMap::get] should be preferred. + /// + /// Immutable raw entries have very limited use; you might instead want + /// [`raw_entry_mut_v1`][Self::raw_entry_mut_v1]. + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use indexmap::map::{IndexMap, RawEntryApiV1}; + /// + /// let mut map = IndexMap::new(); + /// map.extend([("a", 100), ("b", 200), ("c", 300)]); + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// for k in ["a", "b", "c", "d", "e", "f"] { + /// let hash = compute_hash(map.hasher(), k); + /// let i = map.get_index_of(k); + /// let v = map.get(k); + /// let kv = map.get_key_value(k); + /// let ikv = map.get_full(k); + /// + /// println!("Key: {} and value: {:?}", k, v); + /// + /// assert_eq!(map.raw_entry_v1().from_key(k), kv); + /// assert_eq!(map.raw_entry_v1().from_hash(hash, |q| *q == k), kv); + /// assert_eq!(map.raw_entry_v1().from_key_hashed_nocheck(hash, k), kv); + /// assert_eq!(map.raw_entry_v1().from_hash_full(hash, |q| *q == k), ikv); + /// assert_eq!(map.raw_entry_v1().index_from_hash(hash, |q| *q == k), i); + /// } + /// ``` + fn raw_entry_v1(&self) -> RawEntryBuilder<'_, K, V, S>; + + /// Creates a raw entry builder for the [`IndexMap`]. + /// + /// Raw entries provide the lowest level of control for searching and + /// manipulating a map. They must be manually initialized with a hash and + /// then manually searched. After this, insertions into a vacant entry + /// still require an owned key to be provided. + /// + /// Raw entries are useful for such exotic situations as: + /// + /// * Hash memoization + /// * Deferring the creation of an owned key until it is known to be required + /// * Using a search key that doesn't work with the [`Equivalent`] trait + /// * Using custom comparison logic without newtype wrappers + /// + /// Because raw entries provide much more low-level control, it's much easier + /// to put the `IndexMap` into an inconsistent state which, while memory-safe, + /// will cause the map to produce seemingly random results. Higher-level and more + /// foolproof APIs like [`entry`][IndexMap::entry] should be preferred when possible. + /// + /// Raw entries give mutable access to the keys. This must not be used + /// to modify how the key would compare or hash, as the map will not re-evaluate + /// where the key should go, meaning the keys may become "lost" if their + /// location does not reflect their state. For instance, if you change a key + /// so that the map now contains keys which compare equal, search may start + /// acting erratically, with two keys randomly masking each other. Implementations + /// are free to assume this doesn't happen (within the limits of memory-safety). + /// + /// # Examples + /// + /// ``` + /// use core::hash::{BuildHasher, Hash}; + /// use indexmap::map::{IndexMap, RawEntryApiV1}; + /// use indexmap::map::raw_entry_v1::RawEntryMut; + /// + /// let mut map = IndexMap::new(); + /// map.extend([("a", 100), ("b", 200), ("c", 300)]); + /// + /// fn compute_hash(hash_builder: &S, key: &K) -> u64 { + /// use core::hash::Hasher; + /// let mut state = hash_builder.build_hasher(); + /// key.hash(&mut state); + /// state.finish() + /// } + /// + /// // Existing key (insert and update) + /// match map.raw_entry_mut_v1().from_key("a") { + /// RawEntryMut::Vacant(_) => unreachable!(), + /// RawEntryMut::Occupied(mut view) => { + /// assert_eq!(view.index(), 0); + /// assert_eq!(view.get(), &100); + /// let v = view.get_mut(); + /// let new_v = (*v) * 10; + /// *v = new_v; + /// assert_eq!(view.insert(1111), 1000); + /// } + /// } + /// + /// assert_eq!(map["a"], 1111); + /// assert_eq!(map.len(), 3); + /// + /// // Existing key (take) + /// let hash = compute_hash(map.hasher(), "c"); + /// match map.raw_entry_mut_v1().from_key_hashed_nocheck(hash, "c") { + /// RawEntryMut::Vacant(_) => unreachable!(), + /// RawEntryMut::Occupied(view) => { + /// assert_eq!(view.index(), 2); + /// assert_eq!(view.shift_remove_entry(), ("c", 300)); + /// } + /// } + /// assert_eq!(map.raw_entry_v1().from_key("c"), None); + /// assert_eq!(map.len(), 2); + /// + /// // Nonexistent key (insert and update) + /// let key = "d"; + /// let hash = compute_hash(map.hasher(), key); + /// match map.raw_entry_mut_v1().from_hash(hash, |q| *q == key) { + /// RawEntryMut::Occupied(_) => unreachable!(), + /// RawEntryMut::Vacant(view) => { + /// assert_eq!(view.index(), 2); + /// let (k, value) = view.insert("d", 4000); + /// assert_eq!((*k, *value), ("d", 4000)); + /// *value = 40000; + /// } + /// } + /// assert_eq!(map["d"], 40000); + /// assert_eq!(map.len(), 3); + /// + /// match map.raw_entry_mut_v1().from_hash(hash, |q| *q == key) { + /// RawEntryMut::Vacant(_) => unreachable!(), + /// RawEntryMut::Occupied(view) => { + /// assert_eq!(view.index(), 2); + /// assert_eq!(view.swap_remove_entry(), ("d", 40000)); + /// } + /// } + /// assert_eq!(map.get("d"), None); + /// assert_eq!(map.len(), 2); + /// ``` + fn raw_entry_mut_v1(&mut self) -> RawEntryBuilderMut<'_, K, V, S>; +} + +impl RawEntryApiV1 for IndexMap { + fn raw_entry_v1(&self) -> RawEntryBuilder<'_, K, V, S> { + RawEntryBuilder { map: self } + } + + fn raw_entry_mut_v1(&mut self) -> RawEntryBuilderMut<'_, K, V, S> { + RawEntryBuilderMut { map: self } + } +} + +/// A builder for computing where in an [`IndexMap`] a key-value pair would be stored. +/// +/// This `struct` is created by the [`IndexMap::raw_entry_v1`] method, provided by the +/// [`RawEntryApiV1`] trait. See its documentation for more. +pub struct RawEntryBuilder<'a, K, V, S> { + map: &'a IndexMap, +} + +impl fmt::Debug for RawEntryBuilder<'_, K, V, S> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawEntryBuilder").finish_non_exhaustive() + } +} + +impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S> { + /// Access an entry by key. + pub fn from_key(self, key: &Q) -> Option<(&'a K, &'a V)> + where + S: BuildHasher, + Q: ?Sized + Hash + Equivalent, + { + self.map.get_key_value(key) + } + + /// Access an entry by a key and its hash. + pub fn from_key_hashed_nocheck(self, hash: u64, key: &Q) -> Option<(&'a K, &'a V)> + where + Q: ?Sized + Equivalent, + { + let hash = HashValue(hash as usize); + let i = self.map.core.get_index_of(hash, key)?; + self.map.get_index(i) + } + + /// Access an entry by hash. + pub fn from_hash(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)> + where + F: FnMut(&K) -> bool, + { + let map = self.map; + let i = self.index_from_hash(hash, is_match)?; + map.get_index(i) + } + + /// Access an entry by hash, including its index. + pub fn from_hash_full(self, hash: u64, is_match: F) -> Option<(usize, &'a K, &'a V)> + where + F: FnMut(&K) -> bool, + { + let map = self.map; + let i = self.index_from_hash(hash, is_match)?; + let (key, value) = map.get_index(i)?; + Some((i, key, value)) + } + + /// Access the index of an entry by hash. + pub fn index_from_hash(self, hash: u64, mut is_match: F) -> Option + where + F: FnMut(&K) -> bool, + { + let hash = HashValue(hash as usize); + let entries = &*self.map.core.entries; + let eq = move |&i: &usize| is_match(&entries[i].key); + self.map.core.indices.find(hash.get(), eq).copied() + } +} + +/// A builder for computing where in an [`IndexMap`] a key-value pair would be stored. +/// +/// This `struct` is created by the [`IndexMap::raw_entry_mut_v1`] method, provided by the +/// [`RawEntryApiV1`] trait. See its documentation for more. +pub struct RawEntryBuilderMut<'a, K, V, S> { + map: &'a mut IndexMap, +} + +impl fmt::Debug for RawEntryBuilderMut<'_, K, V, S> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawEntryBuilderMut").finish_non_exhaustive() + } +} + +impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S> { + /// Access an entry by key. + pub fn from_key(self, key: &Q) -> RawEntryMut<'a, K, V, S> + where + S: BuildHasher, + Q: ?Sized + Hash + Equivalent, + { + let hash = self.map.hash(key); + self.from_key_hashed_nocheck(hash.get(), key) + } + + /// Access an entry by a key and its hash. + pub fn from_key_hashed_nocheck(self, hash: u64, key: &Q) -> RawEntryMut<'a, K, V, S> + where + Q: ?Sized + Equivalent, + { + self.from_hash(hash, |k| Q::equivalent(key, k)) + } + + /// Access an entry by hash. + pub fn from_hash(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S> + where + F: FnMut(&K) -> bool, + { + let ref_entries = &*self.map.core.entries; + let eq = move |&i: &usize| is_match(&ref_entries[i].key); + match self.map.core.indices.find_entry(hash, eq) { + Ok(index) => RawEntryMut::Occupied(RawOccupiedEntryMut { + entries: &mut self.map.core.entries, + index, + hash_builder: PhantomData, + }), + Err(absent) => RawEntryMut::Vacant(RawVacantEntryMut { + map: RefMut::new(absent.into_table(), &mut self.map.core.entries), + hash_builder: &self.map.hash_builder, + }), + } + } +} + +/// Raw entry for an existing key-value pair or a vacant location to +/// insert one. +pub enum RawEntryMut<'a, K, V, S> { + /// Existing slot with equivalent key. + Occupied(RawOccupiedEntryMut<'a, K, V, S>), + /// Vacant slot (no equivalent key in the map). + Vacant(RawVacantEntryMut<'a, K, V, S>), +} + +impl fmt::Debug for RawEntryMut<'_, K, V, S> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut tuple = f.debug_tuple("RawEntryMut"); + match self { + Self::Vacant(v) => tuple.field(v), + Self::Occupied(o) => tuple.field(o), + }; + tuple.finish() + } +} + +impl<'a, K, V, S> RawEntryMut<'a, K, V, S> { + /// Return the index where the key-value pair exists or may be inserted. + #[inline] + pub fn index(&self) -> usize { + match self { + Self::Occupied(entry) => entry.index(), + Self::Vacant(entry) => entry.index(), + } + } + + /// Inserts the given default key and value in the entry if it is vacant and returns mutable + /// references to them. Otherwise mutable references to an already existent pair are returned. + pub fn or_insert(self, default_key: K, default_value: V) -> (&'a mut K, &'a mut V) + where + K: Hash, + S: BuildHasher, + { + match self { + Self::Occupied(entry) => entry.into_key_value_mut(), + Self::Vacant(entry) => entry.insert(default_key, default_value), + } + } + + /// Inserts the result of the `call` function in the entry if it is vacant and returns mutable + /// references to them. Otherwise mutable references to an already existent pair are returned. + pub fn or_insert_with(self, call: F) -> (&'a mut K, &'a mut V) + where + F: FnOnce() -> (K, V), + K: Hash, + S: BuildHasher, + { + match self { + Self::Occupied(entry) => entry.into_key_value_mut(), + Self::Vacant(entry) => { + let (key, value) = call(); + entry.insert(key, value) + } + } + } + + /// Modifies the entry if it is occupied. + pub fn and_modify(mut self, f: F) -> Self + where + F: FnOnce(&mut K, &mut V), + { + if let Self::Occupied(entry) = &mut self { + let (k, v) = entry.get_key_value_mut(); + f(k, v); + } + self + } +} + +/// A raw view into an occupied entry in an [`IndexMap`]. +/// It is part of the [`RawEntryMut`] enum. +pub struct RawOccupiedEntryMut<'a, K, V, S> { + entries: &'a mut Entries, + index: hash_table::OccupiedEntry<'a, usize>, + hash_builder: PhantomData<&'a S>, +} + +impl fmt::Debug for RawOccupiedEntryMut<'_, K, V, S> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawOccupiedEntryMut") + .field("key", self.key()) + .field("value", self.get()) + .finish_non_exhaustive() + } +} + +impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> { + /// Return the index of the key-value pair + #[inline] + pub fn index(&self) -> usize { + *self.index.get() + } + + #[inline] + fn into_ref_mut(self) -> RefMut<'a, K, V> { + RefMut::new(self.index.into_table(), self.entries) + } + + /// Gets a reference to the entry's key in the map. + /// + /// Note that this is not the key that was used to find the entry. There may be an observable + /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like + /// extra fields or the memory address of an allocation. + pub fn key(&self) -> &K { + &self.entries[self.index()].key + } + + /// Gets a mutable reference to the entry's key in the map. + /// + /// Note that this is not the key that was used to find the entry. There may be an observable + /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like + /// extra fields or the memory address of an allocation. + pub fn key_mut(&mut self) -> &mut K { + let index = self.index(); + &mut self.entries[index].key + } + + /// Converts into a mutable reference to the entry's key in the map, + /// with a lifetime bound to the map itself. + /// + /// Note that this is not the key that was used to find the entry. There may be an observable + /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like + /// extra fields or the memory address of an allocation. + pub fn into_key(self) -> &'a mut K { + let index = self.index(); + &mut self.entries[index].key + } + + /// Gets a reference to the entry's value in the map. + pub fn get(&self) -> &V { + &self.entries[self.index()].value + } + + /// Gets a mutable reference to the entry's value in the map. + /// + /// If you need a reference which may outlive the destruction of the + /// [`RawEntryMut`] value, see [`into_mut`][Self::into_mut]. + pub fn get_mut(&mut self) -> &mut V { + let index = self.index(); + &mut self.entries[index].value + } + + /// Converts into a mutable reference to the entry's value in the map, + /// with a lifetime bound to the map itself. + pub fn into_mut(self) -> &'a mut V { + let index = self.index(); + &mut self.entries[index].value + } + + /// Gets a reference to the entry's key and value in the map. + pub fn get_key_value(&self) -> (&K, &V) { + self.entries[self.index()].refs() + } + + /// Gets a reference to the entry's key and value in the map. + pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) { + let index = self.index(); + self.entries[index].muts() + } + + /// Converts into a mutable reference to the entry's key and value in the map, + /// with a lifetime bound to the map itself. + pub fn into_key_value_mut(self) -> (&'a mut K, &'a mut V) { + let index = self.index(); + self.entries[index].muts() + } + + /// Sets the value of the entry, and returns the entry's old value. + pub fn insert(&mut self, value: V) -> V { + mem::replace(self.get_mut(), value) + } + + /// Sets the key of the entry, and returns the entry's old key. + pub fn insert_key(&mut self, key: K) -> K { + mem::replace(self.key_mut(), key) + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// **NOTE:** This is equivalent to [`.swap_remove()`][Self::swap_remove], replacing this + /// entry's position with the last element, and it is deprecated in favor of calling that + /// explicitly. If you need to preserve the relative order of the keys in the map, use + /// [`.shift_remove()`][Self::shift_remove] instead. + #[deprecated(note = "`remove` disrupts the map order -- \ + use `swap_remove` or `shift_remove` for explicit behavior.")] + pub fn remove(self) -> V { + self.swap_remove() + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// Like [`Vec::swap_remove`][crate::Vec::swap_remove], the pair is removed by swapping it with + /// the last element of the map and popping it off. + /// **This perturbs the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove(self) -> V { + self.swap_remove_entry().1 + } + + /// Remove the key, value pair stored in the map for this entry, and return the value. + /// + /// Like [`Vec::remove`][crate::Vec::remove], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove(self) -> V { + self.shift_remove_entry().1 + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// **NOTE:** This is equivalent to [`.swap_remove_entry()`][Self::swap_remove_entry], + /// replacing this entry's position with the last element, and it is deprecated in favor of + /// calling that explicitly. If you need to preserve the relative order of the keys in the map, + /// use [`.shift_remove_entry()`][Self::shift_remove_entry] instead. + #[deprecated(note = "`remove_entry` disrupts the map order -- \ + use `swap_remove_entry` or `shift_remove_entry` for explicit behavior.")] + pub fn remove_entry(self) -> (K, V) { + self.swap_remove_entry() + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// Like [`Vec::swap_remove`][crate::Vec::swap_remove], the pair is removed by swapping it with + /// the last element of the map and popping it off. + /// **This perturbs the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove_entry(self) -> (K, V) { + let (index, entry) = self.index.remove(); + RefMut::new(entry.into_table(), self.entries).swap_remove_finish(index) + } + + /// Remove and return the key, value pair stored in the map for this entry + /// + /// Like [`Vec::remove`][crate::Vec::remove], the pair is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove_entry(self) -> (K, V) { + let (index, entry) = self.index.remove(); + RefMut::new(entry.into_table(), self.entries).shift_remove_finish(index) + } + + /// Moves the position of the entry to a new index + /// by shifting all other entries in-between. + /// + /// This is equivalent to [`IndexMap::move_index`] + /// coming `from` the current [`.index()`][Self::index]. + /// + /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up. + /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down. + /// + /// ***Panics*** if `to` is out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn move_index(self, to: usize) { + let index = self.index(); + self.into_ref_mut().move_index(index, to); + } + + /// Swaps the position of entry with another. + /// + /// This is equivalent to [`IndexMap::swap_indices`] + /// with the current [`.index()`][Self::index] as one of the two being swapped. + /// + /// ***Panics*** if the `other` index is out of bounds. + /// + /// Computes in **O(1)** time (average). + pub fn swap_indices(self, other: usize) { + let index = self.index(); + self.into_ref_mut().swap_indices(index, other); + } +} + +/// A view into a vacant raw entry in an [`IndexMap`]. +/// It is part of the [`RawEntryMut`] enum. +pub struct RawVacantEntryMut<'a, K, V, S> { + map: RefMut<'a, K, V>, + hash_builder: &'a S, +} + +impl fmt::Debug for RawVacantEntryMut<'_, K, V, S> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RawVacantEntryMut").finish_non_exhaustive() + } +} + +impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> { + /// Return the index where a key-value pair may be inserted. + pub fn index(&self) -> usize { + self.map.indices.len() + } + + /// Inserts the given key and value into the map, + /// and returns mutable references to them. + pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V) + where + K: Hash, + S: BuildHasher, + { + let mut h = self.hash_builder.build_hasher(); + key.hash(&mut h); + self.insert_hashed_nocheck(h.finish(), key, value) + } + + /// Inserts the given key and value into the map with the provided hash, + /// and returns mutable references to them. + pub fn insert_hashed_nocheck(mut self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) { + let hash = HashValue(hash as usize); + let i = self.map.insert_unique(hash, key, value); + self.map.entries[i].muts() + } + + /// Inserts the given key and value into the map at the given index, + /// shifting others to the right, and returns mutable references to them. + /// + /// ***Panics*** if `index` is out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn shift_insert(self, index: usize, key: K, value: V) -> (&'a mut K, &'a mut V) + where + K: Hash, + S: BuildHasher, + { + let mut h = self.hash_builder.build_hasher(); + key.hash(&mut h); + self.shift_insert_hashed_nocheck(index, h.finish(), key, value) + } + + /// Inserts the given key and value into the map with the provided hash + /// at the given index, and returns mutable references to them. + /// + /// ***Panics*** if `index` is out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn shift_insert_hashed_nocheck( + mut self, + index: usize, + hash: u64, + key: K, + value: V, + ) -> (&'a mut K, &'a mut V) { + let hash = HashValue(hash as usize); + self.map.shift_insert_unique(index, hash, key, value); + self.map.entries[index].muts() + } +} + +mod private { + pub trait Sealed {} + + impl Sealed for super::IndexMap {} +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/iter.rs b/bitbox02-bt/vendor/indexmap/src/map/iter.rs new file mode 100644 index 0000000..2943f18 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/iter.rs @@ -0,0 +1,775 @@ +use super::core::IndexMapCore; +use super::{Bucket, Entries, IndexMap, Slice}; + +use alloc::vec::{self, Vec}; +use core::fmt; +use core::hash::{BuildHasher, Hash}; +use core::iter::FusedIterator; +use core::ops::{Index, RangeBounds}; +use core::slice; + +impl<'a, K, V, S> IntoIterator for &'a IndexMap { + type Item = (&'a K, &'a V); + type IntoIter = Iter<'a, K, V>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, K, V, S> IntoIterator for &'a mut IndexMap { + type Item = (&'a K, &'a mut V); + type IntoIter = IterMut<'a, K, V>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +impl IntoIterator for IndexMap { + type Item = (K, V); + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + IntoIter::new(self.into_entries()) + } +} + +/// An iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::iter`] method. +/// See its documentation for more. +pub struct Iter<'a, K, V> { + iter: slice::Iter<'a, Bucket>, +} + +impl<'a, K, V> Iter<'a, K, V> { + pub(super) fn new(entries: &'a [Bucket]) -> Self { + Self { + iter: entries.iter(), + } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &'a Slice { + Slice::from_slice(self.iter.as_slice()) + } +} + +impl<'a, K, V> Iterator for Iter<'a, K, V> { + type Item = (&'a K, &'a V); + + iterator_methods!(Bucket::refs); +} + +impl DoubleEndedIterator for Iter<'_, K, V> { + double_ended_iterator_methods!(Bucket::refs); +} + +impl ExactSizeIterator for Iter<'_, K, V> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for Iter<'_, K, V> {} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl Clone for Iter<'_, K, V> { + fn clone(&self) -> Self { + Iter { + iter: self.iter.clone(), + } + } +} + +impl fmt::Debug for Iter<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl Default for Iter<'_, K, V> { + fn default() -> Self { + Self { iter: [].iter() } + } +} + +/// A mutable iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::iter_mut`] method. +/// See its documentation for more. +pub struct IterMut<'a, K, V> { + iter: slice::IterMut<'a, Bucket>, +} + +impl<'a, K, V> IterMut<'a, K, V> { + pub(super) fn new(entries: &'a mut [Bucket]) -> Self { + Self { + iter: entries.iter_mut(), + } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.iter.as_slice()) + } + + /// Returns a mutable slice of the remaining entries in the iterator. + /// + /// To avoid creating `&mut` references that alias, this is forced to consume the iterator. + pub fn into_slice(self) -> &'a mut Slice { + Slice::from_mut_slice(self.iter.into_slice()) + } +} + +impl<'a, K, V> Iterator for IterMut<'a, K, V> { + type Item = (&'a K, &'a mut V); + + iterator_methods!(Bucket::ref_mut); +} + +impl DoubleEndedIterator for IterMut<'_, K, V> { + double_ended_iterator_methods!(Bucket::ref_mut); +} + +impl ExactSizeIterator for IterMut<'_, K, V> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for IterMut<'_, K, V> {} + +impl fmt::Debug for IterMut<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::refs); + f.debug_list().entries(iter).finish() + } +} + +impl Default for IterMut<'_, K, V> { + fn default() -> Self { + Self { + iter: [].iter_mut(), + } + } +} + +/// A mutable iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`MutableKeys::iter_mut2`][super::MutableKeys::iter_mut2] method. +/// See its documentation for more. +pub struct IterMut2<'a, K, V> { + iter: slice::IterMut<'a, Bucket>, +} + +impl<'a, K, V> IterMut2<'a, K, V> { + pub(super) fn new(entries: &'a mut [Bucket]) -> Self { + Self { + iter: entries.iter_mut(), + } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.iter.as_slice()) + } + + /// Returns a mutable slice of the remaining entries in the iterator. + /// + /// To avoid creating `&mut` references that alias, this is forced to consume the iterator. + pub fn into_slice(self) -> &'a mut Slice { + Slice::from_mut_slice(self.iter.into_slice()) + } +} + +impl<'a, K, V> Iterator for IterMut2<'a, K, V> { + type Item = (&'a mut K, &'a mut V); + + iterator_methods!(Bucket::muts); +} + +impl DoubleEndedIterator for IterMut2<'_, K, V> { + double_ended_iterator_methods!(Bucket::muts); +} + +impl ExactSizeIterator for IterMut2<'_, K, V> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for IterMut2<'_, K, V> {} + +impl fmt::Debug for IterMut2<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::refs); + f.debug_list().entries(iter).finish() + } +} + +impl Default for IterMut2<'_, K, V> { + fn default() -> Self { + Self { + iter: [].iter_mut(), + } + } +} + +/// An owning iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::into_iter`] method +/// (provided by the [`IntoIterator`] trait). See its documentation for more. +#[derive(Clone)] +pub struct IntoIter { + iter: vec::IntoIter>, +} + +impl IntoIter { + pub(super) fn new(entries: Vec>) -> Self { + Self { + iter: entries.into_iter(), + } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.iter.as_slice()) + } + + /// Returns a mutable slice of the remaining entries in the iterator. + pub fn as_mut_slice(&mut self) -> &mut Slice { + Slice::from_mut_slice(self.iter.as_mut_slice()) + } +} + +impl Iterator for IntoIter { + type Item = (K, V); + + iterator_methods!(Bucket::key_value); +} + +impl DoubleEndedIterator for IntoIter { + double_ended_iterator_methods!(Bucket::key_value); +} + +impl ExactSizeIterator for IntoIter { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for IntoIter {} + +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::refs); + f.debug_list().entries(iter).finish() + } +} + +impl Default for IntoIter { + fn default() -> Self { + Self { + iter: Vec::new().into_iter(), + } + } +} + +/// A draining iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::drain`] method. +/// See its documentation for more. +pub struct Drain<'a, K, V> { + iter: vec::Drain<'a, Bucket>, +} + +impl<'a, K, V> Drain<'a, K, V> { + pub(super) fn new(iter: vec::Drain<'a, Bucket>) -> Self { + Self { iter } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.iter.as_slice()) + } +} + +impl Iterator for Drain<'_, K, V> { + type Item = (K, V); + + iterator_methods!(Bucket::key_value); +} + +impl DoubleEndedIterator for Drain<'_, K, V> { + double_ended_iterator_methods!(Bucket::key_value); +} + +impl ExactSizeIterator for Drain<'_, K, V> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for Drain<'_, K, V> {} + +impl fmt::Debug for Drain<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::refs); + f.debug_list().entries(iter).finish() + } +} + +/// An iterator over the keys of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::keys`] method. +/// See its documentation for more. +pub struct Keys<'a, K, V> { + iter: slice::Iter<'a, Bucket>, +} + +impl<'a, K, V> Keys<'a, K, V> { + pub(super) fn new(entries: &'a [Bucket]) -> Self { + Self { + iter: entries.iter(), + } + } +} + +impl<'a, K, V> Iterator for Keys<'a, K, V> { + type Item = &'a K; + + iterator_methods!(Bucket::key_ref); +} + +impl DoubleEndedIterator for Keys<'_, K, V> { + double_ended_iterator_methods!(Bucket::key_ref); +} + +impl ExactSizeIterator for Keys<'_, K, V> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for Keys<'_, K, V> {} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl Clone for Keys<'_, K, V> { + fn clone(&self) -> Self { + Keys { + iter: self.iter.clone(), + } + } +} + +impl fmt::Debug for Keys<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl Default for Keys<'_, K, V> { + fn default() -> Self { + Self { iter: [].iter() } + } +} + +/// Access [`IndexMap`] keys at indexed positions. +/// +/// While [`Index for IndexMap`][values] accesses a map's values, +/// indexing through [`IndexMap::keys`] offers an alternative to access a map's +/// keys instead. +/// +/// [values]: IndexMap#impl-Index-for-IndexMap +/// +/// Since `Keys` is also an iterator, consuming items from the iterator will +/// offset the effective indexes. Similarly, if `Keys` is obtained from +/// [`Slice::keys`], indexes will be interpreted relative to the position of +/// that slice. +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// for word in "Lorem ipsum dolor sit amet".split_whitespace() { +/// map.insert(word.to_lowercase(), word.to_uppercase()); +/// } +/// +/// assert_eq!(map[0], "LOREM"); +/// assert_eq!(map.keys()[0], "lorem"); +/// assert_eq!(map[1], "IPSUM"); +/// assert_eq!(map.keys()[1], "ipsum"); +/// +/// map.reverse(); +/// assert_eq!(map.keys()[0], "amet"); +/// assert_eq!(map.keys()[1], "sit"); +/// +/// map.sort_keys(); +/// assert_eq!(map.keys()[0], "amet"); +/// assert_eq!(map.keys()[1], "dolor"); +/// +/// // Advancing the iterator will offset the indexing +/// let mut keys = map.keys(); +/// assert_eq!(keys[0], "amet"); +/// assert_eq!(keys.next().map(|s| &**s), Some("amet")); +/// assert_eq!(keys[0], "dolor"); +/// assert_eq!(keys[1], "ipsum"); +/// +/// // Slices may have an offset as well +/// let slice = &map[2..]; +/// assert_eq!(slice[0], "IPSUM"); +/// assert_eq!(slice.keys()[0], "ipsum"); +/// ``` +/// +/// ```should_panic +/// use indexmap::IndexMap; +/// +/// let mut map = IndexMap::new(); +/// map.insert("foo", 1); +/// println!("{:?}", map.keys()[10]); // panics! +/// ``` +impl<'a, K, V> Index for Keys<'a, K, V> { + type Output = K; + + /// Returns a reference to the key at the supplied `index`. + /// + /// ***Panics*** if `index` is out of bounds. + fn index(&self, index: usize) -> &K { + &self.iter.as_slice()[index].key + } +} + +/// An owning iterator over the keys of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::into_keys`] method. +/// See its documentation for more. +pub struct IntoKeys { + iter: vec::IntoIter>, +} + +impl IntoKeys { + pub(super) fn new(entries: Vec>) -> Self { + Self { + iter: entries.into_iter(), + } + } +} + +impl Iterator for IntoKeys { + type Item = K; + + iterator_methods!(Bucket::key); +} + +impl DoubleEndedIterator for IntoKeys { + double_ended_iterator_methods!(Bucket::key); +} + +impl ExactSizeIterator for IntoKeys { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for IntoKeys {} + +impl fmt::Debug for IntoKeys { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::key_ref); + f.debug_list().entries(iter).finish() + } +} + +impl Default for IntoKeys { + fn default() -> Self { + Self { + iter: Vec::new().into_iter(), + } + } +} + +/// An iterator over the values of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::values`] method. +/// See its documentation for more. +pub struct Values<'a, K, V> { + iter: slice::Iter<'a, Bucket>, +} + +impl<'a, K, V> Values<'a, K, V> { + pub(super) fn new(entries: &'a [Bucket]) -> Self { + Self { + iter: entries.iter(), + } + } +} + +impl<'a, K, V> Iterator for Values<'a, K, V> { + type Item = &'a V; + + iterator_methods!(Bucket::value_ref); +} + +impl DoubleEndedIterator for Values<'_, K, V> { + double_ended_iterator_methods!(Bucket::value_ref); +} + +impl ExactSizeIterator for Values<'_, K, V> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for Values<'_, K, V> {} + +// FIXME(#26925) Remove in favor of `#[derive(Clone)]` +impl Clone for Values<'_, K, V> { + fn clone(&self) -> Self { + Values { + iter: self.iter.clone(), + } + } +} + +impl fmt::Debug for Values<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl Default for Values<'_, K, V> { + fn default() -> Self { + Self { iter: [].iter() } + } +} + +/// A mutable iterator over the values of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::values_mut`] method. +/// See its documentation for more. +pub struct ValuesMut<'a, K, V> { + iter: slice::IterMut<'a, Bucket>, +} + +impl<'a, K, V> ValuesMut<'a, K, V> { + pub(super) fn new(entries: &'a mut [Bucket]) -> Self { + Self { + iter: entries.iter_mut(), + } + } +} + +impl<'a, K, V> Iterator for ValuesMut<'a, K, V> { + type Item = &'a mut V; + + iterator_methods!(Bucket::value_mut); +} + +impl DoubleEndedIterator for ValuesMut<'_, K, V> { + double_ended_iterator_methods!(Bucket::value_mut); +} + +impl ExactSizeIterator for ValuesMut<'_, K, V> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for ValuesMut<'_, K, V> {} + +impl fmt::Debug for ValuesMut<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::value_ref); + f.debug_list().entries(iter).finish() + } +} + +impl Default for ValuesMut<'_, K, V> { + fn default() -> Self { + Self { + iter: [].iter_mut(), + } + } +} + +/// An owning iterator over the values of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::into_values`] method. +/// See its documentation for more. +pub struct IntoValues { + iter: vec::IntoIter>, +} + +impl IntoValues { + pub(super) fn new(entries: Vec>) -> Self { + Self { + iter: entries.into_iter(), + } + } +} + +impl Iterator for IntoValues { + type Item = V; + + iterator_methods!(Bucket::value); +} + +impl DoubleEndedIterator for IntoValues { + double_ended_iterator_methods!(Bucket::value); +} + +impl ExactSizeIterator for IntoValues { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for IntoValues {} + +impl fmt::Debug for IntoValues { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::value_ref); + f.debug_list().entries(iter).finish() + } +} + +impl Default for IntoValues { + fn default() -> Self { + Self { + iter: Vec::new().into_iter(), + } + } +} + +/// A splicing iterator for `IndexMap`. +/// +/// This `struct` is created by [`IndexMap::splice()`]. +/// See its documentation for more. +pub struct Splice<'a, I, K, V, S> +where + I: Iterator, + K: Hash + Eq, + S: BuildHasher, +{ + map: &'a mut IndexMap, + tail: IndexMapCore, + drain: vec::IntoIter>, + replace_with: I, +} + +impl<'a, I, K, V, S> Splice<'a, I, K, V, S> +where + I: Iterator, + K: Hash + Eq, + S: BuildHasher, +{ + pub(super) fn new(map: &'a mut IndexMap, range: R, replace_with: I) -> Self + where + R: RangeBounds, + { + let (tail, drain) = map.core.split_splice(range); + Self { + map, + tail, + drain, + replace_with, + } + } +} + +impl Drop for Splice<'_, I, K, V, S> +where + I: Iterator, + K: Hash + Eq, + S: BuildHasher, +{ + fn drop(&mut self) { + // Finish draining unconsumed items. We don't strictly *have* to do this + // manually, since we already split it into separate memory, but it will + // match the drop order of `vec::Splice` items this way. + let _ = self.drain.nth(usize::MAX); + + // Now insert all the new items. If a key matches an existing entry, it + // keeps the original position and only replaces the value, like `insert`. + while let Some((key, value)) = self.replace_with.next() { + // Since the tail is disjoint, we can try to update it first, + // or else insert (update or append) the primary map. + let hash = self.map.hash(&key); + if let Some(i) = self.tail.get_index_of(hash, &key) { + self.tail.as_entries_mut()[i].value = value; + } else { + self.map.core.insert_full(hash, key, value); + } + } + + // Finally, re-append the tail + self.map.core.append_unchecked(&mut self.tail); + } +} + +impl Iterator for Splice<'_, I, K, V, S> +where + I: Iterator, + K: Hash + Eq, + S: BuildHasher, +{ + type Item = (K, V); + + fn next(&mut self) -> Option { + self.drain.next().map(Bucket::key_value) + } + + fn size_hint(&self) -> (usize, Option) { + self.drain.size_hint() + } +} + +impl DoubleEndedIterator for Splice<'_, I, K, V, S> +where + I: Iterator, + K: Hash + Eq, + S: BuildHasher, +{ + fn next_back(&mut self) -> Option { + self.drain.next_back().map(Bucket::key_value) + } +} + +impl ExactSizeIterator for Splice<'_, I, K, V, S> +where + I: Iterator, + K: Hash + Eq, + S: BuildHasher, +{ + fn len(&self) -> usize { + self.drain.len() + } +} + +impl FusedIterator for Splice<'_, I, K, V, S> +where + I: Iterator, + K: Hash + Eq, + S: BuildHasher, +{ +} + +impl<'a, I, K, V, S> fmt::Debug for Splice<'a, I, K, V, S> +where + I: fmt::Debug + Iterator, + K: fmt::Debug + Hash + Eq, + V: fmt::Debug, + S: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Follow `vec::Splice` in only printing the drain and replacement + f.debug_struct("Splice") + .field("drain", &self.drain) + .field("replace_with", &self.replace_with) + .finish() + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/mutable.rs b/bitbox02-bt/vendor/indexmap/src/map/mutable.rs new file mode 100644 index 0000000..e429c8b --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/mutable.rs @@ -0,0 +1,166 @@ +use core::hash::{BuildHasher, Hash}; + +use super::{ + Bucket, Entries, Entry, Equivalent, IndexMap, IndexedEntry, IterMut2, OccupiedEntry, + VacantEntry, +}; + +/// Opt-in mutable access to [`IndexMap`] keys. +/// +/// These methods expose `&mut K`, mutable references to the key as it is stored +/// in the map. +/// You are allowed to modify the keys in the map **if the modification +/// does not change the key’s hash and equality**. +/// +/// If keys are modified erroneously, you can no longer look them up. +/// This is sound (memory safe) but a logical error hazard (just like +/// implementing `PartialEq`, `Eq`, or `Hash` incorrectly would be). +/// +/// `use` this trait to enable its methods for `IndexMap`. +/// +/// This trait is sealed and cannot be implemented for types outside this crate. +pub trait MutableKeys: private::Sealed { + type Key; + type Value; + + /// Return item index, mutable reference to key and value + /// + /// Computes in **O(1)** time (average). + fn get_full_mut2(&mut self, key: &Q) -> Option<(usize, &mut Self::Key, &mut Self::Value)> + where + Q: ?Sized + Hash + Equivalent; + + /// Return mutable reference to key and value at an index. + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + fn get_index_mut2(&mut self, index: usize) -> Option<(&mut Self::Key, &mut Self::Value)>; + + /// Return an iterator over the key-value pairs of the map, in their order + fn iter_mut2(&mut self) -> IterMut2<'_, Self::Key, Self::Value>; + + /// Scan through each key-value pair in the map and keep those where the + /// closure `keep` returns `true`. + /// + /// The elements are visited in order, and remaining elements keep their + /// order. + /// + /// Computes in **O(n)** time (average). + fn retain2(&mut self, keep: F) + where + F: FnMut(&mut Self::Key, &mut Self::Value) -> bool; +} + +/// Opt-in mutable access to [`IndexMap`] keys. +/// +/// See [`MutableKeys`] for more information. +impl MutableKeys for IndexMap +where + S: BuildHasher, +{ + type Key = K; + type Value = V; + + fn get_full_mut2(&mut self, key: &Q) -> Option<(usize, &mut K, &mut V)> + where + Q: ?Sized + Hash + Equivalent, + { + if let Some(i) = self.get_index_of(key) { + let entry = &mut self.as_entries_mut()[i]; + Some((i, &mut entry.key, &mut entry.value)) + } else { + None + } + } + + fn get_index_mut2(&mut self, index: usize) -> Option<(&mut K, &mut V)> { + self.as_entries_mut().get_mut(index).map(Bucket::muts) + } + + fn iter_mut2(&mut self) -> IterMut2<'_, Self::Key, Self::Value> { + IterMut2::new(self.as_entries_mut()) + } + + fn retain2(&mut self, keep: F) + where + F: FnMut(&mut K, &mut V) -> bool, + { + self.core.retain_in_order(keep); + } +} + +/// Opt-in mutable access to [`Entry`] keys. +/// +/// These methods expose `&mut K`, mutable references to the key as it is stored +/// in the map. +/// You are allowed to modify the keys in the map **if the modification +/// does not change the key’s hash and equality**. +/// +/// If keys are modified erroneously, you can no longer look them up. +/// This is sound (memory safe) but a logical error hazard (just like +/// implementing `PartialEq`, `Eq`, or `Hash` incorrectly would be). +/// +/// `use` this trait to enable its methods for `Entry`. +/// +/// This trait is sealed and cannot be implemented for types outside this crate. +pub trait MutableEntryKey: private::Sealed { + type Key; + + /// Gets a mutable reference to the entry's key, either within the map if occupied, + /// or else the new key that was used to find the entry. + fn key_mut(&mut self) -> &mut Self::Key; +} + +/// Opt-in mutable access to [`Entry`] keys. +/// +/// See [`MutableEntryKey`] for more information. +impl MutableEntryKey for Entry<'_, K, V> { + type Key = K; + fn key_mut(&mut self) -> &mut Self::Key { + match self { + Entry::Occupied(e) => e.key_mut(), + Entry::Vacant(e) => e.key_mut(), + } + } +} + +/// Opt-in mutable access to [`OccupiedEntry`] keys. +/// +/// See [`MutableEntryKey`] for more information. +impl MutableEntryKey for OccupiedEntry<'_, K, V> { + type Key = K; + fn key_mut(&mut self) -> &mut Self::Key { + self.key_mut() + } +} + +/// Opt-in mutable access to [`VacantEntry`] keys. +/// +/// See [`MutableEntryKey`] for more information. +impl MutableEntryKey for VacantEntry<'_, K, V> { + type Key = K; + fn key_mut(&mut self) -> &mut Self::Key { + self.key_mut() + } +} + +/// Opt-in mutable access to [`IndexedEntry`] keys. +/// +/// See [`MutableEntryKey`] for more information. +impl MutableEntryKey for IndexedEntry<'_, K, V> { + type Key = K; + fn key_mut(&mut self) -> &mut Self::Key { + self.key_mut() + } +} + +mod private { + pub trait Sealed {} + + impl Sealed for super::IndexMap {} + impl Sealed for super::Entry<'_, K, V> {} + impl Sealed for super::OccupiedEntry<'_, K, V> {} + impl Sealed for super::VacantEntry<'_, K, V> {} + impl Sealed for super::IndexedEntry<'_, K, V> {} +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/serde_seq.rs b/bitbox02-bt/vendor/indexmap/src/map/serde_seq.rs new file mode 100644 index 0000000..602ae7d --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/serde_seq.rs @@ -0,0 +1,138 @@ +//! Functions to serialize and deserialize an [`IndexMap`] as an ordered sequence. +//! +//! The default `serde` implementation serializes `IndexMap` as a normal map, +//! but there is no guarantee that serialization formats will preserve the order +//! of the key-value pairs. This module serializes `IndexMap` as a sequence of +//! `(key, value)` elements instead, in order. +//! +//! This module may be used in a field attribute for derived implementations: +//! +//! ``` +//! # use indexmap::IndexMap; +//! # use serde_derive::{Deserialize, Serialize}; +//! #[derive(Deserialize, Serialize)] +//! struct Data { +//! #[serde(with = "indexmap::map::serde_seq")] +//! map: IndexMap, +//! // ... +//! } +//! ``` + +use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor}; +use serde::ser::{Serialize, Serializer}; + +use core::fmt::{self, Formatter}; +use core::hash::{BuildHasher, Hash}; +use core::marker::PhantomData; + +use crate::map::Slice as MapSlice; +use crate::serde::cautious_capacity; +use crate::set::Slice as SetSlice; +use crate::IndexMap; + +/// Serializes a [`map::Slice`][MapSlice] as an ordered sequence. +/// +/// This behaves like [`crate::map::serde_seq`] for `IndexMap`, serializing a sequence +/// of `(key, value)` pairs, rather than as a map that might not preserve order. +impl Serialize for MapSlice +where + K: Serialize, + V: Serialize, +{ + fn serialize(&self, serializer: T) -> Result + where + T: Serializer, + { + serializer.collect_seq(self) + } +} + +/// Serializes a [`set::Slice`][SetSlice] as an ordered sequence. +impl Serialize for SetSlice +where + T: Serialize, +{ + fn serialize(&self, serializer: Se) -> Result + where + Se: Serializer, + { + serializer.collect_seq(self) + } +} + +/// Serializes an [`IndexMap`] as an ordered sequence. +/// +/// This function may be used in a field attribute for deriving [`Serialize`]: +/// +/// ``` +/// # use indexmap::IndexMap; +/// # use serde_derive::Serialize; +/// #[derive(Serialize)] +/// struct Data { +/// #[serde(serialize_with = "indexmap::map::serde_seq::serialize")] +/// map: IndexMap, +/// // ... +/// } +/// ``` +pub fn serialize(map: &IndexMap, serializer: T) -> Result +where + K: Serialize, + V: Serialize, + T: Serializer, +{ + serializer.collect_seq(map) +} + +/// Visitor to deserialize a *sequenced* `IndexMap` +struct SeqVisitor(PhantomData<(K, V, S)>); + +impl<'de, K, V, S> Visitor<'de> for SeqVisitor +where + K: Deserialize<'de> + Eq + Hash, + V: Deserialize<'de>, + S: Default + BuildHasher, +{ + type Value = IndexMap; + + fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + write!(formatter, "a sequenced map") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let capacity = cautious_capacity::(seq.size_hint()); + let mut map = IndexMap::with_capacity_and_hasher(capacity, S::default()); + + while let Some((key, value)) = seq.next_element()? { + map.insert(key, value); + } + + Ok(map) + } +} + +/// Deserializes an [`IndexMap`] from an ordered sequence. +/// +/// This function may be used in a field attribute for deriving [`Deserialize`]: +/// +/// ``` +/// # use indexmap::IndexMap; +/// # use serde_derive::Deserialize; +/// #[derive(Deserialize)] +/// struct Data { +/// #[serde(deserialize_with = "indexmap::map::serde_seq::deserialize")] +/// map: IndexMap, +/// // ... +/// } +/// ``` +pub fn deserialize<'de, D, K, V, S>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + K: Deserialize<'de> + Eq + Hash, + V: Deserialize<'de>, + S: Default + BuildHasher, +{ + deserializer.deserialize_seq(SeqVisitor(PhantomData)) +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/slice.rs b/bitbox02-bt/vendor/indexmap/src/map/slice.rs new file mode 100644 index 0000000..94795b7 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/slice.rs @@ -0,0 +1,539 @@ +use super::{ + Bucket, Entries, IndexMap, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, + ValuesMut, +}; +use crate::util::try_simplify_range; + +use alloc::boxed::Box; +use alloc::vec::Vec; +use core::cmp::Ordering; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::ops::{self, Bound, Index, IndexMut, RangeBounds}; + +/// A dynamically-sized slice of key-value pairs in an [`IndexMap`]. +/// +/// This supports indexed operations much like a `[(K, V)]` slice, +/// but not any hashed operations on the map keys. +/// +/// Unlike `IndexMap`, `Slice` does consider the order for [`PartialEq`] +/// and [`Eq`], and it also implements [`PartialOrd`], [`Ord`], and [`Hash`]. +#[repr(transparent)] +pub struct Slice { + pub(crate) entries: [Bucket], +} + +// SAFETY: `Slice` is a transparent wrapper around `[Bucket]`, +// and reference lifetimes are bound together in function signatures. +#[allow(unsafe_code)] +impl Slice { + pub(super) const fn from_slice(entries: &[Bucket]) -> &Self { + unsafe { &*(entries as *const [Bucket] as *const Self) } + } + + pub(super) fn from_mut_slice(entries: &mut [Bucket]) -> &mut Self { + unsafe { &mut *(entries as *mut [Bucket] as *mut Self) } + } + + pub(super) fn from_boxed(entries: Box<[Bucket]>) -> Box { + unsafe { Box::from_raw(Box::into_raw(entries) as *mut Self) } + } + + fn into_boxed(self: Box) -> Box<[Bucket]> { + unsafe { Box::from_raw(Box::into_raw(self) as *mut [Bucket]) } + } +} + +impl Slice { + pub(crate) fn into_entries(self: Box) -> Vec> { + self.into_boxed().into_vec() + } + + /// Returns an empty slice. + pub const fn new<'a>() -> &'a Self { + Self::from_slice(&[]) + } + + /// Returns an empty mutable slice. + pub fn new_mut<'a>() -> &'a mut Self { + Self::from_mut_slice(&mut []) + } + + /// Return the number of key-value pairs in the map slice. + #[inline] + pub const fn len(&self) -> usize { + self.entries.len() + } + + /// Returns true if the map slice contains no elements. + #[inline] + pub const fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Get a key-value pair by index. + /// + /// Valid indices are `0 <= index < self.len()`. + pub fn get_index(&self, index: usize) -> Option<(&K, &V)> { + self.entries.get(index).map(Bucket::refs) + } + + /// Get a key-value pair by index, with mutable access to the value. + /// + /// Valid indices are `0 <= index < self.len()`. + pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> { + self.entries.get_mut(index).map(Bucket::ref_mut) + } + + /// Returns a slice of key-value pairs in the given range of indices. + /// + /// Valid indices are `0 <= index < self.len()`. + pub fn get_range>(&self, range: R) -> Option<&Self> { + let range = try_simplify_range(range, self.entries.len())?; + self.entries.get(range).map(Slice::from_slice) + } + + /// Returns a mutable slice of key-value pairs in the given range of indices. + /// + /// Valid indices are `0 <= index < self.len()`. + pub fn get_range_mut>(&mut self, range: R) -> Option<&mut Self> { + let range = try_simplify_range(range, self.entries.len())?; + self.entries.get_mut(range).map(Slice::from_mut_slice) + } + + /// Get the first key-value pair. + pub fn first(&self) -> Option<(&K, &V)> { + self.entries.first().map(Bucket::refs) + } + + /// Get the first key-value pair, with mutable access to the value. + pub fn first_mut(&mut self) -> Option<(&K, &mut V)> { + self.entries.first_mut().map(Bucket::ref_mut) + } + + /// Get the last key-value pair. + pub fn last(&self) -> Option<(&K, &V)> { + self.entries.last().map(Bucket::refs) + } + + /// Get the last key-value pair, with mutable access to the value. + pub fn last_mut(&mut self) -> Option<(&K, &mut V)> { + self.entries.last_mut().map(Bucket::ref_mut) + } + + /// Divides one slice into two at an index. + /// + /// ***Panics*** if `index > len`. + pub fn split_at(&self, index: usize) -> (&Self, &Self) { + let (first, second) = self.entries.split_at(index); + (Self::from_slice(first), Self::from_slice(second)) + } + + /// Divides one mutable slice into two at an index. + /// + /// ***Panics*** if `index > len`. + pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) { + let (first, second) = self.entries.split_at_mut(index); + (Self::from_mut_slice(first), Self::from_mut_slice(second)) + } + + /// Returns the first key-value pair and the rest of the slice, + /// or `None` if it is empty. + pub fn split_first(&self) -> Option<((&K, &V), &Self)> { + if let [first, rest @ ..] = &self.entries { + Some((first.refs(), Self::from_slice(rest))) + } else { + None + } + } + + /// Returns the first key-value pair and the rest of the slice, + /// with mutable access to the value, or `None` if it is empty. + pub fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> { + if let [first, rest @ ..] = &mut self.entries { + Some((first.ref_mut(), Self::from_mut_slice(rest))) + } else { + None + } + } + + /// Returns the last key-value pair and the rest of the slice, + /// or `None` if it is empty. + pub fn split_last(&self) -> Option<((&K, &V), &Self)> { + if let [rest @ .., last] = &self.entries { + Some((last.refs(), Self::from_slice(rest))) + } else { + None + } + } + + /// Returns the last key-value pair and the rest of the slice, + /// with mutable access to the value, or `None` if it is empty. + pub fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> { + if let [rest @ .., last] = &mut self.entries { + Some((last.ref_mut(), Self::from_mut_slice(rest))) + } else { + None + } + } + + /// Return an iterator over the key-value pairs of the map slice. + pub fn iter(&self) -> Iter<'_, K, V> { + Iter::new(&self.entries) + } + + /// Return an iterator over the key-value pairs of the map slice. + pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { + IterMut::new(&mut self.entries) + } + + /// Return an iterator over the keys of the map slice. + pub fn keys(&self) -> Keys<'_, K, V> { + Keys::new(&self.entries) + } + + /// Return an owning iterator over the keys of the map slice. + pub fn into_keys(self: Box) -> IntoKeys { + IntoKeys::new(self.into_entries()) + } + + /// Return an iterator over the values of the map slice. + pub fn values(&self) -> Values<'_, K, V> { + Values::new(&self.entries) + } + + /// Return an iterator over mutable references to the the values of the map slice. + pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> { + ValuesMut::new(&mut self.entries) + } + + /// Return an owning iterator over the values of the map slice. + pub fn into_values(self: Box) -> IntoValues { + IntoValues::new(self.into_entries()) + } + + /// Search over a sorted map for a key. + /// + /// Returns the position where that key is present, or the position where it can be inserted to + /// maintain the sort. See [`slice::binary_search`] for more details. + /// + /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up in + /// the map this is a slice from using [`IndexMap::get_index_of`], but this can also position + /// missing keys. + pub fn binary_search_keys(&self, x: &K) -> Result + where + K: Ord, + { + self.binary_search_by(|p, _| p.cmp(x)) + } + + /// Search over a sorted map with a comparator function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result + where + F: FnMut(&'a K, &'a V) -> Ordering, + { + self.entries.binary_search_by(move |a| f(&a.key, &a.value)) + } + + /// Search over a sorted map with an extraction function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by_key`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result + where + F: FnMut(&'a K, &'a V) -> B, + B: Ord, + { + self.binary_search_by(|k, v| f(k, v).cmp(b)) + } + + /// Returns the index of the partition point of a sorted map according to the given predicate + /// (the index of the first element of the second partition). + /// + /// See [`slice::partition_point`] for more details. + /// + /// Computes in **O(log(n))** time. + #[must_use] + pub fn partition_point

(&self, mut pred: P) -> usize + where + P: FnMut(&K, &V) -> bool, + { + self.entries + .partition_point(move |a| pred(&a.key, &a.value)) + } +} + +impl<'a, K, V> IntoIterator for &'a Slice { + type IntoIter = Iter<'a, K, V>; + type Item = (&'a K, &'a V); + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, K, V> IntoIterator for &'a mut Slice { + type IntoIter = IterMut<'a, K, V>; + type Item = (&'a K, &'a mut V); + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +impl IntoIterator for Box> { + type IntoIter = IntoIter; + type Item = (K, V); + + fn into_iter(self) -> Self::IntoIter { + IntoIter::new(self.into_entries()) + } +} + +impl Default for &'_ Slice { + fn default() -> Self { + Slice::from_slice(&[]) + } +} + +impl Default for &'_ mut Slice { + fn default() -> Self { + Slice::from_mut_slice(&mut []) + } +} + +impl Default for Box> { + fn default() -> Self { + Slice::from_boxed(Box::default()) + } +} + +impl Clone for Box> { + fn clone(&self) -> Self { + Slice::from_boxed(self.entries.to_vec().into_boxed_slice()) + } +} + +impl From<&Slice> for Box> { + fn from(slice: &Slice) -> Self { + Slice::from_boxed(Box::from(&slice.entries)) + } +} + +impl fmt::Debug for Slice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self).finish() + } +} + +impl PartialEq for Slice { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.iter().eq(other) + } +} + +impl Eq for Slice {} + +impl PartialOrd for Slice { + fn partial_cmp(&self, other: &Self) -> Option { + self.iter().partial_cmp(other) + } +} + +impl Ord for Slice { + fn cmp(&self, other: &Self) -> Ordering { + self.iter().cmp(other) + } +} + +impl Hash for Slice { + fn hash(&self, state: &mut H) { + self.len().hash(state); + for (key, value) in self { + key.hash(state); + value.hash(state); + } + } +} + +impl Index for Slice { + type Output = V; + + fn index(&self, index: usize) -> &V { + &self.entries[index].value + } +} + +impl IndexMut for Slice { + fn index_mut(&mut self, index: usize) -> &mut V { + &mut self.entries[index].value + } +} + +// We can't have `impl> Index` because that conflicts +// both upstream with `Index` and downstream with `Index<&Q>`. +// Instead, we repeat the implementations for all the core range types. +macro_rules! impl_index { + ($($range:ty),*) => {$( + impl Index<$range> for IndexMap { + type Output = Slice; + + fn index(&self, range: $range) -> &Self::Output { + Slice::from_slice(&self.as_entries()[range]) + } + } + + impl IndexMut<$range> for IndexMap { + fn index_mut(&mut self, range: $range) -> &mut Self::Output { + Slice::from_mut_slice(&mut self.as_entries_mut()[range]) + } + } + + impl Index<$range> for Slice { + type Output = Slice; + + fn index(&self, range: $range) -> &Self { + Self::from_slice(&self.entries[range]) + } + } + + impl IndexMut<$range> for Slice { + fn index_mut(&mut self, range: $range) -> &mut Self { + Self::from_mut_slice(&mut self.entries[range]) + } + } + )*} +} +impl_index!( + ops::Range, + ops::RangeFrom, + ops::RangeFull, + ops::RangeInclusive, + ops::RangeTo, + ops::RangeToInclusive, + (Bound, Bound) +); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slice_index() { + fn check( + vec_slice: &[(i32, i32)], + map_slice: &Slice, + sub_slice: &Slice, + ) { + assert_eq!(map_slice as *const _, sub_slice as *const _); + itertools::assert_equal( + vec_slice.iter().copied(), + map_slice.iter().map(|(&k, &v)| (k, v)), + ); + itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys()); + itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values()); + } + + let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect(); + let map: IndexMap = vec.iter().cloned().collect(); + let slice = map.as_slice(); + + // RangeFull + check(&vec[..], &map[..], &slice[..]); + + for i in 0usize..10 { + // Index + assert_eq!(vec[i].1, map[i]); + assert_eq!(vec[i].1, slice[i]); + assert_eq!(map[&(i as i32)], map[i]); + assert_eq!(map[&(i as i32)], slice[i]); + + // RangeFrom + check(&vec[i..], &map[i..], &slice[i..]); + + // RangeTo + check(&vec[..i], &map[..i], &slice[..i]); + + // RangeToInclusive + check(&vec[..=i], &map[..=i], &slice[..=i]); + + // (Bound, Bound) + let bounds = (Bound::Excluded(i), Bound::Unbounded); + check(&vec[i + 1..], &map[bounds], &slice[bounds]); + + for j in i..=10 { + // Range + check(&vec[i..j], &map[i..j], &slice[i..j]); + } + + for j in i..10 { + // RangeInclusive + check(&vec[i..=j], &map[i..=j], &slice[i..=j]); + } + } + } + + #[test] + fn slice_index_mut() { + fn check_mut( + vec_slice: &[(i32, i32)], + map_slice: &mut Slice, + sub_slice: &mut Slice, + ) { + assert_eq!(map_slice, sub_slice); + itertools::assert_equal( + vec_slice.iter().copied(), + map_slice.iter_mut().map(|(&k, &mut v)| (k, v)), + ); + itertools::assert_equal( + vec_slice.iter().map(|&(_, v)| v), + map_slice.values_mut().map(|&mut v| v), + ); + } + + let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect(); + let mut map: IndexMap = vec.iter().cloned().collect(); + let mut map2 = map.clone(); + let slice = map2.as_mut_slice(); + + // RangeFull + check_mut(&vec[..], &mut map[..], &mut slice[..]); + + for i in 0usize..10 { + // IndexMut + assert_eq!(&mut map[i], &mut slice[i]); + + // RangeFrom + check_mut(&vec[i..], &mut map[i..], &mut slice[i..]); + + // RangeTo + check_mut(&vec[..i], &mut map[..i], &mut slice[..i]); + + // RangeToInclusive + check_mut(&vec[..=i], &mut map[..=i], &mut slice[..=i]); + + // (Bound, Bound) + let bounds = (Bound::Excluded(i), Bound::Unbounded); + check_mut(&vec[i + 1..], &mut map[bounds], &mut slice[bounds]); + + for j in i..=10 { + // Range + check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]); + } + + for j in i..10 { + // RangeInclusive + check_mut(&vec[i..=j], &mut map[i..=j], &mut slice[i..=j]); + } + } + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/map/tests.rs b/bitbox02-bt/vendor/indexmap/src/map/tests.rs new file mode 100644 index 0000000..9de9db1 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/map/tests.rs @@ -0,0 +1,830 @@ +use super::*; +use std::string::String; + +#[test] +fn it_works() { + let mut map = IndexMap::new(); + assert_eq!(map.is_empty(), true); + map.insert(1, ()); + map.insert(1, ()); + assert_eq!(map.len(), 1); + assert!(map.get(&1).is_some()); + assert_eq!(map.is_empty(), false); +} + +#[test] +fn new() { + let map = IndexMap::::new(); + println!("{:?}", map); + assert_eq!(map.capacity(), 0); + assert_eq!(map.len(), 0); + assert_eq!(map.is_empty(), true); +} + +#[test] +fn insert() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5]; + let not_present = [1, 3, 6, 9, 10]; + let mut map = IndexMap::with_capacity(insert.len()); + + for (i, &elt) in insert.iter().enumerate() { + assert_eq!(map.len(), i); + map.insert(elt, elt); + assert_eq!(map.len(), i + 1); + assert_eq!(map.get(&elt), Some(&elt)); + assert_eq!(map[&elt], elt); + } + println!("{:?}", map); + + for &elt in ¬_present { + assert!(map.get(&elt).is_none()); + } +} + +#[test] +fn insert_full() { + let insert = vec![9, 2, 7, 1, 4, 6, 13]; + let present = vec![1, 6, 2]; + let mut map = IndexMap::with_capacity(insert.len()); + + for (i, &elt) in insert.iter().enumerate() { + assert_eq!(map.len(), i); + let (index, existing) = map.insert_full(elt, elt); + assert_eq!(existing, None); + assert_eq!(Some(index), map.get_full(&elt).map(|x| x.0)); + assert_eq!(map.len(), i + 1); + } + + let len = map.len(); + for &elt in &present { + let (index, existing) = map.insert_full(elt, elt); + assert_eq!(existing, Some(elt)); + assert_eq!(Some(index), map.get_full(&elt).map(|x| x.0)); + assert_eq!(map.len(), len); + } +} + +#[test] +fn insert_2() { + let mut map = IndexMap::with_capacity(16); + + let mut keys = vec![]; + keys.extend(0..16); + keys.extend(if cfg!(miri) { 32..64 } else { 128..267 }); + + for &i in &keys { + let old_map = map.clone(); + map.insert(i, ()); + for key in old_map.keys() { + if map.get(key).is_none() { + println!("old_map: {:?}", old_map); + println!("map: {:?}", map); + panic!("did not find {} in map", key); + } + } + } + + for &i in &keys { + assert!(map.get(&i).is_some(), "did not find {}", i); + } +} + +#[test] +fn insert_order() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut map = IndexMap::new(); + + for &elt in &insert { + map.insert(elt, ()); + } + + assert_eq!(map.keys().count(), map.len()); + assert_eq!(map.keys().count(), insert.len()); + for (a, b) in insert.iter().zip(map.keys()) { + assert_eq!(a, b); + } + for (i, k) in (0..insert.len()).zip(map.keys()) { + assert_eq!(map.get_index(i).unwrap().0, k); + } +} + +#[test] +fn shift_insert() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut map = IndexMap::new(); + + for &elt in &insert { + map.shift_insert(0, elt, ()); + } + + assert_eq!(map.keys().count(), map.len()); + assert_eq!(map.keys().count(), insert.len()); + for (a, b) in insert.iter().rev().zip(map.keys()) { + assert_eq!(a, b); + } + for (i, k) in (0..insert.len()).zip(map.keys()) { + assert_eq!(map.get_index(i).unwrap().0, k); + } + + // "insert" that moves an existing entry + map.shift_insert(0, insert[0], ()); + assert_eq!(map.keys().count(), insert.len()); + assert_eq!(insert[0], map.keys()[0]); + for (a, b) in insert[1..].iter().rev().zip(map.keys().skip(1)) { + assert_eq!(a, b); + } +} + +#[test] +fn insert_sorted_bad() { + let mut map = IndexMap::new(); + map.insert(10, ()); + for i in 0..10 { + map.insert(i, ()); + } + + // The binary search will want to insert this at the end (index == len()), + // but that's only possible for *new* inserts. It should still be handled + // without panicking though, and in this case it's simple enough that we + // know the exact result. (But don't read this as an API guarantee!) + assert_eq!(map.first(), Some((&10, &()))); + map.insert_sorted(10, ()); + assert_eq!(map.last(), Some((&10, &()))); + assert!(map.keys().copied().eq(0..=10)); + + // Other out-of-order entries can also "insert" to a binary-searched + // position, moving in either direction. + map.move_index(5, 0); + map.move_index(6, 10); + assert_eq!(map.first(), Some((&5, &()))); + assert_eq!(map.last(), Some((&6, &()))); + map.insert_sorted(5, ()); // moves back up + map.insert_sorted(6, ()); // moves back down + assert!(map.keys().copied().eq(0..=10)); +} + +#[test] +fn grow() { + let insert = [0, 4, 2, 12, 8, 7, 11]; + let not_present = [1, 3, 6, 9, 10]; + let mut map = IndexMap::with_capacity(insert.len()); + + for (i, &elt) in insert.iter().enumerate() { + assert_eq!(map.len(), i); + map.insert(elt, elt); + assert_eq!(map.len(), i + 1); + assert_eq!(map.get(&elt), Some(&elt)); + assert_eq!(map[&elt], elt); + } + + println!("{:?}", map); + for &elt in &insert { + map.insert(elt * 10, elt); + } + for &elt in &insert { + map.insert(elt * 100, elt); + } + for (i, &elt) in insert.iter().cycle().enumerate().take(100) { + map.insert(elt * 100 + i as i32, elt); + } + println!("{:?}", map); + for &elt in ¬_present { + assert!(map.get(&elt).is_none()); + } +} + +#[test] +fn reserve() { + let mut map = IndexMap::::new(); + assert_eq!(map.capacity(), 0); + map.reserve(100); + let capacity = map.capacity(); + assert!(capacity >= 100); + for i in 0..capacity { + assert_eq!(map.len(), i); + map.insert(i, i * i); + assert_eq!(map.len(), i + 1); + assert_eq!(map.capacity(), capacity); + assert_eq!(map.get(&i), Some(&(i * i))); + } + map.insert(capacity, std::usize::MAX); + assert_eq!(map.len(), capacity + 1); + assert!(map.capacity() > capacity); + assert_eq!(map.get(&capacity), Some(&std::usize::MAX)); +} + +#[test] +fn try_reserve() { + let mut map = IndexMap::::new(); + assert_eq!(map.capacity(), 0); + assert_eq!(map.try_reserve(100), Ok(())); + assert!(map.capacity() >= 100); + assert!(map.try_reserve(usize::MAX).is_err()); +} + +#[test] +fn shrink_to_fit() { + let mut map = IndexMap::::new(); + assert_eq!(map.capacity(), 0); + for i in 0..100 { + assert_eq!(map.len(), i); + map.insert(i, i * i); + assert_eq!(map.len(), i + 1); + assert!(map.capacity() >= i + 1); + assert_eq!(map.get(&i), Some(&(i * i))); + map.shrink_to_fit(); + assert_eq!(map.len(), i + 1); + assert_eq!(map.capacity(), i + 1); + assert_eq!(map.get(&i), Some(&(i * i))); + } +} + +#[test] +fn remove() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut map = IndexMap::new(); + + for &elt in &insert { + map.insert(elt, elt); + } + + assert_eq!(map.keys().count(), map.len()); + assert_eq!(map.keys().count(), insert.len()); + for (a, b) in insert.iter().zip(map.keys()) { + assert_eq!(a, b); + } + + let remove_fail = [99, 77]; + let remove = [4, 12, 8, 7]; + + for &key in &remove_fail { + assert!(map.swap_remove_full(&key).is_none()); + } + println!("{:?}", map); + for &key in &remove { + //println!("{:?}", map); + let index = map.get_full(&key).unwrap().0; + assert_eq!(map.swap_remove_full(&key), Some((index, key, key))); + } + println!("{:?}", map); + + for key in &insert { + assert_eq!(map.get(key).is_some(), !remove.contains(key)); + } + assert_eq!(map.len(), insert.len() - remove.len()); + assert_eq!(map.keys().count(), insert.len() - remove.len()); +} + +#[test] +fn remove_to_empty() { + let mut map = indexmap! { 0 => 0, 4 => 4, 5 => 5 }; + map.swap_remove(&5).unwrap(); + map.swap_remove(&4).unwrap(); + map.swap_remove(&0).unwrap(); + assert!(map.is_empty()); +} + +#[test] +fn swap_remove_index() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut map = IndexMap::new(); + + for &elt in &insert { + map.insert(elt, elt * 2); + } + + let mut vector = insert.to_vec(); + let remove_sequence = &[3, 3, 10, 4, 5, 4, 3, 0, 1]; + + // check that the same swap remove sequence on vec and map + // have the same result. + for &rm in remove_sequence { + let out_vec = vector.swap_remove(rm); + let (out_map, _) = map.swap_remove_index(rm).unwrap(); + assert_eq!(out_vec, out_map); + } + assert_eq!(vector.len(), map.len()); + for (a, b) in vector.iter().zip(map.keys()) { + assert_eq!(a, b); + } +} + +#[test] +fn partial_eq_and_eq() { + let mut map_a = IndexMap::new(); + map_a.insert(1, "1"); + map_a.insert(2, "2"); + let mut map_b = map_a.clone(); + assert_eq!(map_a, map_b); + map_b.swap_remove(&1); + assert_ne!(map_a, map_b); + + let map_c: IndexMap<_, String> = map_b.into_iter().map(|(k, v)| (k, v.into())).collect(); + assert_ne!(map_a, map_c); + assert_ne!(map_c, map_a); +} + +#[test] +fn extend() { + let mut map = IndexMap::new(); + map.extend(vec![(&1, &2), (&3, &4)]); + map.extend(vec![(5, 6)]); + assert_eq!( + map.into_iter().collect::>(), + vec![(1, 2), (3, 4), (5, 6)] + ); +} + +#[test] +fn entry() { + let mut map = IndexMap::new(); + + map.insert(1, "1"); + map.insert(2, "2"); + { + let e = map.entry(3); + assert_eq!(e.index(), 2); + let e = e.or_insert("3"); + assert_eq!(e, &"3"); + } + + let e = map.entry(2); + assert_eq!(e.index(), 1); + assert_eq!(e.key(), &2); + match e { + Entry::Occupied(ref e) => assert_eq!(e.get(), &"2"), + Entry::Vacant(_) => panic!(), + } + assert_eq!(e.or_insert("4"), &"2"); +} + +#[test] +fn entry_and_modify() { + let mut map = IndexMap::new(); + + map.insert(1, "1"); + map.entry(1).and_modify(|x| *x = "2"); + assert_eq!(Some(&"2"), map.get(&1)); + + map.entry(2).and_modify(|x| *x = "doesn't exist"); + assert_eq!(None, map.get(&2)); +} + +#[test] +fn entry_or_default() { + let mut map = IndexMap::new(); + + #[derive(Debug, PartialEq)] + enum TestEnum { + DefaultValue, + NonDefaultValue, + } + + impl Default for TestEnum { + fn default() -> Self { + TestEnum::DefaultValue + } + } + + map.insert(1, TestEnum::NonDefaultValue); + assert_eq!(&mut TestEnum::NonDefaultValue, map.entry(1).or_default()); + + assert_eq!(&mut TestEnum::DefaultValue, map.entry(2).or_default()); +} + +#[test] +fn occupied_entry_key() { + // These keys match hash and equality, but their addresses are distinct. + let (k1, k2) = (&mut 1, &mut 1); + let k1_ptr = k1 as *const i32; + let k2_ptr = k2 as *const i32; + assert_ne!(k1_ptr, k2_ptr); + + let mut map = IndexMap::new(); + map.insert(k1, "value"); + match map.entry(k2) { + Entry::Occupied(ref e) => { + // `OccupiedEntry::key` should reference the key in the map, + // not the key that was used to find the entry. + let ptr = *e.key() as *const i32; + assert_eq!(ptr, k1_ptr); + assert_ne!(ptr, k2_ptr); + } + Entry::Vacant(_) => panic!(), + } +} + +#[test] +fn get_index_entry() { + let mut map = IndexMap::new(); + + assert!(map.get_index_entry(0).is_none()); + assert!(map.first_entry().is_none()); + assert!(map.last_entry().is_none()); + + map.insert(0, "0"); + map.insert(1, "1"); + map.insert(2, "2"); + map.insert(3, "3"); + + assert!(map.get_index_entry(4).is_none()); + + { + let e = map.get_index_entry(1).unwrap(); + assert_eq!(*e.key(), 1); + assert_eq!(*e.get(), "1"); + assert_eq!(e.swap_remove(), "1"); + } + + { + let mut e = map.get_index_entry(1).unwrap(); + assert_eq!(*e.key(), 3); + assert_eq!(*e.get(), "3"); + assert_eq!(e.insert("4"), "3"); + } + + assert_eq!(*map.get(&3).unwrap(), "4"); + + { + let e = map.first_entry().unwrap(); + assert_eq!(*e.key(), 0); + assert_eq!(*e.get(), "0"); + } + + { + let e = map.last_entry().unwrap(); + assert_eq!(*e.key(), 2); + assert_eq!(*e.get(), "2"); + } +} + +#[test] +fn from_entries() { + let mut map = IndexMap::from([(1, "1"), (2, "2"), (3, "3")]); + + { + let e = match map.entry(1) { + Entry::Occupied(e) => IndexedEntry::from(e), + Entry::Vacant(_) => panic!(), + }; + assert_eq!(e.index(), 0); + assert_eq!(*e.key(), 1); + assert_eq!(*e.get(), "1"); + } + + { + let e = match map.get_index_entry(1) { + Some(e) => OccupiedEntry::from(e), + None => panic!(), + }; + assert_eq!(e.index(), 1); + assert_eq!(*e.key(), 2); + assert_eq!(*e.get(), "2"); + } +} + +#[test] +fn keys() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: IndexMap<_, _> = vec.into_iter().collect(); + let keys: Vec<_> = map.keys().copied().collect(); + assert_eq!(keys.len(), 3); + assert!(keys.contains(&1)); + assert!(keys.contains(&2)); + assert!(keys.contains(&3)); +} + +#[test] +fn into_keys() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: IndexMap<_, _> = vec.into_iter().collect(); + let keys: Vec = map.into_keys().collect(); + assert_eq!(keys.len(), 3); + assert!(keys.contains(&1)); + assert!(keys.contains(&2)); + assert!(keys.contains(&3)); +} + +#[test] +fn values() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: IndexMap<_, _> = vec.into_iter().collect(); + let values: Vec<_> = map.values().copied().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&'a')); + assert!(values.contains(&'b')); + assert!(values.contains(&'c')); +} + +#[test] +fn values_mut() { + let vec = vec![(1, 1), (2, 2), (3, 3)]; + let mut map: IndexMap<_, _> = vec.into_iter().collect(); + for value in map.values_mut() { + *value *= 2 + } + let values: Vec<_> = map.values().copied().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&2)); + assert!(values.contains(&4)); + assert!(values.contains(&6)); +} + +#[test] +fn into_values() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: IndexMap<_, _> = vec.into_iter().collect(); + let values: Vec = map.into_values().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&'a')); + assert!(values.contains(&'b')); + assert!(values.contains(&'c')); +} + +#[test] +fn drain_range() { + // Test the various heuristics of `erase_indices` + for range in [ + 0..0, // nothing erased + 10..90, // reinsert the few kept (..10 and 90..) + 80..90, // update the few to adjust (80..) + 20..30, // sweep everything + ] { + let mut vec = Vec::from_iter(0..100); + let mut map: IndexMap = (0..100).map(|i| (i, ())).collect(); + drop(vec.drain(range.clone())); + drop(map.drain(range)); + assert!(vec.iter().eq(map.keys())); + for (i, x) in vec.iter().enumerate() { + assert_eq!(map.get_index_of(x), Some(i)); + } + } +} + +#[test] +#[cfg(feature = "std")] +fn from_array() { + let map = IndexMap::from([(1, 2), (3, 4)]); + let mut expected = IndexMap::new(); + expected.insert(1, 2); + expected.insert(3, 4); + + assert_eq!(map, expected) +} + +#[test] +fn iter_default() { + struct K; + struct V; + fn assert_default() + where + T: Default + Iterator, + { + assert!(T::default().next().is_none()); + } + assert_default::>(); + assert_default::>(); + assert_default::>(); + assert_default::>(); + assert_default::>(); + assert_default::>(); + assert_default::>(); + assert_default::>(); + assert_default::>(); +} + +#[test] +fn test_binary_search_by() { + // adapted from std's test for binary_search + let b: IndexMap<_, i32> = [] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&5)), Err(0)); + + let b: IndexMap<_, i32> = [4] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&3)), Err(0)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&4)), Ok(0)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&5)), Err(1)); + + let b: IndexMap<_, i32> = [1, 2, 4, 6, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&5)), Err(3)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&6)), Ok(3)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&7)), Err(4)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&8)), Ok(4)); + + let b: IndexMap<_, i32> = [1, 2, 4, 5, 6, 8] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&9)), Err(6)); + + let b: IndexMap<_, i32> = [1, 2, 4, 6, 7, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&6)), Ok(3)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&5)), Err(3)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&8)), Ok(5)); + + let b: IndexMap<_, i32> = [1, 2, 4, 5, 6, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&7)), Err(5)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&0)), Err(0)); + + let b: IndexMap<_, i32> = [1, 3, 3, 3, 7] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&0)), Err(0)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&1)), Ok(0)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&2)), Err(1)); + assert!(match b.binary_search_by(|_, x| x.cmp(&3)) { + Ok(1..=3) => true, + _ => false, + }); + assert!(match b.binary_search_by(|_, x| x.cmp(&3)) { + Ok(1..=3) => true, + _ => false, + }); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&4)), Err(4)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&5)), Err(4)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&6)), Err(4)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&7)), Ok(4)); + assert_eq!(b.binary_search_by(|_, x| x.cmp(&8)), Err(5)); +} + +#[test] +fn test_binary_search_by_key() { + // adapted from std's test for binary_search + let b: IndexMap<_, i32> = [] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by_key(&5, |_, &x| x), Err(0)); + + let b: IndexMap<_, i32> = [4] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by_key(&3, |_, &x| x), Err(0)); + assert_eq!(b.binary_search_by_key(&4, |_, &x| x), Ok(0)); + assert_eq!(b.binary_search_by_key(&5, |_, &x| x), Err(1)); + + let b: IndexMap<_, i32> = [1, 2, 4, 6, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by_key(&5, |_, &x| x), Err(3)); + assert_eq!(b.binary_search_by_key(&6, |_, &x| x), Ok(3)); + assert_eq!(b.binary_search_by_key(&7, |_, &x| x), Err(4)); + assert_eq!(b.binary_search_by_key(&8, |_, &x| x), Ok(4)); + + let b: IndexMap<_, i32> = [1, 2, 4, 5, 6, 8] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by_key(&9, |_, &x| x), Err(6)); + + let b: IndexMap<_, i32> = [1, 2, 4, 6, 7, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by_key(&6, |_, &x| x), Ok(3)); + assert_eq!(b.binary_search_by_key(&5, |_, &x| x), Err(3)); + assert_eq!(b.binary_search_by_key(&8, |_, &x| x), Ok(5)); + + let b: IndexMap<_, i32> = [1, 2, 4, 5, 6, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by_key(&7, |_, &x| x), Err(5)); + assert_eq!(b.binary_search_by_key(&0, |_, &x| x), Err(0)); + + let b: IndexMap<_, i32> = [1, 3, 3, 3, 7] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.binary_search_by_key(&0, |_, &x| x), Err(0)); + assert_eq!(b.binary_search_by_key(&1, |_, &x| x), Ok(0)); + assert_eq!(b.binary_search_by_key(&2, |_, &x| x), Err(1)); + assert!(match b.binary_search_by_key(&3, |_, &x| x) { + Ok(1..=3) => true, + _ => false, + }); + assert!(match b.binary_search_by_key(&3, |_, &x| x) { + Ok(1..=3) => true, + _ => false, + }); + assert_eq!(b.binary_search_by_key(&4, |_, &x| x), Err(4)); + assert_eq!(b.binary_search_by_key(&5, |_, &x| x), Err(4)); + assert_eq!(b.binary_search_by_key(&6, |_, &x| x), Err(4)); + assert_eq!(b.binary_search_by_key(&7, |_, &x| x), Ok(4)); + assert_eq!(b.binary_search_by_key(&8, |_, &x| x), Err(5)); +} + +#[test] +fn test_partition_point() { + // adapted from std's test for partition_point + let b: IndexMap<_, i32> = [] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.partition_point(|_, &x| x < 5), 0); + + let b: IndexMap<_, i32> = [4] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.partition_point(|_, &x| x < 3), 0); + assert_eq!(b.partition_point(|_, &x| x < 4), 0); + assert_eq!(b.partition_point(|_, &x| x < 5), 1); + + let b: IndexMap<_, i32> = [1, 2, 4, 6, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.partition_point(|_, &x| x < 5), 3); + assert_eq!(b.partition_point(|_, &x| x < 6), 3); + assert_eq!(b.partition_point(|_, &x| x < 7), 4); + assert_eq!(b.partition_point(|_, &x| x < 8), 4); + + let b: IndexMap<_, i32> = [1, 2, 4, 5, 6, 8] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.partition_point(|_, &x| x < 9), 6); + + let b: IndexMap<_, i32> = [1, 2, 4, 6, 7, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.partition_point(|_, &x| x < 6), 3); + assert_eq!(b.partition_point(|_, &x| x < 5), 3); + assert_eq!(b.partition_point(|_, &x| x < 8), 5); + + let b: IndexMap<_, i32> = [1, 2, 4, 5, 6, 8, 9] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.partition_point(|_, &x| x < 7), 5); + assert_eq!(b.partition_point(|_, &x| x < 0), 0); + + let b: IndexMap<_, i32> = [1, 3, 3, 3, 7] + .into_iter() + .enumerate() + .map(|(i, x)| (i + 100, x)) + .collect(); + assert_eq!(b.partition_point(|_, &x| x < 0), 0); + assert_eq!(b.partition_point(|_, &x| x < 1), 0); + assert_eq!(b.partition_point(|_, &x| x < 2), 1); + assert_eq!(b.partition_point(|_, &x| x < 3), 1); + assert_eq!(b.partition_point(|_, &x| x < 4), 4); + assert_eq!(b.partition_point(|_, &x| x < 5), 4); + assert_eq!(b.partition_point(|_, &x| x < 6), 4); + assert_eq!(b.partition_point(|_, &x| x < 7), 4); + assert_eq!(b.partition_point(|_, &x| x < 8), 5); +} + +macro_rules! move_index_oob { + ($test:ident, $from:expr, $to:expr) => { + #[test] + #[should_panic(expected = "index out of bounds")] + fn $test() { + let mut map: IndexMap = (0..10).map(|k| (k, ())).collect(); + map.move_index($from, $to); + } + }; +} +move_index_oob!(test_move_index_out_of_bounds_0_10, 0, 10); +move_index_oob!(test_move_index_out_of_bounds_0_max, 0, usize::MAX); +move_index_oob!(test_move_index_out_of_bounds_10_0, 10, 0); +move_index_oob!(test_move_index_out_of_bounds_max_0, usize::MAX, 0); diff --git a/bitbox02-bt/vendor/indexmap/src/rayon/map.rs b/bitbox02-bt/vendor/indexmap/src/rayon/map.rs new file mode 100644 index 0000000..8236cf7 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/rayon/map.rs @@ -0,0 +1,663 @@ +//! Parallel iterator types for [`IndexMap`] with [`rayon`][::rayon]. +//! +//! You will rarely need to interact with this module directly unless you need to name one of the +//! iterator types. + +use super::collect; +use rayon::iter::plumbing::{Consumer, ProducerCallback, UnindexedConsumer}; +use rayon::prelude::*; + +use crate::vec::Vec; +use alloc::boxed::Box; +use core::cmp::Ordering; +use core::fmt; +use core::hash::{BuildHasher, Hash}; +use core::ops::RangeBounds; + +use crate::map::Slice; +use crate::Bucket; +use crate::Entries; +use crate::IndexMap; + +impl IntoParallelIterator for IndexMap +where + K: Send, + V: Send, +{ + type Item = (K, V); + type Iter = IntoParIter; + + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + entries: self.into_entries(), + } + } +} + +impl IntoParallelIterator for Box> +where + K: Send, + V: Send, +{ + type Item = (K, V); + type Iter = IntoParIter; + + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + entries: self.into_entries(), + } + } +} + +/// A parallel owning iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::into_par_iter`] method +/// (provided by rayon's [`IntoParallelIterator`] trait). See its documentation for more. +pub struct IntoParIter { + entries: Vec>, +} + +impl fmt::Debug for IntoParIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::refs); + f.debug_list().entries(iter).finish() + } +} + +impl ParallelIterator for IntoParIter { + type Item = (K, V); + + parallel_iterator_methods!(Bucket::key_value); +} + +impl IndexedParallelIterator for IntoParIter { + indexed_parallel_iterator_methods!(Bucket::key_value); +} + +impl<'a, K, V, S> IntoParallelIterator for &'a IndexMap +where + K: Sync, + V: Sync, +{ + type Item = (&'a K, &'a V); + type Iter = ParIter<'a, K, V>; + + fn into_par_iter(self) -> Self::Iter { + ParIter { + entries: self.as_entries(), + } + } +} + +impl<'a, K, V> IntoParallelIterator for &'a Slice +where + K: Sync, + V: Sync, +{ + type Item = (&'a K, &'a V); + type Iter = ParIter<'a, K, V>; + + fn into_par_iter(self) -> Self::Iter { + ParIter { + entries: &self.entries, + } + } +} + +/// A parallel iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::par_iter`] method +/// (provided by rayon's [`IntoParallelRefIterator`] trait). See its documentation for more. +/// +/// [`IndexMap::par_iter`]: ../struct.IndexMap.html#method.par_iter +pub struct ParIter<'a, K, V> { + entries: &'a [Bucket], +} + +impl Clone for ParIter<'_, K, V> { + fn clone(&self) -> Self { + ParIter { ..*self } + } +} + +impl fmt::Debug for ParIter<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::refs); + f.debug_list().entries(iter).finish() + } +} + +impl<'a, K: Sync, V: Sync> ParallelIterator for ParIter<'a, K, V> { + type Item = (&'a K, &'a V); + + parallel_iterator_methods!(Bucket::refs); +} + +impl IndexedParallelIterator for ParIter<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::refs); +} + +impl<'a, K, V, S> IntoParallelIterator for &'a mut IndexMap +where + K: Sync + Send, + V: Send, +{ + type Item = (&'a K, &'a mut V); + type Iter = ParIterMut<'a, K, V>; + + fn into_par_iter(self) -> Self::Iter { + ParIterMut { + entries: self.as_entries_mut(), + } + } +} + +impl<'a, K, V> IntoParallelIterator for &'a mut Slice +where + K: Sync + Send, + V: Send, +{ + type Item = (&'a K, &'a mut V); + type Iter = ParIterMut<'a, K, V>; + + fn into_par_iter(self) -> Self::Iter { + ParIterMut { + entries: &mut self.entries, + } + } +} + +/// A parallel mutable iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::par_iter_mut`] method +/// (provided by rayon's [`IntoParallelRefMutIterator`] trait). See its documentation for more. +/// +/// [`IndexMap::par_iter_mut`]: ../struct.IndexMap.html#method.par_iter_mut +pub struct ParIterMut<'a, K, V> { + entries: &'a mut [Bucket], +} + +impl fmt::Debug for ParIterMut<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::refs); + f.debug_list().entries(iter).finish() + } +} + +impl<'a, K: Sync + Send, V: Send> ParallelIterator for ParIterMut<'a, K, V> { + type Item = (&'a K, &'a mut V); + + parallel_iterator_methods!(Bucket::ref_mut); +} + +impl IndexedParallelIterator for ParIterMut<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::ref_mut); +} + +impl<'a, K, V, S> ParallelDrainRange for &'a mut IndexMap +where + K: Send, + V: Send, +{ + type Item = (K, V); + type Iter = ParDrain<'a, K, V>; + + fn par_drain>(self, range: R) -> Self::Iter { + ParDrain { + entries: self.core.par_drain(range), + } + } +} + +/// A parallel draining iterator over the entries of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::par_drain`] method +/// (provided by rayon's [`ParallelDrainRange`] trait). See its documentation for more. +/// +/// [`IndexMap::par_drain`]: ../struct.IndexMap.html#method.par_drain +pub struct ParDrain<'a, K: Send, V: Send> { + entries: rayon::vec::Drain<'a, Bucket>, +} + +impl ParallelIterator for ParDrain<'_, K, V> { + type Item = (K, V); + + parallel_iterator_methods!(Bucket::key_value); +} + +impl IndexedParallelIterator for ParDrain<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::key_value); +} + +/// Parallel iterator methods and other parallel methods. +/// +/// The following methods **require crate feature `"rayon"`**. +/// +/// See also the `IntoParallelIterator` implementations. +impl IndexMap +where + K: Sync, + V: Sync, +{ + /// Return a parallel iterator over the keys of the map. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the map is still preserved for operations like `reduce` and `collect`. + pub fn par_keys(&self) -> ParKeys<'_, K, V> { + ParKeys { + entries: self.as_entries(), + } + } + + /// Return a parallel iterator over the values of the map. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the map is still preserved for operations like `reduce` and `collect`. + pub fn par_values(&self) -> ParValues<'_, K, V> { + ParValues { + entries: self.as_entries(), + } + } +} + +/// Parallel iterator methods and other parallel methods. +/// +/// The following methods **require crate feature `"rayon"`**. +/// +/// See also the `IntoParallelIterator` implementations. +impl Slice +where + K: Sync, + V: Sync, +{ + /// Return a parallel iterator over the keys of the map slice. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the slice is still preserved for operations like `reduce` and `collect`. + pub fn par_keys(&self) -> ParKeys<'_, K, V> { + ParKeys { + entries: &self.entries, + } + } + + /// Return a parallel iterator over the values of the map slice. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the slice is still preserved for operations like `reduce` and `collect`. + pub fn par_values(&self) -> ParValues<'_, K, V> { + ParValues { + entries: &self.entries, + } + } +} + +impl IndexMap +where + K: Hash + Eq + Sync, + V: Sync, + S: BuildHasher, +{ + /// Returns `true` if `self` contains all of the same key-value pairs as `other`, + /// regardless of each map's indexed order, determined in parallel. + pub fn par_eq(&self, other: &IndexMap) -> bool + where + V: PartialEq, + V2: Sync, + S2: BuildHasher + Sync, + { + self.len() == other.len() + && self + .par_iter() + .all(move |(key, value)| other.get(key).map_or(false, |v| *value == *v)) + } +} + +/// A parallel iterator over the keys of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::par_keys`] method. +/// See its documentation for more. +pub struct ParKeys<'a, K, V> { + entries: &'a [Bucket], +} + +impl Clone for ParKeys<'_, K, V> { + fn clone(&self) -> Self { + ParKeys { ..*self } + } +} + +impl fmt::Debug for ParKeys<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::key_ref); + f.debug_list().entries(iter).finish() + } +} + +impl<'a, K: Sync, V: Sync> ParallelIterator for ParKeys<'a, K, V> { + type Item = &'a K; + + parallel_iterator_methods!(Bucket::key_ref); +} + +impl IndexedParallelIterator for ParKeys<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::key_ref); +} + +/// A parallel iterator over the values of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::par_values`] method. +/// See its documentation for more. +pub struct ParValues<'a, K, V> { + entries: &'a [Bucket], +} + +impl Clone for ParValues<'_, K, V> { + fn clone(&self) -> Self { + ParValues { ..*self } + } +} + +impl fmt::Debug for ParValues<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::value_ref); + f.debug_list().entries(iter).finish() + } +} + +impl<'a, K: Sync, V: Sync> ParallelIterator for ParValues<'a, K, V> { + type Item = &'a V; + + parallel_iterator_methods!(Bucket::value_ref); +} + +impl IndexedParallelIterator for ParValues<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::value_ref); +} + +impl IndexMap +where + K: Send, + V: Send, +{ + /// Return a parallel iterator over mutable references to the values of the map + /// + /// While parallel iterators can process items in any order, their relative order + /// in the map is still preserved for operations like `reduce` and `collect`. + pub fn par_values_mut(&mut self) -> ParValuesMut<'_, K, V> { + ParValuesMut { + entries: self.as_entries_mut(), + } + } +} + +impl Slice +where + K: Send, + V: Send, +{ + /// Return a parallel iterator over mutable references to the the values of the map slice. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the slice is still preserved for operations like `reduce` and `collect`. + pub fn par_values_mut(&mut self) -> ParValuesMut<'_, K, V> { + ParValuesMut { + entries: &mut self.entries, + } + } +} + +impl IndexMap +where + K: Send, + V: Send, +{ + /// Sort the map’s key-value pairs in parallel, by the default ordering of the keys. + pub fn par_sort_keys(&mut self) + where + K: Ord, + { + self.with_entries(|entries| { + entries.par_sort_by(|a, b| K::cmp(&a.key, &b.key)); + }); + } + + /// Sort the map’s key-value pairs in place and in parallel, using the comparison + /// function `cmp`. + /// + /// The comparison function receives two key and value pairs to compare (you + /// can sort by keys or values or their combination as needed). + pub fn par_sort_by(&mut self, cmp: F) + where + F: Fn(&K, &V, &K, &V) -> Ordering + Sync, + { + self.with_entries(|entries| { + entries.par_sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + }); + } + + /// Sort the key-value pairs of the map in parallel and return a by-value parallel + /// iterator of the key-value pairs with the result. + pub fn par_sorted_by(self, cmp: F) -> IntoParIter + where + F: Fn(&K, &V, &K, &V) -> Ordering + Sync, + { + let mut entries = self.into_entries(); + entries.par_sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + IntoParIter { entries } + } + + /// Sort the map's key-value pairs in parallel, by the default ordering of the keys. + pub fn par_sort_unstable_keys(&mut self) + where + K: Ord, + { + self.with_entries(|entries| { + entries.par_sort_unstable_by(|a, b| K::cmp(&a.key, &b.key)); + }); + } + + /// Sort the map's key-value pairs in place and in parallel, using the comparison + /// function `cmp`. + /// + /// The comparison function receives two key and value pairs to compare (you + /// can sort by keys or values or their combination as needed). + pub fn par_sort_unstable_by(&mut self, cmp: F) + where + F: Fn(&K, &V, &K, &V) -> Ordering + Sync, + { + self.with_entries(|entries| { + entries.par_sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + }); + } + + /// Sort the key-value pairs of the map in parallel and return a by-value parallel + /// iterator of the key-value pairs with the result. + pub fn par_sorted_unstable_by(self, cmp: F) -> IntoParIter + where + F: Fn(&K, &V, &K, &V) -> Ordering + Sync, + { + let mut entries = self.into_entries(); + entries.par_sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value)); + IntoParIter { entries } + } + + /// Sort the map’s key-value pairs in place and in parallel, using a sort-key extraction + /// function. + pub fn par_sort_by_cached_key(&mut self, sort_key: F) + where + T: Ord + Send, + F: Fn(&K, &V) -> T + Sync, + { + self.with_entries(move |entries| { + entries.par_sort_by_cached_key(move |a| sort_key(&a.key, &a.value)); + }); + } +} + +/// A parallel mutable iterator over the values of an [`IndexMap`]. +/// +/// This `struct` is created by the [`IndexMap::par_values_mut`] method. +/// See its documentation for more. +pub struct ParValuesMut<'a, K, V> { + entries: &'a mut [Bucket], +} + +impl fmt::Debug for ParValuesMut<'_, K, V> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::value_ref); + f.debug_list().entries(iter).finish() + } +} + +impl<'a, K: Send, V: Send> ParallelIterator for ParValuesMut<'a, K, V> { + type Item = &'a mut V; + + parallel_iterator_methods!(Bucket::value_mut); +} + +impl IndexedParallelIterator for ParValuesMut<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::value_mut); +} + +impl FromParallelIterator<(K, V)> for IndexMap +where + K: Eq + Hash + Send, + V: Send, + S: BuildHasher + Default + Send, +{ + fn from_par_iter(iter: I) -> Self + where + I: IntoParallelIterator, + { + let list = collect(iter); + let len = list.iter().map(Vec::len).sum(); + let mut map = Self::with_capacity_and_hasher(len, S::default()); + for vec in list { + map.extend(vec); + } + map + } +} + +impl ParallelExtend<(K, V)> for IndexMap +where + K: Eq + Hash + Send, + V: Send, + S: BuildHasher + Send, +{ + fn par_extend(&mut self, iter: I) + where + I: IntoParallelIterator, + { + for vec in collect(iter) { + self.extend(vec); + } + } +} + +impl<'a, K: 'a, V: 'a, S> ParallelExtend<(&'a K, &'a V)> for IndexMap +where + K: Copy + Eq + Hash + Send + Sync, + V: Copy + Send + Sync, + S: BuildHasher + Send, +{ + fn par_extend(&mut self, iter: I) + where + I: IntoParallelIterator, + { + for vec in collect(iter) { + self.extend(vec); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::string::String; + + #[test] + fn insert_order() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut map = IndexMap::new(); + + for &elt in &insert { + map.insert(elt, ()); + } + + assert_eq!(map.par_keys().count(), map.len()); + assert_eq!(map.par_keys().count(), insert.len()); + insert.par_iter().zip(map.par_keys()).for_each(|(a, b)| { + assert_eq!(a, b); + }); + (0..insert.len()) + .into_par_iter() + .zip(map.par_keys()) + .for_each(|(i, k)| { + assert_eq!(map.get_index(i).unwrap().0, k); + }); + } + + #[test] + fn partial_eq_and_eq() { + let mut map_a = IndexMap::new(); + map_a.insert(1, "1"); + map_a.insert(2, "2"); + let mut map_b = map_a.clone(); + assert!(map_a.par_eq(&map_b)); + map_b.swap_remove(&1); + assert!(!map_a.par_eq(&map_b)); + map_b.insert(3, "3"); + assert!(!map_a.par_eq(&map_b)); + + let map_c: IndexMap<_, String> = + map_b.into_par_iter().map(|(k, v)| (k, v.into())).collect(); + assert!(!map_a.par_eq(&map_c)); + assert!(!map_c.par_eq(&map_a)); + } + + #[test] + fn extend() { + let mut map = IndexMap::new(); + map.par_extend(vec![(&1, &2), (&3, &4)]); + map.par_extend(vec![(5, 6)]); + assert_eq!( + map.into_par_iter().collect::>(), + vec![(1, 2), (3, 4), (5, 6)] + ); + } + + #[test] + fn keys() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: IndexMap<_, _> = vec.into_par_iter().collect(); + let keys: Vec<_> = map.par_keys().copied().collect(); + assert_eq!(keys.len(), 3); + assert!(keys.contains(&1)); + assert!(keys.contains(&2)); + assert!(keys.contains(&3)); + } + + #[test] + fn values() { + let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let map: IndexMap<_, _> = vec.into_par_iter().collect(); + let values: Vec<_> = map.par_values().copied().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&'a')); + assert!(values.contains(&'b')); + assert!(values.contains(&'c')); + } + + #[test] + fn values_mut() { + let vec = vec![(1, 1), (2, 2), (3, 3)]; + let mut map: IndexMap<_, _> = vec.into_par_iter().collect(); + map.par_values_mut().for_each(|value| *value *= 2); + let values: Vec<_> = map.par_values().copied().collect(); + assert_eq!(values.len(), 3); + assert!(values.contains(&2)); + assert!(values.contains(&4)); + assert!(values.contains(&6)); + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/rayon/mod.rs b/bitbox02-bt/vendor/indexmap/src/rayon/mod.rs new file mode 100644 index 0000000..1d21569 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/rayon/mod.rs @@ -0,0 +1,29 @@ +#![cfg_attr(docsrs, doc(cfg(feature = "rayon")))] + +use rayon::prelude::*; + +use alloc::collections::LinkedList; + +use crate::vec::Vec; + +pub mod map; +pub mod set; + +// This form of intermediate collection is also how Rayon collects `HashMap`. +// Note that the order will also be preserved! +fn collect(iter: I) -> LinkedList> { + iter.into_par_iter() + .fold(Vec::new, |mut vec, elem| { + vec.push(elem); + vec + }) + .map(|vec| { + let mut list = LinkedList::new(); + list.push_back(vec); + list + }) + .reduce(LinkedList::new, |mut list1, mut list2| { + list1.append(&mut list2); + list1 + }) +} diff --git a/bitbox02-bt/vendor/indexmap/src/rayon/set.rs b/bitbox02-bt/vendor/indexmap/src/rayon/set.rs new file mode 100644 index 0000000..3904234 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/rayon/set.rs @@ -0,0 +1,756 @@ +//! Parallel iterator types for [`IndexSet`] with [rayon][::rayon]. +//! +//! You will rarely need to interact with this module directly unless you need to name one of the +//! iterator types. + +use super::collect; +use rayon::iter::plumbing::{Consumer, ProducerCallback, UnindexedConsumer}; +use rayon::prelude::*; + +use crate::vec::Vec; +use alloc::boxed::Box; +use core::cmp::Ordering; +use core::fmt; +use core::hash::{BuildHasher, Hash}; +use core::ops::RangeBounds; + +use crate::set::Slice; +use crate::Entries; +use crate::IndexSet; + +type Bucket = crate::Bucket; + +impl IntoParallelIterator for IndexSet +where + T: Send, +{ + type Item = T; + type Iter = IntoParIter; + + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + entries: self.into_entries(), + } + } +} + +impl IntoParallelIterator for Box> +where + T: Send, +{ + type Item = T; + type Iter = IntoParIter; + + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + entries: self.into_entries(), + } + } +} + +/// A parallel owning iterator over the items of an [`IndexSet`]. +/// +/// This `struct` is created by the [`IndexSet::into_par_iter`] method +/// (provided by rayon's [`IntoParallelIterator`] trait). See its documentation for more. +pub struct IntoParIter { + entries: Vec>, +} + +impl fmt::Debug for IntoParIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::key_ref); + f.debug_list().entries(iter).finish() + } +} + +impl ParallelIterator for IntoParIter { + type Item = T; + + parallel_iterator_methods!(Bucket::key); +} + +impl IndexedParallelIterator for IntoParIter { + indexed_parallel_iterator_methods!(Bucket::key); +} + +impl<'a, T, S> IntoParallelIterator for &'a IndexSet +where + T: Sync, +{ + type Item = &'a T; + type Iter = ParIter<'a, T>; + + fn into_par_iter(self) -> Self::Iter { + ParIter { + entries: self.as_entries(), + } + } +} + +impl<'a, T> IntoParallelIterator for &'a Slice +where + T: Sync, +{ + type Item = &'a T; + type Iter = ParIter<'a, T>; + + fn into_par_iter(self) -> Self::Iter { + ParIter { + entries: &self.entries, + } + } +} + +/// A parallel iterator over the items of an [`IndexSet`]. +/// +/// This `struct` is created by the [`IndexSet::par_iter`] method +/// (provided by rayon's [`IntoParallelRefIterator`] trait). See its documentation for more. +/// +/// [`IndexSet::par_iter`]: ../struct.IndexSet.html#method.par_iter +pub struct ParIter<'a, T> { + entries: &'a [Bucket], +} + +impl Clone for ParIter<'_, T> { + fn clone(&self) -> Self { + ParIter { ..*self } + } +} + +impl fmt::Debug for ParIter<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.entries.iter().map(Bucket::key_ref); + f.debug_list().entries(iter).finish() + } +} + +impl<'a, T: Sync> ParallelIterator for ParIter<'a, T> { + type Item = &'a T; + + parallel_iterator_methods!(Bucket::key_ref); +} + +impl IndexedParallelIterator for ParIter<'_, T> { + indexed_parallel_iterator_methods!(Bucket::key_ref); +} + +impl<'a, T, S> ParallelDrainRange for &'a mut IndexSet +where + T: Send, +{ + type Item = T; + type Iter = ParDrain<'a, T>; + + fn par_drain>(self, range: R) -> Self::Iter { + ParDrain { + entries: self.map.core.par_drain(range), + } + } +} + +/// A parallel draining iterator over the items of an [`IndexSet`]. +/// +/// This `struct` is created by the [`IndexSet::par_drain`] method +/// (provided by rayon's [`ParallelDrainRange`] trait). See its documentation for more. +/// +/// [`IndexSet::par_drain`]: ../struct.IndexSet.html#method.par_drain +pub struct ParDrain<'a, T: Send> { + entries: rayon::vec::Drain<'a, Bucket>, +} + +impl ParallelIterator for ParDrain<'_, T> { + type Item = T; + + parallel_iterator_methods!(Bucket::key); +} + +impl IndexedParallelIterator for ParDrain<'_, T> { + indexed_parallel_iterator_methods!(Bucket::key); +} + +/// Parallel iterator methods and other parallel methods. +/// +/// The following methods **require crate feature `"rayon"`**. +/// +/// See also the `IntoParallelIterator` implementations. +impl IndexSet +where + T: Hash + Eq + Sync, + S: BuildHasher + Sync, +{ + /// Return a parallel iterator over the values that are in `self` but not `other`. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the `self` set is still preserved for operations like `reduce` and `collect`. + pub fn par_difference<'a, S2>( + &'a self, + other: &'a IndexSet, + ) -> ParDifference<'a, T, S, S2> + where + S2: BuildHasher + Sync, + { + ParDifference { + set1: self, + set2: other, + } + } + + /// Return a parallel iterator over the values that are in `self` or `other`, + /// but not in both. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the sets is still preserved for operations like `reduce` and `collect`. + /// Values from `self` are produced in their original order, followed by + /// values from `other` in their original order. + pub fn par_symmetric_difference<'a, S2>( + &'a self, + other: &'a IndexSet, + ) -> ParSymmetricDifference<'a, T, S, S2> + where + S2: BuildHasher + Sync, + { + ParSymmetricDifference { + set1: self, + set2: other, + } + } + + /// Return a parallel iterator over the values that are in both `self` and `other`. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the `self` set is still preserved for operations like `reduce` and `collect`. + pub fn par_intersection<'a, S2>( + &'a self, + other: &'a IndexSet, + ) -> ParIntersection<'a, T, S, S2> + where + S2: BuildHasher + Sync, + { + ParIntersection { + set1: self, + set2: other, + } + } + + /// Return a parallel iterator over all values that are in `self` or `other`. + /// + /// While parallel iterators can process items in any order, their relative order + /// in the sets is still preserved for operations like `reduce` and `collect`. + /// Values from `self` are produced in their original order, followed by + /// values that are unique to `other` in their original order. + pub fn par_union<'a, S2>(&'a self, other: &'a IndexSet) -> ParUnion<'a, T, S, S2> + where + S2: BuildHasher + Sync, + { + ParUnion { + set1: self, + set2: other, + } + } + + /// Returns `true` if `self` contains all of the same values as `other`, + /// regardless of each set's indexed order, determined in parallel. + pub fn par_eq(&self, other: &IndexSet) -> bool + where + S2: BuildHasher + Sync, + { + self.len() == other.len() && self.par_is_subset(other) + } + + /// Returns `true` if `self` has no elements in common with `other`, + /// determined in parallel. + pub fn par_is_disjoint(&self, other: &IndexSet) -> bool + where + S2: BuildHasher + Sync, + { + if self.len() <= other.len() { + self.par_iter().all(move |value| !other.contains(value)) + } else { + other.par_iter().all(move |value| !self.contains(value)) + } + } + + /// Returns `true` if all elements of `other` are contained in `self`, + /// determined in parallel. + pub fn par_is_superset(&self, other: &IndexSet) -> bool + where + S2: BuildHasher + Sync, + { + other.par_is_subset(self) + } + + /// Returns `true` if all elements of `self` are contained in `other`, + /// determined in parallel. + pub fn par_is_subset(&self, other: &IndexSet) -> bool + where + S2: BuildHasher + Sync, + { + self.len() <= other.len() && self.par_iter().all(move |value| other.contains(value)) + } +} + +/// A parallel iterator producing elements in the difference of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::par_difference`] method. +/// See its documentation for more. +pub struct ParDifference<'a, T, S1, S2> { + set1: &'a IndexSet, + set2: &'a IndexSet, +} + +impl Clone for ParDifference<'_, T, S1, S2> { + fn clone(&self) -> Self { + ParDifference { ..*self } + } +} + +impl fmt::Debug for ParDifference<'_, T, S1, S2> +where + T: fmt::Debug + Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(self.set1.difference(self.set2)) + .finish() + } +} + +impl<'a, T, S1, S2> ParallelIterator for ParDifference<'a, T, S1, S2> +where + T: Hash + Eq + Sync, + S1: BuildHasher + Sync, + S2: BuildHasher + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + let Self { set1, set2 } = self; + + set1.par_iter() + .filter(move |&item| !set2.contains(item)) + .drive_unindexed(consumer) + } +} + +/// A parallel iterator producing elements in the intersection of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::par_intersection`] method. +/// See its documentation for more. +pub struct ParIntersection<'a, T, S1, S2> { + set1: &'a IndexSet, + set2: &'a IndexSet, +} + +impl Clone for ParIntersection<'_, T, S1, S2> { + fn clone(&self) -> Self { + ParIntersection { ..*self } + } +} + +impl fmt::Debug for ParIntersection<'_, T, S1, S2> +where + T: fmt::Debug + Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(self.set1.intersection(self.set2)) + .finish() + } +} + +impl<'a, T, S1, S2> ParallelIterator for ParIntersection<'a, T, S1, S2> +where + T: Hash + Eq + Sync, + S1: BuildHasher + Sync, + S2: BuildHasher + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + let Self { set1, set2 } = self; + + set1.par_iter() + .filter(move |&item| set2.contains(item)) + .drive_unindexed(consumer) + } +} + +/// A parallel iterator producing elements in the symmetric difference of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::par_symmetric_difference`] method. +/// See its documentation for more. +pub struct ParSymmetricDifference<'a, T, S1, S2> { + set1: &'a IndexSet, + set2: &'a IndexSet, +} + +impl Clone for ParSymmetricDifference<'_, T, S1, S2> { + fn clone(&self) -> Self { + ParSymmetricDifference { ..*self } + } +} + +impl fmt::Debug for ParSymmetricDifference<'_, T, S1, S2> +where + T: fmt::Debug + Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + .entries(self.set1.symmetric_difference(self.set2)) + .finish() + } +} + +impl<'a, T, S1, S2> ParallelIterator for ParSymmetricDifference<'a, T, S1, S2> +where + T: Hash + Eq + Sync, + S1: BuildHasher + Sync, + S2: BuildHasher + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + let Self { set1, set2 } = self; + + set1.par_difference(set2) + .chain(set2.par_difference(set1)) + .drive_unindexed(consumer) + } +} + +/// A parallel iterator producing elements in the union of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::par_union`] method. +/// See its documentation for more. +pub struct ParUnion<'a, T, S1, S2> { + set1: &'a IndexSet, + set2: &'a IndexSet, +} + +impl Clone for ParUnion<'_, T, S1, S2> { + fn clone(&self) -> Self { + ParUnion { ..*self } + } +} + +impl fmt::Debug for ParUnion<'_, T, S1, S2> +where + T: fmt::Debug + Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.set1.union(self.set2)).finish() + } +} + +impl<'a, T, S1, S2> ParallelIterator for ParUnion<'a, T, S1, S2> +where + T: Hash + Eq + Sync, + S1: BuildHasher + Sync, + S2: BuildHasher + Sync, +{ + type Item = &'a T; + + fn drive_unindexed(self, consumer: C) -> C::Result + where + C: UnindexedConsumer, + { + let Self { set1, set2 } = self; + + set1.par_iter() + .chain(set2.par_difference(set1)) + .drive_unindexed(consumer) + } +} + +/// Parallel sorting methods. +/// +/// The following methods **require crate feature `"rayon"`**. +impl IndexSet +where + T: Send, +{ + /// Sort the set’s values in parallel by their default ordering. + pub fn par_sort(&mut self) + where + T: Ord, + { + self.with_entries(|entries| { + entries.par_sort_by(|a, b| T::cmp(&a.key, &b.key)); + }); + } + + /// Sort the set’s values in place and in parallel, using the comparison function `cmp`. + pub fn par_sort_by(&mut self, cmp: F) + where + F: Fn(&T, &T) -> Ordering + Sync, + { + self.with_entries(|entries| { + entries.par_sort_by(move |a, b| cmp(&a.key, &b.key)); + }); + } + + /// Sort the values of the set in parallel and return a by-value parallel iterator of + /// the values with the result. + pub fn par_sorted_by(self, cmp: F) -> IntoParIter + where + F: Fn(&T, &T) -> Ordering + Sync, + { + let mut entries = self.into_entries(); + entries.par_sort_by(move |a, b| cmp(&a.key, &b.key)); + IntoParIter { entries } + } + + /// Sort the set's values in parallel by their default ordering. + pub fn par_sort_unstable(&mut self) + where + T: Ord, + { + self.with_entries(|entries| { + entries.par_sort_unstable_by(|a, b| T::cmp(&a.key, &b.key)); + }); + } + + /// Sort the set’s values in place and in parallel, using the comparison function `cmp`. + pub fn par_sort_unstable_by(&mut self, cmp: F) + where + F: Fn(&T, &T) -> Ordering + Sync, + { + self.with_entries(|entries| { + entries.par_sort_unstable_by(move |a, b| cmp(&a.key, &b.key)); + }); + } + + /// Sort the values of the set in parallel and return a by-value parallel iterator of + /// the values with the result. + pub fn par_sorted_unstable_by(self, cmp: F) -> IntoParIter + where + F: Fn(&T, &T) -> Ordering + Sync, + { + let mut entries = self.into_entries(); + entries.par_sort_unstable_by(move |a, b| cmp(&a.key, &b.key)); + IntoParIter { entries } + } + + /// Sort the set’s values in place and in parallel, using a key extraction function. + pub fn par_sort_by_cached_key(&mut self, sort_key: F) + where + K: Ord + Send, + F: Fn(&T) -> K + Sync, + { + self.with_entries(move |entries| { + entries.par_sort_by_cached_key(move |a| sort_key(&a.key)); + }); + } +} + +impl FromParallelIterator for IndexSet +where + T: Eq + Hash + Send, + S: BuildHasher + Default + Send, +{ + fn from_par_iter(iter: I) -> Self + where + I: IntoParallelIterator, + { + let list = collect(iter); + let len = list.iter().map(Vec::len).sum(); + let mut set = Self::with_capacity_and_hasher(len, S::default()); + for vec in list { + set.extend(vec); + } + set + } +} + +impl ParallelExtend for IndexSet +where + T: Eq + Hash + Send, + S: BuildHasher + Send, +{ + fn par_extend(&mut self, iter: I) + where + I: IntoParallelIterator, + { + for vec in collect(iter) { + self.extend(vec); + } + } +} + +impl<'a, T: 'a, S> ParallelExtend<&'a T> for IndexSet +where + T: Copy + Eq + Hash + Send + Sync, + S: BuildHasher + Send, +{ + fn par_extend(&mut self, iter: I) + where + I: IntoParallelIterator, + { + for vec in collect(iter) { + self.extend(vec); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn insert_order() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut set = IndexSet::new(); + + for &elt in &insert { + set.insert(elt); + } + + assert_eq!(set.par_iter().count(), set.len()); + assert_eq!(set.par_iter().count(), insert.len()); + insert.par_iter().zip(&set).for_each(|(a, b)| { + assert_eq!(a, b); + }); + (0..insert.len()) + .into_par_iter() + .zip(&set) + .for_each(|(i, v)| { + assert_eq!(set.get_index(i).unwrap(), v); + }); + } + + #[test] + fn partial_eq_and_eq() { + let mut set_a = IndexSet::new(); + set_a.insert(1); + set_a.insert(2); + let mut set_b = set_a.clone(); + assert!(set_a.par_eq(&set_b)); + set_b.swap_remove(&1); + assert!(!set_a.par_eq(&set_b)); + set_b.insert(3); + assert!(!set_a.par_eq(&set_b)); + + let set_c: IndexSet<_> = set_b.into_par_iter().collect(); + assert!(!set_a.par_eq(&set_c)); + assert!(!set_c.par_eq(&set_a)); + } + + #[test] + fn extend() { + let mut set = IndexSet::new(); + set.par_extend(vec![&1, &2, &3, &4]); + set.par_extend(vec![5, 6]); + assert_eq!( + set.into_par_iter().collect::>(), + vec![1, 2, 3, 4, 5, 6] + ); + } + + #[test] + fn comparisons() { + let set_a: IndexSet<_> = (0..3).collect(); + let set_b: IndexSet<_> = (3..6).collect(); + let set_c: IndexSet<_> = (0..6).collect(); + let set_d: IndexSet<_> = (3..9).collect(); + + assert!(!set_a.par_is_disjoint(&set_a)); + assert!(set_a.par_is_subset(&set_a)); + assert!(set_a.par_is_superset(&set_a)); + + assert!(set_a.par_is_disjoint(&set_b)); + assert!(set_b.par_is_disjoint(&set_a)); + assert!(!set_a.par_is_subset(&set_b)); + assert!(!set_b.par_is_subset(&set_a)); + assert!(!set_a.par_is_superset(&set_b)); + assert!(!set_b.par_is_superset(&set_a)); + + assert!(!set_a.par_is_disjoint(&set_c)); + assert!(!set_c.par_is_disjoint(&set_a)); + assert!(set_a.par_is_subset(&set_c)); + assert!(!set_c.par_is_subset(&set_a)); + assert!(!set_a.par_is_superset(&set_c)); + assert!(set_c.par_is_superset(&set_a)); + + assert!(!set_c.par_is_disjoint(&set_d)); + assert!(!set_d.par_is_disjoint(&set_c)); + assert!(!set_c.par_is_subset(&set_d)); + assert!(!set_d.par_is_subset(&set_c)); + assert!(!set_c.par_is_superset(&set_d)); + assert!(!set_d.par_is_superset(&set_c)); + } + + #[test] + fn iter_comparisons() { + use std::iter::empty; + + fn check<'a, I1, I2>(iter1: I1, iter2: I2) + where + I1: ParallelIterator, + I2: Iterator, + { + let v1: Vec<_> = iter1.copied().collect(); + let v2: Vec<_> = iter2.collect(); + assert_eq!(v1, v2); + } + + let set_a: IndexSet<_> = (0..3).collect(); + let set_b: IndexSet<_> = (3..6).collect(); + let set_c: IndexSet<_> = (0..6).collect(); + let set_d: IndexSet<_> = (3..9).rev().collect(); + + check(set_a.par_difference(&set_a), empty()); + check(set_a.par_symmetric_difference(&set_a), empty()); + check(set_a.par_intersection(&set_a), 0..3); + check(set_a.par_union(&set_a), 0..3); + + check(set_a.par_difference(&set_b), 0..3); + check(set_b.par_difference(&set_a), 3..6); + check(set_a.par_symmetric_difference(&set_b), 0..6); + check(set_b.par_symmetric_difference(&set_a), (3..6).chain(0..3)); + check(set_a.par_intersection(&set_b), empty()); + check(set_b.par_intersection(&set_a), empty()); + check(set_a.par_union(&set_b), 0..6); + check(set_b.par_union(&set_a), (3..6).chain(0..3)); + + check(set_a.par_difference(&set_c), empty()); + check(set_c.par_difference(&set_a), 3..6); + check(set_a.par_symmetric_difference(&set_c), 3..6); + check(set_c.par_symmetric_difference(&set_a), 3..6); + check(set_a.par_intersection(&set_c), 0..3); + check(set_c.par_intersection(&set_a), 0..3); + check(set_a.par_union(&set_c), 0..6); + check(set_c.par_union(&set_a), 0..6); + + check(set_c.par_difference(&set_d), 0..3); + check(set_d.par_difference(&set_c), (6..9).rev()); + check( + set_c.par_symmetric_difference(&set_d), + (0..3).chain((6..9).rev()), + ); + check( + set_d.par_symmetric_difference(&set_c), + (6..9).rev().chain(0..3), + ); + check(set_c.par_intersection(&set_d), 3..6); + check(set_d.par_intersection(&set_c), (3..6).rev()); + check(set_c.par_union(&set_d), (0..6).chain((6..9).rev())); + check(set_d.par_union(&set_c), (3..9).rev().chain(0..3)); + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/rustc.rs b/bitbox02-bt/vendor/indexmap/src/rustc.rs new file mode 100644 index 0000000..b843858 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/rustc.rs @@ -0,0 +1,158 @@ +//! Minimal support for `rustc-rayon`, not intended for general use. + +use crate::vec::Vec; +use crate::{Bucket, Entries, IndexMap, IndexSet}; + +use rustc_rayon::iter::plumbing::{Consumer, ProducerCallback, UnindexedConsumer}; +use rustc_rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; + +mod map { + use super::*; + + impl IntoParallelIterator for IndexMap + where + K: Send, + V: Send, + { + type Item = (K, V); + type Iter = IntoParIter; + + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + entries: self.into_entries(), + } + } + } + + pub struct IntoParIter { + entries: Vec>, + } + + impl ParallelIterator for IntoParIter { + type Item = (K, V); + + parallel_iterator_methods!(Bucket::key_value); + } + + impl IndexedParallelIterator for IntoParIter { + indexed_parallel_iterator_methods!(Bucket::key_value); + } + + impl<'a, K, V, S> IntoParallelIterator for &'a IndexMap + where + K: Sync, + V: Sync, + { + type Item = (&'a K, &'a V); + type Iter = ParIter<'a, K, V>; + + fn into_par_iter(self) -> Self::Iter { + ParIter { + entries: self.as_entries(), + } + } + } + + pub struct ParIter<'a, K, V> { + entries: &'a [Bucket], + } + + impl<'a, K: Sync, V: Sync> ParallelIterator for ParIter<'a, K, V> { + type Item = (&'a K, &'a V); + + parallel_iterator_methods!(Bucket::refs); + } + + impl IndexedParallelIterator for ParIter<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::refs); + } + + impl<'a, K, V, S> IntoParallelIterator for &'a mut IndexMap + where + K: Sync + Send, + V: Send, + { + type Item = (&'a K, &'a mut V); + type Iter = ParIterMut<'a, K, V>; + + fn into_par_iter(self) -> Self::Iter { + ParIterMut { + entries: self.as_entries_mut(), + } + } + } + + pub struct ParIterMut<'a, K, V> { + entries: &'a mut [Bucket], + } + + impl<'a, K: Sync + Send, V: Send> ParallelIterator for ParIterMut<'a, K, V> { + type Item = (&'a K, &'a mut V); + + parallel_iterator_methods!(Bucket::ref_mut); + } + + impl IndexedParallelIterator for ParIterMut<'_, K, V> { + indexed_parallel_iterator_methods!(Bucket::ref_mut); + } +} + +mod set { + use super::*; + + impl IntoParallelIterator for IndexSet + where + T: Send, + { + type Item = T; + type Iter = IntoParIter; + + fn into_par_iter(self) -> Self::Iter { + IntoParIter { + entries: self.into_entries(), + } + } + } + + pub struct IntoParIter { + entries: Vec>, + } + + impl ParallelIterator for IntoParIter { + type Item = T; + + parallel_iterator_methods!(Bucket::key); + } + + impl IndexedParallelIterator for IntoParIter { + indexed_parallel_iterator_methods!(Bucket::key); + } + + impl<'a, T, S> IntoParallelIterator for &'a IndexSet + where + T: Sync, + { + type Item = &'a T; + type Iter = ParIter<'a, T>; + + fn into_par_iter(self) -> Self::Iter { + ParIter { + entries: self.as_entries(), + } + } + } + + pub struct ParIter<'a, T> { + entries: &'a [Bucket], + } + + impl<'a, T: Sync> ParallelIterator for ParIter<'a, T> { + type Item = &'a T; + + parallel_iterator_methods!(Bucket::key_ref); + } + + impl IndexedParallelIterator for ParIter<'_, T> { + indexed_parallel_iterator_methods!(Bucket::key_ref); + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/serde.rs b/bitbox02-bt/vendor/indexmap/src/serde.rs new file mode 100644 index 0000000..25546d5 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/serde.rs @@ -0,0 +1,166 @@ +#![cfg_attr(docsrs, doc(cfg(feature = "serde")))] + +use serde::de::value::{MapDeserializer, SeqDeserializer}; +use serde::de::{ + Deserialize, Deserializer, Error, IntoDeserializer, MapAccess, SeqAccess, Visitor, +}; +use serde::ser::{Serialize, Serializer}; + +use core::fmt::{self, Formatter}; +use core::hash::{BuildHasher, Hash}; +use core::marker::PhantomData; +use core::{cmp, mem}; + +use crate::{Bucket, IndexMap, IndexSet}; + +/// Limit our preallocated capacity from a deserializer `size_hint()`. +/// +/// We do account for the `Bucket` overhead from its saved `hash` field, but we don't count the +/// `RawTable` allocation or the fact that its raw capacity will be rounded up to a power of two. +/// The "max" is an arbitrary choice anyway, not something that needs precise adherence. +/// +/// This is based on the internal `serde::de::size_hint::cautious(hint)` function. +pub(crate) fn cautious_capacity(hint: Option) -> usize { + const MAX_PREALLOC_BYTES: usize = 1024 * 1024; + + cmp::min( + hint.unwrap_or(0), + MAX_PREALLOC_BYTES / mem::size_of::>(), + ) +} + +impl Serialize for IndexMap +where + K: Serialize, + V: Serialize, +{ + fn serialize(&self, serializer: T) -> Result + where + T: Serializer, + { + serializer.collect_map(self) + } +} + +struct IndexMapVisitor(PhantomData<(K, V, S)>); + +impl<'de, K, V, S> Visitor<'de> for IndexMapVisitor +where + K: Deserialize<'de> + Eq + Hash, + V: Deserialize<'de>, + S: Default + BuildHasher, +{ + type Value = IndexMap; + + fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + write!(formatter, "a map") + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let capacity = cautious_capacity::(map.size_hint()); + let mut values = IndexMap::with_capacity_and_hasher(capacity, S::default()); + + while let Some((key, value)) = map.next_entry()? { + values.insert(key, value); + } + + Ok(values) + } +} + +impl<'de, K, V, S> Deserialize<'de> for IndexMap +where + K: Deserialize<'de> + Eq + Hash, + V: Deserialize<'de>, + S: Default + BuildHasher, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_map(IndexMapVisitor(PhantomData)) + } +} + +impl<'de, K, V, S, E> IntoDeserializer<'de, E> for IndexMap +where + K: IntoDeserializer<'de, E> + Eq + Hash, + V: IntoDeserializer<'de, E>, + S: BuildHasher, + E: Error, +{ + type Deserializer = MapDeserializer<'de, ::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +impl Serialize for IndexSet +where + T: Serialize, +{ + fn serialize(&self, serializer: Se) -> Result + where + Se: Serializer, + { + serializer.collect_seq(self) + } +} + +struct IndexSetVisitor(PhantomData<(T, S)>); + +impl<'de, T, S> Visitor<'de> for IndexSetVisitor +where + T: Deserialize<'de> + Eq + Hash, + S: Default + BuildHasher, +{ + type Value = IndexSet; + + fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + write!(formatter, "a set") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let capacity = cautious_capacity::(seq.size_hint()); + let mut values = IndexSet::with_capacity_and_hasher(capacity, S::default()); + + while let Some(value) = seq.next_element()? { + values.insert(value); + } + + Ok(values) + } +} + +impl<'de, T, S> Deserialize<'de> for IndexSet +where + T: Deserialize<'de> + Eq + Hash, + S: Default + BuildHasher, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_seq(IndexSetVisitor(PhantomData)) + } +} + +impl<'de, T, S, E> IntoDeserializer<'de, E> for IndexSet +where + T: IntoDeserializer<'de, E> + Eq + Hash, + S: BuildHasher, + E: Error, +{ + type Deserializer = SeqDeserializer<::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/set.rs b/bitbox02-bt/vendor/indexmap/src/set.rs new file mode 100644 index 0000000..5a91db9 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/set.rs @@ -0,0 +1,1290 @@ +//! A hash set implemented using [`IndexMap`] + +mod iter; +mod mutable; +mod slice; + +#[cfg(test)] +mod tests; + +pub use self::iter::{ + Difference, Drain, Intersection, IntoIter, Iter, Splice, SymmetricDifference, Union, +}; +pub use self::mutable::MutableValues; +pub use self::slice::Slice; + +#[cfg(feature = "rayon")] +pub use crate::rayon::set as rayon; +use crate::TryReserveError; + +#[cfg(feature = "std")] +use std::collections::hash_map::RandomState; + +use crate::util::try_simplify_range; +use alloc::boxed::Box; +use alloc::vec::Vec; +use core::cmp::Ordering; +use core::fmt; +use core::hash::{BuildHasher, Hash}; +use core::ops::{BitAnd, BitOr, BitXor, Index, RangeBounds, Sub}; + +use super::{Entries, Equivalent, IndexMap}; + +type Bucket = super::Bucket; + +/// A hash set where the iteration order of the values is independent of their +/// hash values. +/// +/// The interface is closely compatible with the standard +/// [`HashSet`][std::collections::HashSet], +/// but also has additional features. +/// +/// # Order +/// +/// The values have a consistent order that is determined by the sequence of +/// insertion and removal calls on the set. The order does not depend on the +/// values or the hash function at all. Note that insertion order and value +/// are not affected if a re-insertion is attempted once an element is +/// already present. +/// +/// All iterators traverse the set *in order*. Set operation iterators like +/// [`IndexSet::union`] produce a concatenated order, as do their matching "bitwise" +/// operators. See their documentation for specifics. +/// +/// The insertion order is preserved, with **notable exceptions** like the +/// [`.remove()`][Self::remove] or [`.swap_remove()`][Self::swap_remove] methods. +/// Methods such as [`.sort_by()`][Self::sort_by] of +/// course result in a new order, depending on the sorting order. +/// +/// # Indices +/// +/// The values are indexed in a compact range without holes in the range +/// `0..self.len()`. For example, the method `.get_full` looks up the index for +/// a value, and the method `.get_index` looks up the value by index. +/// +/// # Complexity +/// +/// Internally, `IndexSet` just holds an [`IndexMap`](IndexMap). Thus the complexity +/// of the two are the same for most methods. +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexSet; +/// +/// // Collects which letters appear in a sentence. +/// let letters: IndexSet<_> = "a short treatise on fungi".chars().collect(); +/// +/// assert!(letters.contains(&'s')); +/// assert!(letters.contains(&'t')); +/// assert!(letters.contains(&'u')); +/// assert!(!letters.contains(&'y')); +/// ``` +#[cfg(feature = "std")] +pub struct IndexSet { + pub(crate) map: IndexMap, +} +#[cfg(not(feature = "std"))] +pub struct IndexSet { + pub(crate) map: IndexMap, +} + +impl Clone for IndexSet +where + T: Clone, + S: Clone, +{ + fn clone(&self) -> Self { + IndexSet { + map: self.map.clone(), + } + } + + fn clone_from(&mut self, other: &Self) { + self.map.clone_from(&other.map); + } +} + +impl Entries for IndexSet { + type Entry = Bucket; + + #[inline] + fn into_entries(self) -> Vec { + self.map.into_entries() + } + + #[inline] + fn as_entries(&self) -> &[Self::Entry] { + self.map.as_entries() + } + + #[inline] + fn as_entries_mut(&mut self) -> &mut [Self::Entry] { + self.map.as_entries_mut() + } + + fn with_entries(&mut self, f: F) + where + F: FnOnce(&mut [Self::Entry]), + { + self.map.with_entries(f); + } +} + +impl fmt::Debug for IndexSet +where + T: fmt::Debug, +{ + #[cfg(not(feature = "test_debug"))] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set().entries(self.iter()).finish() + } + + #[cfg(feature = "test_debug")] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Let the inner `IndexMap` print all of its details + f.debug_struct("IndexSet").field("map", &self.map).finish() + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl IndexSet { + /// Create a new set. (Does not allocate.) + pub fn new() -> Self { + IndexSet { + map: IndexMap::new(), + } + } + + /// Create a new set with capacity for `n` elements. + /// (Does not allocate if `n` is zero.) + /// + /// Computes in **O(n)** time. + pub fn with_capacity(n: usize) -> Self { + IndexSet { + map: IndexMap::with_capacity(n), + } + } +} + +impl IndexSet { + /// Create a new set with capacity for `n` elements. + /// (Does not allocate if `n` is zero.) + /// + /// Computes in **O(n)** time. + pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self { + IndexSet { + map: IndexMap::with_capacity_and_hasher(n, hash_builder), + } + } + + /// Create a new set with `hash_builder`. + /// + /// This function is `const`, so it + /// can be called in `static` contexts. + pub const fn with_hasher(hash_builder: S) -> Self { + IndexSet { + map: IndexMap::with_hasher(hash_builder), + } + } + + /// Return the number of elements the set can hold without reallocating. + /// + /// This number is a lower bound; the set might be able to hold more, + /// but is guaranteed to be able to hold at least this many. + /// + /// Computes in **O(1)** time. + pub fn capacity(&self) -> usize { + self.map.capacity() + } + + /// Return a reference to the set's `BuildHasher`. + pub fn hasher(&self) -> &S { + self.map.hasher() + } + + /// Return the number of elements in the set. + /// + /// Computes in **O(1)** time. + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns true if the set contains no elements. + /// + /// Computes in **O(1)** time. + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + + /// Return an iterator over the values of the set, in their order + pub fn iter(&self) -> Iter<'_, T> { + Iter::new(self.as_entries()) + } + + /// Remove all elements in the set, while preserving its capacity. + /// + /// Computes in **O(n)** time. + pub fn clear(&mut self) { + self.map.clear(); + } + + /// Shortens the set, keeping the first `len` elements and dropping the rest. + /// + /// If `len` is greater than the set's current length, this has no effect. + pub fn truncate(&mut self, len: usize) { + self.map.truncate(len); + } + + /// Clears the `IndexSet` in the given index range, returning those values + /// as a drain iterator. + /// + /// The range may be any type that implements [`RangeBounds`], + /// including all of the `std::ops::Range*` types, or even a tuple pair of + /// `Bound` start and end values. To drain the set entirely, use `RangeFull` + /// like `set.drain(..)`. + /// + /// This shifts down all entries following the drained range to fill the + /// gap, and keeps the allocated memory for reuse. + /// + /// ***Panics*** if the starting point is greater than the end point or if + /// the end point is greater than the length of the set. + pub fn drain(&mut self, range: R) -> Drain<'_, T> + where + R: RangeBounds, + { + Drain::new(self.map.core.drain(range)) + } + + /// Splits the collection into two at the given index. + /// + /// Returns a newly allocated set containing the elements in the range + /// `[at, len)`. After the call, the original set will be left containing + /// the elements `[0, at)` with its previous capacity unchanged. + /// + /// ***Panics*** if `at > len`. + pub fn split_off(&mut self, at: usize) -> Self + where + S: Clone, + { + Self { + map: self.map.split_off(at), + } + } + + /// Reserve capacity for `additional` more values. + /// + /// Computes in **O(n)** time. + pub fn reserve(&mut self, additional: usize) { + self.map.reserve(additional); + } + + /// Reserve capacity for `additional` more values, without over-allocating. + /// + /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid + /// frequent re-allocations. However, the underlying data structures may still have internal + /// capacity requirements, and the allocator itself may give more space than requested, so this + /// cannot be relied upon to be precisely minimal. + /// + /// Computes in **O(n)** time. + pub fn reserve_exact(&mut self, additional: usize) { + self.map.reserve_exact(additional); + } + + /// Try to reserve capacity for `additional` more values. + /// + /// Computes in **O(n)** time. + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.map.try_reserve(additional) + } + + /// Try to reserve capacity for `additional` more values, without over-allocating. + /// + /// Unlike `try_reserve`, this does not deliberately over-allocate the entry capacity to avoid + /// frequent re-allocations. However, the underlying data structures may still have internal + /// capacity requirements, and the allocator itself may give more space than requested, so this + /// cannot be relied upon to be precisely minimal. + /// + /// Computes in **O(n)** time. + pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.map.try_reserve_exact(additional) + } + + /// Shrink the capacity of the set as much as possible. + /// + /// Computes in **O(n)** time. + pub fn shrink_to_fit(&mut self) { + self.map.shrink_to_fit(); + } + + /// Shrink the capacity of the set with a lower limit. + /// + /// Computes in **O(n)** time. + pub fn shrink_to(&mut self, min_capacity: usize) { + self.map.shrink_to(min_capacity); + } +} + +impl IndexSet +where + T: Hash + Eq, + S: BuildHasher, +{ + /// Insert the value into the set. + /// + /// If an equivalent item already exists in the set, it returns + /// `false` leaving the original value in the set and without + /// altering its insertion order. Otherwise, it inserts the new + /// item and returns `true`. + /// + /// Computes in **O(1)** time (amortized average). + pub fn insert(&mut self, value: T) -> bool { + self.map.insert(value, ()).is_none() + } + + /// Insert the value into the set, and get its index. + /// + /// If an equivalent item already exists in the set, it returns + /// the index of the existing item and `false`, leaving the + /// original value in the set and without altering its insertion + /// order. Otherwise, it inserts the new item and returns the index + /// of the inserted item and `true`. + /// + /// Computes in **O(1)** time (amortized average). + pub fn insert_full(&mut self, value: T) -> (usize, bool) { + let (index, existing) = self.map.insert_full(value, ()); + (index, existing.is_none()) + } + + /// Insert the value into the set at its ordered position among sorted values. + /// + /// This is equivalent to finding the position with + /// [`binary_search`][Self::binary_search], and if needed calling + /// [`insert_before`][Self::insert_before] for a new value. + /// + /// If the sorted item is found in the set, it returns the index of that + /// existing item and `false`, without any change. Otherwise, it inserts the + /// new item and returns its sorted index and `true`. + /// + /// If the existing items are **not** already sorted, then the insertion + /// index is unspecified (like [`slice::binary_search`]), but the value + /// is moved to or inserted at that position regardless. + /// + /// Computes in **O(n)** time (average). Instead of repeating calls to + /// `insert_sorted`, it may be faster to call batched [`insert`][Self::insert] + /// or [`extend`][Self::extend] and only call [`sort`][Self::sort] or + /// [`sort_unstable`][Self::sort_unstable] once. + pub fn insert_sorted(&mut self, value: T) -> (usize, bool) + where + T: Ord, + { + let (index, existing) = self.map.insert_sorted(value, ()); + (index, existing.is_none()) + } + + /// Insert the value into the set before the value at the given index, or at the end. + /// + /// If an equivalent item already exists in the set, it returns `false` leaving the + /// original value in the set, but moved to the new position. The returned index + /// will either be the given index or one less, depending on how the value moved. + /// (See [`shift_insert`](Self::shift_insert) for different behavior here.) + /// + /// Otherwise, it inserts the new value exactly at the given index and returns `true`. + /// + /// ***Panics*** if `index` is out of bounds. + /// Valid indices are `0..=set.len()` (inclusive). + /// + /// Computes in **O(n)** time (average). + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexSet; + /// let mut set: IndexSet = ('a'..='z').collect(); + /// + /// // The new value '*' goes exactly at the given index. + /// assert_eq!(set.get_index_of(&'*'), None); + /// assert_eq!(set.insert_before(10, '*'), (10, true)); + /// assert_eq!(set.get_index_of(&'*'), Some(10)); + /// + /// // Moving the value 'a' up will shift others down, so this moves *before* 10 to index 9. + /// assert_eq!(set.insert_before(10, 'a'), (9, false)); + /// assert_eq!(set.get_index_of(&'a'), Some(9)); + /// assert_eq!(set.get_index_of(&'*'), Some(10)); + /// + /// // Moving the value 'z' down will shift others up, so this moves to exactly 10. + /// assert_eq!(set.insert_before(10, 'z'), (10, false)); + /// assert_eq!(set.get_index_of(&'z'), Some(10)); + /// assert_eq!(set.get_index_of(&'*'), Some(11)); + /// + /// // Moving or inserting before the endpoint is also valid. + /// assert_eq!(set.len(), 27); + /// assert_eq!(set.insert_before(set.len(), '*'), (26, false)); + /// assert_eq!(set.get_index_of(&'*'), Some(26)); + /// assert_eq!(set.insert_before(set.len(), '+'), (27, true)); + /// assert_eq!(set.get_index_of(&'+'), Some(27)); + /// assert_eq!(set.len(), 28); + /// ``` + pub fn insert_before(&mut self, index: usize, value: T) -> (usize, bool) { + let (index, existing) = self.map.insert_before(index, value, ()); + (index, existing.is_none()) + } + + /// Insert the value into the set at the given index. + /// + /// If an equivalent item already exists in the set, it returns `false` leaving + /// the original value in the set, but moved to the given index. + /// Note that existing values **cannot** be moved to `index == set.len()`! + /// (See [`insert_before`](Self::insert_before) for different behavior here.) + /// + /// Otherwise, it inserts the new value at the given index and returns `true`. + /// + /// ***Panics*** if `index` is out of bounds. + /// Valid indices are `0..set.len()` (exclusive) when moving an existing value, or + /// `0..=set.len()` (inclusive) when inserting a new value. + /// + /// Computes in **O(n)** time (average). + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexSet; + /// let mut set: IndexSet = ('a'..='z').collect(); + /// + /// // The new value '*' goes exactly at the given index. + /// assert_eq!(set.get_index_of(&'*'), None); + /// assert_eq!(set.shift_insert(10, '*'), true); + /// assert_eq!(set.get_index_of(&'*'), Some(10)); + /// + /// // Moving the value 'a' up to 10 will shift others down, including the '*' that was at 10. + /// assert_eq!(set.shift_insert(10, 'a'), false); + /// assert_eq!(set.get_index_of(&'a'), Some(10)); + /// assert_eq!(set.get_index_of(&'*'), Some(9)); + /// + /// // Moving the value 'z' down to 9 will shift others up, including the '*' that was at 9. + /// assert_eq!(set.shift_insert(9, 'z'), false); + /// assert_eq!(set.get_index_of(&'z'), Some(9)); + /// assert_eq!(set.get_index_of(&'*'), Some(10)); + /// + /// // Existing values can move to len-1 at most, but new values can insert at the endpoint. + /// assert_eq!(set.len(), 27); + /// assert_eq!(set.shift_insert(set.len() - 1, '*'), false); + /// assert_eq!(set.get_index_of(&'*'), Some(26)); + /// assert_eq!(set.shift_insert(set.len(), '+'), true); + /// assert_eq!(set.get_index_of(&'+'), Some(27)); + /// assert_eq!(set.len(), 28); + /// ``` + /// + /// ```should_panic + /// use indexmap::IndexSet; + /// let mut set: IndexSet = ('a'..='z').collect(); + /// + /// // This is an invalid index for moving an existing value! + /// set.shift_insert(set.len(), 'a'); + /// ``` + pub fn shift_insert(&mut self, index: usize, value: T) -> bool { + self.map.shift_insert(index, value, ()).is_none() + } + + /// Adds a value to the set, replacing the existing value, if any, that is + /// equal to the given one, without altering its insertion order. Returns + /// the replaced value. + /// + /// Computes in **O(1)** time (average). + pub fn replace(&mut self, value: T) -> Option { + self.replace_full(value).1 + } + + /// Adds a value to the set, replacing the existing value, if any, that is + /// equal to the given one, without altering its insertion order. Returns + /// the index of the item and its replaced value. + /// + /// Computes in **O(1)** time (average). + pub fn replace_full(&mut self, value: T) -> (usize, Option) { + let hash = self.map.hash(&value); + match self.map.core.replace_full(hash, value, ()) { + (i, Some((replaced, ()))) => (i, Some(replaced)), + (i, None) => (i, None), + } + } + + /// Return an iterator over the values that are in `self` but not `other`. + /// + /// Values are produced in the same order that they appear in `self`. + pub fn difference<'a, S2>(&'a self, other: &'a IndexSet) -> Difference<'a, T, S2> + where + S2: BuildHasher, + { + Difference::new(self, other) + } + + /// Return an iterator over the values that are in `self` or `other`, + /// but not in both. + /// + /// Values from `self` are produced in their original order, followed by + /// values from `other` in their original order. + pub fn symmetric_difference<'a, S2>( + &'a self, + other: &'a IndexSet, + ) -> SymmetricDifference<'a, T, S, S2> + where + S2: BuildHasher, + { + SymmetricDifference::new(self, other) + } + + /// Return an iterator over the values that are in both `self` and `other`. + /// + /// Values are produced in the same order that they appear in `self`. + pub fn intersection<'a, S2>(&'a self, other: &'a IndexSet) -> Intersection<'a, T, S2> + where + S2: BuildHasher, + { + Intersection::new(self, other) + } + + /// Return an iterator over all values that are in `self` or `other`. + /// + /// Values from `self` are produced in their original order, followed by + /// values that are unique to `other` in their original order. + pub fn union<'a, S2>(&'a self, other: &'a IndexSet) -> Union<'a, T, S> + where + S2: BuildHasher, + { + Union::new(self, other) + } + + /// Creates a splicing iterator that replaces the specified range in the set + /// with the given `replace_with` iterator and yields the removed items. + /// `replace_with` does not need to be the same length as `range`. + /// + /// The `range` is removed even if the iterator is not consumed until the + /// end. It is unspecified how many elements are removed from the set if the + /// `Splice` value is leaked. + /// + /// The input iterator `replace_with` is only consumed when the `Splice` + /// value is dropped. If a value from the iterator matches an existing entry + /// in the set (outside of `range`), then the original will be unchanged. + /// Otherwise, the new value will be inserted in the replaced `range`. + /// + /// ***Panics*** if the starting point is greater than the end point or if + /// the end point is greater than the length of the set. + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexSet; + /// + /// let mut set = IndexSet::from([0, 1, 2, 3, 4]); + /// let new = [5, 4, 3, 2, 1]; + /// let removed: Vec<_> = set.splice(2..4, new).collect(); + /// + /// // 1 and 4 kept their positions, while 5, 3, and 2 were newly inserted. + /// assert!(set.into_iter().eq([0, 1, 5, 3, 2, 4])); + /// assert_eq!(removed, &[2, 3]); + /// ``` + pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, T, S> + where + R: RangeBounds, + I: IntoIterator, + { + Splice::new(self, range, replace_with.into_iter()) + } + + /// Moves all values from `other` into `self`, leaving `other` empty. + /// + /// This is equivalent to calling [`insert`][Self::insert] for each value + /// from `other` in order, which means that values that already exist + /// in `self` are unchanged in their current position. + /// + /// See also [`union`][Self::union] to iterate the combined values by + /// reference, without modifying `self` or `other`. + /// + /// # Examples + /// + /// ``` + /// use indexmap::IndexSet; + /// + /// let mut a = IndexSet::from([3, 2, 1]); + /// let mut b = IndexSet::from([3, 4, 5]); + /// let old_capacity = b.capacity(); + /// + /// a.append(&mut b); + /// + /// assert_eq!(a.len(), 5); + /// assert_eq!(b.len(), 0); + /// assert_eq!(b.capacity(), old_capacity); + /// + /// assert!(a.iter().eq(&[3, 2, 1, 4, 5])); + /// ``` + pub fn append(&mut self, other: &mut IndexSet) { + self.map.append(&mut other.map); + } +} + +impl IndexSet +where + S: BuildHasher, +{ + /// Return `true` if an equivalent to `value` exists in the set. + /// + /// Computes in **O(1)** time (average). + pub fn contains(&self, value: &Q) -> bool + where + Q: ?Sized + Hash + Equivalent, + { + self.map.contains_key(value) + } + + /// Return a reference to the value stored in the set, if it is present, + /// else `None`. + /// + /// Computes in **O(1)** time (average). + pub fn get(&self, value: &Q) -> Option<&T> + where + Q: ?Sized + Hash + Equivalent, + { + self.map.get_key_value(value).map(|(x, &())| x) + } + + /// Return item index and value + pub fn get_full(&self, value: &Q) -> Option<(usize, &T)> + where + Q: ?Sized + Hash + Equivalent, + { + self.map.get_full(value).map(|(i, x, &())| (i, x)) + } + + /// Return item index, if it exists in the set + /// + /// Computes in **O(1)** time (average). + pub fn get_index_of(&self, value: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + self.map.get_index_of(value) + } + + /// Remove the value from the set, and return `true` if it was present. + /// + /// **NOTE:** This is equivalent to [`.swap_remove(value)`][Self::swap_remove], replacing this + /// value's position with the last element, and it is deprecated in favor of calling that + /// explicitly. If you need to preserve the relative order of the values in the set, use + /// [`.shift_remove(value)`][Self::shift_remove] instead. + #[deprecated(note = "`remove` disrupts the set order -- \ + use `swap_remove` or `shift_remove` for explicit behavior.")] + pub fn remove(&mut self, value: &Q) -> bool + where + Q: ?Sized + Hash + Equivalent, + { + self.swap_remove(value) + } + + /// Remove the value from the set, and return `true` if it was present. + /// + /// Like [`Vec::swap_remove`], the value is removed by swapping it with the + /// last element of the set and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Return `false` if `value` was not in the set. + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove(&mut self, value: &Q) -> bool + where + Q: ?Sized + Hash + Equivalent, + { + self.map.swap_remove(value).is_some() + } + + /// Remove the value from the set, and return `true` if it was present. + /// + /// Like [`Vec::remove`], the value is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Return `false` if `value` was not in the set. + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove(&mut self, value: &Q) -> bool + where + Q: ?Sized + Hash + Equivalent, + { + self.map.shift_remove(value).is_some() + } + + /// Removes and returns the value in the set, if any, that is equal to the + /// given one. + /// + /// **NOTE:** This is equivalent to [`.swap_take(value)`][Self::swap_take], replacing this + /// value's position with the last element, and it is deprecated in favor of calling that + /// explicitly. If you need to preserve the relative order of the values in the set, use + /// [`.shift_take(value)`][Self::shift_take] instead. + #[deprecated(note = "`take` disrupts the set order -- \ + use `swap_take` or `shift_take` for explicit behavior.")] + pub fn take(&mut self, value: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + self.swap_take(value) + } + + /// Removes and returns the value in the set, if any, that is equal to the + /// given one. + /// + /// Like [`Vec::swap_remove`], the value is removed by swapping it with the + /// last element of the set and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Return `None` if `value` was not in the set. + /// + /// Computes in **O(1)** time (average). + pub fn swap_take(&mut self, value: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + self.map.swap_remove_entry(value).map(|(x, ())| x) + } + + /// Removes and returns the value in the set, if any, that is equal to the + /// given one. + /// + /// Like [`Vec::remove`], the value is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Return `None` if `value` was not in the set. + /// + /// Computes in **O(n)** time (average). + pub fn shift_take(&mut self, value: &Q) -> Option + where + Q: ?Sized + Hash + Equivalent, + { + self.map.shift_remove_entry(value).map(|(x, ())| x) + } + + /// Remove the value from the set return it and the index it had. + /// + /// Like [`Vec::swap_remove`], the value is removed by swapping it with the + /// last element of the set and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Return `None` if `value` was not in the set. + pub fn swap_remove_full(&mut self, value: &Q) -> Option<(usize, T)> + where + Q: ?Sized + Hash + Equivalent, + { + self.map.swap_remove_full(value).map(|(i, x, ())| (i, x)) + } + + /// Remove the value from the set return it and the index it had. + /// + /// Like [`Vec::remove`], the value is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Return `None` if `value` was not in the set. + pub fn shift_remove_full(&mut self, value: &Q) -> Option<(usize, T)> + where + Q: ?Sized + Hash + Equivalent, + { + self.map.shift_remove_full(value).map(|(i, x, ())| (i, x)) + } +} + +impl IndexSet { + /// Remove the last value + /// + /// This preserves the order of the remaining elements. + /// + /// Computes in **O(1)** time (average). + #[doc(alias = "pop_last")] // like `BTreeSet` + pub fn pop(&mut self) -> Option { + self.map.pop().map(|(x, ())| x) + } + + /// Scan through each value in the set and keep those where the + /// closure `keep` returns `true`. + /// + /// The elements are visited in order, and remaining elements keep their + /// order. + /// + /// Computes in **O(n)** time (average). + pub fn retain(&mut self, mut keep: F) + where + F: FnMut(&T) -> bool, + { + self.map.retain(move |x, &mut ()| keep(x)) + } + + /// Sort the set’s values by their default ordering. + /// + /// This is a stable sort -- but equivalent values should not normally coexist in + /// a set at all, so [`sort_unstable`][Self::sort_unstable] is preferred + /// because it is generally faster and doesn't allocate auxiliary memory. + /// + /// See [`sort_by`](Self::sort_by) for details. + pub fn sort(&mut self) + where + T: Ord, + { + self.map.sort_keys() + } + + /// Sort the set’s values in place using the comparison function `cmp`. + /// + /// Computes in **O(n log n)** time and **O(n)** space. The sort is stable. + pub fn sort_by(&mut self, mut cmp: F) + where + F: FnMut(&T, &T) -> Ordering, + { + self.map.sort_by(move |a, _, b, _| cmp(a, b)); + } + + /// Sort the values of the set and return a by-value iterator of + /// the values with the result. + /// + /// The sort is stable. + pub fn sorted_by(self, mut cmp: F) -> IntoIter + where + F: FnMut(&T, &T) -> Ordering, + { + let mut entries = self.into_entries(); + entries.sort_by(move |a, b| cmp(&a.key, &b.key)); + IntoIter::new(entries) + } + + /// Sort the set's values by their default ordering. + /// + /// See [`sort_unstable_by`](Self::sort_unstable_by) for details. + pub fn sort_unstable(&mut self) + where + T: Ord, + { + self.map.sort_unstable_keys() + } + + /// Sort the set's values in place using the comparison function `cmp`. + /// + /// Computes in **O(n log n)** time. The sort is unstable. + pub fn sort_unstable_by(&mut self, mut cmp: F) + where + F: FnMut(&T, &T) -> Ordering, + { + self.map.sort_unstable_by(move |a, _, b, _| cmp(a, b)) + } + + /// Sort the values of the set and return a by-value iterator of + /// the values with the result. + pub fn sorted_unstable_by(self, mut cmp: F) -> IntoIter + where + F: FnMut(&T, &T) -> Ordering, + { + let mut entries = self.into_entries(); + entries.sort_unstable_by(move |a, b| cmp(&a.key, &b.key)); + IntoIter::new(entries) + } + + /// Sort the set’s values in place using a key extraction function. + /// + /// During sorting, the function is called at most once per entry, by using temporary storage + /// to remember the results of its evaluation. The order of calls to the function is + /// unspecified and may change between versions of `indexmap` or the standard library. + /// + /// Computes in **O(m n + n log n + c)** time () and **O(n)** space, where the function is + /// **O(m)**, *n* is the length of the map, and *c* the capacity. The sort is stable. + pub fn sort_by_cached_key(&mut self, mut sort_key: F) + where + K: Ord, + F: FnMut(&T) -> K, + { + self.with_entries(move |entries| { + entries.sort_by_cached_key(move |a| sort_key(&a.key)); + }); + } + + /// Search over a sorted set for a value. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search`] for more details. + /// + /// Computes in **O(log(n))** time, which is notably less scalable than looking the value up + /// using [`get_index_of`][IndexSet::get_index_of], but this can also position missing values. + pub fn binary_search(&self, x: &T) -> Result + where + T: Ord, + { + self.as_slice().binary_search(x) + } + + /// Search over a sorted set with a comparator function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result + where + F: FnMut(&'a T) -> Ordering, + { + self.as_slice().binary_search_by(f) + } + + /// Search over a sorted set with an extraction function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by_key`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result + where + F: FnMut(&'a T) -> B, + B: Ord, + { + self.as_slice().binary_search_by_key(b, f) + } + + /// Returns the index of the partition point of a sorted set according to the given predicate + /// (the index of the first element of the second partition). + /// + /// See [`slice::partition_point`] for more details. + /// + /// Computes in **O(log(n))** time. + #[must_use] + pub fn partition_point

(&self, pred: P) -> usize + where + P: FnMut(&T) -> bool, + { + self.as_slice().partition_point(pred) + } + + /// Reverses the order of the set’s values in place. + /// + /// Computes in **O(n)** time and **O(1)** space. + pub fn reverse(&mut self) { + self.map.reverse() + } + + /// Returns a slice of all the values in the set. + /// + /// Computes in **O(1)** time. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.as_entries()) + } + + /// Converts into a boxed slice of all the values in the set. + /// + /// Note that this will drop the inner hash table and any excess capacity. + pub fn into_boxed_slice(self) -> Box> { + Slice::from_boxed(self.into_entries().into_boxed_slice()) + } + + /// Get a value by index + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + pub fn get_index(&self, index: usize) -> Option<&T> { + self.as_entries().get(index).map(Bucket::key_ref) + } + + /// Returns a slice of values in the given range of indices. + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + pub fn get_range>(&self, range: R) -> Option<&Slice> { + let entries = self.as_entries(); + let range = try_simplify_range(range, entries.len())?; + entries.get(range).map(Slice::from_slice) + } + + /// Get the first value + /// + /// Computes in **O(1)** time. + pub fn first(&self) -> Option<&T> { + self.as_entries().first().map(Bucket::key_ref) + } + + /// Get the last value + /// + /// Computes in **O(1)** time. + pub fn last(&self) -> Option<&T> { + self.as_entries().last().map(Bucket::key_ref) + } + + /// Remove the value by index + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Like [`Vec::swap_remove`], the value is removed by swapping it with the + /// last element of the set and popping it off. **This perturbs + /// the position of what used to be the last element!** + /// + /// Computes in **O(1)** time (average). + pub fn swap_remove_index(&mut self, index: usize) -> Option { + self.map.swap_remove_index(index).map(|(x, ())| x) + } + + /// Remove the value by index + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Like [`Vec::remove`], the value is removed by shifting all of the + /// elements that follow it, preserving their relative order. + /// **This perturbs the index of all of those elements!** + /// + /// Computes in **O(n)** time (average). + pub fn shift_remove_index(&mut self, index: usize) -> Option { + self.map.shift_remove_index(index).map(|(x, ())| x) + } + + /// Moves the position of a value from one index to another + /// by shifting all other values in-between. + /// + /// * If `from < to`, the other values will shift down while the targeted value moves up. + /// * If `from > to`, the other values will shift up while the targeted value moves down. + /// + /// ***Panics*** if `from` or `to` are out of bounds. + /// + /// Computes in **O(n)** time (average). + pub fn move_index(&mut self, from: usize, to: usize) { + self.map.move_index(from, to) + } + + /// Swaps the position of two values in the set. + /// + /// ***Panics*** if `a` or `b` are out of bounds. + /// + /// Computes in **O(1)** time (average). + pub fn swap_indices(&mut self, a: usize, b: usize) { + self.map.swap_indices(a, b) + } +} + +/// Access [`IndexSet`] values at indexed positions. +/// +/// # Examples +/// +/// ``` +/// use indexmap::IndexSet; +/// +/// let mut set = IndexSet::new(); +/// for word in "Lorem ipsum dolor sit amet".split_whitespace() { +/// set.insert(word.to_string()); +/// } +/// assert_eq!(set[0], "Lorem"); +/// assert_eq!(set[1], "ipsum"); +/// set.reverse(); +/// assert_eq!(set[0], "amet"); +/// assert_eq!(set[1], "sit"); +/// set.sort(); +/// assert_eq!(set[0], "Lorem"); +/// assert_eq!(set[1], "amet"); +/// ``` +/// +/// ```should_panic +/// use indexmap::IndexSet; +/// +/// let mut set = IndexSet::new(); +/// set.insert("foo"); +/// println!("{:?}", set[10]); // panics! +/// ``` +impl Index for IndexSet { + type Output = T; + + /// Returns a reference to the value at the supplied `index`. + /// + /// ***Panics*** if `index` is out of bounds. + fn index(&self, index: usize) -> &T { + self.get_index(index) + .expect("IndexSet: index out of bounds") + } +} + +impl FromIterator for IndexSet +where + T: Hash + Eq, + S: BuildHasher + Default, +{ + fn from_iter>(iterable: I) -> Self { + let iter = iterable.into_iter().map(|x| (x, ())); + IndexSet { + map: IndexMap::from_iter(iter), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl From<[T; N]> for IndexSet +where + T: Eq + Hash, +{ + /// # Examples + /// + /// ``` + /// use indexmap::IndexSet; + /// + /// let set1 = IndexSet::from([1, 2, 3, 4]); + /// let set2: IndexSet<_> = [1, 2, 3, 4].into(); + /// assert_eq!(set1, set2); + /// ``` + fn from(arr: [T; N]) -> Self { + Self::from_iter(arr) + } +} + +impl Extend for IndexSet +where + T: Hash + Eq, + S: BuildHasher, +{ + fn extend>(&mut self, iterable: I) { + let iter = iterable.into_iter().map(|x| (x, ())); + self.map.extend(iter); + } +} + +impl<'a, T, S> Extend<&'a T> for IndexSet +where + T: Hash + Eq + Copy + 'a, + S: BuildHasher, +{ + fn extend>(&mut self, iterable: I) { + let iter = iterable.into_iter().copied(); + self.extend(iter); + } +} + +impl Default for IndexSet +where + S: Default, +{ + /// Return an empty [`IndexSet`] + fn default() -> Self { + IndexSet { + map: IndexMap::default(), + } + } +} + +impl PartialEq> for IndexSet +where + T: Hash + Eq, + S1: BuildHasher, + S2: BuildHasher, +{ + fn eq(&self, other: &IndexSet) -> bool { + self.len() == other.len() && self.is_subset(other) + } +} + +impl Eq for IndexSet +where + T: Eq + Hash, + S: BuildHasher, +{ +} + +impl IndexSet +where + T: Eq + Hash, + S: BuildHasher, +{ + /// Returns `true` if `self` has no elements in common with `other`. + pub fn is_disjoint(&self, other: &IndexSet) -> bool + where + S2: BuildHasher, + { + if self.len() <= other.len() { + self.iter().all(move |value| !other.contains(value)) + } else { + other.iter().all(move |value| !self.contains(value)) + } + } + + /// Returns `true` if all elements of `self` are contained in `other`. + pub fn is_subset(&self, other: &IndexSet) -> bool + where + S2: BuildHasher, + { + self.len() <= other.len() && self.iter().all(move |value| other.contains(value)) + } + + /// Returns `true` if all elements of `other` are contained in `self`. + pub fn is_superset(&self, other: &IndexSet) -> bool + where + S2: BuildHasher, + { + other.is_subset(self) + } +} + +impl BitAnd<&IndexSet> for &IndexSet +where + T: Eq + Hash + Clone, + S1: BuildHasher + Default, + S2: BuildHasher, +{ + type Output = IndexSet; + + /// Returns the set intersection, cloned into a new set. + /// + /// Values are collected in the same order that they appear in `self`. + fn bitand(self, other: &IndexSet) -> Self::Output { + self.intersection(other).cloned().collect() + } +} + +impl BitOr<&IndexSet> for &IndexSet +where + T: Eq + Hash + Clone, + S1: BuildHasher + Default, + S2: BuildHasher, +{ + type Output = IndexSet; + + /// Returns the set union, cloned into a new set. + /// + /// Values from `self` are collected in their original order, followed by + /// values that are unique to `other` in their original order. + fn bitor(self, other: &IndexSet) -> Self::Output { + self.union(other).cloned().collect() + } +} + +impl BitXor<&IndexSet> for &IndexSet +where + T: Eq + Hash + Clone, + S1: BuildHasher + Default, + S2: BuildHasher, +{ + type Output = IndexSet; + + /// Returns the set symmetric-difference, cloned into a new set. + /// + /// Values from `self` are collected in their original order, followed by + /// values from `other` in their original order. + fn bitxor(self, other: &IndexSet) -> Self::Output { + self.symmetric_difference(other).cloned().collect() + } +} + +impl Sub<&IndexSet> for &IndexSet +where + T: Eq + Hash + Clone, + S1: BuildHasher + Default, + S2: BuildHasher, +{ + type Output = IndexSet; + + /// Returns the set difference, cloned into a new set. + /// + /// Values are collected in the same order that they appear in `self`. + fn sub(self, other: &IndexSet) -> Self::Output { + self.difference(other).cloned().collect() + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/set/iter.rs b/bitbox02-bt/vendor/indexmap/src/set/iter.rs new file mode 100644 index 0000000..3198276 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/set/iter.rs @@ -0,0 +1,627 @@ +use super::{Bucket, Entries, IndexSet, Slice}; + +use alloc::vec::{self, Vec}; +use core::fmt; +use core::hash::{BuildHasher, Hash}; +use core::iter::{Chain, FusedIterator}; +use core::ops::RangeBounds; +use core::slice::Iter as SliceIter; + +impl<'a, T, S> IntoIterator for &'a IndexSet { + type Item = &'a T; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl IntoIterator for IndexSet { + type Item = T; + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + IntoIter::new(self.into_entries()) + } +} + +/// An iterator over the items of an [`IndexSet`]. +/// +/// This `struct` is created by the [`IndexSet::iter`] method. +/// See its documentation for more. +pub struct Iter<'a, T> { + iter: SliceIter<'a, Bucket>, +} + +impl<'a, T> Iter<'a, T> { + pub(super) fn new(entries: &'a [Bucket]) -> Self { + Self { + iter: entries.iter(), + } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &'a Slice { + Slice::from_slice(self.iter.as_slice()) + } +} + +impl<'a, T> Iterator for Iter<'a, T> { + type Item = &'a T; + + iterator_methods!(Bucket::key_ref); +} + +impl DoubleEndedIterator for Iter<'_, T> { + double_ended_iterator_methods!(Bucket::key_ref); +} + +impl ExactSizeIterator for Iter<'_, T> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for Iter<'_, T> {} + +impl Clone for Iter<'_, T> { + fn clone(&self) -> Self { + Iter { + iter: self.iter.clone(), + } + } +} + +impl fmt::Debug for Iter<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +impl Default for Iter<'_, T> { + fn default() -> Self { + Self { iter: [].iter() } + } +} + +/// An owning iterator over the items of an [`IndexSet`]. +/// +/// This `struct` is created by the [`IndexSet::into_iter`] method +/// (provided by the [`IntoIterator`] trait). See its documentation for more. +#[derive(Clone)] +pub struct IntoIter { + iter: vec::IntoIter>, +} + +impl IntoIter { + pub(super) fn new(entries: Vec>) -> Self { + Self { + iter: entries.into_iter(), + } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.iter.as_slice()) + } +} + +impl Iterator for IntoIter { + type Item = T; + + iterator_methods!(Bucket::key); +} + +impl DoubleEndedIterator for IntoIter { + double_ended_iterator_methods!(Bucket::key); +} + +impl ExactSizeIterator for IntoIter { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for IntoIter {} + +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::key_ref); + f.debug_list().entries(iter).finish() + } +} + +impl Default for IntoIter { + fn default() -> Self { + Self { + iter: Vec::new().into_iter(), + } + } +} + +/// A draining iterator over the items of an [`IndexSet`]. +/// +/// This `struct` is created by the [`IndexSet::drain`] method. +/// See its documentation for more. +pub struct Drain<'a, T> { + iter: vec::Drain<'a, Bucket>, +} + +impl<'a, T> Drain<'a, T> { + pub(super) fn new(iter: vec::Drain<'a, Bucket>) -> Self { + Self { iter } + } + + /// Returns a slice of the remaining entries in the iterator. + pub fn as_slice(&self) -> &Slice { + Slice::from_slice(self.iter.as_slice()) + } +} + +impl Iterator for Drain<'_, T> { + type Item = T; + + iterator_methods!(Bucket::key); +} + +impl DoubleEndedIterator for Drain<'_, T> { + double_ended_iterator_methods!(Bucket::key); +} + +impl ExactSizeIterator for Drain<'_, T> { + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for Drain<'_, T> {} + +impl fmt::Debug for Drain<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let iter = self.iter.as_slice().iter().map(Bucket::key_ref); + f.debug_list().entries(iter).finish() + } +} + +/// A lazy iterator producing elements in the difference of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::difference`] method. +/// See its documentation for more. +pub struct Difference<'a, T, S> { + iter: Iter<'a, T>, + other: &'a IndexSet, +} + +impl<'a, T, S> Difference<'a, T, S> { + pub(super) fn new(set: &'a IndexSet, other: &'a IndexSet) -> Self { + Self { + iter: set.iter(), + other, + } + } +} + +impl<'a, T, S> Iterator for Difference<'a, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ + type Item = &'a T; + + fn next(&mut self) -> Option { + while let Some(item) = self.iter.next() { + if !self.other.contains(item) { + return Some(item); + } + } + None + } + + fn size_hint(&self) -> (usize, Option) { + (0, self.iter.size_hint().1) + } +} + +impl DoubleEndedIterator for Difference<'_, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ + fn next_back(&mut self) -> Option { + while let Some(item) = self.iter.next_back() { + if !self.other.contains(item) { + return Some(item); + } + } + None + } +} + +impl FusedIterator for Difference<'_, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ +} + +impl Clone for Difference<'_, T, S> { + fn clone(&self) -> Self { + Difference { + iter: self.iter.clone(), + ..*self + } + } +} + +impl fmt::Debug for Difference<'_, T, S> +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A lazy iterator producing elements in the intersection of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::intersection`] method. +/// See its documentation for more. +pub struct Intersection<'a, T, S> { + iter: Iter<'a, T>, + other: &'a IndexSet, +} + +impl<'a, T, S> Intersection<'a, T, S> { + pub(super) fn new(set: &'a IndexSet, other: &'a IndexSet) -> Self { + Self { + iter: set.iter(), + other, + } + } +} + +impl<'a, T, S> Iterator for Intersection<'a, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ + type Item = &'a T; + + fn next(&mut self) -> Option { + while let Some(item) = self.iter.next() { + if self.other.contains(item) { + return Some(item); + } + } + None + } + + fn size_hint(&self) -> (usize, Option) { + (0, self.iter.size_hint().1) + } +} + +impl DoubleEndedIterator for Intersection<'_, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ + fn next_back(&mut self) -> Option { + while let Some(item) = self.iter.next_back() { + if self.other.contains(item) { + return Some(item); + } + } + None + } +} + +impl FusedIterator for Intersection<'_, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ +} + +impl Clone for Intersection<'_, T, S> { + fn clone(&self) -> Self { + Intersection { + iter: self.iter.clone(), + ..*self + } + } +} + +impl fmt::Debug for Intersection<'_, T, S> +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A lazy iterator producing elements in the symmetric difference of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::symmetric_difference`] method. +/// See its documentation for more. +pub struct SymmetricDifference<'a, T, S1, S2> { + iter: Chain, Difference<'a, T, S1>>, +} + +impl<'a, T, S1, S2> SymmetricDifference<'a, T, S1, S2> +where + T: Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + pub(super) fn new(set1: &'a IndexSet, set2: &'a IndexSet) -> Self { + let diff1 = set1.difference(set2); + let diff2 = set2.difference(set1); + Self { + iter: diff1.chain(diff2), + } + } +} + +impl<'a, T, S1, S2> Iterator for SymmetricDifference<'a, T, S1, S2> +where + T: Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + type Item = &'a T; + + fn next(&mut self) -> Option { + self.iter.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + fn fold(self, init: B, f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, f) + } +} + +impl DoubleEndedIterator for SymmetricDifference<'_, T, S1, S2> +where + T: Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + fn next_back(&mut self) -> Option { + self.iter.next_back() + } + + fn rfold(self, init: B, f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + self.iter.rfold(init, f) + } +} + +impl FusedIterator for SymmetricDifference<'_, T, S1, S2> +where + T: Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ +} + +impl Clone for SymmetricDifference<'_, T, S1, S2> { + fn clone(&self) -> Self { + SymmetricDifference { + iter: self.iter.clone(), + } + } +} + +impl fmt::Debug for SymmetricDifference<'_, T, S1, S2> +where + T: fmt::Debug + Eq + Hash, + S1: BuildHasher, + S2: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A lazy iterator producing elements in the union of [`IndexSet`]s. +/// +/// This `struct` is created by the [`IndexSet::union`] method. +/// See its documentation for more. +pub struct Union<'a, T, S> { + iter: Chain, Difference<'a, T, S>>, +} + +impl<'a, T, S> Union<'a, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ + pub(super) fn new(set1: &'a IndexSet, set2: &'a IndexSet) -> Self + where + S2: BuildHasher, + { + Self { + iter: set1.iter().chain(set2.difference(set1)), + } + } +} + +impl<'a, T, S> Iterator for Union<'a, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ + type Item = &'a T; + + fn next(&mut self) -> Option { + self.iter.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + fn fold(self, init: B, f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + self.iter.fold(init, f) + } +} + +impl DoubleEndedIterator for Union<'_, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ + fn next_back(&mut self) -> Option { + self.iter.next_back() + } + + fn rfold(self, init: B, f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + self.iter.rfold(init, f) + } +} + +impl FusedIterator for Union<'_, T, S> +where + T: Eq + Hash, + S: BuildHasher, +{ +} + +impl Clone for Union<'_, T, S> { + fn clone(&self) -> Self { + Union { + iter: self.iter.clone(), + } + } +} + +impl fmt::Debug for Union<'_, T, S> +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} + +/// A splicing iterator for `IndexSet`. +/// +/// This `struct` is created by [`IndexSet::splice()`]. +/// See its documentation for more. +pub struct Splice<'a, I, T, S> +where + I: Iterator, + T: Hash + Eq, + S: BuildHasher, +{ + iter: crate::map::Splice<'a, UnitValue, T, (), S>, +} + +impl<'a, I, T, S> Splice<'a, I, T, S> +where + I: Iterator, + T: Hash + Eq, + S: BuildHasher, +{ + pub(super) fn new(set: &'a mut IndexSet, range: R, replace_with: I) -> Self + where + R: RangeBounds, + { + Self { + iter: set.map.splice(range, UnitValue(replace_with)), + } + } +} + +impl Iterator for Splice<'_, I, T, S> +where + I: Iterator, + T: Hash + Eq, + S: BuildHasher, +{ + type Item = T; + + fn next(&mut self) -> Option { + Some(self.iter.next()?.0) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl DoubleEndedIterator for Splice<'_, I, T, S> +where + I: Iterator, + T: Hash + Eq, + S: BuildHasher, +{ + fn next_back(&mut self) -> Option { + Some(self.iter.next_back()?.0) + } +} + +impl ExactSizeIterator for Splice<'_, I, T, S> +where + I: Iterator, + T: Hash + Eq, + S: BuildHasher, +{ + fn len(&self) -> usize { + self.iter.len() + } +} + +impl FusedIterator for Splice<'_, I, T, S> +where + I: Iterator, + T: Hash + Eq, + S: BuildHasher, +{ +} + +struct UnitValue(I); + +impl Iterator for UnitValue { + type Item = (I::Item, ()); + + fn next(&mut self) -> Option { + self.0.next().map(|x| (x, ())) + } +} + +impl<'a, I, T, S> fmt::Debug for Splice<'a, I, T, S> +where + I: fmt::Debug + Iterator, + T: fmt::Debug + Hash + Eq, + S: BuildHasher, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.iter, f) + } +} + +impl fmt::Debug for UnitValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/set/mutable.rs b/bitbox02-bt/vendor/indexmap/src/set/mutable.rs new file mode 100644 index 0000000..21615f3 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/set/mutable.rs @@ -0,0 +1,86 @@ +use core::hash::{BuildHasher, Hash}; + +use super::{Equivalent, IndexSet}; +use crate::map::MutableKeys; + +/// Opt-in mutable access to [`IndexSet`] values. +/// +/// These methods expose `&mut T`, mutable references to the value as it is stored +/// in the set. +/// You are allowed to modify the values in the set **if the modification +/// does not change the value’s hash and equality**. +/// +/// If values are modified erroneously, you can no longer look them up. +/// This is sound (memory safe) but a logical error hazard (just like +/// implementing `PartialEq`, `Eq`, or `Hash` incorrectly would be). +/// +/// `use` this trait to enable its methods for `IndexSet`. +/// +/// This trait is sealed and cannot be implemented for types outside this crate. +pub trait MutableValues: private::Sealed { + type Value; + + /// Return item index and mutable reference to the value + /// + /// Computes in **O(1)** time (average). + fn get_full_mut2(&mut self, value: &Q) -> Option<(usize, &mut Self::Value)> + where + Q: ?Sized + Hash + Equivalent; + + /// Return mutable reference to the value at an index. + /// + /// Valid indices are `0 <= index < self.len()`. + /// + /// Computes in **O(1)** time. + fn get_index_mut2(&mut self, index: usize) -> Option<&mut Self::Value>; + + /// Scan through each value in the set and keep those where the + /// closure `keep` returns `true`. + /// + /// The values are visited in order, and remaining values keep their order. + /// + /// Computes in **O(n)** time (average). + fn retain2(&mut self, keep: F) + where + F: FnMut(&mut Self::Value) -> bool; +} + +/// Opt-in mutable access to [`IndexSet`] values. +/// +/// See [`MutableValues`] for more information. +impl MutableValues for IndexSet +where + S: BuildHasher, +{ + type Value = T; + + fn get_full_mut2(&mut self, value: &Q) -> Option<(usize, &mut T)> + where + Q: ?Sized + Hash + Equivalent, + { + match self.map.get_full_mut2(value) { + Some((index, value, ())) => Some((index, value)), + None => None, + } + } + + fn get_index_mut2(&mut self, index: usize) -> Option<&mut T> { + match self.map.get_index_mut2(index) { + Some((value, ())) => Some(value), + None => None, + } + } + + fn retain2(&mut self, mut keep: F) + where + F: FnMut(&mut T) -> bool, + { + self.map.retain2(move |value, ()| keep(value)); + } +} + +mod private { + pub trait Sealed {} + + impl Sealed for super::IndexSet {} +} diff --git a/bitbox02-bt/vendor/indexmap/src/set/slice.rs b/bitbox02-bt/vendor/indexmap/src/set/slice.rs new file mode 100644 index 0000000..f980e97 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/set/slice.rs @@ -0,0 +1,340 @@ +use super::{Bucket, Entries, IndexSet, IntoIter, Iter}; +use crate::util::try_simplify_range; + +use alloc::boxed::Box; +use alloc::vec::Vec; +use core::cmp::Ordering; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::ops::{self, Bound, Index, RangeBounds}; + +/// A dynamically-sized slice of values in an [`IndexSet`]. +/// +/// This supports indexed operations much like a `[T]` slice, +/// but not any hashed operations on the values. +/// +/// Unlike `IndexSet`, `Slice` does consider the order for [`PartialEq`] +/// and [`Eq`], and it also implements [`PartialOrd`], [`Ord`], and [`Hash`]. +#[repr(transparent)] +pub struct Slice { + pub(crate) entries: [Bucket], +} + +// SAFETY: `Slice` is a transparent wrapper around `[Bucket]`, +// and reference lifetimes are bound together in function signatures. +#[allow(unsafe_code)] +impl Slice { + pub(super) const fn from_slice(entries: &[Bucket]) -> &Self { + unsafe { &*(entries as *const [Bucket] as *const Self) } + } + + pub(super) fn from_boxed(entries: Box<[Bucket]>) -> Box { + unsafe { Box::from_raw(Box::into_raw(entries) as *mut Self) } + } + + fn into_boxed(self: Box) -> Box<[Bucket]> { + unsafe { Box::from_raw(Box::into_raw(self) as *mut [Bucket]) } + } +} + +impl Slice { + pub(crate) fn into_entries(self: Box) -> Vec> { + self.into_boxed().into_vec() + } + + /// Returns an empty slice. + pub const fn new<'a>() -> &'a Self { + Self::from_slice(&[]) + } + + /// Return the number of elements in the set slice. + pub const fn len(&self) -> usize { + self.entries.len() + } + + /// Returns true if the set slice contains no elements. + pub const fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Get a value by index. + /// + /// Valid indices are `0 <= index < self.len()`. + pub fn get_index(&self, index: usize) -> Option<&T> { + self.entries.get(index).map(Bucket::key_ref) + } + + /// Returns a slice of values in the given range of indices. + /// + /// Valid indices are `0 <= index < self.len()`. + pub fn get_range>(&self, range: R) -> Option<&Self> { + let range = try_simplify_range(range, self.entries.len())?; + self.entries.get(range).map(Self::from_slice) + } + + /// Get the first value. + pub fn first(&self) -> Option<&T> { + self.entries.first().map(Bucket::key_ref) + } + + /// Get the last value. + pub fn last(&self) -> Option<&T> { + self.entries.last().map(Bucket::key_ref) + } + + /// Divides one slice into two at an index. + /// + /// ***Panics*** if `index > len`. + pub fn split_at(&self, index: usize) -> (&Self, &Self) { + let (first, second) = self.entries.split_at(index); + (Self::from_slice(first), Self::from_slice(second)) + } + + /// Returns the first value and the rest of the slice, + /// or `None` if it is empty. + pub fn split_first(&self) -> Option<(&T, &Self)> { + if let [first, rest @ ..] = &self.entries { + Some((&first.key, Self::from_slice(rest))) + } else { + None + } + } + + /// Returns the last value and the rest of the slice, + /// or `None` if it is empty. + pub fn split_last(&self) -> Option<(&T, &Self)> { + if let [rest @ .., last] = &self.entries { + Some((&last.key, Self::from_slice(rest))) + } else { + None + } + } + + /// Return an iterator over the values of the set slice. + pub fn iter(&self) -> Iter<'_, T> { + Iter::new(&self.entries) + } + + /// Search over a sorted set for a value. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search`] for more details. + /// + /// Computes in **O(log(n))** time, which is notably less scalable than looking the value up in + /// the set this is a slice from using [`IndexSet::get_index_of`], but this can also position + /// missing values. + pub fn binary_search(&self, x: &T) -> Result + where + T: Ord, + { + self.binary_search_by(|p| p.cmp(x)) + } + + /// Search over a sorted set with a comparator function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result + where + F: FnMut(&'a T) -> Ordering, + { + self.entries.binary_search_by(move |a| f(&a.key)) + } + + /// Search over a sorted set with an extraction function. + /// + /// Returns the position where that value is present, or the position where it can be inserted + /// to maintain the sort. See [`slice::binary_search_by_key`] for more details. + /// + /// Computes in **O(log(n))** time. + #[inline] + pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result + where + F: FnMut(&'a T) -> B, + B: Ord, + { + self.binary_search_by(|k| f(k).cmp(b)) + } + + /// Returns the index of the partition point of a sorted set according to the given predicate + /// (the index of the first element of the second partition). + /// + /// See [`slice::partition_point`] for more details. + /// + /// Computes in **O(log(n))** time. + #[must_use] + pub fn partition_point

(&self, mut pred: P) -> usize + where + P: FnMut(&T) -> bool, + { + self.entries.partition_point(move |a| pred(&a.key)) + } +} + +impl<'a, T> IntoIterator for &'a Slice { + type IntoIter = Iter<'a, T>; + type Item = &'a T; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl IntoIterator for Box> { + type IntoIter = IntoIter; + type Item = T; + + fn into_iter(self) -> Self::IntoIter { + IntoIter::new(self.into_entries()) + } +} + +impl Default for &'_ Slice { + fn default() -> Self { + Slice::from_slice(&[]) + } +} + +impl Default for Box> { + fn default() -> Self { + Slice::from_boxed(Box::default()) + } +} + +impl Clone for Box> { + fn clone(&self) -> Self { + Slice::from_boxed(self.entries.to_vec().into_boxed_slice()) + } +} + +impl From<&Slice> for Box> { + fn from(slice: &Slice) -> Self { + Slice::from_boxed(Box::from(&slice.entries)) + } +} + +impl fmt::Debug for Slice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self).finish() + } +} + +impl PartialEq for Slice { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.iter().eq(other) + } +} + +impl Eq for Slice {} + +impl PartialOrd for Slice { + fn partial_cmp(&self, other: &Self) -> Option { + self.iter().partial_cmp(other) + } +} + +impl Ord for Slice { + fn cmp(&self, other: &Self) -> Ordering { + self.iter().cmp(other) + } +} + +impl Hash for Slice { + fn hash(&self, state: &mut H) { + self.len().hash(state); + for value in self { + value.hash(state); + } + } +} + +impl Index for Slice { + type Output = T; + + fn index(&self, index: usize) -> &Self::Output { + &self.entries[index].key + } +} + +// We can't have `impl> Index` because that conflicts with `Index`. +// Instead, we repeat the implementations for all the core range types. +macro_rules! impl_index { + ($($range:ty),*) => {$( + impl Index<$range> for IndexSet { + type Output = Slice; + + fn index(&self, range: $range) -> &Self::Output { + Slice::from_slice(&self.as_entries()[range]) + } + } + + impl Index<$range> for Slice { + type Output = Self; + + fn index(&self, range: $range) -> &Self::Output { + Slice::from_slice(&self.entries[range]) + } + } + )*} +} +impl_index!( + ops::Range, + ops::RangeFrom, + ops::RangeFull, + ops::RangeInclusive, + ops::RangeTo, + ops::RangeToInclusive, + (Bound, Bound) +); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slice_index() { + fn check(vec_slice: &[i32], set_slice: &Slice, sub_slice: &Slice) { + assert_eq!(set_slice as *const _, sub_slice as *const _); + itertools::assert_equal(vec_slice, set_slice); + } + + let vec: Vec = (0..10).map(|i| i * i).collect(); + let set: IndexSet = vec.iter().cloned().collect(); + let slice = set.as_slice(); + + // RangeFull + check(&vec[..], &set[..], &slice[..]); + + for i in 0usize..10 { + // Index + assert_eq!(vec[i], set[i]); + assert_eq!(vec[i], slice[i]); + + // RangeFrom + check(&vec[i..], &set[i..], &slice[i..]); + + // RangeTo + check(&vec[..i], &set[..i], &slice[..i]); + + // RangeToInclusive + check(&vec[..=i], &set[..=i], &slice[..=i]); + + // (Bound, Bound) + let bounds = (Bound::Excluded(i), Bound::Unbounded); + check(&vec[i + 1..], &set[bounds], &slice[bounds]); + + for j in i..=10 { + // Range + check(&vec[i..j], &set[i..j], &slice[i..j]); + } + + for j in i..10 { + // RangeInclusive + check(&vec[i..=j], &set[i..=j], &slice[i..=j]); + } + } + } +} diff --git a/bitbox02-bt/vendor/indexmap/src/set/tests.rs b/bitbox02-bt/vendor/indexmap/src/set/tests.rs new file mode 100644 index 0000000..35a076e --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/set/tests.rs @@ -0,0 +1,723 @@ +use super::*; +use std::string::String; + +#[test] +fn it_works() { + let mut set = IndexSet::new(); + assert_eq!(set.is_empty(), true); + set.insert(1); + set.insert(1); + assert_eq!(set.len(), 1); + assert!(set.get(&1).is_some()); + assert_eq!(set.is_empty(), false); +} + +#[test] +fn new() { + let set = IndexSet::::new(); + println!("{:?}", set); + assert_eq!(set.capacity(), 0); + assert_eq!(set.len(), 0); + assert_eq!(set.is_empty(), true); +} + +#[test] +fn insert() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5]; + let not_present = [1, 3, 6, 9, 10]; + let mut set = IndexSet::with_capacity(insert.len()); + + for (i, &elt) in insert.iter().enumerate() { + assert_eq!(set.len(), i); + set.insert(elt); + assert_eq!(set.len(), i + 1); + assert_eq!(set.get(&elt), Some(&elt)); + } + println!("{:?}", set); + + for &elt in ¬_present { + assert!(set.get(&elt).is_none()); + } +} + +#[test] +fn insert_full() { + let insert = vec![9, 2, 7, 1, 4, 6, 13]; + let present = vec![1, 6, 2]; + let mut set = IndexSet::with_capacity(insert.len()); + + for (i, &elt) in insert.iter().enumerate() { + assert_eq!(set.len(), i); + let (index, success) = set.insert_full(elt); + assert!(success); + assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0)); + assert_eq!(set.len(), i + 1); + } + + let len = set.len(); + for &elt in &present { + let (index, success) = set.insert_full(elt); + assert!(!success); + assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0)); + assert_eq!(set.len(), len); + } +} + +#[test] +fn insert_2() { + let mut set = IndexSet::with_capacity(16); + + let mut values = vec![]; + values.extend(0..16); + values.extend(if cfg!(miri) { 32..64 } else { 128..267 }); + + for &i in &values { + let old_set = set.clone(); + set.insert(i); + for value in old_set.iter() { + if set.get(value).is_none() { + println!("old_set: {:?}", old_set); + println!("set: {:?}", set); + panic!("did not find {} in set", value); + } + } + } + + for &i in &values { + assert!(set.get(&i).is_some(), "did not find {}", i); + } +} + +#[test] +fn insert_dup() { + let mut elements = vec![0, 2, 4, 6, 8]; + let mut set: IndexSet = elements.drain(..).collect(); + { + let (i, v) = set.get_full(&0).unwrap(); + assert_eq!(set.len(), 5); + assert_eq!(i, 0); + assert_eq!(*v, 0); + } + { + let inserted = set.insert(0); + let (i, v) = set.get_full(&0).unwrap(); + assert_eq!(set.len(), 5); + assert_eq!(inserted, false); + assert_eq!(i, 0); + assert_eq!(*v, 0); + } +} + +#[test] +fn insert_order() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut set = IndexSet::new(); + + for &elt in &insert { + set.insert(elt); + } + + assert_eq!(set.iter().count(), set.len()); + assert_eq!(set.iter().count(), insert.len()); + for (a, b) in insert.iter().zip(set.iter()) { + assert_eq!(a, b); + } + for (i, v) in (0..insert.len()).zip(set.iter()) { + assert_eq!(set.get_index(i).unwrap(), v); + } +} + +#[test] +fn shift_insert() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut set = IndexSet::new(); + + for &elt in &insert { + set.shift_insert(0, elt); + } + + assert_eq!(set.iter().count(), set.len()); + assert_eq!(set.iter().count(), insert.len()); + for (a, b) in insert.iter().rev().zip(set.iter()) { + assert_eq!(a, b); + } + for (i, v) in (0..insert.len()).zip(set.iter()) { + assert_eq!(set.get_index(i).unwrap(), v); + } + + // "insert" that moves an existing entry + set.shift_insert(0, insert[0]); + assert_eq!(set.iter().count(), insert.len()); + assert_eq!(insert[0], set[0]); + for (a, b) in insert[1..].iter().rev().zip(set.iter().skip(1)) { + assert_eq!(a, b); + } +} + +#[test] +fn replace() { + let replace = [0, 4, 2, 12, 8, 7, 11, 5]; + let not_present = [1, 3, 6, 9, 10]; + let mut set = IndexSet::with_capacity(replace.len()); + + for (i, &elt) in replace.iter().enumerate() { + assert_eq!(set.len(), i); + set.replace(elt); + assert_eq!(set.len(), i + 1); + assert_eq!(set.get(&elt), Some(&elt)); + } + println!("{:?}", set); + + for &elt in ¬_present { + assert!(set.get(&elt).is_none()); + } +} + +#[test] +fn replace_full() { + let replace = vec![9, 2, 7, 1, 4, 6, 13]; + let present = vec![1, 6, 2]; + let mut set = IndexSet::with_capacity(replace.len()); + + for (i, &elt) in replace.iter().enumerate() { + assert_eq!(set.len(), i); + let (index, replaced) = set.replace_full(elt); + assert!(replaced.is_none()); + assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0)); + assert_eq!(set.len(), i + 1); + } + + let len = set.len(); + for &elt in &present { + let (index, replaced) = set.replace_full(elt); + assert_eq!(Some(elt), replaced); + assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0)); + assert_eq!(set.len(), len); + } +} + +#[test] +fn replace_2() { + let mut set = IndexSet::with_capacity(16); + + let mut values = vec![]; + values.extend(0..16); + values.extend(if cfg!(miri) { 32..64 } else { 128..267 }); + + for &i in &values { + let old_set = set.clone(); + set.replace(i); + for value in old_set.iter() { + if set.get(value).is_none() { + println!("old_set: {:?}", old_set); + println!("set: {:?}", set); + panic!("did not find {} in set", value); + } + } + } + + for &i in &values { + assert!(set.get(&i).is_some(), "did not find {}", i); + } +} + +#[test] +fn replace_dup() { + let mut elements = vec![0, 2, 4, 6, 8]; + let mut set: IndexSet = elements.drain(..).collect(); + { + let (i, v) = set.get_full(&0).unwrap(); + assert_eq!(set.len(), 5); + assert_eq!(i, 0); + assert_eq!(*v, 0); + } + { + let replaced = set.replace(0); + let (i, v) = set.get_full(&0).unwrap(); + assert_eq!(set.len(), 5); + assert_eq!(replaced, Some(0)); + assert_eq!(i, 0); + assert_eq!(*v, 0); + } +} + +#[test] +fn replace_order() { + let replace = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut set = IndexSet::new(); + + for &elt in &replace { + set.replace(elt); + } + + assert_eq!(set.iter().count(), set.len()); + assert_eq!(set.iter().count(), replace.len()); + for (a, b) in replace.iter().zip(set.iter()) { + assert_eq!(a, b); + } + for (i, v) in (0..replace.len()).zip(set.iter()) { + assert_eq!(set.get_index(i).unwrap(), v); + } +} + +#[test] +fn replace_change() { + // Check pointers to make sure it really changes + let mut set = indexset!(vec![42]); + let old_ptr = set[0].as_ptr(); + let new = set[0].clone(); + let new_ptr = new.as_ptr(); + assert_ne!(old_ptr, new_ptr); + let replaced = set.replace(new).unwrap(); + assert_eq!(replaced.as_ptr(), old_ptr); +} + +#[test] +fn grow() { + let insert = [0, 4, 2, 12, 8, 7, 11]; + let not_present = [1, 3, 6, 9, 10]; + let mut set = IndexSet::with_capacity(insert.len()); + + for (i, &elt) in insert.iter().enumerate() { + assert_eq!(set.len(), i); + set.insert(elt); + assert_eq!(set.len(), i + 1); + assert_eq!(set.get(&elt), Some(&elt)); + } + + println!("{:?}", set); + for &elt in &insert { + set.insert(elt * 10); + } + for &elt in &insert { + set.insert(elt * 100); + } + for (i, &elt) in insert.iter().cycle().enumerate().take(100) { + set.insert(elt * 100 + i as i32); + } + println!("{:?}", set); + for &elt in ¬_present { + assert!(set.get(&elt).is_none()); + } +} + +#[test] +fn reserve() { + let mut set = IndexSet::::new(); + assert_eq!(set.capacity(), 0); + set.reserve(100); + let capacity = set.capacity(); + assert!(capacity >= 100); + for i in 0..capacity { + assert_eq!(set.len(), i); + set.insert(i); + assert_eq!(set.len(), i + 1); + assert_eq!(set.capacity(), capacity); + assert_eq!(set.get(&i), Some(&i)); + } + set.insert(capacity); + assert_eq!(set.len(), capacity + 1); + assert!(set.capacity() > capacity); + assert_eq!(set.get(&capacity), Some(&capacity)); +} + +#[test] +fn try_reserve() { + let mut set = IndexSet::::new(); + assert_eq!(set.capacity(), 0); + assert_eq!(set.try_reserve(100), Ok(())); + assert!(set.capacity() >= 100); + assert!(set.try_reserve(usize::MAX).is_err()); +} + +#[test] +fn shrink_to_fit() { + let mut set = IndexSet::::new(); + assert_eq!(set.capacity(), 0); + for i in 0..100 { + assert_eq!(set.len(), i); + set.insert(i); + assert_eq!(set.len(), i + 1); + assert!(set.capacity() >= i + 1); + assert_eq!(set.get(&i), Some(&i)); + set.shrink_to_fit(); + assert_eq!(set.len(), i + 1); + assert_eq!(set.capacity(), i + 1); + assert_eq!(set.get(&i), Some(&i)); + } +} + +#[test] +fn remove() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut set = IndexSet::new(); + + for &elt in &insert { + set.insert(elt); + } + + assert_eq!(set.iter().count(), set.len()); + assert_eq!(set.iter().count(), insert.len()); + for (a, b) in insert.iter().zip(set.iter()) { + assert_eq!(a, b); + } + + let remove_fail = [99, 77]; + let remove = [4, 12, 8, 7]; + + for &value in &remove_fail { + assert!(set.swap_remove_full(&value).is_none()); + } + println!("{:?}", set); + for &value in &remove { + //println!("{:?}", set); + let index = set.get_full(&value).unwrap().0; + assert_eq!(set.swap_remove_full(&value), Some((index, value))); + } + println!("{:?}", set); + + for value in &insert { + assert_eq!(set.get(value).is_some(), !remove.contains(value)); + } + assert_eq!(set.len(), insert.len() - remove.len()); + assert_eq!(set.iter().count(), insert.len() - remove.len()); +} + +#[test] +fn swap_remove_index() { + let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23]; + let mut set = IndexSet::new(); + + for &elt in &insert { + set.insert(elt); + } + + let mut vector = insert.to_vec(); + let remove_sequence = &[3, 3, 10, 4, 5, 4, 3, 0, 1]; + + // check that the same swap remove sequence on vec and set + // have the same result. + for &rm in remove_sequence { + let out_vec = vector.swap_remove(rm); + let out_set = set.swap_remove_index(rm).unwrap(); + assert_eq!(out_vec, out_set); + } + assert_eq!(vector.len(), set.len()); + for (a, b) in vector.iter().zip(set.iter()) { + assert_eq!(a, b); + } +} + +#[test] +fn partial_eq_and_eq() { + let mut set_a = IndexSet::new(); + set_a.insert(1); + set_a.insert(2); + let mut set_b = set_a.clone(); + assert_eq!(set_a, set_b); + set_b.swap_remove(&1); + assert_ne!(set_a, set_b); + + let set_c: IndexSet<_> = set_b.into_iter().collect(); + assert_ne!(set_a, set_c); + assert_ne!(set_c, set_a); +} + +#[test] +fn extend() { + let mut set = IndexSet::new(); + set.extend(vec![&1, &2, &3, &4]); + set.extend(vec![5, 6]); + assert_eq!(set.into_iter().collect::>(), vec![1, 2, 3, 4, 5, 6]); +} + +#[test] +fn comparisons() { + let set_a: IndexSet<_> = (0..3).collect(); + let set_b: IndexSet<_> = (3..6).collect(); + let set_c: IndexSet<_> = (0..6).collect(); + let set_d: IndexSet<_> = (3..9).collect(); + + assert!(!set_a.is_disjoint(&set_a)); + assert!(set_a.is_subset(&set_a)); + assert!(set_a.is_superset(&set_a)); + + assert!(set_a.is_disjoint(&set_b)); + assert!(set_b.is_disjoint(&set_a)); + assert!(!set_a.is_subset(&set_b)); + assert!(!set_b.is_subset(&set_a)); + assert!(!set_a.is_superset(&set_b)); + assert!(!set_b.is_superset(&set_a)); + + assert!(!set_a.is_disjoint(&set_c)); + assert!(!set_c.is_disjoint(&set_a)); + assert!(set_a.is_subset(&set_c)); + assert!(!set_c.is_subset(&set_a)); + assert!(!set_a.is_superset(&set_c)); + assert!(set_c.is_superset(&set_a)); + + assert!(!set_c.is_disjoint(&set_d)); + assert!(!set_d.is_disjoint(&set_c)); + assert!(!set_c.is_subset(&set_d)); + assert!(!set_d.is_subset(&set_c)); + assert!(!set_c.is_superset(&set_d)); + assert!(!set_d.is_superset(&set_c)); +} + +#[test] +fn iter_comparisons() { + use std::iter::empty; + + fn check<'a, I1, I2>(iter1: I1, iter2: I2) + where + I1: Iterator, + I2: Iterator, + { + assert!(iter1.copied().eq(iter2)); + } + + let set_a: IndexSet<_> = (0..3).collect(); + let set_b: IndexSet<_> = (3..6).collect(); + let set_c: IndexSet<_> = (0..6).collect(); + let set_d: IndexSet<_> = (3..9).rev().collect(); + + check(set_a.difference(&set_a), empty()); + check(set_a.symmetric_difference(&set_a), empty()); + check(set_a.intersection(&set_a), 0..3); + check(set_a.union(&set_a), 0..3); + + check(set_a.difference(&set_b), 0..3); + check(set_b.difference(&set_a), 3..6); + check(set_a.symmetric_difference(&set_b), 0..6); + check(set_b.symmetric_difference(&set_a), (3..6).chain(0..3)); + check(set_a.intersection(&set_b), empty()); + check(set_b.intersection(&set_a), empty()); + check(set_a.union(&set_b), 0..6); + check(set_b.union(&set_a), (3..6).chain(0..3)); + + check(set_a.difference(&set_c), empty()); + check(set_c.difference(&set_a), 3..6); + check(set_a.symmetric_difference(&set_c), 3..6); + check(set_c.symmetric_difference(&set_a), 3..6); + check(set_a.intersection(&set_c), 0..3); + check(set_c.intersection(&set_a), 0..3); + check(set_a.union(&set_c), 0..6); + check(set_c.union(&set_a), 0..6); + + check(set_c.difference(&set_d), 0..3); + check(set_d.difference(&set_c), (6..9).rev()); + check( + set_c.symmetric_difference(&set_d), + (0..3).chain((6..9).rev()), + ); + check(set_d.symmetric_difference(&set_c), (6..9).rev().chain(0..3)); + check(set_c.intersection(&set_d), 3..6); + check(set_d.intersection(&set_c), (3..6).rev()); + check(set_c.union(&set_d), (0..6).chain((6..9).rev())); + check(set_d.union(&set_c), (3..9).rev().chain(0..3)); +} + +#[test] +fn ops() { + let empty = IndexSet::::new(); + let set_a: IndexSet<_> = (0..3).collect(); + let set_b: IndexSet<_> = (3..6).collect(); + let set_c: IndexSet<_> = (0..6).collect(); + let set_d: IndexSet<_> = (3..9).rev().collect(); + + #[allow(clippy::eq_op)] + { + assert_eq!(&set_a & &set_a, set_a); + assert_eq!(&set_a | &set_a, set_a); + assert_eq!(&set_a ^ &set_a, empty); + assert_eq!(&set_a - &set_a, empty); + } + + assert_eq!(&set_a & &set_b, empty); + assert_eq!(&set_b & &set_a, empty); + assert_eq!(&set_a | &set_b, set_c); + assert_eq!(&set_b | &set_a, set_c); + assert_eq!(&set_a ^ &set_b, set_c); + assert_eq!(&set_b ^ &set_a, set_c); + assert_eq!(&set_a - &set_b, set_a); + assert_eq!(&set_b - &set_a, set_b); + + assert_eq!(&set_a & &set_c, set_a); + assert_eq!(&set_c & &set_a, set_a); + assert_eq!(&set_a | &set_c, set_c); + assert_eq!(&set_c | &set_a, set_c); + assert_eq!(&set_a ^ &set_c, set_b); + assert_eq!(&set_c ^ &set_a, set_b); + assert_eq!(&set_a - &set_c, empty); + assert_eq!(&set_c - &set_a, set_b); + + assert_eq!(&set_c & &set_d, set_b); + assert_eq!(&set_d & &set_c, set_b); + assert_eq!(&set_c | &set_d, &set_a | &set_d); + assert_eq!(&set_d | &set_c, &set_a | &set_d); + assert_eq!(&set_c ^ &set_d, &set_a | &(&set_d - &set_b)); + assert_eq!(&set_d ^ &set_c, &set_a | &(&set_d - &set_b)); + assert_eq!(&set_c - &set_d, set_a); + assert_eq!(&set_d - &set_c, &set_d - &set_b); +} + +#[test] +#[cfg(feature = "std")] +fn from_array() { + let set1 = IndexSet::from([1, 2, 3, 4]); + let set2: IndexSet<_> = [1, 2, 3, 4].into(); + + assert_eq!(set1, set2); +} + +#[test] +fn iter_default() { + struct Item; + fn assert_default() + where + T: Default + Iterator, + { + assert!(T::default().next().is_none()); + } + assert_default::>(); + assert_default::>(); +} + +#[test] +fn test_binary_search_by() { + // adapted from std's test for binary_search + let b: IndexSet = [].into(); + assert_eq!(b.binary_search_by(|x| x.cmp(&5)), Err(0)); + + let b: IndexSet = [4].into(); + assert_eq!(b.binary_search_by(|x| x.cmp(&3)), Err(0)); + assert_eq!(b.binary_search_by(|x| x.cmp(&4)), Ok(0)); + assert_eq!(b.binary_search_by(|x| x.cmp(&5)), Err(1)); + + let b: IndexSet = [1, 2, 4, 6, 8, 9].into(); + assert_eq!(b.binary_search_by(|x| x.cmp(&5)), Err(3)); + assert_eq!(b.binary_search_by(|x| x.cmp(&6)), Ok(3)); + assert_eq!(b.binary_search_by(|x| x.cmp(&7)), Err(4)); + assert_eq!(b.binary_search_by(|x| x.cmp(&8)), Ok(4)); + + let b: IndexSet = [1, 2, 4, 5, 6, 8].into(); + assert_eq!(b.binary_search_by(|x| x.cmp(&9)), Err(6)); + + let b: IndexSet = [1, 2, 4, 6, 7, 8, 9].into(); + assert_eq!(b.binary_search_by(|x| x.cmp(&6)), Ok(3)); + assert_eq!(b.binary_search_by(|x| x.cmp(&5)), Err(3)); + assert_eq!(b.binary_search_by(|x| x.cmp(&8)), Ok(5)); + + let b: IndexSet = [1, 2, 4, 5, 6, 8, 9].into(); + assert_eq!(b.binary_search_by(|x| x.cmp(&7)), Err(5)); + assert_eq!(b.binary_search_by(|x| x.cmp(&0)), Err(0)); + + let b: IndexSet = [1, 3, 3, 3, 7].into(); + assert_eq!(b.binary_search_by(|x| x.cmp(&0)), Err(0)); + assert_eq!(b.binary_search_by(|x| x.cmp(&1)), Ok(0)); + assert_eq!(b.binary_search_by(|x| x.cmp(&2)), Err(1)); + // diff from std as set merges the duplicate keys + assert!(match b.binary_search_by(|x| x.cmp(&3)) { + Ok(1..=2) => true, + _ => false, + }); + assert!(match b.binary_search_by(|x| x.cmp(&3)) { + Ok(1..=2) => true, + _ => false, + }); + assert_eq!(b.binary_search_by(|x| x.cmp(&4)), Err(2)); + assert_eq!(b.binary_search_by(|x| x.cmp(&5)), Err(2)); + assert_eq!(b.binary_search_by(|x| x.cmp(&6)), Err(2)); + assert_eq!(b.binary_search_by(|x| x.cmp(&7)), Ok(2)); + assert_eq!(b.binary_search_by(|x| x.cmp(&8)), Err(3)); +} + +#[test] +fn test_binary_search_by_key() { + // adapted from std's test for binary_search + let b: IndexSet = [].into(); + assert_eq!(b.binary_search_by_key(&5, |&x| x), Err(0)); + + let b: IndexSet = [4].into(); + assert_eq!(b.binary_search_by_key(&3, |&x| x), Err(0)); + assert_eq!(b.binary_search_by_key(&4, |&x| x), Ok(0)); + assert_eq!(b.binary_search_by_key(&5, |&x| x), Err(1)); + + let b: IndexSet = [1, 2, 4, 6, 8, 9].into(); + assert_eq!(b.binary_search_by_key(&5, |&x| x), Err(3)); + assert_eq!(b.binary_search_by_key(&6, |&x| x), Ok(3)); + assert_eq!(b.binary_search_by_key(&7, |&x| x), Err(4)); + assert_eq!(b.binary_search_by_key(&8, |&x| x), Ok(4)); + + let b: IndexSet = [1, 2, 4, 5, 6, 8].into(); + assert_eq!(b.binary_search_by_key(&9, |&x| x), Err(6)); + + let b: IndexSet = [1, 2, 4, 6, 7, 8, 9].into(); + assert_eq!(b.binary_search_by_key(&6, |&x| x), Ok(3)); + assert_eq!(b.binary_search_by_key(&5, |&x| x), Err(3)); + assert_eq!(b.binary_search_by_key(&8, |&x| x), Ok(5)); + + let b: IndexSet = [1, 2, 4, 5, 6, 8, 9].into(); + assert_eq!(b.binary_search_by_key(&7, |&x| x), Err(5)); + assert_eq!(b.binary_search_by_key(&0, |&x| x), Err(0)); + + let b: IndexSet = [1, 3, 3, 3, 7].into(); + assert_eq!(b.binary_search_by_key(&0, |&x| x), Err(0)); + assert_eq!(b.binary_search_by_key(&1, |&x| x), Ok(0)); + assert_eq!(b.binary_search_by_key(&2, |&x| x), Err(1)); + // diff from std as set merges the duplicate keys + assert!(match b.binary_search_by_key(&3, |&x| x) { + Ok(1..=2) => true, + _ => false, + }); + assert!(match b.binary_search_by_key(&3, |&x| x) { + Ok(1..=2) => true, + _ => false, + }); + assert_eq!(b.binary_search_by_key(&4, |&x| x), Err(2)); + assert_eq!(b.binary_search_by_key(&5, |&x| x), Err(2)); + assert_eq!(b.binary_search_by_key(&6, |&x| x), Err(2)); + assert_eq!(b.binary_search_by_key(&7, |&x| x), Ok(2)); + assert_eq!(b.binary_search_by_key(&8, |&x| x), Err(3)); +} + +#[test] +fn test_partition_point() { + // adapted from std's test for partition_point + let b: IndexSet = [].into(); + assert_eq!(b.partition_point(|&x| x < 5), 0); + + let b: IndexSet<_> = [4].into(); + assert_eq!(b.partition_point(|&x| x < 3), 0); + assert_eq!(b.partition_point(|&x| x < 4), 0); + assert_eq!(b.partition_point(|&x| x < 5), 1); + + let b: IndexSet<_> = [1, 2, 4, 6, 8, 9].into(); + assert_eq!(b.partition_point(|&x| x < 5), 3); + assert_eq!(b.partition_point(|&x| x < 6), 3); + assert_eq!(b.partition_point(|&x| x < 7), 4); + assert_eq!(b.partition_point(|&x| x < 8), 4); + + let b: IndexSet<_> = [1, 2, 4, 5, 6, 8].into(); + assert_eq!(b.partition_point(|&x| x < 9), 6); + + let b: IndexSet<_> = [1, 2, 4, 6, 7, 8, 9].into(); + assert_eq!(b.partition_point(|&x| x < 6), 3); + assert_eq!(b.partition_point(|&x| x < 5), 3); + assert_eq!(b.partition_point(|&x| x < 8), 5); + + let b: IndexSet<_> = [1, 2, 4, 5, 6, 8, 9].into(); + assert_eq!(b.partition_point(|&x| x < 7), 5); + assert_eq!(b.partition_point(|&x| x < 0), 0); + + let b: IndexSet<_> = [1, 3, 3, 3, 7].into(); + assert_eq!(b.partition_point(|&x| x < 0), 0); + assert_eq!(b.partition_point(|&x| x < 1), 0); + assert_eq!(b.partition_point(|&x| x < 2), 1); + assert_eq!(b.partition_point(|&x| x < 3), 1); + assert_eq!(b.partition_point(|&x| x < 4), 2); // diff from std as set merges the duplicate keys + assert_eq!(b.partition_point(|&x| x < 5), 2); + assert_eq!(b.partition_point(|&x| x < 6), 2); + assert_eq!(b.partition_point(|&x| x < 7), 2); + assert_eq!(b.partition_point(|&x| x < 8), 3); +} diff --git a/bitbox02-bt/vendor/indexmap/src/util.rs b/bitbox02-bt/vendor/indexmap/src/util.rs new file mode 100644 index 0000000..377ff51 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/src/util.rs @@ -0,0 +1,53 @@ +use core::ops::{Bound, Range, RangeBounds}; + +pub(crate) fn third(t: (A, B, C)) -> C { + t.2 +} + +pub(crate) fn simplify_range(range: R, len: usize) -> Range +where + R: RangeBounds, +{ + let start = match range.start_bound() { + Bound::Unbounded => 0, + Bound::Included(&i) if i <= len => i, + Bound::Excluded(&i) if i < len => i + 1, + bound => panic!("range start {:?} should be <= length {}", bound, len), + }; + let end = match range.end_bound() { + Bound::Unbounded => len, + Bound::Excluded(&i) if i <= len => i, + Bound::Included(&i) if i < len => i + 1, + bound => panic!("range end {:?} should be <= length {}", bound, len), + }; + if start > end { + panic!( + "range start {:?} should be <= range end {:?}", + range.start_bound(), + range.end_bound() + ); + } + start..end +} + +pub(crate) fn try_simplify_range(range: R, len: usize) -> Option> +where + R: RangeBounds, +{ + let start = match range.start_bound() { + Bound::Unbounded => 0, + Bound::Included(&i) if i <= len => i, + Bound::Excluded(&i) if i < len => i + 1, + _ => return None, + }; + let end = match range.end_bound() { + Bound::Unbounded => len, + Bound::Excluded(&i) if i <= len => i, + Bound::Included(&i) if i < len => i + 1, + _ => return None, + }; + if start > end { + return None; + } + Some(start..end) +} diff --git a/bitbox02-bt/vendor/indexmap/tests/equivalent_trait.rs b/bitbox02-bt/vendor/indexmap/tests/equivalent_trait.rs new file mode 100644 index 0000000..ff5943a --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/tests/equivalent_trait.rs @@ -0,0 +1,53 @@ +use indexmap::indexmap; +use indexmap::Equivalent; + +use std::hash::Hash; + +#[derive(Debug, Hash)] +pub struct Pair(pub A, pub B); + +impl PartialEq<(A, B)> for Pair +where + C: PartialEq, + D: PartialEq, +{ + fn eq(&self, rhs: &(A, B)) -> bool { + self.0 == rhs.0 && self.1 == rhs.1 + } +} + +impl Equivalent for Pair +where + Pair: PartialEq, + A: Hash + Eq, + B: Hash + Eq, +{ + fn equivalent(&self, other: &X) -> bool { + *self == *other + } +} + +#[test] +fn test_lookup() { + let s = String::from; + let map = indexmap! { + (s("a"), s("b")) => 1, + (s("a"), s("x")) => 2, + }; + + assert!(map.contains_key(&Pair("a", "b"))); + assert!(!map.contains_key(&Pair("b", "a"))); +} + +#[test] +fn test_string_str() { + let s = String::from; + let mut map = indexmap! { + s("a") => 1, s("b") => 2, + s("x") => 3, s("y") => 4, + }; + + assert!(map.contains_key("a")); + assert!(!map.contains_key("z")); + assert_eq!(map.swap_remove("b"), Some(2)); +} diff --git a/bitbox02-bt/vendor/indexmap/tests/macros_full_path.rs b/bitbox02-bt/vendor/indexmap/tests/macros_full_path.rs new file mode 100644 index 0000000..2467d9b --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/tests/macros_full_path.rs @@ -0,0 +1,19 @@ +#[test] +fn test_create_map() { + let _m = indexmap::indexmap! { + 1 => 2, + 7 => 1, + 2 => 2, + 3 => 3, + }; +} + +#[test] +fn test_create_set() { + let _s = indexmap::indexset! { + 1, + 7, + 2, + 3, + }; +} diff --git a/bitbox02-bt/vendor/indexmap/tests/quick.rs b/bitbox02-bt/vendor/indexmap/tests/quick.rs new file mode 100644 index 0000000..56afee7 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/tests/quick.rs @@ -0,0 +1,759 @@ +use indexmap::{IndexMap, IndexSet}; +use itertools::Itertools; + +use quickcheck::Arbitrary; +use quickcheck::Gen; +use quickcheck::QuickCheck; +use quickcheck::TestResult; + +use fnv::FnvHasher; +use std::hash::{BuildHasher, BuildHasherDefault}; +type FnvBuilder = BuildHasherDefault; +type IndexMapFnv = IndexMap; + +use std::cmp::min; +use std::collections::HashMap; +use std::collections::HashSet; +use std::fmt::Debug; +use std::hash::Hash; +use std::ops::Bound; +use std::ops::Deref; + +use indexmap::map::Entry; +use std::collections::hash_map::Entry as StdEntry; + +fn set<'a, T: 'a, I>(iter: I) -> HashSet +where + I: IntoIterator, + T: Copy + Hash + Eq, +{ + iter.into_iter().copied().collect() +} + +fn indexmap<'a, T: 'a, I>(iter: I) -> IndexMap +where + I: IntoIterator, + T: Copy + Hash + Eq, +{ + IndexMap::from_iter(iter.into_iter().copied().map(|k| (k, ()))) +} + +// Helper macro to allow us to use smaller quickcheck limits under miri. +macro_rules! quickcheck_limit { + (@as_items $($i:item)*) => ($($i)*); + { + $( + $(#[$m:meta])* + fn $fn_name:ident($($arg_name:ident : $arg_ty:ty),*) -> $ret:ty { + $($code:tt)* + } + )* + } => ( + quickcheck::quickcheck! { + @as_items + $( + #[test] + $(#[$m])* + fn $fn_name() { + fn prop($($arg_name: $arg_ty),*) -> $ret { + $($code)* + } + let mut quickcheck = QuickCheck::new(); + if cfg!(miri) { + quickcheck = quickcheck + .gen(Gen::new(10)) + .tests(10) + .max_tests(100); + } + + quickcheck.quickcheck(prop as fn($($arg_ty),*) -> $ret); + } + )* + } + ) +} + +quickcheck_limit! { + fn contains(insert: Vec) -> bool { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + insert.iter().all(|&key| map.get(&key).is_some()) + } + + fn contains_not(insert: Vec, not: Vec) -> bool { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + let nots = &set(¬) - &set(&insert); + nots.iter().all(|&key| map.get(&key).is_none()) + } + + fn insert_remove(insert: Vec, remove: Vec) -> bool { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + for &key in &remove { + map.swap_remove(&key); + } + let elements = &set(&insert) - &set(&remove); + map.len() == elements.len() && map.iter().count() == elements.len() && + elements.iter().all(|k| map.get(k).is_some()) + } + + fn insertion_order(insert: Vec) -> bool { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + itertools::assert_equal(insert.iter().unique(), map.keys()); + true + } + + fn insert_sorted(insert: Vec<(u32, u32)>) -> bool { + let mut hmap = HashMap::new(); + let mut map = IndexMap::new(); + let mut map2 = IndexMap::new(); + for &(key, value) in &insert { + hmap.insert(key, value); + map.insert_sorted(key, value); + match map2.entry(key) { + Entry::Occupied(e) => *e.into_mut() = value, + Entry::Vacant(e) => { e.insert_sorted(value); } + } + } + itertools::assert_equal(hmap.iter().sorted(), &map); + itertools::assert_equal(&map, &map2); + true + } + + fn pop(insert: Vec) -> bool { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + let mut pops = Vec::new(); + while let Some((key, _v)) = map.pop() { + pops.push(key); + } + pops.reverse(); + + itertools::assert_equal(insert.iter().unique(), &pops); + true + } + + fn with_cap(template: Vec<()>) -> bool { + let cap = template.len(); + let map: IndexMap = IndexMap::with_capacity(cap); + println!("wish: {}, got: {} (diff: {})", cap, map.capacity(), map.capacity() as isize - cap as isize); + map.capacity() >= cap + } + + fn drain_full(insert: Vec) -> bool { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + let mut clone = map.clone(); + let drained = clone.drain(..); + for (key, _) in drained { + map.swap_remove(&key); + } + map.is_empty() + } + + fn drain_bounds(insert: Vec, range: (Bound, Bound)) -> TestResult { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + + // First see if `Vec::drain` is happy with this range. + let result = std::panic::catch_unwind(|| { + let mut keys: Vec = map.keys().copied().collect(); + keys.drain(range); + keys + }); + + if let Ok(keys) = result { + map.drain(range); + // Check that our `drain` matches the same key order. + assert!(map.keys().eq(&keys)); + // Check that hash lookups all work too. + assert!(keys.iter().all(|key| map.contains_key(key))); + TestResult::passed() + } else { + // If `Vec::drain` panicked, so should we. + TestResult::must_fail(move || { map.drain(range); }) + } + } + + fn shift_remove(insert: Vec, remove: Vec) -> bool { + let mut map = IndexMap::new(); + for &key in &insert { + map.insert(key, ()); + } + for &key in &remove { + map.shift_remove(&key); + } + let elements = &set(&insert) - &set(&remove); + + // Check that order is preserved after removals + let mut iter = map.keys(); + for &key in insert.iter().unique() { + if elements.contains(&key) { + assert_eq!(Some(&key), iter.next()); + } + } + + map.len() == elements.len() && map.iter().count() == elements.len() && + elements.iter().all(|k| map.get(k).is_some()) + } + + fn indexing(insert: Vec) -> bool { + let mut map: IndexMap<_, _> = insert.into_iter().map(|x| (x, x)).collect(); + let set: IndexSet<_> = map.keys().copied().collect(); + assert_eq!(map.len(), set.len()); + + for (i, &key) in set.iter().enumerate() { + assert_eq!(map.get_index(i), Some((&key, &key))); + assert_eq!(set.get_index(i), Some(&key)); + assert_eq!(map[i], key); + assert_eq!(set[i], key); + + *map.get_index_mut(i).unwrap().1 >>= 1; + map[i] <<= 1; + } + + set.iter().enumerate().all(|(i, &key)| { + let value = key & !1; + map[&key] == value && map[i] == value + }) + } + + // Use `u8` test indices so quickcheck is less likely to go out of bounds. + fn set_swap_indices(vec: Vec, a: u8, b: u8) -> TestResult { + let mut set = IndexSet::::from_iter(vec); + let a = usize::from(a); + let b = usize::from(b); + + if a >= set.len() || b >= set.len() { + return TestResult::discard(); + } + + let mut vec = Vec::from_iter(set.iter().cloned()); + vec.swap(a, b); + + set.swap_indices(a, b); + + // Check both iteration order and hash lookups + assert!(set.iter().eq(vec.iter())); + assert!(vec.iter().enumerate().all(|(i, x)| { + set.get_index_of(x) == Some(i) + })); + TestResult::passed() + } + + fn map_swap_indices(vec: Vec, from: u8, to: u8) -> TestResult { + test_map_swap_indices(vec, from, to, IndexMap::swap_indices) + } + + fn occupied_entry_swap_indices(vec: Vec, from: u8, to: u8) -> TestResult { + test_map_swap_indices(vec, from, to, |map, from, to| { + let key = map.keys()[from]; + match map.entry(key) { + Entry::Occupied(entry) => entry.swap_indices(to), + _ => unreachable!(), + } + }) + } + + fn indexed_entry_swap_indices(vec: Vec, from: u8, to: u8) -> TestResult { + test_map_swap_indices(vec, from, to, |map, from, to| { + map.get_index_entry(from).unwrap().swap_indices(to); + }) + } + + fn raw_occupied_entry_swap_indices(vec: Vec, from: u8, to: u8) -> TestResult { + use indexmap::map::raw_entry_v1::{RawEntryApiV1, RawEntryMut}; + test_map_swap_indices(vec, from, to, |map, from, to| { + let key = map.keys()[from]; + match map.raw_entry_mut_v1().from_key(&key) { + RawEntryMut::Occupied(entry) => entry.swap_indices(to), + _ => unreachable!(), + } + }) + } + + // Use `u8` test indices so quickcheck is less likely to go out of bounds. + fn set_move_index(vec: Vec, from: u8, to: u8) -> TestResult { + let mut set = IndexSet::::from_iter(vec); + let from = usize::from(from); + let to = usize::from(to); + + if from >= set.len() || to >= set.len() { + return TestResult::discard(); + } + + let mut vec = Vec::from_iter(set.iter().cloned()); + let x = vec.remove(from); + vec.insert(to, x); + + set.move_index(from, to); + + // Check both iteration order and hash lookups + assert!(set.iter().eq(vec.iter())); + assert!(vec.iter().enumerate().all(|(i, x)| { + set.get_index_of(x) == Some(i) + })); + TestResult::passed() + } + + fn map_move_index(vec: Vec, from: u8, to: u8) -> TestResult { + test_map_move_index(vec, from, to, IndexMap::move_index) + } + + fn occupied_entry_move_index(vec: Vec, from: u8, to: u8) -> TestResult { + test_map_move_index(vec, from, to, |map, from, to| { + let key = map.keys()[from]; + match map.entry(key) { + Entry::Occupied(entry) => entry.move_index(to), + _ => unreachable!(), + } + }) + } + + fn indexed_entry_move_index(vec: Vec, from: u8, to: u8) -> TestResult { + test_map_move_index(vec, from, to, |map, from, to| { + map.get_index_entry(from).unwrap().move_index(to); + }) + } + + fn raw_occupied_entry_move_index(vec: Vec, from: u8, to: u8) -> TestResult { + use indexmap::map::raw_entry_v1::{RawEntryApiV1, RawEntryMut}; + test_map_move_index(vec, from, to, |map, from, to| { + let key = map.keys()[from]; + match map.raw_entry_mut_v1().from_key(&key) { + RawEntryMut::Occupied(entry) => entry.move_index(to), + _ => unreachable!(), + } + }) + } + + fn occupied_entry_shift_insert(vec: Vec, i: u8) -> TestResult { + test_map_shift_insert(vec, i, |map, i, key| { + match map.entry(key) { + Entry::Vacant(entry) => entry.shift_insert(i, ()), + _ => unreachable!(), + }; + }) + } + + fn raw_occupied_entry_shift_insert(vec: Vec, i: u8) -> TestResult { + use indexmap::map::raw_entry_v1::{RawEntryApiV1, RawEntryMut}; + test_map_shift_insert(vec, i, |map, i, key| { + match map.raw_entry_mut_v1().from_key(&key) { + RawEntryMut::Vacant(entry) => entry.shift_insert(i, key, ()), + _ => unreachable!(), + }; + }) + } +} + +fn test_map_swap_indices(vec: Vec, a: u8, b: u8, swap_indices: F) -> TestResult +where + F: FnOnce(&mut IndexMap, usize, usize), +{ + let mut map = IndexMap::::from_iter(vec.into_iter().map(|k| (k, ()))); + let a = usize::from(a); + let b = usize::from(b); + + if a >= map.len() || b >= map.len() { + return TestResult::discard(); + } + + let mut vec = Vec::from_iter(map.keys().copied()); + vec.swap(a, b); + + swap_indices(&mut map, a, b); + + // Check both iteration order and hash lookups + assert!(map.keys().eq(vec.iter())); + assert!(vec + .iter() + .enumerate() + .all(|(i, x)| { map.get_index_of(x) == Some(i) })); + TestResult::passed() +} + +fn test_map_move_index(vec: Vec, from: u8, to: u8, move_index: F) -> TestResult +where + F: FnOnce(&mut IndexMap, usize, usize), +{ + let mut map = IndexMap::::from_iter(vec.into_iter().map(|k| (k, ()))); + let from = usize::from(from); + let to = usize::from(to); + + if from >= map.len() || to >= map.len() { + return TestResult::discard(); + } + + let mut vec = Vec::from_iter(map.keys().copied()); + let x = vec.remove(from); + vec.insert(to, x); + + move_index(&mut map, from, to); + + // Check both iteration order and hash lookups + assert!(map.keys().eq(vec.iter())); + assert!(vec + .iter() + .enumerate() + .all(|(i, x)| { map.get_index_of(x) == Some(i) })); + TestResult::passed() +} + +fn test_map_shift_insert(vec: Vec, i: u8, shift_insert: F) -> TestResult +where + F: FnOnce(&mut IndexMap, usize, u8), +{ + let mut map = IndexMap::::from_iter(vec.into_iter().map(|k| (k, ()))); + let i = usize::from(i); + if i >= map.len() { + return TestResult::discard(); + } + + let mut vec = Vec::from_iter(map.keys().copied()); + let x = vec.pop().unwrap(); + vec.insert(i, x); + + let (last, ()) = map.pop().unwrap(); + assert_eq!(x, last); + map.shrink_to_fit(); // so we might have to grow and rehash the table + + shift_insert(&mut map, i, last); + + // Check both iteration order and hash lookups + assert!(map.keys().eq(vec.iter())); + assert!(vec + .iter() + .enumerate() + .all(|(i, x)| { map.get_index_of(x) == Some(i) })); + TestResult::passed() +} + +use crate::Op::*; +#[derive(Copy, Clone, Debug)] +enum Op { + Add(K, V), + Remove(K), + AddEntry(K, V), + RemoveEntry(K), +} + +impl Arbitrary for Op +where + K: Arbitrary, + V: Arbitrary, +{ + fn arbitrary(g: &mut Gen) -> Self { + match u32::arbitrary(g) % 4 { + 0 => Add(K::arbitrary(g), V::arbitrary(g)), + 1 => AddEntry(K::arbitrary(g), V::arbitrary(g)), + 2 => Remove(K::arbitrary(g)), + _ => RemoveEntry(K::arbitrary(g)), + } + } +} + +fn do_ops(ops: &[Op], a: &mut IndexMap, b: &mut HashMap) +where + K: Hash + Eq + Clone, + V: Clone, + S: BuildHasher, +{ + for op in ops { + match *op { + Add(ref k, ref v) => { + a.insert(k.clone(), v.clone()); + b.insert(k.clone(), v.clone()); + } + AddEntry(ref k, ref v) => { + a.entry(k.clone()).or_insert_with(|| v.clone()); + b.entry(k.clone()).or_insert_with(|| v.clone()); + } + Remove(ref k) => { + a.swap_remove(k); + b.remove(k); + } + RemoveEntry(ref k) => { + if let Entry::Occupied(ent) = a.entry(k.clone()) { + ent.swap_remove_entry(); + } + if let StdEntry::Occupied(ent) = b.entry(k.clone()) { + ent.remove_entry(); + } + } + } + //println!("{:?}", a); + } +} + +fn assert_maps_equivalent(a: &IndexMap, b: &HashMap) -> bool +where + K: Hash + Eq + Debug, + V: Eq + Debug, +{ + assert_eq!(a.len(), b.len()); + assert_eq!(a.iter().next().is_some(), b.iter().next().is_some()); + for key in a.keys() { + assert!(b.contains_key(key), "b does not contain {:?}", key); + } + for key in b.keys() { + assert!(a.get(key).is_some(), "a does not contain {:?}", key); + } + for key in a.keys() { + assert_eq!(a[key], b[key]); + } + true +} + +quickcheck_limit! { + fn operations_i8(ops: Large>>) -> bool { + let mut map = IndexMap::new(); + let mut reference = HashMap::new(); + do_ops(&ops, &mut map, &mut reference); + assert_maps_equivalent(&map, &reference) + } + + fn operations_string(ops: Vec>) -> bool { + let mut map = IndexMap::new(); + let mut reference = HashMap::new(); + do_ops(&ops, &mut map, &mut reference); + assert_maps_equivalent(&map, &reference) + } + + fn keys_values(ops: Large>>) -> bool { + let mut map = IndexMap::new(); + let mut reference = HashMap::new(); + do_ops(&ops, &mut map, &mut reference); + let mut visit = IndexMap::new(); + for (k, v) in map.keys().zip(map.values()) { + assert_eq!(&map[k], v); + assert!(!visit.contains_key(k)); + visit.insert(*k, *v); + } + assert_eq!(visit.len(), reference.len()); + true + } + + fn keys_values_mut(ops: Large>>) -> bool { + let mut map = IndexMap::new(); + let mut reference = HashMap::new(); + do_ops(&ops, &mut map, &mut reference); + let mut visit = IndexMap::new(); + let keys = Vec::from_iter(map.keys().copied()); + for (k, v) in keys.iter().zip(map.values_mut()) { + assert_eq!(&reference[k], v); + assert!(!visit.contains_key(k)); + visit.insert(*k, *v); + } + assert_eq!(visit.len(), reference.len()); + true + } + + fn equality(ops1: Vec>, removes: Vec) -> bool { + let mut map = IndexMap::new(); + let mut reference = HashMap::new(); + do_ops(&ops1, &mut map, &mut reference); + let mut ops2 = ops1.clone(); + for &r in &removes { + if !ops2.is_empty() { + let i = r % ops2.len(); + ops2.remove(i); + } + } + let mut map2 = IndexMapFnv::default(); + let mut reference2 = HashMap::new(); + do_ops(&ops2, &mut map2, &mut reference2); + assert_eq!(map == map2, reference == reference2); + true + } + + fn retain_ordered(keys: Large>, remove: Large>) -> () { + let mut map = indexmap(keys.iter()); + let initial_map = map.clone(); // deduplicated in-order input + let remove_map = indexmap(remove.iter()); + let keys_s = set(keys.iter()); + let remove_s = set(remove.iter()); + let answer = &keys_s - &remove_s; + map.retain(|k, _| !remove_map.contains_key(k)); + + // check the values + assert_eq!(map.len(), answer.len()); + for key in &answer { + assert!(map.contains_key(key)); + } + // check the order + itertools::assert_equal(map.keys(), initial_map.keys().filter(|&k| !remove_map.contains_key(k))); + } + + fn sort_1(keyvals: Large>) -> () { + let mut map: IndexMap<_, _> = IndexMap::from_iter(keyvals.to_vec()); + let mut answer = keyvals.0; + answer.sort_by_key(|t| t.0); + + // reverse dedup: Because IndexMap::from_iter keeps the last value for + // identical keys + answer.reverse(); + answer.dedup_by_key(|t| t.0); + answer.reverse(); + + map.sort_by(|k1, _, k2, _| Ord::cmp(k1, k2)); + + // check it contains all the values it should + for &(key, val) in &answer { + assert_eq!(map[&key], val); + } + + // check the order + + let mapv = Vec::from_iter(map); + assert_eq!(answer, mapv); + + } + + fn sort_2(keyvals: Large>) -> () { + let mut map: IndexMap<_, _> = IndexMap::from_iter(keyvals.to_vec()); + map.sort_by(|_, v1, _, v2| Ord::cmp(v1, v2)); + assert_sorted_by_key(map, |t| t.1); + } + + fn sort_3(keyvals: Large>) -> () { + let mut map: IndexMap<_, _> = IndexMap::from_iter(keyvals.to_vec()); + map.sort_by_cached_key(|&k, _| std::cmp::Reverse(k)); + assert_sorted_by_key(map, |t| std::cmp::Reverse(t.0)); + } + + fn reverse(keyvals: Large>) -> () { + let mut map: IndexMap<_, _> = IndexMap::from_iter(keyvals.to_vec()); + + fn generate_answer(input: &Vec<(i8, i8)>) -> Vec<(i8, i8)> { + // to mimic what `IndexMap::from_iter` does: + // need to get (A) the unique keys in forward order, and (B) the + // last value of each of those keys. + + // create (A): an iterable that yields the unique keys in ltr order + let mut seen_keys = HashSet::new(); + let unique_keys_forward = input.iter().filter_map(move |(k, _)| { + if seen_keys.contains(k) { None } + else { seen_keys.insert(*k); Some(*k) } + }); + + // create (B): a mapping of keys to the last value seen for that key + // this is the same as reversing the input and taking the first + // value seen for that key! + let mut last_val_per_key = HashMap::new(); + for &(k, v) in input.iter().rev() { + if !last_val_per_key.contains_key(&k) { + last_val_per_key.insert(k, v); + } + } + + // iterate over the keys in (A) in order, and match each one with + // the corresponding last value from (B) + let mut ans: Vec<_> = unique_keys_forward + .map(|k| (k, *last_val_per_key.get(&k).unwrap())) + .collect(); + + // finally, since this test is testing `.reverse()`, reverse the + // answer in-place + ans.reverse(); + + ans + } + + let answer = generate_answer(&keyvals.0); + + // perform the work + map.reverse(); + + // check it contains all the values it should + for &(key, val) in &answer { + assert_eq!(map[&key], val); + } + + // check the order + let mapv = Vec::from_iter(map); + assert_eq!(answer, mapv); + } +} + +fn assert_sorted_by_key(iterable: I, key: Key) +where + I: IntoIterator, + I::Item: Ord + Clone + Debug, + Key: Fn(&I::Item) -> X, + X: Ord, +{ + let input = Vec::from_iter(iterable); + let mut sorted = input.clone(); + sorted.sort_by_key(key); + assert_eq!(input, sorted); +} + +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +struct Alpha(String); + +impl Deref for Alpha { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; + +impl Arbitrary for Alpha { + fn arbitrary(g: &mut Gen) -> Self { + let len = usize::arbitrary(g) % g.size(); + let len = min(len, 16); + Alpha( + (0..len) + .map(|_| ALPHABET[usize::arbitrary(g) % ALPHABET.len()] as char) + .collect(), + ) + } + + fn shrink(&self) -> Box> { + Box::new((**self).shrink().map(Alpha)) + } +} + +/// quickcheck Arbitrary adaptor -- make a larger vec +#[derive(Clone, Debug)] +struct Large(T); + +impl Deref for Large { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +impl Arbitrary for Large> +where + T: Arbitrary, +{ + fn arbitrary(g: &mut Gen) -> Self { + let len = usize::arbitrary(g) % (g.size() * 10); + Large((0..len).map(|_| T::arbitrary(g)).collect()) + } + + fn shrink(&self) -> Box> { + Box::new((**self).shrink().map(Large)) + } +} diff --git a/bitbox02-bt/vendor/indexmap/tests/tests.rs b/bitbox02-bt/vendor/indexmap/tests/tests.rs new file mode 100644 index 0000000..7d522f1 --- /dev/null +++ b/bitbox02-bt/vendor/indexmap/tests/tests.rs @@ -0,0 +1,28 @@ +use indexmap::{indexmap, indexset}; + +#[test] +fn test_sort() { + let m = indexmap! { + 1 => 2, + 7 => 1, + 2 => 2, + 3 => 3, + }; + + itertools::assert_equal( + m.sorted_by(|_k1, v1, _k2, v2| v1.cmp(v2)), + vec![(7, 1), (1, 2), (2, 2), (3, 3)], + ); +} + +#[test] +fn test_sort_set() { + let s = indexset! { + 1, + 7, + 2, + 3, + }; + + itertools::assert_equal(s.sorted_by(|v1, v2| v1.cmp(v2)), vec![1, 2, 3, 7]); +} diff --git a/bitbox02-bt/vendor/itoa/.cargo-checksum.json b/bitbox02-bt/vendor/itoa/.cargo-checksum.json new file mode 100644 index 0000000..ff584ba --- /dev/null +++ b/bitbox02-bt/vendor/itoa/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"4b12156f19f1d3a10516ba0177197325f072340e40de4b6a376732fcef3105b2","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"48573443063fa4e0786c3b46f42b6efd1f171c6b73408a64afc1b34de89f31fe","benches/bench.rs":"636f3093bd461210ad3063289d455f90669c4a1be3273bcd30898de39f02c641","src/lib.rs":"22f02b06399d4c6849dac5a1b517d3e5736dd33edc3955101ee0be6afc8376eb","src/udiv128.rs":"d28c1872c37ee2185931babcb20a221b8706a5aa8abc4963419763888023ff17","tests/test.rs":"aa1e910573a1d847d39773b4a2e4c597a8d3810070332673df0f6864cab24807"},"package":"49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/itoa/Cargo.toml b/bitbox02-bt/vendor/itoa/Cargo.toml new file mode 100644 index 0000000..91fe913 --- /dev/null +++ b/bitbox02-bt/vendor/itoa/Cargo.toml @@ -0,0 +1,43 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.36" +name = "itoa" +version = "1.0.11" +authors = ["David Tolnay "] +exclude = [ + "performance.png", + "chart/**", +] +description = "Fast integer primitive to string conversion" +documentation = "https://docs.rs/itoa" +readme = "README.md" +keywords = ["integer"] +categories = [ + "value-formatting", + "no-std", + "no-std::no-alloc", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/itoa" + +[package.metadata.docs.rs] +rustdoc-args = ["--generate-link-to-definition"] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +doc-scrape-examples = false + +[dependencies.no-panic] +version = "0.1" +optional = true diff --git a/bitbox02-bt/vendor/itoa/LICENSE-APACHE b/bitbox02-bt/vendor/itoa/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/itoa/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/itoa/LICENSE-MIT b/bitbox02-bt/vendor/itoa/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/itoa/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/itoa/README.md b/bitbox02-bt/vendor/itoa/README.md new file mode 100644 index 0000000..5728fb7 --- /dev/null +++ b/bitbox02-bt/vendor/itoa/README.md @@ -0,0 +1,59 @@ +itoa +==== + +[github](https://github.com/dtolnay/itoa) +[crates.io](https://crates.io/crates/itoa) +[docs.rs](https://docs.rs/itoa) +[build status](https://github.com/dtolnay/itoa/actions?query=branch%3Amaster) + +This crate provides a fast conversion of integer primitives to decimal strings. +The implementation comes straight from [libcore] but avoids the performance +penalty of going through [`core::fmt::Formatter`]. + +See also [`ryu`] for printing floating point primitives. + +*Version requirement: rustc 1.36+* + +[libcore]: https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L201-L254 +[`core::fmt::Formatter`]: https://doc.rust-lang.org/std/fmt/struct.Formatter.html +[`ryu`]: https://github.com/dtolnay/ryu + +```toml +[dependencies] +itoa = "1.0" +``` + +
+ +## Example + +```rust +fn main() { + let mut buffer = itoa::Buffer::new(); + let printed = buffer.format(128u64); + assert_eq!(printed, "128"); +} +``` + +
+ +## Performance (lower is better) + +![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/performance.png) + +
+ +#### License + + +Licensed under either of
Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/itoa/benches/bench.rs b/bitbox02-bt/vendor/itoa/benches/bench.rs new file mode 100644 index 0000000..acd2a0c --- /dev/null +++ b/bitbox02-bt/vendor/itoa/benches/bench.rs @@ -0,0 +1,55 @@ +#![feature(test)] +#![allow(non_snake_case)] +#![allow(clippy::cast_lossless)] + +extern crate test; + +macro_rules! benches { + ($($name:ident($value:expr))*) => { + mod bench_itoa_format { + use test::{Bencher, black_box}; + + $( + #[bench] + fn $name(b: &mut Bencher) { + let mut buffer = itoa::Buffer::new(); + + b.iter(|| { + let printed = buffer.format(black_box($value)); + black_box(printed); + }); + } + )* + } + + mod bench_std_fmt { + use std::io::Write; + use test::{Bencher, black_box}; + + $( + #[bench] + fn $name(b: &mut Bencher) { + let mut buf = Vec::with_capacity(40); + + b.iter(|| { + buf.clear(); + write!(&mut buf, "{}", black_box($value)).unwrap(); + black_box(&buf); + }); + } + )* + } + } +} + +benches! { + bench_u64_0(0u64) + bench_u64_half(u32::max_value() as u64) + bench_u64_max(u64::max_value()) + + bench_i16_0(0i16) + bench_i16_min(i16::min_value()) + + bench_u128_0(0u128) + bench_u128_max(u128::max_value()) +} diff --git a/bitbox02-bt/vendor/itoa/src/lib.rs b/bitbox02-bt/vendor/itoa/src/lib.rs new file mode 100644 index 0000000..8d6721d --- /dev/null +++ b/bitbox02-bt/vendor/itoa/src/lib.rs @@ -0,0 +1,309 @@ +//! [![github]](https://github.com/dtolnay/itoa) [![crates-io]](https://crates.io/crates/itoa) [![docs-rs]](https://docs.rs/itoa) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs +//! +//!
+//! +//! This crate provides a fast conversion of integer primitives to decimal +//! strings. The implementation comes straight from [libcore] but avoids the +//! performance penalty of going through [`core::fmt::Formatter`]. +//! +//! See also [`ryu`] for printing floating point primitives. +//! +//! [libcore]: https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L201-L254 +//! [`core::fmt::Formatter`]: https://doc.rust-lang.org/std/fmt/struct.Formatter.html +//! [`ryu`]: https://github.com/dtolnay/ryu +//! +//! # Example +//! +//! ``` +//! fn main() { +//! let mut buffer = itoa::Buffer::new(); +//! let printed = buffer.format(128u64); +//! assert_eq!(printed, "128"); +//! } +//! ``` +//! +//! # Performance (lower is better) +//! +//! ![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/performance.png) + +#![doc(html_root_url = "https://docs.rs/itoa/1.0.11")] +#![no_std] +#![allow( + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::expl_impl_clone_on_copy, + clippy::must_use_candidate, + clippy::needless_doctest_main, + clippy::unreadable_literal +)] + +mod udiv128; + +use core::mem::{self, MaybeUninit}; +use core::{ptr, slice, str}; +#[cfg(feature = "no-panic")] +use no_panic::no_panic; + +/// A correctly sized stack allocation for the formatted integer to be written +/// into. +/// +/// # Example +/// +/// ``` +/// let mut buffer = itoa::Buffer::new(); +/// let printed = buffer.format(1234); +/// assert_eq!(printed, "1234"); +/// ``` +pub struct Buffer { + bytes: [MaybeUninit; I128_MAX_LEN], +} + +impl Default for Buffer { + #[inline] + fn default() -> Buffer { + Buffer::new() + } +} + +impl Copy for Buffer {} + +impl Clone for Buffer { + #[inline] + #[allow(clippy::non_canonical_clone_impl)] // false positive https://github.com/rust-lang/rust-clippy/issues/11072 + fn clone(&self) -> Self { + Buffer::new() + } +} + +impl Buffer { + /// This is a cheap operation; you don't need to worry about reusing buffers + /// for efficiency. + #[inline] + #[cfg_attr(feature = "no-panic", no_panic)] + pub fn new() -> Buffer { + let bytes = [MaybeUninit::::uninit(); I128_MAX_LEN]; + Buffer { bytes } + } + + /// Print an integer into this buffer and return a reference to its string + /// representation within the buffer. + #[cfg_attr(feature = "no-panic", no_panic)] + pub fn format(&mut self, i: I) -> &str { + i.write(unsafe { + &mut *(&mut self.bytes as *mut [MaybeUninit; I128_MAX_LEN] + as *mut ::Buffer) + }) + } +} + +/// An integer that can be written into an [`itoa::Buffer`][Buffer]. +/// +/// This trait is sealed and cannot be implemented for types outside of itoa. +pub trait Integer: private::Sealed {} + +// Seal to prevent downstream implementations of the Integer trait. +mod private { + pub trait Sealed: Copy { + type Buffer: 'static; + fn write(self, buf: &mut Self::Buffer) -> &str; + } +} + +const DEC_DIGITS_LUT: &[u8] = b"\ + 0001020304050607080910111213141516171819\ + 2021222324252627282930313233343536373839\ + 4041424344454647484950515253545556575859\ + 6061626364656667686970717273747576777879\ + 8081828384858687888990919293949596979899"; + +// Adaptation of the original implementation at +// https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266 +macro_rules! impl_Integer { + ($($max_len:expr => $t:ident),* as $conv_fn:ident) => {$( + impl Integer for $t {} + + impl private::Sealed for $t { + type Buffer = [MaybeUninit; $max_len]; + + #[allow(unused_comparisons)] + #[inline] + #[cfg_attr(feature = "no-panic", no_panic)] + fn write(self, buf: &mut [MaybeUninit; $max_len]) -> &str { + let is_nonnegative = self >= 0; + let mut n = if is_nonnegative { + self as $conv_fn + } else { + // Convert negative number to positive by summing 1 to its two's complement. + (!(self as $conv_fn)).wrapping_add(1) + }; + let mut curr = buf.len() as isize; + let buf_ptr = buf.as_mut_ptr() as *mut u8; + let lut_ptr = DEC_DIGITS_LUT.as_ptr(); + + // Need at least 16 bits for the 4-digits-at-a-time to work. + if mem::size_of::<$t>() >= 2 { + // Eagerly decode 4 digits at a time. + while n >= 10000 { + let rem = (n % 10000) as isize; + n /= 10000; + + let d1 = (rem / 100) << 1; + let d2 = (rem % 100) << 1; + curr -= 4; + unsafe { + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(curr + 2), 2); + } + } + } + + // If we reach here, numbers are <=9999 so at most 4 digits long. + let mut n = n as isize; // Possibly reduce 64-bit math. + + // Decode 2 more digits, if >2 digits. + if n >= 100 { + let d1 = (n % 100) << 1; + n /= 100; + curr -= 2; + unsafe { + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + } + } + + // Decode last 1 or 2 digits. + if n < 10 { + curr -= 1; + unsafe { + *buf_ptr.offset(curr) = (n as u8) + b'0'; + } + } else { + let d1 = n << 1; + curr -= 2; + unsafe { + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + } + } + + if !is_nonnegative { + curr -= 1; + unsafe { + *buf_ptr.offset(curr) = b'-'; + } + } + + let len = buf.len() - curr as usize; + let bytes = unsafe { slice::from_raw_parts(buf_ptr.offset(curr), len) }; + unsafe { str::from_utf8_unchecked(bytes) } + } + } + )*}; +} + +const I8_MAX_LEN: usize = 4; +const U8_MAX_LEN: usize = 3; +const I16_MAX_LEN: usize = 6; +const U16_MAX_LEN: usize = 5; +const I32_MAX_LEN: usize = 11; +const U32_MAX_LEN: usize = 10; +const I64_MAX_LEN: usize = 20; +const U64_MAX_LEN: usize = 20; + +impl_Integer!( + I8_MAX_LEN => i8, + U8_MAX_LEN => u8, + I16_MAX_LEN => i16, + U16_MAX_LEN => u16, + I32_MAX_LEN => i32, + U32_MAX_LEN => u32 + as u32); + +impl_Integer!(I64_MAX_LEN => i64, U64_MAX_LEN => u64 as u64); + +#[cfg(target_pointer_width = "16")] +impl_Integer!(I16_MAX_LEN => isize, U16_MAX_LEN => usize as u16); + +#[cfg(target_pointer_width = "32")] +impl_Integer!(I32_MAX_LEN => isize, U32_MAX_LEN => usize as u32); + +#[cfg(target_pointer_width = "64")] +impl_Integer!(I64_MAX_LEN => isize, U64_MAX_LEN => usize as u64); + +macro_rules! impl_Integer128 { + ($($max_len:expr => $t:ident),*) => {$( + impl Integer for $t {} + + impl private::Sealed for $t { + type Buffer = [MaybeUninit; $max_len]; + + #[allow(unused_comparisons)] + #[inline] + #[cfg_attr(feature = "no-panic", no_panic)] + fn write(self, buf: &mut [MaybeUninit; $max_len]) -> &str { + let is_nonnegative = self >= 0; + let n = if is_nonnegative { + self as u128 + } else { + // Convert negative number to positive by summing 1 to its two's complement. + (!(self as u128)).wrapping_add(1) + }; + let mut curr = buf.len() as isize; + let buf_ptr = buf.as_mut_ptr() as *mut u8; + + // Divide by 10^19 which is the highest power less than 2^64. + let (n, rem) = udiv128::udivmod_1e19(n); + let buf1 = unsafe { buf_ptr.offset(curr - U64_MAX_LEN as isize) as *mut [MaybeUninit; U64_MAX_LEN] }; + curr -= rem.write(unsafe { &mut *buf1 }).len() as isize; + + if n != 0 { + // Memset the base10 leading zeros of rem. + let target = buf.len() as isize - 19; + unsafe { + ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); + } + curr = target; + + // Divide by 10^19 again. + let (n, rem) = udiv128::udivmod_1e19(n); + let buf2 = unsafe { buf_ptr.offset(curr - U64_MAX_LEN as isize) as *mut [MaybeUninit; U64_MAX_LEN] }; + curr -= rem.write(unsafe { &mut *buf2 }).len() as isize; + + if n != 0 { + // Memset the leading zeros. + let target = buf.len() as isize - 38; + unsafe { + ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); + } + curr = target; + + // There is at most one digit left + // because u128::MAX / 10^19 / 10^19 is 3. + curr -= 1; + unsafe { + *buf_ptr.offset(curr) = (n as u8) + b'0'; + } + } + } + + if !is_nonnegative { + curr -= 1; + unsafe { + *buf_ptr.offset(curr) = b'-'; + } + } + + let len = buf.len() - curr as usize; + let bytes = unsafe { slice::from_raw_parts(buf_ptr.offset(curr), len) }; + unsafe { str::from_utf8_unchecked(bytes) } + } + } + )*}; +} + +const U128_MAX_LEN: usize = 39; +const I128_MAX_LEN: usize = 40; + +impl_Integer128!(I128_MAX_LEN => i128, U128_MAX_LEN => u128); diff --git a/bitbox02-bt/vendor/itoa/src/udiv128.rs b/bitbox02-bt/vendor/itoa/src/udiv128.rs new file mode 100644 index 0000000..0587047 --- /dev/null +++ b/bitbox02-bt/vendor/itoa/src/udiv128.rs @@ -0,0 +1,48 @@ +#[cfg(feature = "no-panic")] +use no_panic::no_panic; + +/// Multiply unsigned 128 bit integers, return upper 128 bits of the result +#[inline] +#[cfg_attr(feature = "no-panic", no_panic)] +fn u128_mulhi(x: u128, y: u128) -> u128 { + let x_lo = x as u64; + let x_hi = (x >> 64) as u64; + let y_lo = y as u64; + let y_hi = (y >> 64) as u64; + + // handle possibility of overflow + let carry = (x_lo as u128 * y_lo as u128) >> 64; + let m = x_lo as u128 * y_hi as u128 + carry; + let high1 = m >> 64; + + let m_lo = m as u64; + let high2 = (x_hi as u128 * y_lo as u128 + m_lo as u128) >> 64; + + x_hi as u128 * y_hi as u128 + high1 + high2 +} + +/// Divide `n` by 1e19 and return quotient and remainder +/// +/// Integer division algorithm is based on the following paper: +/// +/// T. Granlund and P. Montgomery, “Division by Invariant Integers Using Multiplication” +/// in Proc. of the SIGPLAN94 Conference on Programming Language Design and +/// Implementation, 1994, pp. 61–72 +/// +#[inline] +#[cfg_attr(feature = "no-panic", no_panic)] +pub fn udivmod_1e19(n: u128) -> (u128, u64) { + let d = 10_000_000_000_000_000_000_u64; // 10^19 + + let quot = if n < 1 << 83 { + ((n >> 19) as u64 / (d >> 19)) as u128 + } else { + u128_mulhi(n, 156927543384667019095894735580191660403) >> 62 + }; + + let rem = (n - quot * d as u128) as u64; + debug_assert_eq!(quot, n / d as u128); + debug_assert_eq!(rem as u128, n % d as u128); + + (quot, rem) +} diff --git a/bitbox02-bt/vendor/itoa/tests/test.rs b/bitbox02-bt/vendor/itoa/tests/test.rs new file mode 100644 index 0000000..f8275d6 --- /dev/null +++ b/bitbox02-bt/vendor/itoa/tests/test.rs @@ -0,0 +1,30 @@ +#![allow(non_snake_case)] +#![allow(clippy::cast_lossless)] + +macro_rules! test { + ($($name:ident($value:expr, $expected:expr))*) => { + $( + #[test] + fn $name() { + let mut buffer = itoa::Buffer::new(); + let s = buffer.format($value); + assert_eq!(s, $expected); + } + )* + } +} + +test! { + test_u64_0(0u64, "0") + test_u64_half(u32::max_value() as u64, "4294967295") + test_u64_max(u64::max_value(), "18446744073709551615") + test_i64_min(i64::min_value(), "-9223372036854775808") + + test_i16_0(0i16, "0") + test_i16_min(i16::min_value(), "-32768") + + test_u128_0(0u128, "0") + test_u128_max(u128::max_value(), "340282366920938463463374607431768211455") + test_i128_min(i128::min_value(), "-170141183460469231731687303715884105728") + test_i128_max(i128::max_value(), "170141183460469231731687303715884105727") +} diff --git a/bitbox02-bt/vendor/nb-0.1.3/.cargo-checksum.json b/bitbox02-bt/vendor/nb-0.1.3/.cargo-checksum.json new file mode 100644 index 0000000..39a1a4a --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"6656d9902a33a76e1f57ae269cc4290a20f0660b7098451f0222d6a2e05211a6","Cargo.toml":"f277cf77fc1263e49054d92acb079e11bb747b1a310a66d262f9824c7ebaf573","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"035e70219855119df4273b3c5b97543ae82e0dd60c520416e759107c602f651b","README.md":"f58c64d699a84555e9542fad4acf71d3f4fb6bc266199efa9dde7d999ece9263","bors.toml":"b96eaac6b3dc8487a2bcc6cb415e745a28d9a61937090df48186c62d2b614aeb","src/lib.rs":"7dc2ec005f5307821c792536841c9db8285614ebff5471fc029de8300d410008"},"package":"801d31da0513b6ec5214e9bf433a77966320625a37860f910be265be6e18d06f"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/nb-0.1.3/CHANGELOG.md b/bitbox02-bt/vendor/nb-0.1.3/CHANGELOG.md new file mode 100644 index 0000000..23feb87 --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/CHANGELOG.md @@ -0,0 +1,37 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.1.3] - 2020-07-07 + +This release of the 0.1 version exists for compatibility with 1.0.0. +There are no functional changes compared to 0.1.2. + +## [v0.1.2] - 2019-04-21 + +### Added + +- `Error` gained a `map` method that lets you transform the error in the + `Error::Other` variant into a different type. + +- `Error` now implements the `From` trait. + +## [v0.1.1] - 2018-01-10 + +### Fixed + +- The `await!` macro now works when the expression `$e` mutably borrows `self`. + +## v0.1.0 - 2018-01-10 + +Initial release + +[Unreleased]: https://github.com/rust-embedded/nb/compare/v0.1.3...HEAD +[v0.1.3]: https://github.com/rust-embedded/nb/compare/v0.1.2...v0.1.3 +[v0.1.2]: https://github.com/rust-embedded/nb/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/rust-embedded/nb/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/nb-0.1.3/Cargo.toml b/bitbox02-bt/vendor/nb-0.1.3/Cargo.toml new file mode 100644 index 0000000..983933b --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/Cargo.toml @@ -0,0 +1,34 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "nb" +version = "0.1.3" +authors = ["Jorge Aparicio "] +description = "Minimal non-blocking I/O layer" +homepage = "https://github.com/rust-embedded/nb" +documentation = "https://docs.rs/nb" +readme = "README.md" +keywords = ["await", "futures", "IO"] +categories = ["asynchronous", "embedded", "no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-embedded/nb" + +[lib] +doctest = false +[dependencies.nb] +version = "1" +[dev-dependencies.futures] +version = "0.1.17" + +[features] +unstable = [] diff --git a/bitbox02-bt/vendor/nb-0.1.3/LICENSE-APACHE b/bitbox02-bt/vendor/nb-0.1.3/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/nb-0.1.3/LICENSE-MIT b/bitbox02-bt/vendor/nb-0.1.3/LICENSE-MIT new file mode 100644 index 0000000..a128ba4 --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017 Jorge Aparicio + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/nb-0.1.3/README.md b/bitbox02-bt/vendor/nb-0.1.3/README.md new file mode 100644 index 0000000..13ec08d --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/README.md @@ -0,0 +1,25 @@ +# `nb` + +> Minimal and reusable non-blocking I/O layer + +This project is developed and maintained by the [HAL team][team]. + +## [Documentation](https://docs.rs/nb) + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +[team]: https://github.com/rust-embedded/wg#the-hal-team diff --git a/bitbox02-bt/vendor/nb-0.1.3/bors.toml b/bitbox02-bt/vendor/nb-0.1.3/bors.toml new file mode 100644 index 0000000..5ccee21 --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/bors.toml @@ -0,0 +1,3 @@ +status = [ + "continuous-integration/travis-ci/push", +] \ No newline at end of file diff --git a/bitbox02-bt/vendor/nb-0.1.3/src/lib.rs b/bitbox02-bt/vendor/nb-0.1.3/src/lib.rs new file mode 100644 index 0000000..a1f534f --- /dev/null +++ b/bitbox02-bt/vendor/nb-0.1.3/src/lib.rs @@ -0,0 +1,438 @@ +//! Minimal and reusable non-blocking I/O layer +//! +//! The ultimate goal of this crate is *code reuse*. With this crate you can +//! write *core* I/O APIs that can then be adapted to operate in either blocking +//! or non-blocking manner. Furthermore those APIs are not tied to a particular +//! asynchronous model and can be adapted to work with the `futures` model or +//! with the `async` / `await` model. +//! +//! # Core idea +//! +//! The [`WouldBlock`](enum.Error.html) error variant signals that the operation +//! can't be completed *right now* and would need to block to complete. +//! [`WouldBlock`](enum.Error.html) is a special error in the sense that's not +//! *fatal*; the operation can still be completed by retrying again later. +//! +//! [`nb::Result`](type.Result.html) is based on the API of +//! [`std::io::Result`](https://doc.rust-lang.org/std/io/type.Result.html), +//! which has a `WouldBlock` variant in its +//! [`ErrorKind`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html). +//! +//! We can map [`WouldBlock`](enum.Error.html) to different blocking and +//! non-blocking models: +//! +//! - In blocking mode: [`WouldBlock`](enum.Error.html) means try again right +//! now (i.e. busy wait) +//! - In `futures` mode: [`WouldBlock`](enum.Error.html) means +//! [`Async::NotReady`](https://docs.rs/futures) +//! - In `await` mode: [`WouldBlock`](enum.Error.html) means `yield` +//! (suspend the generator) +//! +//! # How to use this crate +//! +//! Application specific errors can be put inside the `Other` variant in the +//! [`nb::Error`](enum.Error.html) enum. +//! +//! So in your API instead of returning `Result` return +//! `nb::Result` +//! +//! ``` +//! enum MyError { +//! ThisError, +//! ThatError, +//! // .. +//! } +//! +//! // This is a blocking function, so it returns a normal `Result` +//! fn before() -> Result<(), MyError> { +//! // .. +//! # Ok(()) +//! } +//! +//! // This is now a potentially (read: *non*) blocking function so it returns `nb::Result` +//! // instead of blocking +//! fn after() -> nb::Result<(), MyError> { +//! // .. +//! # Ok(()) +//! } +//! ``` +//! +//! You can use the *never type* (`!`) to signal that some API has no fatal +//! errors but may block: +//! +//! ``` +//! #![feature(never_type)] +//! +//! // This returns `Ok(())` or `Err(nb::Error::WouldBlock)` +//! fn maybe_blocking_api() -> nb::Result<(), !> { +//! // .. +//! # Ok(()) +//! } +//! ``` +//! +//! Once your API uses [`nb::Result`](type.Result.html) you can leverage the +//! [`block!`], [`try_nb!`] and [`await!`] macros to adapt it for blocking +//! operation, or for non-blocking operation with `futures` or `await`. +//! +//! **NOTE** Currently, both `try_nb!` and `await!` are feature gated behind the `unstable` Cargo +//! feature. +//! +//! [`block!`]: macro.block.html +//! [`try_nb!`]: macro.try_nb.html +//! [`await!`]: macro.await.html +//! +//! # Examples +//! +//! ## A Core I/O API +//! +//! Imagine the code (crate) below represents a Hardware Abstraction Layer for some microcontroller +//! (or microcontroller family). +//! +//! *In this and the following examples let's assume for simplicity that peripherals are treated +//! as global singletons and that no preemption is possible (i.e. interrupts are disabled).* +//! +//! ``` +//! #![feature(never_type)] +//! +//! // This is the `hal` crate +//! // Note that it doesn't depend on the `futures` crate +//! +//! extern crate nb; +//! +//! /// An LED +//! pub struct Led; +//! +//! impl Led { +//! pub fn off(&self) { +//! // .. +//! } +//! pub fn on(&self) { +//! // .. +//! } +//! } +//! +//! /// Serial interface +//! pub struct Serial; +//! pub enum Error { +//! Overrun, +//! // .. +//! } +//! +//! impl Serial { +//! /// Reads a single byte from the serial interface +//! pub fn read(&self) -> nb::Result { +//! // .. +//! # Ok(0) +//! } +//! +//! /// Writes a single byte to the serial interface +//! pub fn write(&self, byte: u8) -> nb::Result<(), Error> { +//! // .. +//! # Ok(()) +//! } +//! } +//! +//! /// A timer used for timeouts +//! pub struct Timer; +//! +//! impl Timer { +//! /// Waits until the timer times out +//! pub fn wait(&self) -> nb::Result<(), !> { +//! //^ NOTE the `!` indicates that this operation can block but has no +//! // other form of error +//! +//! // .. +//! # Ok(()) +//! } +//! } +//! ``` +//! +//! ## Blocking mode +//! +//! Turn on an LED for one second and *then* loops back serial data. +//! +//! ``` +//! # #![feature(never_type)] +//! #[macro_use(block)] +//! extern crate nb; +//! +//! use hal::{Led, Serial, Timer}; +//! +//! fn main() { +//! // Turn the LED on for one second +//! Led.on(); +//! block!(Timer.wait()).unwrap(); // NOTE(unwrap) E = ! +//! Led.off(); +//! +//! // Serial interface loopback +//! # return; +//! loop { +//! let byte = block!(Serial.read()).unwrap(); +//! block!(Serial.write(byte)).unwrap(); +//! } +//! } +//! +//! # mod hal { +//! # use nb; +//! # pub struct Led; +//! # impl Led { +//! # pub fn off(&self) {} +//! # pub fn on(&self) {} +//! # } +//! # pub struct Serial; +//! # impl Serial { +//! # pub fn read(&self) -> nb::Result { Ok(0) } +//! # pub fn write(&self, _: u8) -> nb::Result<(), ()> { Ok(()) } +//! # } +//! # pub struct Timer; +//! # impl Timer { +//! # pub fn wait(&self) -> nb::Result<(), !> { Ok(()) } +//! # } +//! # } +//! ``` +//! +//! ## `futures` +//! +//! Blinks an LED every second *and* loops back serial data. Both tasks run +//! concurrently. +//! +//! ``` +//! #![feature(conservative_impl_trait)] +//! #![feature(never_type)] +//! +//! extern crate futures; +//! #[macro_use(try_nb)] +//! extern crate nb; +//! +//! use futures::{Async, Future}; +//! use futures::future::{self, Loop}; +//! use hal::{Error, Led, Serial, Timer}; +//! +//! /// `futures` version of `Timer.wait` +//! /// +//! /// This returns a future that must be polled to completion +//! fn wait() -> impl Future { +//! future::poll_fn(|| { +//! Ok(Async::Ready(try_nb!(Timer.wait()))) +//! }) +//! } +//! +//! /// `futures` version of `Serial.read` +//! /// +//! /// This returns a future that must be polled to completion +//! fn read() -> impl Future { +//! future::poll_fn(|| { +//! Ok(Async::Ready(try_nb!(Serial.read()))) +//! }) +//! } +//! +//! /// `futures` version of `Serial.write` +//! /// +//! /// This returns a future that must be polled to completion +//! fn write(byte: u8) -> impl Future { +//! future::poll_fn(move || { +//! Ok(Async::Ready(try_nb!(Serial.write(byte)))) +//! }) +//! } +//! +//! fn main() { +//! // Tasks +//! let mut blinky = future::loop_fn::<_, (), _, _>(true, |state| { +//! wait().map(move |_| { +//! if state { +//! Led.on(); +//! } else { +//! Led.off(); +//! } +//! +//! Loop::Continue(!state) +//! }) +//! }); +//! +//! let mut loopback = future::loop_fn::<_, (), _, _>((), |_| { +//! read().and_then(|byte| { +//! write(byte) +//! }).map(|_| { +//! Loop::Continue(()) +//! }) +//! }); +//! +//! // Event loop +//! loop { +//! blinky.poll().unwrap(); // NOTE(unwrap) E = ! +//! loopback.poll().unwrap(); +//! # break +//! } +//! } +//! +//! # mod hal { +//! # use nb; +//! # pub struct Led; +//! # impl Led { +//! # pub fn off(&self) {panic!()} +//! # pub fn on(&self) {} +//! # } +//! # #[derive(Debug)] +//! # pub enum Error {} +//! # pub struct Serial; +//! # impl Serial { +//! # pub fn read(&self) -> nb::Result { Err(nb::Error::WouldBlock) } +//! # pub fn write(&self, _: u8) -> nb::Result<(), Error> { Err(nb::Error::WouldBlock) } +//! # } +//! # pub struct Timer; +//! # impl Timer { +//! # pub fn wait(&self) -> nb::Result<(), !> { Err(nb::Error::WouldBlock) } +//! # } +//! # } +//! ``` +//! +//! ## `await!` +//! +//! This is equivalent to the `futures` example but with much less boilerplate. +//! +//! ``` +//! #![feature(generator_trait)] +//! #![feature(generators)] +//! #![feature(never_type)] +//! +//! #[macro_use(await)] +//! extern crate nb; +//! +//! use std::ops::Generator; +//! +//! use hal::{Led, Serial, Timer}; +//! +//! fn main() { +//! // Tasks +//! let mut blinky = || { +//! let mut state = false; +//! loop { +//! // `await!` means suspend / yield instead of blocking +//! await!(Timer.wait()).unwrap(); // NOTE(unwrap) E = ! +//! +//! state = !state; +//! +//! if state { +//! Led.on(); +//! } else { +//! Led.off(); +//! } +//! } +//! }; +//! +//! let mut loopback = || { +//! loop { +//! let byte = await!(Serial.read()).unwrap(); +//! await!(Serial.write(byte)).unwrap(); +//! } +//! }; +//! +//! // Event loop +//! loop { +//! blinky.resume(); +//! loopback.resume(); +//! # break +//! } +//! } +//! +//! # mod hal { +//! # use nb; +//! # pub struct Led; +//! # impl Led { +//! # pub fn off(&self) {} +//! # pub fn on(&self) {} +//! # } +//! # pub struct Serial; +//! # impl Serial { +//! # pub fn read(&self) -> nb::Result { Err(nb::Error::WouldBlock) } +//! # pub fn write(&self, _: u8) -> nb::Result<(), ()> { Err(nb::Error::WouldBlock) } +//! # } +//! # pub struct Timer; +//! # impl Timer { +//! # pub fn wait(&self) -> nb::Result<(), !> { Err(nb::Error::WouldBlock) } +//! # } +//! # } +//! ``` + +#![no_std] +#![doc(html_root_url = "https://docs.rs/nb/0.1.3")] + +extern crate nb; +pub use nb::{block, Error, Result}; + +/// Await operation (*won't work until the language gains support for +/// generators*) +/// +/// This macro evaluates the expression `$e` *cooperatively* yielding control +/// back to the (generator) caller whenever `$e` evaluates to +/// `Error::WouldBlock`. +/// +/// # Requirements +/// +/// This macro must be called within a generator body. +/// +/// # Input +/// +/// An expression `$e` that evaluates to `nb::Result` +/// +/// # Output +/// +/// - `Ok(t)` if `$e` evaluates to `Ok(t)` +/// - `Err(e)` if `$e` evaluates to `Err(nb::Error::Other(e))` +#[cfg(feature = "unstable")] +#[macro_export] +macro_rules! await { + ($e:expr) => { + loop { + #[allow(unreachable_patterns)] + match $e { + Err($crate::Error::Other(e)) => + { + #[allow(unreachable_code)] + break Err(e) + } + Err($crate::Error::WouldBlock) => {} // yield (see below) + Ok(x) => break Ok(x), + } + + yield + } + }; +} + +/// Future adapter +/// +/// This is a *try* operation from a `nb::Result` to a `futures::Poll` +/// +/// # Requirements +/// +/// This macro must be called within a function / closure that has signature +/// `fn(..) -> futures::Poll`. +/// +/// This macro requires that the [`futures`] crate is in the root of the crate. +/// +/// [`futures`]: https://crates.io/crates/futures +/// +/// # Input +/// +/// An expression `$e` that evaluates to `nb::Result` +/// +/// # Early return +/// +/// - `Ok(Async::NotReady)` if `$e` evaluates to `Err(nb::Error::WouldBlock)` +/// - `Err(e)` if `$e` evaluates to `Err(nb::Error::Other(e))` +/// +/// # Output +/// +/// `t` if `$e` evaluates to `Ok(t)` +#[cfg(feature = "unstable")] +#[macro_export] +macro_rules! try_nb { + ($e:expr) => { + match $e { + Err($crate::Error::Other(e)) => return Err(e), + Err($crate::Error::WouldBlock) => return Ok(::futures::Async::NotReady), + Ok(x) => x, + } + }; +} diff --git a/bitbox02-bt/vendor/nb/.cargo-checksum.json b/bitbox02-bt/vendor/nb/.cargo-checksum.json new file mode 100644 index 0000000..91e2895 --- /dev/null +++ b/bitbox02-bt/vendor/nb/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"8c8c3a6709b7d9e37d679847e26fff0ec77b2321bb2adb2c93f458a7bf22845f","CODE_OF_CONDUCT.md":"8e25e95078b1a582086587adf8e1d907d43aacee6a072b8630d54a6289e5e0b9","Cargo.toml":"12d0bce4dfc6ac4921ee58cb25e1b03d3d0cb29d261bd175cd5f1e4d407aee43","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"035e70219855119df4273b3c5b97543ae82e0dd60c520416e759107c602f651b","README.md":"0731dbd8d3223e6f7a34aafa90bfc0a822e46958c5f2730420eeaa6782a856b6","src/lib.rs":"9073399b07e2b981f47a7d9523f9d73be83c511f397c372a2f408d8206a8abcd","triagebot.toml":"a135e10c777cd13459559bdf74fb704c1379af7c9b0f70bc49fa6f5a837daa81"},"package":"8d5439c4ad607c3c23abf66de8c8bf57ba8adcd1f129e699851a6e43935d339d"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/nb/CHANGELOG.md b/bitbox02-bt/vendor/nb/CHANGELOG.md new file mode 100644 index 0000000..8d18a8c --- /dev/null +++ b/bitbox02-bt/vendor/nb/CHANGELOG.md @@ -0,0 +1,46 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v1.1.0] - 2023-03-07 + +### Added + +- Add `defmt` as optional dependency and implement `defmt::Format` for `Error`, enabled by `defmt-0-3` unstable feature. + +## [v1.0.0] - 2020-07-07 + +### Changed + +- [breaking-change] The `unstable` feature and its code has been removed. + This includes the macros `try_nb!` and `await!`. + +## [v0.1.2] - 2019-04-21 + +### Added + +- `Error` gained a `map` method that lets you transform the error in the + `Error::Other` variant into a different type. + +- `Error` now implements the `From` trait. + +## [v0.1.1] - 2018-01-10 + +### Fixed + +- The `await!` macro now works when the expression `$e` mutably borrows `self`. + +## v0.1.0 - 2018-01-10 + +Initial release + +[Unreleased]: https://github.com/rust-embedded/nb/compare/v1.1.0...HEAD +[v1.1.0]: https://github.com/rust-embedded/nb/compare/v1.0.0...v1.1.0 +[v1.0.0]: https://github.com/rust-embedded/nb/compare/v0.1.2...v1.0.0 +[v0.1.2]: https://github.com/rust-embedded/nb/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/rust-embedded/nb/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/nb/CODE_OF_CONDUCT.md b/bitbox02-bt/vendor/nb/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..bcefc6a --- /dev/null +++ b/bitbox02-bt/vendor/nb/CODE_OF_CONDUCT.md @@ -0,0 +1,37 @@ +# The Rust Code of Conduct + +## Conduct + +**Contact**: [HAL team][team] + +* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. +* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. +* Please be kind and courteous. There's no need to be mean or rude. +* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. +* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. +* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. +* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [HAL team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. +* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. + +## Moderation + +These are the policies for upholding our community's standards of conduct. + +1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) +2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. +3. Moderators will first respond to such remarks with a warning. +4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off. +5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded. +6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology. +7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed. +8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others. + +In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. + +And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. + +The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org). + +*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* + +[team]: https://github.com/rust-embedded/wg#the-hal-team diff --git a/bitbox02-bt/vendor/nb/Cargo.toml b/bitbox02-bt/vendor/nb/Cargo.toml new file mode 100644 index 0000000..e1cac94 --- /dev/null +++ b/bitbox02-bt/vendor/nb/Cargo.toml @@ -0,0 +1,40 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.60" +name = "nb" +version = "1.1.0" +authors = ["Jorge Aparicio "] +description = "Minimal non-blocking I/O layer" +homepage = "https://github.com/rust-embedded/nb" +documentation = "https://docs.rs/nb" +readme = "README.md" +keywords = [ + "await", + "futures", + "IO", +] +categories = [ + "asynchronous", + "embedded", + "no-std", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-embedded/nb" + +[dependencies.defmt] +version = "0.3" +optional = true + +[features] +defmt-0-3 = ["dep:defmt"] diff --git a/bitbox02-bt/vendor/nb/LICENSE-APACHE b/bitbox02-bt/vendor/nb/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/nb/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/nb/LICENSE-MIT b/bitbox02-bt/vendor/nb/LICENSE-MIT new file mode 100644 index 0000000..a128ba4 --- /dev/null +++ b/bitbox02-bt/vendor/nb/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017 Jorge Aparicio + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/nb/README.md b/bitbox02-bt/vendor/nb/README.md new file mode 100644 index 0000000..0fe23df --- /dev/null +++ b/bitbox02-bt/vendor/nb/README.md @@ -0,0 +1,37 @@ +# `nb` + +> Minimal and reusable non-blocking I/O layer + +This project is developed and maintained by the [HAL team][team]. + +## [Documentation](https://docs.rs/nb) + +## Minimum Supported Rust Version (MSRV) + +This crate is guaranteed to compile on stable Rust 1.35 and up. It *might* +compile with older versions but that may change in any new patch release. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +## Code of Conduct + +Contribution to this crate is organized under the terms of the [Rust Code of +Conduct][CoC], the maintainer of this crate, the [HAL team][team], promises +to intervene to uphold that code of conduct. + +[CoC]: CODE_OF_CONDUCT.md +[team]: https://github.com/rust-embedded/wg#the-hal-team diff --git a/bitbox02-bt/vendor/nb/src/lib.rs b/bitbox02-bt/vendor/nb/src/lib.rs new file mode 100644 index 0000000..ca5b591 --- /dev/null +++ b/bitbox02-bt/vendor/nb/src/lib.rs @@ -0,0 +1,283 @@ +//! Minimal and reusable non-blocking I/O layer +//! +//! The ultimate goal of this crate is *code reuse*. With this crate you can +//! write *core* I/O APIs that can then be adapted to operate in either blocking +//! or non-blocking manner. Furthermore those APIs are not tied to a particular +//! asynchronous model and can be adapted to work with the `futures` model or +//! with the `async` / `await` model. +//! +//! # Core idea +//! +//! The [`WouldBlock`](enum.Error.html) error variant signals that the operation +//! can't be completed *right now* and would need to block to complete. +//! [`WouldBlock`](enum.Error.html) is a special error in the sense that's not +//! *fatal*; the operation can still be completed by retrying again later. +//! +//! [`nb::Result`](type.Result.html) is based on the API of +//! [`std::io::Result`](https://doc.rust-lang.org/std/io/type.Result.html), +//! which has a `WouldBlock` variant in its +//! [`ErrorKind`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html). +//! +//! We can map [`WouldBlock`](enum.Error.html) to different blocking and +//! non-blocking models: +//! +//! - In blocking mode: [`WouldBlock`](enum.Error.html) means try again right +//! now (i.e. busy wait) +//! - In `futures` mode: [`WouldBlock`](enum.Error.html) means +//! [`Async::NotReady`](https://docs.rs/futures) +//! - In `await` mode: [`WouldBlock`](enum.Error.html) means `yield` +//! (suspend the generator) +//! +//! # How to use this crate +//! +//! Application specific errors can be put inside the `Other` variant in the +//! [`nb::Error`](enum.Error.html) enum. +//! +//! So in your API instead of returning `Result` return +//! `nb::Result` +//! +//! ``` +//! enum MyError { +//! ThisError, +//! ThatError, +//! // .. +//! } +//! +//! // This is a blocking function, so it returns a normal `Result` +//! fn before() -> Result<(), MyError> { +//! // .. +//! # Ok(()) +//! } +//! +//! // This is now a potentially (read: *non*) blocking function so it returns `nb::Result` +//! // instead of blocking +//! fn after() -> nb::Result<(), MyError> { +//! // .. +//! # Ok(()) +//! } +//! ``` +//! +//! You can use `Infallible` to signal that some API has no fatal +//! errors but may block: +//! +//! ``` +//! use core::convert::Infallible; +//! +//! // This returns `Ok(())` or `Err(nb::Error::WouldBlock)` +//! fn maybe_blocking_api() -> nb::Result<(), Infallible> { +//! // .. +//! # Ok(()) +//! } +//! ``` +//! +//! Once your API uses [`nb::Result`] you can leverage the [`block!`], macro +//! to adapt it for blocking operation, or handle scheduling yourself. +//! +//! [`block!`]: macro.block.html +//! [`nb::Result`]: type.Result.html +//! +//! # Examples +//! +//! ## A Core I/O API +//! +//! Imagine the code (crate) below represents a Hardware Abstraction Layer for some microcontroller +//! (or microcontroller family). +//! +//! *In this and the following examples let's assume for simplicity that peripherals are treated +//! as global singletons and that no preemption is possible (i.e. interrupts are disabled).* +//! +//! ``` +//! # use core::convert::Infallible; +//! // This is the `hal` crate +//! use nb; +//! +//! /// An LED +//! pub struct Led; +//! +//! impl Led { +//! pub fn off(&self) { +//! // .. +//! } +//! pub fn on(&self) { +//! // .. +//! } +//! } +//! +//! /// Serial interface +//! pub struct Serial; +//! pub enum Error { +//! Overrun, +//! // .. +//! } +//! +//! impl Serial { +//! /// Reads a single byte from the serial interface +//! pub fn read(&self) -> nb::Result { +//! // .. +//! # Ok(0) +//! } +//! +//! /// Writes a single byte to the serial interface +//! pub fn write(&self, byte: u8) -> nb::Result<(), Error> { +//! // .. +//! # Ok(()) +//! } +//! } +//! +//! /// A timer used for timeouts +//! pub struct Timer; +//! +//! impl Timer { +//! /// Waits until the timer times out +//! pub fn wait(&self) -> nb::Result<(), Infallible> { +//! //^ NOTE the `Infallible` indicates that this operation can block but has no +//! // other form of error +//! +//! // .. +//! # Ok(()) +//! } +//! } +//! ``` +//! +//! ## Blocking mode +//! +//! Turn on an LED for one second and *then* loops back serial data. +//! +//! ``` +//! use core::convert::Infallible; +//! use nb::block; +//! +//! use hal::{Led, Serial, Timer}; +//! +//! # fn main() -> Result<(), Infallible> { +//! // Turn the LED on for one second +//! Led.on(); +//! block!(Timer.wait())?; +//! Led.off(); +//! +//! // Serial interface loopback +//! # return Ok(()); +//! loop { +//! let byte = block!(Serial.read())?; +//! block!(Serial.write(byte))?; +//! } +//! # } +//! +//! # mod hal { +//! # use nb; +//! # use core::convert::Infallible; +//! # pub struct Led; +//! # impl Led { +//! # pub fn off(&self) {} +//! # pub fn on(&self) {} +//! # } +//! # pub struct Serial; +//! # impl Serial { +//! # pub fn read(&self) -> nb::Result { Ok(0) } +//! # pub fn write(&self, _: u8) -> nb::Result<(), Infallible> { Ok(()) } +//! # } +//! # pub struct Timer; +//! # impl Timer { +//! # pub fn wait(&self) -> nb::Result<(), Infallible> { Ok(()) } +//! # } +//! # } +//! ``` +//! +//! # Features +//! +//! - `defmt-0-3` - unstable feature which adds [`defmt::Format`] impl for [`Error`]. + +#![no_std] + +use core::fmt; + +/// A non-blocking result +pub type Result = ::core::result::Result>; + +/// A non-blocking error +/// +/// The main use of this enum is to add a `WouldBlock` variant to an existing +/// error enum. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Error { + /// A different kind of error + Other(E), + /// This operation requires blocking behavior to complete + WouldBlock, +} + +#[cfg(feature = "defmt-0-3")] +impl defmt::Format for Error +where + E: defmt::Format, +{ + fn format(&self, f: defmt::Formatter) { + match *self { + Error::Other(ref e) => defmt::Format::format(e, f), + Error::WouldBlock => defmt::write!(f, "WouldBlock",), + } + } +} + +impl fmt::Debug for Error +where + E: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Other(ref e) => fmt::Debug::fmt(e, f), + Error::WouldBlock => f.write_str("WouldBlock"), + } + } +} + +impl Error { + /// Maps an `Error` to `Error` by applying a function to a contained + /// `Error::Other` value, leaving an `Error::WouldBlock` value untouched. + pub fn map(self, op: F) -> Error + where + F: FnOnce(E) -> T, + { + match self { + Error::Other(e) => Error::Other(op(e)), + Error::WouldBlock => Error::WouldBlock, + } + } +} + +impl From for Error { + fn from(error: E) -> Error { + Error::Other(error) + } +} + +/// Turns the non-blocking expression `$e` into a blocking operation. +/// +/// This is accomplished by continuously calling the expression `$e` until it no +/// longer returns `Error::WouldBlock` +/// +/// # Input +/// +/// An expression `$e` that evaluates to `nb::Result` +/// +/// # Output +/// +/// - `Ok(t)` if `$e` evaluates to `Ok(t)` +/// - `Err(e)` if `$e` evaluates to `Err(nb::Error::Other(e))` +#[macro_export] +macro_rules! block { + ($e:expr) => { + loop { + #[allow(unreachable_patterns)] + match $e { + Err($crate::Error::Other(e)) => + { + #[allow(unreachable_code)] + break Err(e) + } + Err($crate::Error::WouldBlock) => {} + Ok(x) => break Ok(x), + } + } + }; +} diff --git a/bitbox02-bt/vendor/nb/triagebot.toml b/bitbox02-bt/vendor/nb/triagebot.toml new file mode 100644 index 0000000..fa0824a --- /dev/null +++ b/bitbox02-bt/vendor/nb/triagebot.toml @@ -0,0 +1 @@ +[assign] diff --git a/bitbox02-bt/vendor/panic-abort/.cargo-checksum.json b/bitbox02-bt/vendor/panic-abort/.cargo-checksum.json new file mode 100644 index 0000000..87b6eed --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"1e89ec5a9769b08df2d2dcdfad044433b34641fdefb01820e58b734333d37524","Cargo.toml":"bcaa5ad739f212a02e2d6703a8debfad1a6f8a8526aea50a81742be5b40bc2ab","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c986bcdb83103d4ddf58aeb7b5302359782e54dc4eea14a0cc27c62dcbd50729","README.md":"45b32806bd5abe8e6eaa76b44ef24bf74b7935d8a0c403925f897999415a70dd","ci/after-success.sh":"00af890edbf22ca469ee2a9a6b6bb169b7d418fa481ce500cc6751b408af1819","ci/install.sh":"e295d97db9e12ac6ee3e523e4597ad58fedcca2b8aa3a21302951ad2327b88a9","ci/script.sh":"08265dc695d44a4b4a6bbe1ad0464efaa116a5343ff8725fe47bfc321eb360ec","src/lib.rs":"08764738c062063392d96378b15ed5d7366a585f4be11ca71864107342e71a1a"},"package":"4e20e6499bbbc412f280b04a42346b356c6fa0753d5fd22b7bd752ff34c778ee"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/panic-abort/CHANGELOG.md b/bitbox02-bt/vendor/panic-abort/CHANGELOG.md new file mode 100644 index 0000000..6009398 --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/CHANGELOG.md @@ -0,0 +1,48 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.3.2] - 2019-10-15 + +### Changed + +- Updated the documentation to indicate the current behavior of `intrinsics::abort`. + +## [v0.3.1] - 2018-09-09 + +### Added + +- `panic-handler` to the list of keywords. + +## [v0.3.0] - 2018-09-03 + +- [breaking-change] Move from the `panic_implementation` attribute to the + `panic_handler` attribute, which will be stabilized. + +## [v0.2.0] - 2018-06-04 + +### Changed + +- [breaking-change] moved from the, now removed, `panic_fmt` lang item to the + `#[panic_implementation]` attribute. + +## [v0.1.1] - 2018-04-09 + +### Changed + +- Tweaked the documentation and the crate metadata (keywords) + +## v0.1.0 - 2018-04-09 + +Initial release + +[Unreleased]: https://github.com/japaric/panic-abort/compare/v0.3.1...HEAD +[v0.3.1]: https://github.com/japaric/panic-abort/compare/v0.3.0...v0.3.1 +[v0.3.0]: https://github.com/japaric/panic-abort/compare/v0.2.0...v0.3.0 +[v0.2.0]: https://github.com/japaric/panic-abort/compare/v0.1.1...v0.2.0 +[v0.1.1]: https://github.com/japaric/panic-abort/compare/v0.1.0...v0.1.1 diff --git a/bitbox02-bt/vendor/panic-abort/Cargo.toml b/bitbox02-bt/vendor/panic-abort/Cargo.toml new file mode 100644 index 0000000..86cccfb --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/Cargo.toml @@ -0,0 +1,22 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "panic-abort" +version = "0.3.2" +authors = ["Jorge Aparicio "] +description = "Set panicking behavior to abort" +documentation = "https://japaric.github.io/panic-abort/panic_abort" +keywords = ["panic-impl", "panic-handler", "panic", "abort"] +categories = ["no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/japaric/panic-abort" diff --git a/bitbox02-bt/vendor/panic-abort/LICENSE-APACHE b/bitbox02-bt/vendor/panic-abort/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/panic-abort/LICENSE-MIT b/bitbox02-bt/vendor/panic-abort/LICENSE-MIT new file mode 100644 index 0000000..432fbea --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Jorge Aparicio + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/panic-abort/README.md b/bitbox02-bt/vendor/panic-abort/README.md new file mode 100644 index 0000000..dae7c42 --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/README.md @@ -0,0 +1,19 @@ +# `panic-abort` + +> Set the panicking behavior to abort + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the +work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/bitbox02-bt/vendor/panic-abort/ci/after-success.sh b/bitbox02-bt/vendor/panic-abort/ci/after-success.sh new file mode 100644 index 0000000..4377267 --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/ci/after-success.sh @@ -0,0 +1,20 @@ +set -euxo pipefail + +main() { + cargo doc + + mkdir ghp-import + + curl -Ls https://github.com/davisp/ghp-import/archive/master.tar.gz | + tar --strip-components 1 -C ghp-import -xz + + ./ghp-import/ghp_import.py target/doc + + set +x + git push -fq https://$GH_TOKEN@github.com/$TRAVIS_REPO_SLUG.git gh-pages && echo OK +} + +# only publish on successful merges to master +if [ $TRAVIS_BRANCH = master ] && [ $TRAVIS_PULL_REQUEST = false ] && [ $TARGET = x86_64-unknown-linux-gnu ]; then + main +fi diff --git a/bitbox02-bt/vendor/panic-abort/ci/install.sh b/bitbox02-bt/vendor/panic-abort/ci/install.sh new file mode 100644 index 0000000..3c41921 --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/ci/install.sh @@ -0,0 +1,9 @@ +set -euxo pipefail + +main() { + if [ $TARGET != x86_64-unknown-linux-gnu ]; then + rustup target add $TARGET + fi +} + +main diff --git a/bitbox02-bt/vendor/panic-abort/ci/script.sh b/bitbox02-bt/vendor/panic-abort/ci/script.sh new file mode 100644 index 0000000..9e10e88 --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/ci/script.sh @@ -0,0 +1,7 @@ +set -euxo pipefail + +main() { + cargo check --target $TARGET +} + +main diff --git a/bitbox02-bt/vendor/panic-abort/src/lib.rs b/bitbox02-bt/vendor/panic-abort/src/lib.rs new file mode 100644 index 0000000..0077f61 --- /dev/null +++ b/bitbox02-bt/vendor/panic-abort/src/lib.rs @@ -0,0 +1,50 @@ +//! Set the panicking behavior to abort +//! +//! This crate contains an implementation of `panic_fmt` that simply calls [`intrinsics::abort`]. +//! +//! [`intrinsics::abort`]: https://doc.rust-lang.org/core/intrinsics/fn.abort.html +//! +//! # Behavior +//! +//! As of Rust 1.38.0, `intrinsics::abort` lowers to a trap instruction on *most* architectures; on +//! some architectures it simply lowers to call to the `abort` function (unmangled name). The exact +//! behavior of `intrinsics::abort` is architecture and system dependent. +//! +//! On bare-metal (no OS) systems the trap instruction usually causes a *hardware* exception to be +//! raised in a *synchronous* fashion -- hardware exceptions have nothing to do with C++ exceptions +//! and are closer in semantics to POSIX signals (see `man 7 signals` on UNIX-y systems). +//! +//! On hosted applications (applications running under an OS), the trap instruction *usually* +//! terminates the whole process with an exit code that corresponds to SIGILL *unless* a signal +//! handler that handles this particular signal was registered (again, see `man 7 signals` on UNIX-y +//! systems). +//! +//! *HEADS UP* Because `intrinsics::abort` is an unstable API its semantics could change in any new +//! Rust release (minor or patch release). +//! +//! # Usage +//! +//! ``` ignore +//! #![no_std] +//! +//! extern crate panic_abort; +//! +//! fn main() { +//! panic!("argument is ignored"); +//! } +//! ``` + +#![allow(stable_features)] +#![deny(missing_docs)] +#![deny(warnings)] +#![feature(core_intrinsics)] +#![feature(panic_handler)] +#![no_std] + +use core::intrinsics; +use core::panic::PanicInfo; + +#[panic_handler] +fn panic(_info: &PanicInfo) -> ! { + unsafe { intrinsics::abort() } +} diff --git a/bitbox02-bt/vendor/paste/.cargo-checksum.json b/bitbox02-bt/vendor/paste/.cargo-checksum.json new file mode 100644 index 0000000..a0cb66f --- /dev/null +++ b/bitbox02-bt/vendor/paste/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b639e399e32159609ed573ffdb1a4edf06fba8aee208d9259e9dba031834aaaa","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"cd8f304fa9cca9566dff0bb3492beae55f47f3972ddfb8f1fa38c3da1068b4a8","build.rs":"dba46ae4291317fb644ba2143f44eaf54a8ab946ba1367a33d055d694715f68a","src/attr.rs":"e8301f019e107ef9f5d8a3bbed355ffa9c0fd73396646d7fedbba333d341b7bc","src/error.rs":"be08d9d48b4cb9984b5141b12f21c31bd7293942c18b3ce25754723930cf54f5","src/lib.rs":"12a0578bb1d011ae759a94aa4850e970fc1c74102d1ede62b9f405675d7e182e","src/segment.rs":"462be04eea3ad48028d0841e8000c13205eb049522b8003bcc2926f21e93cb78","tests/compiletest.rs":"022a8e400ef813d7ea1875b944549cee5125f6a995dc33e93b48cba3e1b57bd1","tests/test_attr.rs":"39a55dcce5a127b2f85e9127a810b4aa3318e408cac93ff678301a2120aac5b5","tests/test_doc.rs":"7afb22427cb1c54fcf75a581fec5503404d8e93274027040b4d901f8caa597bb","tests/test_expr.rs":"d25ff118a78bd8e7d38ff532f0b9abb046bd0fbe61db8080b973bff67743af4e","tests/test_item.rs":"ee373a6658b384d1b2a0053653ac18e19d4053bbd04c8024980340894c04dcdc","tests/ui/case-warning.rs":"6b7cb803527911fe698e7fbe080160bc5d07c0da36fac0ec29d599753ce8bd10","tests/ui/case-warning.stderr":"7b7d470edc2a11b0864534099b360e0c42d423e068f49cea7858e0b340c2ef3d","tests/ui/env-empty.rs":"093fb0844475f4710580b5e4cad162918896d4fb48d1516bae04eb39dddd265a","tests/ui/env-empty.stderr":"3462f06f6f21130a81efff3be3bc838b395f6107bfbf753e479ec5a60e09b15d","tests/ui/env-non-string.rs":"516460860e7790b412b0fcd203289720a155dfba2498616967e4d7e6e6ab4990","tests/ui/env-non-string.stderr":"fea08d588a238e0f4c06de5c5ae97ac195bb2bcfc070040fb8087bdf4d1f4eee","tests/ui/env-suffix.rs":"0f1756608efc7a6c5810b8b21528092546ac95371e048c6060064e747c1b0a27","tests/ui/env-suffix.stderr":"287fecb2a91abc61501e0bd71d7f111670a526960ab18a554f4d16ed83d940b5","tests/ui/env-unexpected.rs":"18f06317e72ea16dae6ebe7c20bf5ef26b46e01a5c54fd31dc2a351ba68e8ca5","tests/ui/env-unexpected.stderr":"14d9a40160daf0191efc2b53be5fdde5b066674053e76af170e58af08f4022aa","tests/ui/invalid-ident.rs":"c3f375cac04d56684e427834076128b6e77eeeb9e99067a06307e27693b0ff51","tests/ui/invalid-ident.stderr":"b56d1c26253dec71ba1f97ffa01602b3a4429fc85a6b5c87f5290aab0568ea30","tests/ui/missing-paren-on-env.rs":"05cafef972e8c99f82834e164e7713f6056ac1a24b1f31d0320ac4fe361a53bd","tests/ui/missing-paren-on-env.stderr":"baf7b420d201f033e2113eaebd85376047397d991c35c441f07e5c6f1ec2b685","tests/ui/no-env-var.rs":"330bb71f2f3d98d23176acc5aeb1c0b66443af14c0857bb5bc92bfd130eb4a62","tests/ui/no-env-var.stderr":"68af072d3ccb2537bca9a5cd6d5796bb5ab5408f59564c8e8c66b1590ac7c5a5","tests/ui/no-ident-after-colon.rs":"a5af9548ab8d7f5b6130e1410c90f2cc589c595eb99f6939e6deb3f54e7262a2","tests/ui/no-ident-after-colon.stderr":"efac036a78f077c9c10a1ed048d69531293dcb97784ed784af0b24788ecbab54","tests/ui/unexpected-group.rs":"6b2e398a9ad3e077ea49c68b7c134ec3268e398723f4d9d5ef7b4d7b8513ac44","tests/ui/unexpected-group.stderr":"1260b5a4c295639958e3dd0da475c385184f0a916f5fdc4f1f2bfe232688f43c","tests/ui/unexpected-modifier.rs":"8b7e4c93f06fe7e7be469375e8bbaf19fec5fdffe688a0c29d2de2944a420337","tests/ui/unexpected-modifier.stderr":"581212b89358ac6bd38632bfd4322c25c171046875711fd639cfb498e01629c8","tests/ui/unexpected-punct.rs":"430e98bc03abdcc46f72cea01264c278a9c25f3d1d63064a6d78f4ae71b6a2d9","tests/ui/unexpected-punct.stderr":"24ab2e32d2da8dad93ef04dc05a2ecf6fdeb11bdebeae9454ad4759cc2b16551","tests/ui/unsupported-literal.rs":"1b2d3634fba5dc35d5ac9012d488aa93e329d1fa4489df1eadee65613a010e59","tests/ui/unsupported-literal.stderr":"6b137ccd6bc2a341aeb1e0d5321a896aa6c8db9a4e2571f4e41bd744511760bf","tests/ui/unsupported-modifier.rs":"03bb0239880070e8b470a6072c06094e1483ea91256e7cb4b9f2e8761696fa5a","tests/ui/unsupported-modifier.stderr":"890d7f484fdbd46da72923db4d7aba0ac3eaece253bb7195b7a36ae9a918027e"},"package":"57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/paste/Cargo.toml b/bitbox02-bt/vendor/paste/Cargo.toml new file mode 100644 index 0000000..c587287 --- /dev/null +++ b/bitbox02-bt/vendor/paste/Cargo.toml @@ -0,0 +1,72 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.31" +name = "paste" +version = "1.0.15" +authors = ["David Tolnay "] +build = "build.rs" +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Macros for all your token pasting needs" +documentation = "https://docs.rs/paste" +readme = "README.md" +keywords = ["macros"] +categories = [ + "development-tools", + "no-std", + "no-std::no-alloc", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/paste" + +[package.metadata.docs.rs] +rustdoc-args = ["--generate-link-to-definition"] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +name = "paste" +path = "src/lib.rs" +proc-macro = true + +[[test]] +name = "test_item" +path = "tests/test_item.rs" + +[[test]] +name = "test_attr" +path = "tests/test_attr.rs" + +[[test]] +name = "compiletest" +path = "tests/compiletest.rs" + +[[test]] +name = "test_doc" +path = "tests/test_doc.rs" + +[[test]] +name = "test_expr" +path = "tests/test_expr.rs" + +[dev-dependencies.paste-test-suite] +version = "0" + +[dev-dependencies.rustversion] +version = "1.0" + +[dev-dependencies.trybuild] +version = "1.0.49" +features = ["diff"] diff --git a/bitbox02-bt/vendor/paste/LICENSE-APACHE b/bitbox02-bt/vendor/paste/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/paste/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/paste/LICENSE-MIT b/bitbox02-bt/vendor/paste/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/paste/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/paste/README.md b/bitbox02-bt/vendor/paste/README.md new file mode 100644 index 0000000..c32d424 --- /dev/null +++ b/bitbox02-bt/vendor/paste/README.md @@ -0,0 +1,157 @@ +Macros for all your token pasting needs +======================================= + +[github](https://github.com/dtolnay/paste) +[crates.io](https://crates.io/crates/paste) +[docs.rs](https://docs.rs/paste) +[build status](https://github.com/dtolnay/paste/actions?query=branch%3Amaster) + +The nightly-only [`concat_idents!`] macro in the Rust standard library is +notoriously underpowered in that its concatenated identifiers can only refer to +existing items, they can never be used to define something new. + +[`concat_idents!`]: https://doc.rust-lang.org/std/macro.concat_idents.html + +This crate provides a flexible way to paste together identifiers in a macro, +including using pasted identifiers to define new items. + +```toml +[dependencies] +paste = "1.0" +``` + +This approach works with any Rust compiler 1.31+. + +
+ +## Pasting identifiers + +Within the `paste!` macro, identifiers inside `[<`...`>]` are pasted together to +form a single identifier. + +```rust +use paste::paste; + +paste! { + // Defines a const called `QRST`. + const []: &str = "success!"; +} + +fn main() { + assert_eq!( + paste! { [].len() }, + 8, + ); +} +``` + +
+ +## More elaborate example + +The next example shows a macro that generates accessor methods for some struct +fields. It demonstrates how you might find it useful to bundle a paste +invocation inside of a macro\_rules macro. + +```rust +use paste::paste; + +macro_rules! make_a_struct_and_getters { + ($name:ident { $($field:ident),* }) => { + // Define a struct. This expands to: + // + // pub struct S { + // a: String, + // b: String, + // c: String, + // } + pub struct $name { + $( + $field: String, + )* + } + + // Build an impl block with getters. This expands to: + // + // impl S { + // pub fn get_a(&self) -> &str { &self.a } + // pub fn get_b(&self) -> &str { &self.b } + // pub fn get_c(&self) -> &str { &self.c } + // } + paste! { + impl $name { + $( + pub fn [](&self) -> &str { + &self.$field + } + )* + } + } + } +} + +make_a_struct_and_getters!(S { a, b, c }); + +fn call_some_getters(s: &S) -> bool { + s.get_a() == s.get_b() && s.get_c().is_empty() +} +``` + +
+ +## Case conversion + +Use `$var:lower` or `$var:upper` in the segment list to convert an interpolated +segment to lower- or uppercase as part of the paste. For example, `[]` would paste to `ld_bc_expr` if invoked with $reg=`Bc`. + +Use `$var:snake` to convert CamelCase input to snake\_case. +Use `$var:camel` to convert snake\_case to CamelCase. +These compose, so for example `$var:snake:upper` would give you SCREAMING\_CASE. + +The precise Unicode conversions are as defined by [`str::to_lowercase`] and +[`str::to_uppercase`]. + +[`str::to_lowercase`]: https://doc.rust-lang.org/std/primitive.str.html#method.to_lowercase +[`str::to_uppercase`]: https://doc.rust-lang.org/std/primitive.str.html#method.to_uppercase + +
+ +## Pasting documentation strings + +Within the `paste!` macro, arguments to a #\[doc ...\] attribute are implicitly +concatenated together to form a coherent documentation string. + +```rust +use paste::paste; + +macro_rules! method_new { + ($ret:ident) => { + paste! { + #[doc = "Create a new `" $ret "` object."] + pub fn new() -> $ret { todo!() } + } + }; +} + +pub struct Paste {} + +method_new!(Paste); // expands to #[doc = "Create a new `Paste` object"] +``` + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/paste/build.rs b/bitbox02-bt/vendor/paste/build.rs new file mode 100644 index 0000000..c9e5fe1 --- /dev/null +++ b/bitbox02-bt/vendor/paste/build.rs @@ -0,0 +1,38 @@ +use std::env; +use std::process::Command; +use std::str; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + + let version = match rustc_version() { + Some(version) => version, + None => return, + }; + + if version.minor >= 80 { + println!("cargo:rustc-check-cfg=cfg(no_literal_fromstr)"); + println!("cargo:rustc-check-cfg=cfg(feature, values(\"protocol_feature_paste\"))"); + } + + if version.minor < 54 { + // https://github.com/rust-lang/rust/pull/84717 + println!("cargo:rustc-cfg=no_literal_fromstr"); + } +} + +struct RustcVersion { + minor: u32, +} + +fn rustc_version() -> Option { + let rustc = env::var_os("RUSTC")?; + let output = Command::new(rustc).arg("--version").output().ok()?; + let version = str::from_utf8(&output.stdout).ok()?; + let mut pieces = version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + let minor = pieces.next()?.parse().ok()?; + Some(RustcVersion { minor }) +} diff --git a/bitbox02-bt/vendor/paste/src/attr.rs b/bitbox02-bt/vendor/paste/src/attr.rs new file mode 100644 index 0000000..d66b843 --- /dev/null +++ b/bitbox02-bt/vendor/paste/src/attr.rs @@ -0,0 +1,164 @@ +use crate::error::Result; +use crate::segment::{self, Segment}; +use proc_macro::{Delimiter, Group, Spacing, Span, TokenStream, TokenTree}; +use std::iter; +use std::mem; +use std::str::FromStr; + +pub fn expand_attr( + attr: TokenStream, + span: Span, + contains_paste: &mut bool, +) -> Result { + let mut tokens = attr.clone().into_iter(); + let mut leading_colons = 0; // $(::)? + let mut leading_path = 0; // $($ident)::+ + + let mut token; + let group = loop { + token = tokens.next(); + match token { + // colon after `$(:)?` + Some(TokenTree::Punct(ref punct)) + if punct.as_char() == ':' && leading_colons < 2 && leading_path == 0 => + { + leading_colons += 1; + } + // ident after `$(::)? $($ident ::)*` + Some(TokenTree::Ident(_)) if leading_colons != 1 && leading_path % 3 == 0 => { + leading_path += 1; + } + // colon after `$(::)? $($ident ::)* $ident $(:)?` + Some(TokenTree::Punct(ref punct)) if punct.as_char() == ':' && leading_path % 3 > 0 => { + leading_path += 1; + } + // eq+value after `$(::)? $($ident)::+` + Some(TokenTree::Punct(ref punct)) + if punct.as_char() == '=' && leading_path % 3 == 1 => + { + let mut count = 0; + if tokens.inspect(|_| count += 1).all(|tt| is_stringlike(&tt)) && count > 1 { + *contains_paste = true; + let leading = leading_colons + leading_path; + return do_paste_name_value_attr(attr, span, leading); + } + return Ok(attr); + } + // parens after `$(::)? $($ident)::+` + Some(TokenTree::Group(ref group)) + if group.delimiter() == Delimiter::Parenthesis && leading_path % 3 == 1 => + { + break group; + } + // bail out + _ => return Ok(attr), + } + }; + + // There can't be anything else after the first group in a valid attribute. + if tokens.next().is_some() { + return Ok(attr); + } + + let mut group_contains_paste = false; + let mut expanded = TokenStream::new(); + let mut nested_attr = TokenStream::new(); + for tt in group.stream() { + match &tt { + TokenTree::Punct(punct) if punct.as_char() == ',' => { + expanded.extend(expand_attr( + nested_attr, + group.span(), + &mut group_contains_paste, + )?); + expanded.extend(iter::once(tt)); + nested_attr = TokenStream::new(); + } + _ => nested_attr.extend(iter::once(tt)), + } + } + + if !nested_attr.is_empty() { + expanded.extend(expand_attr( + nested_attr, + group.span(), + &mut group_contains_paste, + )?); + } + + if group_contains_paste { + *contains_paste = true; + let mut group = Group::new(Delimiter::Parenthesis, expanded); + group.set_span(span); + Ok(attr + .into_iter() + // Just keep the initial ident in `#[ident(...)]`. + .take(leading_colons + leading_path) + .chain(iter::once(TokenTree::Group(group))) + .collect()) + } else { + Ok(attr) + } +} + +fn do_paste_name_value_attr(attr: TokenStream, span: Span, leading: usize) -> Result { + let mut expanded = TokenStream::new(); + let mut tokens = attr.into_iter().peekable(); + expanded.extend(tokens.by_ref().take(leading + 1)); // `doc =` + + let mut segments = segment::parse(&mut tokens)?; + + for segment in &mut segments { + if let Segment::String(string) = segment { + if let Some(open_quote) = string.value.find('"') { + if open_quote == 0 { + string.value.truncate(string.value.len() - 1); + string.value.remove(0); + } else { + let begin = open_quote + 1; + let end = string.value.rfind('"').unwrap(); + let raw_string = mem::replace(&mut string.value, String::new()); + for ch in raw_string[begin..end].chars() { + string.value.extend(ch.escape_default()); + } + } + } + } + } + + let mut lit = segment::paste(&segments)?; + lit.insert(0, '"'); + lit.push('"'); + + let mut lit = TokenStream::from_str(&lit) + .unwrap() + .into_iter() + .next() + .unwrap(); + lit.set_span(span); + expanded.extend(iter::once(lit)); + Ok(expanded) +} + +fn is_stringlike(token: &TokenTree) -> bool { + match token { + TokenTree::Ident(_) => true, + TokenTree::Literal(literal) => { + let repr = literal.to_string(); + !repr.starts_with('b') && !repr.starts_with('\'') + } + TokenTree::Group(group) => { + if group.delimiter() != Delimiter::None { + return false; + } + let mut inner = group.stream().into_iter(); + match inner.next() { + Some(first) => inner.next().is_none() && is_stringlike(&first), + None => false, + } + } + TokenTree::Punct(punct) => { + punct.as_char() == '\'' || punct.as_char() == ':' && punct.spacing() == Spacing::Alone + } + } +} diff --git a/bitbox02-bt/vendor/paste/src/error.rs b/bitbox02-bt/vendor/paste/src/error.rs new file mode 100644 index 0000000..7c5badb --- /dev/null +++ b/bitbox02-bt/vendor/paste/src/error.rs @@ -0,0 +1,47 @@ +use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::iter::FromIterator; + +pub type Result = std::result::Result; + +pub struct Error { + begin: Span, + end: Span, + msg: String, +} + +impl Error { + pub fn new(span: Span, msg: &str) -> Self { + Self::new2(span, span, msg) + } + + pub fn new2(begin: Span, end: Span, msg: &str) -> Self { + Error { + begin, + end, + msg: msg.to_owned(), + } + } + + pub fn to_compile_error(&self) -> TokenStream { + // compile_error! { $msg } + TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("compile_error", self.begin)), + TokenTree::Punct({ + let mut punct = Punct::new('!', Spacing::Alone); + punct.set_span(self.begin); + punct + }), + TokenTree::Group({ + let mut group = Group::new(Delimiter::Brace, { + TokenStream::from_iter(vec![TokenTree::Literal({ + let mut string = Literal::string(&self.msg); + string.set_span(self.end); + string + })]) + }); + group.set_span(self.end); + group + }), + ]) + } +} diff --git a/bitbox02-bt/vendor/paste/src/lib.rs b/bitbox02-bt/vendor/paste/src/lib.rs new file mode 100644 index 0000000..9bb86bf --- /dev/null +++ b/bitbox02-bt/vendor/paste/src/lib.rs @@ -0,0 +1,454 @@ +//! [![github]](https://github.com/dtolnay/paste) [![crates-io]](https://crates.io/crates/paste) [![docs-rs]](https://docs.rs/paste) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs +//! +//!
+//! +//! The nightly-only [`concat_idents!`] macro in the Rust standard library is +//! notoriously underpowered in that its concatenated identifiers can only refer to +//! existing items, they can never be used to define something new. +//! +//! [`concat_idents!`]: https://doc.rust-lang.org/std/macro.concat_idents.html +//! +//! This crate provides a flexible way to paste together identifiers in a macro, +//! including using pasted identifiers to define new items. +//! +//! This approach works with any Rust compiler 1.31+. +//! +//!
+//! +//! # Pasting identifiers +//! +//! Within the `paste!` macro, identifiers inside `[<`...`>]` are pasted +//! together to form a single identifier. +//! +//! ``` +//! use paste::paste; +//! +//! paste! { +//! // Defines a const called `QRST`. +//! const []: &str = "success!"; +//! } +//! +//! fn main() { +//! assert_eq!( +//! paste! { [].len() }, +//! 8, +//! ); +//! } +//! ``` +//! +//!

+//! +//! # More elaborate example +//! +//! The next example shows a macro that generates accessor methods for some +//! struct fields. It demonstrates how you might find it useful to bundle a +//! paste invocation inside of a macro\_rules macro. +//! +//! ``` +//! use paste::paste; +//! +//! macro_rules! make_a_struct_and_getters { +//! ($name:ident { $($field:ident),* }) => { +//! // Define a struct. This expands to: +//! // +//! // pub struct S { +//! // a: String, +//! // b: String, +//! // c: String, +//! // } +//! pub struct $name { +//! $( +//! $field: String, +//! )* +//! } +//! +//! // Build an impl block with getters. This expands to: +//! // +//! // impl S { +//! // pub fn get_a(&self) -> &str { &self.a } +//! // pub fn get_b(&self) -> &str { &self.b } +//! // pub fn get_c(&self) -> &str { &self.c } +//! // } +//! paste! { +//! impl $name { +//! $( +//! pub fn [](&self) -> &str { +//! &self.$field +//! } +//! )* +//! } +//! } +//! } +//! } +//! +//! make_a_struct_and_getters!(S { a, b, c }); +//! +//! fn call_some_getters(s: &S) -> bool { +//! s.get_a() == s.get_b() && s.get_c().is_empty() +//! } +//! # +//! # fn main() {} +//! ``` +//! +//!

+//! +//! # Case conversion +//! +//! Use `$var:lower` or `$var:upper` in the segment list to convert an +//! interpolated segment to lower- or uppercase as part of the paste. For +//! example, `[]` would paste to `ld_bc_expr` if invoked +//! with $reg=`Bc`. +//! +//! Use `$var:snake` to convert CamelCase input to snake\_case. +//! Use `$var:camel` to convert snake\_case to CamelCase. +//! These compose, so for example `$var:snake:upper` would give you SCREAMING\_CASE. +//! +//! The precise Unicode conversions are as defined by [`str::to_lowercase`] and +//! [`str::to_uppercase`]. +//! +//! [`str::to_lowercase`]: https://doc.rust-lang.org/std/primitive.str.html#method.to_lowercase +//! [`str::to_uppercase`]: https://doc.rust-lang.org/std/primitive.str.html#method.to_uppercase +//! +//!
+//! +//! # Pasting documentation strings +//! +//! Within the `paste!` macro, arguments to a #\[doc ...\] attribute are +//! implicitly concatenated together to form a coherent documentation string. +//! +//! ``` +//! use paste::paste; +//! +//! macro_rules! method_new { +//! ($ret:ident) => { +//! paste! { +//! #[doc = "Create a new `" $ret "` object."] +//! pub fn new() -> $ret { todo!() } +//! } +//! }; +//! } +//! +//! pub struct Paste {} +//! +//! method_new!(Paste); // expands to #[doc = "Create a new `Paste` object"] +//! ``` + +#![doc(html_root_url = "https://docs.rs/paste/1.0.15")] +#![allow( + clippy::derive_partial_eq_without_eq, + clippy::doc_markdown, + clippy::match_same_arms, + clippy::module_name_repetitions, + clippy::needless_doctest_main, + clippy::too_many_lines +)] + +extern crate proc_macro; + +mod attr; +mod error; +mod segment; + +use crate::attr::expand_attr; +use crate::error::{Error, Result}; +use crate::segment::Segment; +use proc_macro::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::char; +use std::iter; +use std::panic; + +#[proc_macro] +pub fn paste(input: TokenStream) -> TokenStream { + let mut contains_paste = false; + let flatten_single_interpolation = true; + match expand( + input.clone(), + &mut contains_paste, + flatten_single_interpolation, + ) { + Ok(expanded) => { + if contains_paste { + expanded + } else { + input + } + } + Err(err) => err.to_compile_error(), + } +} + +#[doc(hidden)] +#[proc_macro] +pub fn item(input: TokenStream) -> TokenStream { + paste(input) +} + +#[doc(hidden)] +#[proc_macro] +pub fn expr(input: TokenStream) -> TokenStream { + paste(input) +} + +fn expand( + input: TokenStream, + contains_paste: &mut bool, + flatten_single_interpolation: bool, +) -> Result { + let mut expanded = TokenStream::new(); + let mut lookbehind = Lookbehind::Other; + let mut prev_none_group = None::; + let mut tokens = input.into_iter().peekable(); + loop { + let token = tokens.next(); + if let Some(group) = prev_none_group.take() { + if match (&token, tokens.peek()) { + (Some(TokenTree::Punct(fst)), Some(TokenTree::Punct(snd))) => { + fst.as_char() == ':' && snd.as_char() == ':' && fst.spacing() == Spacing::Joint + } + _ => false, + } { + expanded.extend(group.stream()); + *contains_paste = true; + } else { + expanded.extend(iter::once(TokenTree::Group(group))); + } + } + match token { + Some(TokenTree::Group(group)) => { + let delimiter = group.delimiter(); + let content = group.stream(); + let span = group.span(); + if delimiter == Delimiter::Bracket && is_paste_operation(&content) { + let segments = parse_bracket_as_segments(content, span)?; + let pasted = segment::paste(&segments)?; + let tokens = pasted_to_tokens(pasted, span)?; + expanded.extend(tokens); + *contains_paste = true; + } else if flatten_single_interpolation + && delimiter == Delimiter::None + && is_single_interpolation_group(&content) + { + expanded.extend(content); + *contains_paste = true; + } else { + let mut group_contains_paste = false; + let is_attribute = delimiter == Delimiter::Bracket + && (lookbehind == Lookbehind::Pound || lookbehind == Lookbehind::PoundBang); + let mut nested = expand( + content, + &mut group_contains_paste, + flatten_single_interpolation && !is_attribute, + )?; + if is_attribute { + nested = expand_attr(nested, span, &mut group_contains_paste)?; + } + let group = if group_contains_paste { + let mut group = Group::new(delimiter, nested); + group.set_span(span); + *contains_paste = true; + group + } else { + group.clone() + }; + if delimiter != Delimiter::None { + expanded.extend(iter::once(TokenTree::Group(group))); + } else if lookbehind == Lookbehind::DoubleColon { + expanded.extend(group.stream()); + *contains_paste = true; + } else { + prev_none_group = Some(group); + } + } + lookbehind = Lookbehind::Other; + } + Some(TokenTree::Punct(punct)) => { + lookbehind = match punct.as_char() { + ':' if lookbehind == Lookbehind::JointColon => Lookbehind::DoubleColon, + ':' if punct.spacing() == Spacing::Joint => Lookbehind::JointColon, + '#' => Lookbehind::Pound, + '!' if lookbehind == Lookbehind::Pound => Lookbehind::PoundBang, + _ => Lookbehind::Other, + }; + expanded.extend(iter::once(TokenTree::Punct(punct))); + } + Some(other) => { + lookbehind = Lookbehind::Other; + expanded.extend(iter::once(other)); + } + None => return Ok(expanded), + } + } +} + +#[derive(PartialEq)] +enum Lookbehind { + JointColon, + DoubleColon, + Pound, + PoundBang, + Other, +} + +// https://github.com/dtolnay/paste/issues/26 +fn is_single_interpolation_group(input: &TokenStream) -> bool { + #[derive(PartialEq)] + enum State { + Init, + Ident, + Literal, + Apostrophe, + Lifetime, + Colon1, + Colon2, + } + + let mut state = State::Init; + for tt in input.clone() { + state = match (state, &tt) { + (State::Init, TokenTree::Ident(_)) => State::Ident, + (State::Init, TokenTree::Literal(_)) => State::Literal, + (State::Init, TokenTree::Punct(punct)) if punct.as_char() == '\'' => State::Apostrophe, + (State::Apostrophe, TokenTree::Ident(_)) => State::Lifetime, + (State::Ident, TokenTree::Punct(punct)) + if punct.as_char() == ':' && punct.spacing() == Spacing::Joint => + { + State::Colon1 + } + (State::Colon1, TokenTree::Punct(punct)) + if punct.as_char() == ':' && punct.spacing() == Spacing::Alone => + { + State::Colon2 + } + (State::Colon2, TokenTree::Ident(_)) => State::Ident, + _ => return false, + }; + } + + state == State::Ident || state == State::Literal || state == State::Lifetime +} + +fn is_paste_operation(input: &TokenStream) -> bool { + let mut tokens = input.clone().into_iter(); + + match &tokens.next() { + Some(TokenTree::Punct(punct)) if punct.as_char() == '<' => {} + _ => return false, + } + + let mut has_token = false; + loop { + match &tokens.next() { + Some(TokenTree::Punct(punct)) if punct.as_char() == '>' => { + return has_token && tokens.next().is_none(); + } + Some(_) => has_token = true, + None => return false, + } + } +} + +fn parse_bracket_as_segments(input: TokenStream, scope: Span) -> Result> { + let mut tokens = input.into_iter().peekable(); + + match &tokens.next() { + Some(TokenTree::Punct(punct)) if punct.as_char() == '<' => {} + Some(wrong) => return Err(Error::new(wrong.span(), "expected `<`")), + None => return Err(Error::new(scope, "expected `[< ... >]`")), + } + + let mut segments = segment::parse(&mut tokens)?; + + match &tokens.next() { + Some(TokenTree::Punct(punct)) if punct.as_char() == '>' => {} + Some(wrong) => return Err(Error::new(wrong.span(), "expected `>`")), + None => return Err(Error::new(scope, "expected `[< ... >]`")), + } + + if let Some(unexpected) = tokens.next() { + return Err(Error::new( + unexpected.span(), + "unexpected input, expected `[< ... >]`", + )); + } + + for segment in &mut segments { + if let Segment::String(string) = segment { + if string.value.starts_with("'\\u{") { + let hex = &string.value[4..string.value.len() - 2]; + if let Ok(unsigned) = u32::from_str_radix(hex, 16) { + if let Some(ch) = char::from_u32(unsigned) { + string.value.clear(); + string.value.push(ch); + continue; + } + } + } + if string.value.contains(&['#', '\\', '.', '+'][..]) + || string.value.starts_with("b'") + || string.value.starts_with("b\"") + || string.value.starts_with("br\"") + { + return Err(Error::new(string.span, "unsupported literal")); + } + let mut range = 0..string.value.len(); + if string.value.starts_with("r\"") { + range.start += 2; + range.end -= 1; + } else if string.value.starts_with(&['"', '\''][..]) { + range.start += 1; + range.end -= 1; + } + string.value = string.value[range].replace('-', "_"); + } + } + + Ok(segments) +} + +fn pasted_to_tokens(mut pasted: String, span: Span) -> Result { + let mut tokens = TokenStream::new(); + + #[cfg(not(no_literal_fromstr))] + { + use proc_macro::{LexError, Literal}; + use std::str::FromStr; + + if pasted.starts_with(|ch: char| ch.is_ascii_digit()) { + let literal = match panic::catch_unwind(|| Literal::from_str(&pasted)) { + Ok(Ok(literal)) => TokenTree::Literal(literal), + Ok(Err(LexError { .. })) | Err(_) => { + return Err(Error::new( + span, + &format!("`{:?}` is not a valid literal", pasted), + )); + } + }; + tokens.extend(iter::once(literal)); + return Ok(tokens); + } + } + + if pasted.starts_with('\'') { + let mut apostrophe = TokenTree::Punct(Punct::new('\'', Spacing::Joint)); + apostrophe.set_span(span); + tokens.extend(iter::once(apostrophe)); + pasted.remove(0); + } + + let ident = match panic::catch_unwind(|| Ident::new(&pasted, span)) { + Ok(ident) => TokenTree::Ident(ident), + Err(_) => { + return Err(Error::new( + span, + &format!("`{:?}` is not a valid identifier", pasted), + )); + } + }; + + tokens.extend(iter::once(ident)); + Ok(tokens) +} diff --git a/bitbox02-bt/vendor/paste/src/segment.rs b/bitbox02-bt/vendor/paste/src/segment.rs new file mode 100644 index 0000000..592a047 --- /dev/null +++ b/bitbox02-bt/vendor/paste/src/segment.rs @@ -0,0 +1,233 @@ +use crate::error::{Error, Result}; +use proc_macro::{token_stream, Delimiter, Ident, Span, TokenTree}; +use std::iter::Peekable; + +pub(crate) enum Segment { + String(LitStr), + Apostrophe(Span), + Env(LitStr), + Modifier(Colon, Ident), +} + +pub(crate) struct LitStr { + pub value: String, + pub span: Span, +} + +pub(crate) struct Colon { + pub span: Span, +} + +pub(crate) fn parse(tokens: &mut Peekable) -> Result> { + let mut segments = Vec::new(); + while match tokens.peek() { + None => false, + Some(TokenTree::Punct(punct)) => punct.as_char() != '>', + Some(_) => true, + } { + match tokens.next().unwrap() { + TokenTree::Ident(ident) => { + let mut fragment = ident.to_string(); + if fragment.starts_with("r#") { + fragment = fragment.split_off(2); + } + if fragment == "env" + && match tokens.peek() { + Some(TokenTree::Punct(punct)) => punct.as_char() == '!', + _ => false, + } + { + let bang = tokens.next().unwrap(); // `!` + let expect_group = tokens.next(); + let parenthesized = match &expect_group { + Some(TokenTree::Group(group)) + if group.delimiter() == Delimiter::Parenthesis => + { + group + } + Some(wrong) => return Err(Error::new(wrong.span(), "expected `(`")), + None => { + return Err(Error::new2( + ident.span(), + bang.span(), + "expected `(` after `env!`", + )); + } + }; + let mut inner = parenthesized.stream().into_iter(); + let lit = match inner.next() { + Some(TokenTree::Literal(lit)) => lit, + Some(wrong) => { + return Err(Error::new(wrong.span(), "expected string literal")) + } + None => { + return Err(Error::new2( + ident.span(), + parenthesized.span(), + "expected string literal as argument to env! macro", + )) + } + }; + let lit_string = lit.to_string(); + if lit_string.starts_with('"') + && lit_string.ends_with('"') + && lit_string.len() >= 2 + { + // TODO: maybe handle escape sequences in the string if + // someone has a use case. + segments.push(Segment::Env(LitStr { + value: lit_string[1..lit_string.len() - 1].to_owned(), + span: lit.span(), + })); + } else { + return Err(Error::new(lit.span(), "expected string literal")); + } + if let Some(unexpected) = inner.next() { + return Err(Error::new( + unexpected.span(), + "unexpected token in env! macro", + )); + } + } else { + segments.push(Segment::String(LitStr { + value: fragment, + span: ident.span(), + })); + } + } + TokenTree::Literal(lit) => { + segments.push(Segment::String(LitStr { + value: lit.to_string(), + span: lit.span(), + })); + } + TokenTree::Punct(punct) => match punct.as_char() { + '_' => segments.push(Segment::String(LitStr { + value: "_".to_owned(), + span: punct.span(), + })), + '\'' => segments.push(Segment::Apostrophe(punct.span())), + ':' => { + let colon_span = punct.span(); + let colon = Colon { span: colon_span }; + let ident = match tokens.next() { + Some(TokenTree::Ident(ident)) => ident, + wrong => { + let span = wrong.as_ref().map_or(colon_span, TokenTree::span); + return Err(Error::new(span, "expected identifier after `:`")); + } + }; + segments.push(Segment::Modifier(colon, ident)); + } + _ => return Err(Error::new(punct.span(), "unexpected punct")), + }, + TokenTree::Group(group) => { + if group.delimiter() == Delimiter::None { + let mut inner = group.stream().into_iter().peekable(); + let nested = parse(&mut inner)?; + if let Some(unexpected) = inner.next() { + return Err(Error::new(unexpected.span(), "unexpected token")); + } + segments.extend(nested); + } else { + return Err(Error::new(group.span(), "unexpected token")); + } + } + } + } + Ok(segments) +} + +pub(crate) fn paste(segments: &[Segment]) -> Result { + let mut evaluated = Vec::new(); + let mut is_lifetime = false; + + for segment in segments { + match segment { + Segment::String(segment) => { + evaluated.push(segment.value.clone()); + } + Segment::Apostrophe(span) => { + if is_lifetime { + return Err(Error::new(*span, "unexpected lifetime")); + } + is_lifetime = true; + } + Segment::Env(var) => { + let resolved = match std::env::var(&var.value) { + Ok(resolved) => resolved, + Err(_) => { + return Err(Error::new( + var.span, + &format!("no such env var: {:?}", var.value), + )); + } + }; + let resolved = resolved.replace('-', "_"); + evaluated.push(resolved); + } + Segment::Modifier(colon, ident) => { + let last = match evaluated.pop() { + Some(last) => last, + None => { + return Err(Error::new2(colon.span, ident.span(), "unexpected modifier")) + } + }; + match ident.to_string().as_str() { + "lower" => { + evaluated.push(last.to_lowercase()); + } + "upper" => { + evaluated.push(last.to_uppercase()); + } + "snake" => { + let mut acc = String::new(); + let mut prev = '_'; + for ch in last.chars() { + if ch.is_uppercase() && prev != '_' { + acc.push('_'); + } + acc.push(ch); + prev = ch; + } + evaluated.push(acc.to_lowercase()); + } + "camel" => { + let mut acc = String::new(); + let mut prev = '_'; + for ch in last.chars() { + if ch != '_' { + if prev == '_' { + for chu in ch.to_uppercase() { + acc.push(chu); + } + } else if prev.is_uppercase() { + for chl in ch.to_lowercase() { + acc.push(chl); + } + } else { + acc.push(ch); + } + } + prev = ch; + } + evaluated.push(acc); + } + _ => { + return Err(Error::new2( + colon.span, + ident.span(), + "unsupported modifier", + )); + } + } + } + } + } + + let mut pasted = evaluated.into_iter().collect::(); + if is_lifetime { + pasted.insert(0, '\''); + } + Ok(pasted) +} diff --git a/bitbox02-bt/vendor/paste/tests/compiletest.rs b/bitbox02-bt/vendor/paste/tests/compiletest.rs new file mode 100644 index 0000000..7974a62 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/compiletest.rs @@ -0,0 +1,7 @@ +#[rustversion::attr(not(nightly), ignore)] +#[cfg_attr(miri, ignore)] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/ui/*.rs"); +} diff --git a/bitbox02-bt/vendor/paste/tests/test_attr.rs b/bitbox02-bt/vendor/paste/tests/test_attr.rs new file mode 100644 index 0000000..6c49808 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/test_attr.rs @@ -0,0 +1,62 @@ +#![allow(clippy::let_underscore_untyped)] + +use paste::paste; +use paste_test_suite::paste_test; + +#[test] +fn test_attr() { + paste! { + #[paste_test(k = "val" "ue")] + struct A; + + #[paste_test_suite::paste_test(k = "val" "ue")] + struct B; + + #[::paste_test_suite::paste_test(k = "val" "ue")] + struct C; + + #[paste_test(k = "va" [] e)] + struct D; + } + + let _ = A; + let _ = B; + let _ = C; + let _ = D; +} + +#[test] +fn test_paste_cfg() { + macro_rules! m { + ($ret:ident, $width:expr) => { + paste! { + #[cfg(any(feature = "protocol_feature_" $ret:snake, target_pointer_width = "" $width))] + fn new() -> $ret { todo!() } + } + }; + } + + struct Paste; + + #[cfg(target_pointer_width = "64")] + m!(Paste, 64); + #[cfg(target_pointer_width = "32")] + m!(Paste, 32); + + let _ = new; +} + +#[test] +fn test_path_in_attr() { + macro_rules! m { + (#[x = $x:ty]) => { + stringify!($x) + }; + } + + let ty = paste! { + m!(#[x = foo::Bar]) + }; + + assert_eq!("foo::Bar", ty); +} diff --git a/bitbox02-bt/vendor/paste/tests/test_doc.rs b/bitbox02-bt/vendor/paste/tests/test_doc.rs new file mode 100644 index 0000000..3dd66aa --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/test_doc.rs @@ -0,0 +1,79 @@ +#![allow(clippy::let_underscore_untyped)] + +use paste::paste; + +#[test] +fn test_paste_doc() { + macro_rules! m { + ($ret:ident) => { + paste! { + #[doc = "Create a new [`" $ret "`] object."] + fn new() -> $ret { todo!() } + } + }; + } + + struct Paste; + m!(Paste); + + let _ = new; +} + +macro_rules! get_doc { + (#[doc = $literal:tt]) => { + $literal + }; +} + +#[test] +fn test_escaping() { + let doc = paste! { + get_doc!(#[doc = "s\"" r#"r#""#]) + }; + + let expected = "s\"r#\""; + assert_eq!(doc, expected); +} + +#[test] +fn test_literals() { + let doc = paste! { + get_doc!(#[doc = "int=" 0x1 " bool=" true " float=" 0.01]) + }; + + let expected = "int=0x1 bool=true float=0.01"; + assert_eq!(doc, expected); +} + +#[test] +fn test_case() { + let doc = paste! { + get_doc!(#[doc = "HTTP " get:upper "!"]) + }; + + let expected = "HTTP GET!"; + assert_eq!(doc, expected); +} + +// https://github.com/dtolnay/paste/issues/63 +#[test] +fn test_stringify() { + macro_rules! create { + ($doc:expr) => { + paste! { + #[doc = $doc] + pub struct Struct; + } + }; + } + + macro_rules! forward { + ($name:ident) => { + create!(stringify!($name)); + }; + } + + forward!(documentation); + + let _ = Struct; +} diff --git a/bitbox02-bt/vendor/paste/tests/test_expr.rs b/bitbox02-bt/vendor/paste/tests/test_expr.rs new file mode 100644 index 0000000..a8e6bd8 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/test_expr.rs @@ -0,0 +1,285 @@ +#![allow(clippy::let_underscore_untyped)] + +use paste::paste; + +#[test] +fn test_shared_hygiene() { + paste! { + let [] = 1; + assert_eq!([], 1); + } +} + +#[test] +fn test_repeat() { + const ROCKET_A: &str = "/a"; + const ROCKET_B: &str = "/b"; + + macro_rules! routes { + ($($route:ident),*) => {{ + paste! { + vec![$( [] ),*] + } + }} + } + + let routes = routes!(A, B); + assert_eq!(routes, vec!["/a", "/b"]); +} + +#[test] +fn test_literal_to_identifier() { + const CONST0: &str = "const0"; + + let pasted = paste!([]); + assert_eq!(pasted, CONST0); + + let pasted = paste!([]); + assert_eq!(pasted, CONST0); + + let pasted = paste!([]); + assert_eq!(pasted, CONST0); + + let pasted = paste!([]); + assert_eq!(pasted, CONST0); + + let pasted = paste!([]); + assert_eq!(pasted, CONST0); +} + +#[test] +fn test_literal_suffix() { + macro_rules! literal { + ($bit:tt) => { + paste!([<1_u $bit>]) + }; + } + + assert_eq!(literal!(32), 1); +} + +#[test] +fn test_underscore() { + paste! { + const A_B: usize = 0; + assert_eq!([], 0); + } +} + +#[test] +fn test_lifetime() { + paste! { + #[allow(dead_code)] + struct S<[<'d e>]> { + q: &[<'d e>] str, + } + } +} + +#[test] +fn test_keyword() { + paste! { + struct []; + + let _ = Fmove; + } +} + +#[test] +fn test_literal_str() { + paste! { + #[allow(non_camel_case_types)] + struct []; + + let _ = FooBar_Baz; + } +} + +#[test] +fn test_env_literal() { + paste! { + struct []; + + let _ = Libenvbar; + } +} + +#[test] +fn test_env_present() { + paste! { + struct []; + + let _ = Libpaste; + } +} + +#[test] +fn test_raw_identifier() { + paste! { + struct []; + + let _ = Fmove; + } +} + +#[test] +fn test_false_start() { + trait Trait { + fn f() -> usize; + } + + struct S; + + impl Trait for S { + fn f() -> usize { + 0 + } + } + + paste! { + let x = [::f()]; + assert_eq!(x[0], 0); + } +} + +#[test] +fn test_local_variable() { + let yy = 0; + + paste! { + assert_eq!([], 0); + } +} + +#[test] +fn test_empty() { + paste! { + assert_eq!(stringify!([]), "yy"); + assert_eq!(stringify!([<>]).replace(' ', ""), "[<>]"); + } +} + +#[test] +fn test_env_to_lower() { + paste! { + struct []; + + let _ = Libpaste; + } +} + +#[test] +fn test_env_to_upper() { + paste! { + const []: &str = "libpaste"; + + let _ = LIBPASTE; + } +} + +#[test] +fn test_env_to_snake() { + paste! { + const []: &str = "libpaste"; + + let _ = LIBPASTE; + } +} + +#[test] +fn test_env_to_camel() { + paste! { + #[allow(non_upper_case_globals)] + const []: &str = "libpaste"; + + let _ = LIBPaste; + } +} + +mod test_x86_feature_literal { + // work around https://github.com/rust-lang/rust/issues/72726 + + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + macro_rules! my_is_x86_feature_detected { + ($feat:literal) => { + use paste::paste; + + paste! { + #[test] + fn test() { + let _ = is_x86_feature_detected!($feat); + } + } + }; + } + + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + macro_rules! my_is_x86_feature_detected { + ($feat:literal) => { + #[ignore] + #[test] + fn test() {} + }; + } + + my_is_x86_feature_detected!("mmx"); +} + +#[rustversion::since(1.46)] +mod test_local_setter { + // https://github.com/dtolnay/paste/issues/7 + + use paste::paste; + + #[derive(Default)] + struct Test { + val: i32, + } + + impl Test { + fn set_val(&mut self, arg: i32) { + self.val = arg; + } + } + + macro_rules! setter { + ($obj:expr, $field:ident, $value:expr) => { + paste! { $obj.[]($value); } + }; + + ($field:ident, $value:expr) => {{ + let mut new = Test::default(); + setter!(new, val, $value); + new + }}; + } + + #[test] + fn test_local_setter() { + let a = setter!(val, 42); + assert_eq!(a.val, 42); + } +} + +// https://github.com/dtolnay/paste/issues/85 +#[test] +fn test_top_level_none_delimiter() { + macro_rules! clone { + ($val:expr) => { + paste! { + $val.clone() + } + }; + } + + #[derive(Clone)] + struct A; + + impl A { + fn consume_self(self) { + let _ = self; + } + } + + clone!(&A).consume_self(); +} diff --git a/bitbox02-bt/vendor/paste/tests/test_item.rs b/bitbox02-bt/vendor/paste/tests/test_item.rs new file mode 100644 index 0000000..4f26c9c --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/test_item.rs @@ -0,0 +1,271 @@ +#![allow(clippy::let_underscore_untyped)] + +mod test_basic { + use paste::paste; + + struct Struct; + + paste! { + impl Struct { + fn []() {} + } + } + + #[test] + fn test() { + Struct::abc(); + } +} + +mod test_in_impl { + use paste::paste; + + struct Struct; + + impl Struct { + paste! { + fn []() {} + } + } + + #[test] + fn test() { + Struct::abc(); + } +} + +mod test_none_delimited_single_ident { + use paste::paste; + + macro_rules! m { + ($id:ident) => { + paste! { + fn f() -> &'static str { + stringify!($id) + } + } + }; + } + + m!(i32x4); + + #[test] + fn test() { + assert_eq!(f(), "i32x4"); + } +} + +mod test_none_delimited_single_lifetime { + use paste::paste; + + macro_rules! m { + ($life:lifetime) => { + paste! { + pub struct S<$life>(#[allow(dead_code)] pub &$life ()); + impl<$life> S<$life> { + fn f() {} + } + } + }; + } + + m!('a); + + #[test] + fn test() { + S::f(); + } +} + +mod test_to_lower { + use paste::paste; + + macro_rules! m { + ($id:ident) => { + paste! { + fn [](_arg: u8) -> &'static str { + stringify!([<$id:lower>]) + } + } + }; + } + + m!(Test); + + #[test] + fn test_to_lower() { + assert_eq!(my_test_here(0), "test"); + } +} + +mod test_to_upper { + use paste::paste; + + macro_rules! m { + ($id:ident) => { + paste! { + const []: &str = stringify!([<$id:upper>]); + } + }; + } + + m!(Test); + + #[test] + fn test_to_upper() { + assert_eq!(MY_TEST_HERE, "TEST"); + } +} + +mod test_to_snake { + use paste::paste; + + macro_rules! m { + ($id:ident) => { + paste! { + const DEFAULT_SNAKE: &str = stringify!([<$id:snake>]); + const LOWER_SNAKE: &str = stringify!([<$id:snake:lower>]); + const UPPER_SNAKE: &str = stringify!([<$id:snake:upper>]); + } + }; + } + + m!(ThisIsButATest); + + #[test] + fn test_to_snake() { + assert_eq!(DEFAULT_SNAKE, "this_is_but_a_test"); + assert_eq!(LOWER_SNAKE, "this_is_but_a_test"); + assert_eq!(UPPER_SNAKE, "THIS_IS_BUT_A_TEST"); + } +} + +mod test_to_camel { + use paste::paste; + + macro_rules! m { + ($id:ident) => { + paste! { + const DEFAULT_CAMEL: &str = stringify!([<$id:camel>]); + const LOWER_CAMEL: &str = stringify!([<$id:camel:lower>]); + const UPPER_CAMEL: &str = stringify!([<$id:camel:upper>]); + } + }; + } + + m!(this_is_but_a_test); + + #[test] + fn test_to_camel() { + assert_eq!(DEFAULT_CAMEL, "ThisIsButATest"); + assert_eq!(LOWER_CAMEL, "thisisbutatest"); + assert_eq!(UPPER_CAMEL, "THISISBUTATEST"); + } +} + +mod test_doc_expr { + // https://github.com/dtolnay/paste/issues/29 + + use paste::paste; + + macro_rules! doc_expr { + ($doc:expr) => { + paste! { + #[doc = $doc] + pub struct S; + } + }; + } + + doc_expr!(stringify!(...)); + + #[test] + fn test_doc_expr() { + let _: S; + } +} + +mod test_type_in_path { + // https://github.com/dtolnay/paste/issues/31 + + use paste::paste; + + mod keys { + #[derive(Default)] + pub struct Mib(std::marker::PhantomData); + } + + macro_rules! types { + ($mib:ty) => { + paste! { + #[derive(Default)] + pub struct S(pub keys::$mib); + } + }; + } + + macro_rules! write { + ($fn:ident, $field:ty) => { + paste! { + pub fn $fn() -> $field { + $field::default() + } + } + }; + } + + types! {Mib<[usize; 2]>} + write! {get_a, keys::Mib} + write! {get_b, usize} + + #[test] + fn test_type_in_path() { + let _: S; + let _ = get_a; + let _ = get_b; + } +} + +mod test_type_in_fn_arg { + // https://github.com/dtolnay/paste/issues/38 + + use paste::paste; + + fn _jit_address(_node: ()) {} + + macro_rules! jit_reexport { + ($fn:ident, $arg:ident : $typ:ty) => { + paste! { + pub fn $fn($arg: $typ) { + [<_jit_ $fn>]($arg); + } + } + }; + } + + jit_reexport!(address, node: ()); + + #[test] + fn test_type_in_fn_arg() { + let _ = address; + } +} + +mod test_pat_in_expr_position { + // https://github.com/xiph/rav1e/pull/2324/files + + use paste::paste; + + macro_rules! rav1e_bad { + ($e:pat) => { + paste! { + #[test] + fn test() { + let _ = $e; + } + } + }; + } + + rav1e_bad!(std::fmt::Error); +} diff --git a/bitbox02-bt/vendor/paste/tests/ui/case-warning.rs b/bitbox02-bt/vendor/paste/tests/ui/case-warning.rs new file mode 100644 index 0000000..fdea4d6 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/case-warning.rs @@ -0,0 +1,15 @@ +#![deny(warnings)] + +use paste::paste; + +macro_rules! m { + ($i:ident) => { + paste! { + pub fn []() {} + } + }; +} + +m!(Bar); + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/case-warning.stderr b/bitbox02-bt/vendor/paste/tests/ui/case-warning.stderr new file mode 100644 index 0000000..8309912 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/case-warning.stderr @@ -0,0 +1,16 @@ +error: function `fooBar` should have a snake case name + --> tests/ui/case-warning.rs:8:20 + | +8 | pub fn []() {} + | ^^^^^^^^^^ help: convert the identifier to snake case: `foo_bar` +... +13 | m!(Bar); + | ------- in this macro invocation + | +note: the lint level is defined here + --> tests/ui/case-warning.rs:1:9 + | +1 | #![deny(warnings)] + | ^^^^^^^^ + = note: `#[deny(non_snake_case)]` implied by `#[deny(warnings)]` + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-empty.rs b/bitbox02-bt/vendor/paste/tests/ui/env-empty.rs new file mode 100644 index 0000000..1e9f2d0 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-empty.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-empty.stderr b/bitbox02-bt/vendor/paste/tests/ui/env-empty.stderr new file mode 100644 index 0000000..a1ef2e2 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-empty.stderr @@ -0,0 +1,5 @@ +error: expected string literal as argument to env! macro + --> tests/ui/env-empty.rs:4:10 + | +4 | fn []() {} + | ^^^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-non-string.rs b/bitbox02-bt/vendor/paste/tests/ui/env-non-string.rs new file mode 100644 index 0000000..55255ef --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-non-string.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-non-string.stderr b/bitbox02-bt/vendor/paste/tests/ui/env-non-string.stderr new file mode 100644 index 0000000..05b8deb --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-non-string.stderr @@ -0,0 +1,5 @@ +error: expected string literal + --> tests/ui/env-non-string.rs:4:15 + | +4 | fn []() {} + | ^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-suffix.rs b/bitbox02-bt/vendor/paste/tests/ui/env-suffix.rs new file mode 100644 index 0000000..b5c60af --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-suffix.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-suffix.stderr b/bitbox02-bt/vendor/paste/tests/ui/env-suffix.stderr new file mode 100644 index 0000000..d723cbc --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-suffix.stderr @@ -0,0 +1,5 @@ +error: expected string literal + --> tests/ui/env-suffix.rs:4:15 + | +4 | fn []() {} + | ^^^^^^^^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-unexpected.rs b/bitbox02-bt/vendor/paste/tests/ui/env-unexpected.rs new file mode 100644 index 0000000..39cb770 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-unexpected.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/env-unexpected.stderr b/bitbox02-bt/vendor/paste/tests/ui/env-unexpected.stderr new file mode 100644 index 0000000..25387b1 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/env-unexpected.stderr @@ -0,0 +1,5 @@ +error: unexpected token in env! macro + --> tests/ui/env-unexpected.rs:4:21 + | +4 | fn []() {} + | ^^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/invalid-ident.rs b/bitbox02-bt/vendor/paste/tests/ui/invalid-ident.rs new file mode 100644 index 0000000..6a8cf3c --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/invalid-ident.rs @@ -0,0 +1,15 @@ +use paste::paste; + +paste! { + fn [<0 f>]() {} +} + +paste! { + fn []() {} +} + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/invalid-ident.stderr b/bitbox02-bt/vendor/paste/tests/ui/invalid-ident.stderr new file mode 100644 index 0000000..ca1585e --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/invalid-ident.stderr @@ -0,0 +1,26 @@ +error: expected identifier, found `0f` + --> tests/ui/invalid-ident.rs:3:1 + | +3 | / paste! { +4 | | fn [<0 f>]() {} +5 | | } + | |_^ expected identifier + | +help: identifiers cannot start with a number + --> tests/ui/invalid-ident.rs:3:1 + | +3 | paste! { + | ^ + = note: this error originates in the macro `paste` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: `"f\""` is not a valid identifier + --> tests/ui/invalid-ident.rs:8:8 + | +8 | fn []() {} + | ^^^^^^^^^ + +error: `"f'"` is not a valid identifier + --> tests/ui/invalid-ident.rs:12:8 + | +12 | fn []() {} + | ^^^^^^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.rs b/bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.rs new file mode 100644 index 0000000..44fefbd --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.stderr b/bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.stderr new file mode 100644 index 0000000..7b4bc46 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/missing-paren-on-env.stderr @@ -0,0 +1,5 @@ +error: expected `(` + --> tests/ui/missing-paren-on-env.rs:4:15 + | +4 | fn []() {} + | ^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/no-env-var.rs b/bitbox02-bt/vendor/paste/tests/ui/no-env-var.rs new file mode 100644 index 0000000..c6d8c3d --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/no-env-var.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/no-env-var.stderr b/bitbox02-bt/vendor/paste/tests/ui/no-env-var.stderr new file mode 100644 index 0000000..60de9ed --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/no-env-var.stderr @@ -0,0 +1,5 @@ +error: no such env var: "PASTE_UNKNOWN" + --> tests/ui/no-env-var.rs:4:17 + | +4 | fn []() {} + | ^^^^^^^^^^^^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.rs b/bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.rs new file mode 100644 index 0000000..50b3b0d --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.stderr b/bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.stderr new file mode 100644 index 0000000..9db91eb --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/no-ident-after-colon.stderr @@ -0,0 +1,5 @@ +error: expected identifier after `:` + --> tests/ui/no-ident-after-colon.rs:4:15 + | +4 | fn []() {} + | ^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/unexpected-group.rs b/bitbox02-bt/vendor/paste/tests/ui/unexpected-group.rs new file mode 100644 index 0000000..63ee516 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unexpected-group.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/unexpected-group.stderr b/bitbox02-bt/vendor/paste/tests/ui/unexpected-group.stderr new file mode 100644 index 0000000..f66f5c1 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unexpected-group.stderr @@ -0,0 +1,5 @@ +error: unexpected token + --> tests/ui/unexpected-group.rs:4:12 + | +4 | fn []() {} + | ^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.rs b/bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.rs new file mode 100644 index 0000000..99fe68f --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn [<:lower x>]() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.stderr b/bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.stderr new file mode 100644 index 0000000..1eaba31 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unexpected-modifier.stderr @@ -0,0 +1,5 @@ +error: unexpected modifier + --> tests/ui/unexpected-modifier.rs:4:10 + | +4 | fn [<:lower x>]() {} + | ^^^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.rs b/bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.rs new file mode 100644 index 0000000..d0edb92 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.stderr b/bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.stderr new file mode 100644 index 0000000..1a74a61 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unexpected-punct.stderr @@ -0,0 +1,5 @@ +error: unexpected punct + --> tests/ui/unexpected-punct.rs:4:12 + | +4 | fn []() {} + | ^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.rs b/bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.rs new file mode 100644 index 0000000..7a9c490 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.rs @@ -0,0 +1,21 @@ +use paste::paste; + +paste! { + fn []() {} +} + +paste! { + // `xyz` is not correct. `xbyz` is certainly not correct. Maybe `x121z` + // would be justifiable but for now don't accept this. + fn []() {} +} + +paste! { + fn []() {} +} + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.stderr b/bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.stderr new file mode 100644 index 0000000..a802b45 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unsupported-literal.stderr @@ -0,0 +1,23 @@ +error: unsupported literal + --> tests/ui/unsupported-literal.rs:4:12 + | +4 | fn []() {} + | ^^^^^^ + +error: unsupported literal + --> tests/ui/unsupported-literal.rs:10:12 + | +10 | fn []() {} + | ^^^^ + +error: unsupported literal + --> tests/ui/unsupported-literal.rs:14:12 + | +14 | fn []() {} + | ^^^^ + +error: unsupported literal + --> tests/ui/unsupported-literal.rs:18:12 + | +18 | fn []() {} + | ^^^^^ diff --git a/bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.rs b/bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.rs new file mode 100644 index 0000000..a65b36a --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.rs @@ -0,0 +1,7 @@ +use paste::paste; + +paste! { + fn []() {} +} + +fn main() {} diff --git a/bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.stderr b/bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.stderr new file mode 100644 index 0000000..3c70435 --- /dev/null +++ b/bitbox02-bt/vendor/paste/tests/ui/unsupported-modifier.stderr @@ -0,0 +1,5 @@ +error: unsupported modifier + --> tests/ui/unsupported-modifier.rs:4:11 + | +4 | fn []() {} + | ^^^^^^^ diff --git a/bitbox02-bt/vendor/portable-atomic/.cargo-checksum.json b/bitbox02-bt/vendor/portable-atomic/.cargo-checksum.json new file mode 100644 index 0000000..a4580bb --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"993db732063bc4e9666741b010abbc67764709efcc15d2269578e9839135c472","Cargo.toml":"54e38fad09c68a2e8eeffa1fd5894525daf4e494260b39e48cd37031b0b77de5","LICENSE-APACHE":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"adc9de23a63ab5c104273c71d8133eb257d2ff08fab74e5c8d2f9e4cd5df1962","build.rs":"0d5e11d1d1376259bbd99269b52728a5a7e3f93403d82fa4ee1cfbd11ed892dd","no_atomic.rs":"f3cbde2210b7275786334ac8baa6900da591f7dc72c1c15f958b059a4faec9e2","src/cfgs.rs":"63426deb7134d9bf992b7a53a12b9cd21bcd210514358544cf24f1abcfe349e6","src/gen/utils.rs":"f97d5ca5102825e475d9cdd9aa8c84320e0d71ed432b1b55073a095d8103bbdd","src/imp/atomic128/README.md":"1ba7f2d9a9ef1b848382c4c23f76ac83c65b0109b9f8328d0b1dbd10eb8fc32a","src/imp/atomic128/aarch64.rs":"f6dbc1cc808f295eae2291fa7aa7793025f5330d535b5ea43c3b18a9642e9bb1","src/imp/atomic128/intrinsics.rs":"cd8786c26d340d1201a3516c36fceef88835c0bd9dde5f27138cf6ee23c21a73","src/imp/atomic128/macros.rs":"9b5aca0eead3840360f3f31839b0f6520ccda65e66b64adba2fb6160611808cb","src/imp/atomic128/mod.rs":"dfbcc9b20dc9cece46cbaa54a6661edd67d352a2e74f674052f641c676ce3eae","src/imp/atomic128/powerpc64.rs":"3f9c78246f9c27b218092293fdc68e1465f8c7de0a196d10572eb3b51f1761db","src/imp/atomic128/riscv64.rs":"73f1d27f671c4c7c519fcf3d9a731718adc415a2f6632b0cc7e33891756c8186","src/imp/atomic128/s390x.rs":"e86cf49c6e5bcb7d5d98ccc8fb775c809f30ca2d1b1d841265aa26b146dce4f1","src/imp/atomic128/x86_64.rs":"19bc111a8dfc976781d1e728994484274527b9ad954f0a9afcccdea0c0c6182d","src/imp/atomic64/README.md":"2d92719675d696ea8ee8b5b5f4a61607880359548152de11eed8283d584676ea","src/imp/atomic64/arm_linux.rs":"5db69d12916105f1718fb3a10c0a2bf353f6f25f49a409732c12e7ba0d33bdac","src/imp/atomic64/macros.rs":"155a95cf41e3633cc65e4879b21b7c61b2ff366ba1109951b5056c4143f7fd02","src/imp/atomic64/mod.rs":"a9facfd1c33c1c4255e5a2d8d24f9e32e567bdca63170234a0f030a959edbef3","src/imp/atomic64/riscv32.rs":"15da80c3c3e41c586c8e75547066bba6b8d8def246b427ce2e2b009ddc725512","src/imp/core_atomic.rs":"afaabb56674509dda72669cd9274c87477b832d2818df11c9dede2aaeaa96026","src/imp/detect/README.md":"c86e60e6102b155e543f3b3a29599681a51c7febc6f4ceb89a300d9184e5596b","src/imp/detect/aarch64_aa64reg.rs":"fb1119dc0ceed6210ce63ca813f451aea4abd4b234251631f126594b4a31fc37","src/imp/detect/aarch64_apple.rs":"17c837b5220f6ff7ed1613be931e1cabd177044c037078edf1950bb1bc23844d","src/imp/detect/aarch64_fuchsia.rs":"74a3f99fc7fc9ebb674d8460c8824e5ff81c6b779e2120158bd0ded367daf21a","src/imp/detect/aarch64_illumos.rs":"b0de2b046a028fe2917ed8d703bb4f85d171f711d8a9c4787c445f0831865dfc","src/imp/detect/aarch64_windows.rs":"154f6fca3190902d74a0e43e2b036afe84b985d1bd7c7ff112c37ceb34fc52a7","src/imp/detect/auxv.rs":"edfbc88457ecbe42673a56136e6a46af9f42b84d6afd9572eb4dd5ea38bc22ac","src/imp/detect/common.rs":"3206ffa1907e258c77d81a686eb0b1830ce9c0ee3c9c468be1571a7fbb600d98","src/imp/detect/riscv_linux.rs":"063383a0cb9472180a3b65a8353c3f7b12bbd8a3693d1b4d79f792720500553f","src/imp/detect/x86_64.rs":"e720542a951c7fcfb9aca471abee8d157c8c17bfe439e950067ac798547ad311","src/imp/fallback/mod.rs":"426e23db75887a6a60a93d5489e79b6a7a4565f52ffb35b672658c4791e46e2d","src/imp/fallback/outline_atomics.rs":"56ff7b7d62c738be021d02d9d023829297a3b2e8b57964657d6faa7b135f0309","src/imp/fallback/seq_lock.rs":"b591a77f202095e31c855f61932145e85206a489ee1a0b23b89e4411ef02807e","src/imp/fallback/seq_lock_wide.rs":"e8f22b7bda9eb7b55c4c216dd78a2c4e3ca3ba8fda3385d1a55605e302d39f53","src/imp/fallback/utils.rs":"6d5926247f47004b74e6beb6cf1f2902f8fda628afd6cf4c739cf79a91122c46","src/imp/float.rs":"6276cf08331a504e17c440fad6d78b7bd4e76accf77943757f53de7b60306a26","src/imp/interrupt/README.md":"2fbcb1782c3f58e5d6654bc6e8f0a8adffbf1e0f11910e8c0dacf0275b0487aa","src/imp/interrupt/armv4t.rs":"41e8f41130d04d136858c1f6dc194e361e9ce4cb4cda2265252a1a0ef0554e5c","src/imp/interrupt/armv6m.rs":"de49033c3c4e1be24ce1fc2cc3542f24209c3a3c6cd741c37d778b04d0dcec4d","src/imp/interrupt/avr.rs":"dde90fa6f6f71caccb3e58189cc6282b41f6b612c750df237257c95f4f753260","src/imp/interrupt/mod.rs":"6b18929cab553c5816f71cf5823cbbbccef41e1f66e7f25371c9c5b58fa04d6f","src/imp/interrupt/msp430.rs":"0caab96fda16af9710581f2e0702a77e22b267462c67bbedd5759e53eb05d7bb","src/imp/interrupt/riscv.rs":"1a47f45dd7d01ac11647b1f12ded4291464ba87815b1920f7183f0d39ea0792b","src/imp/interrupt/xtensa.rs":"a1a892476cab0ddab8076c78c1f62ad29a26133a2bea2b1284ce4e175abcbefd","src/imp/mod.rs":"8fa65d46f9cb415843411667b4510e4332bc3a3b2abc274d56cc4db88d358df1","src/imp/msp430.rs":"c6f02a69b5d70142cd38c11eab82490de22b25d101a5b571b7c0c415820eb2c5","src/imp/riscv.rs":"cb2e61dfb61c78e8b82be9f5f5b3aa941a8cfe9d3c1a3dafebd24314b16ff53b","src/imp/x86.rs":"dde59a08724667434f4f451e256e607eca4804d07e137c7eb6d2dbb715293337","src/lib.rs":"8dbbec405639595638194aed73b621e3ea195e0e025ff4f064b137fae442b605","src/tests/helper.rs":"ba6c139393e950bfb2c476f20082f50098899375ee7b05e0d0e14f162d2a56ed","src/tests/mod.rs":"8766be6dbc80f3556819a4613a4aee5c6fbd3242535b14973b3da523b810e277","src/utils.rs":"10910a955ab7868fc0c94fe856d2ee5cb0b99172d3a0af81e1a8e8448d59b8dc","version.rs":"e72ed7550f8edacc41e2ebcf0b5adcb1baa30b4d74df90b8b68e1c62fd8da78b"},"package":"cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/portable-atomic/CHANGELOG.md b/bitbox02-bt/vendor/portable-atomic/CHANGELOG.md new file mode 100644 index 0000000..b386a27 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/CHANGELOG.md @@ -0,0 +1,531 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](https://semver.org). + + + +## [Unreleased] + +## [1.9.0] - 2024-09-28 + +- RISC-V without A-extension: Support RMW when Zaamo extension enabled (even when `unsafe-assume-single-core` disabled). ([#185](https://github.com/taiki-e/portable-atomic/pull/185), [9983a8b](https://github.com/taiki-e/portable-atomic/commit/9983a8b9ad66efe4303b95678014369a56839aef)) + See "operations don't require disabling interrupts" list in [`interrupt` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/interrupt/README.md) for the operations provided. + +- Support run-time detection of RISC-V Zacas extension (currently disabled by default). ([#183](https://github.com/taiki-e/portable-atomic/pull/183)) + +- Support 128-bit atomics on Arm64EC (currently nightly-only) ([#184](https://github.com/taiki-e/portable-atomic/pull/184)) + +- Improve compile-time detection of powerpc64 quadword-atomics. ([3eb8507](https://github.com/taiki-e/portable-atomic/commit/3eb8507f91c1ab382d9f455b2311a8664a4c33ff)) + +## [1.8.0] - 2024-09-20 + +- Improve diagnostics when method that requires CAS is unavailable. ([#181](https://github.com/taiki-e/portable-atomic/pull/181)) + + Before: + + ```text + error[E0599]: no method named `compare_exchange` found for struct `portable_atomic::AtomicUsize` in the current scope + --> src/race.rs:60:24 + | + 60 | self.inner.compare_exchange(0, value.get(), Ordering::AcqRel, Ordering::Acquire); + | ^^^^^^^^^^^^^^^^ method not found in `AtomicUsize` + ``` + + After: + + ```text + error[E0277]: `compare_exchange` requires atomic CAS but not available on this target by default + --> src/race.rs:60:24 + | + 60 | self.inner.compare_exchange(0, value.get(), Ordering::AcqRel, Ordering::Acquire); + | ^^^^^^^^^^^^^^^^ this associated function is not available on this target by default + | + = help: the trait `HasCompareExchange` is not implemented for `&portable_atomic::AtomicUsize` + = note: consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features + = note: see for more. + ``` + +- Improve compile error messages for some other cases ([19716ac](https://github.com/taiki-e/portable-atomic/commit/19716ac1d3b6082a8cb838af532ccab871041249), [61dcaaa](https://github.com/taiki-e/portable-atomic/commit/61dcaaa320cb347ab799c6c4f4480600692de2ad)) + +- Various improvements to RISC-V. + - riscv64: Support 128-bit atomics when Zacas extension enabled. ([173](https://github.com/taiki-e/portable-atomic/pull/173)) This is currently marked as experimental because LLVM marking the corresponding target feature as experimental. + - riscv32: Support 64-bit atomics when Zacas extension enabled. ([173](https://github.com/taiki-e/portable-atomic/pull/173)) This is currently marked as experimental because LLVM marking the corresponding target feature as experimental. + - Improvements for RISC-V without A-extension: + - Support zaamo target feature. When building for single-core RISC-V without A-extension, this is equivalent to force-amo feature ([8abba4b](https://github.com/taiki-e/portable-atomic/commit/8abba4b0ea920d23799c2d7b6985617e6392d176)) + - Support zabha target feature. ([694364a](https://github.com/taiki-e/portable-atomic/commit/694364a179441f723e429516132436c46f5857b4)) + - Strengthen SeqCst store to improve compatibility with code that uses atomic instruction mapping that differs from LLVM and GCC. ([5b10b15](https://github.com/taiki-e/portable-atomic/commit/5b10b1516e056b16b851e498a271f751152feed9)) + +- Improve support of run-time detection and outline-atomics: + - aarch64: Support run-time detection of FEAT_LRCPC3/FEAT_LSE128 for load/store. ([#174](https://github.com/taiki-e/portable-atomic/pull/174)) + - aarch64: Support run-time detection of FEAT_LSE2 on OpenBSD. ([4f8c735](https://github.com/taiki-e/portable-atomic/commit/4f8c7350fd80d005233d85191707e4329a5ef484)) + - aarch64: Support run-time detection of FEAT_LSE/FEAT_LSE2 on illumos (currently disabled by default because illumos AArch64 port is experimental). ([#175](https://github.com/taiki-e/portable-atomic/pull/175)) + - powerpc64: Support run-time detection on OpenBSD 7.6+ (currently disabled by default for compatibility with old versions). ([09a967b](https://github.com/taiki-e/portable-atomic/commit/09a967b59c217dc9ebb4d78ec114758ef9941fc8)) + +- Support AArch64 FEAT_LRCPC3/FEAT_LSE128 with pre-16 LLVM. ([#178](https://github.com/taiki-e/portable-atomic/pull/178)) + +- Improve compile-time detection of AArch64 FEAT_LSE2/FEAT_LRCPC3/FEAT_LSE128. ([10d47de](https://github.com/taiki-e/portable-atomic/commit/10d47def74b9c13fd864436d6118e902f118c028)) + +- Relax minimal version of `serde` (supported via optional feature) to 1.0.60. + +## [1.7.0] - 2024-07-19 + +- Support run-time detection for cmpxchg16b on x86_64 on pre-1.69 rustc. ([#154](https://github.com/taiki-e/portable-atomic/pull/154)) + +- Make `into_inner` `const fn` on Rust 1.56+. (align to the [std atomic change in Rust 1.79](https://github.com/rust-lang/rust/pull/123522)) ([dee1f89](https://github.com/taiki-e/portable-atomic/commit/dee1f89739594271e4f5b5d3f122d2762fcbbd7d)) + +- Work around [rustc_codegen_gcc bug on x86_64](https://github.com/rust-lang/rustc_codegen_gcc/issues/485). ([d938f77](https://github.com/taiki-e/portable-atomic/commit/d938f77f3f2f353cbfb525ac23e63e880cd583df)) + +- Optimize x86_64 atomics. + - Optimize 128-bit load/store on Zhaoxin CPU with AVX. ([86cee8f](https://github.com/taiki-e/portable-atomic/commit/86cee8fccf7deedb5b8cbcb3868ec2e43aca575f)) + - Optimize 128-bit SeqCst store on Intel/AMD/Zhaoxin CPU with AVX. ([#156](https://github.com/taiki-e/portable-atomic/pull/156), [0483042](https://github.com/taiki-e/portable-atomic/commit/0483042671fad4ccd0bdb691424a967fc2a5cb8e)) + - Remove needless test in CAS. ([573e025](https://github.com/taiki-e/portable-atomic/commit/573e02586f933a257c8e7383dcf64408b4708b85)) + +- Make rustc version detection robust for custom toolchains. ([f8ea85e](https://github.com/taiki-e/portable-atomic/commit/f8ea85e1aa46fa00bc865633fb40b05f8a0c823b)) + +- Respect `RUSTC_WRAPPER` in rustc version detection. + +- Our build script is now less likely to be [re-run unnecessarily](https://github.com/taiki-e/portable-atomic/issues/151) in versions where the cargo bug fix is available (cargo 1.79+). ([52c277b](https://github.com/taiki-e/portable-atomic/commit/52c277bc9a9a8031175aaed54987260da1750af4)) + +## [1.6.0] - 2023-12-06 + +- Add `cfg_{has,no}_atomic_{8,16,32,64,128,ptr}` macros to enable code when the corresponding atomic implementation is available/unavailable. + +- Add `cfg_{has,no}_atomic_cas` macros to enable code when atomic CAS/RMW implementation is available/unavailable. + +- Improve support for RISC-V targets without atomic CAS. + +## [1.5.1] - 2023-10-29 + +- Fix bug in `i{8,16}` `fetch_{or,xor}` on RISC-V without A-extension where `unsafe-assume-single-core` and `force-amo` are enabled. + +- Optimize `swap` for targets that do not have native atomic CAS instructions. + +## [1.5.0] - 2023-10-23 + +**Note:** This release has been yanked due to a bug fixed in 1.5.1. + +- Add `from_ptr`. + +- Add `force-amo` feature (`portable_atomic_force_amo` cfg) for single-core RISC-V without A-extension. ([#124](https://github.com/taiki-e/portable-atomic/pull/124)) + +- Support run-time detection on AArch64 on pre-1.61 rustc. ([#98](https://github.com/taiki-e/portable-atomic/pull/98)) + + This also solves [a compatibility issue with rustc_codegen_cranelift](https://github.com/rust-lang/rustc_codegen_cranelift/issues/1400). + +- Support run-time detection of FEAT_LSE2. ([#126](https://github.com/taiki-e/portable-atomic/pull/126)) + +- Support run-time detection of FEAT_LSE on AArch64 NetBSD. ([#66](https://github.com/taiki-e/portable-atomic/pull/66)) + +- Acknowledge ESP-IDF targets' 64-bit atomics are not lock-free. See [#122](https://github.com/taiki-e/portable-atomic/issues/122) for more. + +- Optimize 128-bit weak CAS on powerpc64. + +- Optimize interrupt disable on no-std pre-v6 Arm where `unsafe-assume-single-core` and `disable-fiq` are enabled. ([771c45d](https://github.com/taiki-e/portable-atomic/commit/771c45da2d2afc4f83df033dd4bdf3f976d14a74)) + +- Improve detection of Apple hardware. ([5c3a43b](https://github.com/taiki-e/portable-atomic/commit/5c3a43b53f1c4188f9dd597599633bc1a315bf44)) + +- Improve compatibility with the future version of Miri. + +## [1.4.3] - 2023-08-25 + +- Optimize AArch64 128-bit atomic store/swap/fetch_and/fetch_or when the `lse128` target feature is enabled at compile-time. ([#68](https://github.com/taiki-e/portable-atomic/pull/68)) + +- Optimize AArch64 128-bit atomic load/store when the `rcpc3` target feature is enabled at compile-time. ([#68](https://github.com/taiki-e/portable-atomic/pull/68)) + +- Optimize inline assemblies on Arm, AArch64, and MSP430. + +## [1.4.2] - 2023-07-27 + +- Optimize `AtomicBool` on RISC-V/LoongArch64. This is the same as [rust-lang/rust#114034](https://github.com/rust-lang/rust/pull/114034), but is available for all rustc versions. + +## [1.4.1] - 2023-07-15 + +- Improve compatibility with the future version of Miri. + +## [1.4.0] - 2023-07-11 + +- Allow using embedded-related cfgs as Cargo features. ([#94](https://github.com/taiki-e/portable-atomic/pull/94), thanks @Dirbaio) + + Originally, we were providing these as cfgs instead of features, but based on a strong request from the embedded ecosystem, we have agreed to provide them as features as well. See [#94](https://github.com/taiki-e/portable-atomic/pull/94) for more. + + cfgs are kept and can be used as aliases for features. + +- Acknowledge all x86_64 Apple targets support 128-bit atomics. + + Our code already recognizes this via `cfg(target_feature)`, so this only affects docs and users using pre-1.69 stable rustc. + + See also [rust-lang/rust#112150](https://github.com/rust-lang/rust/pull/112150). + +- Optimize 128-bit atomics on AArch64/s390x. + +## [1.3.3] - 2023-05-31 + +- Fix build error on AArch64 ILP32 ABI targets (tier 3). + +- Optimize 128-bit atomics on s390x. + +## [1.3.2] - 2023-05-09 + +- Fix bug in powerpc64/s390x 128-bit atomic RMWs on old nightly. + +- Optimize 128-bit atomics on powerpc64/s390x. + +## [1.3.1] - 2023-05-07 + +- Documentation improvements. + +## [1.3.0] - 2023-05-06 + +- Add `require-cas` feature. ([#100](https://github.com/taiki-e/portable-atomic/pull/100)) + + If your crate supports no-std environment and requires atomic CAS, enabling this feature will allow the `portable-atomic` to display helpful error messages to users on targets requiring additional action on the user side to provide atomic CAS. + + ```toml + [dependencies] + portable-atomic = { version = "1.3", default-features = false, features = ["require-cas"] } + ``` + + See [#100](https://github.com/taiki-e/portable-atomic/pull/100) for more. + +- Support `portable_atomic_unsafe_assume_single_core` cfg on Xtensa targets without atomic CAS. ([#86](https://github.com/taiki-e/portable-atomic/pull/86)) + +- Fix bug in AArch64 128-bit SeqCst load when FEAT_LSE2 is enabled at compile-time. This is [the same bug that was fixed in the recently released GCC 13.1](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108891). LLVM also has the same bug, which had not yet been fixed when the patch was created; I will open a bug report if necessary after looking into the situation in LLVM. ([a29154b](https://github.com/taiki-e/portable-atomic/commit/a29154b21da270e90cb86f6865b591ab36eade7d)) + +- Fix compile error on `bpf{eb,el}-unknown-none` (tier 3) and `mipsel-sony-psx` (tier 3) when `critical-section` feature is disabled. + +- Various optimizations + - Optimize x86_64 128-bit outline-atomics. This improves performance by up to 15% in concurrent RMW/store for cases where the `cmpxchg16b` target feature is not available at compile-time. ([40c4cd4](https://github.com/taiki-e/portable-atomic/commit/40c4cd4f682f1cb153f18d4d6a88795bafaf5667)) + - Optimize x86_64 128-bit load that uses cmpxchg16b. ([40c4cd4](https://github.com/taiki-e/portable-atomic/commit/40c4cd4f682f1cb153f18d4d6a88795bafaf5667)) + - Optimize AArch64 128-bit load that uses FEAT_LSE. ([40c4cd4](https://github.com/taiki-e/portable-atomic/commit/40c4cd4f682f1cb153f18d4d6a88795bafaf5667)) + - Optimize pre-Armv6 Linux/Android 64-bit atomics. ([efacc89](https://github.com/taiki-e/portable-atomic/commit/efacc89c210d7a34ef5e879821112189da5d1901)) + - Support outline-atomics for powerpc64 128-bit atomics. This is currently disabled by default, and can be enabled by `--cfg portable_atomic_outline_atomics`. ([#90](https://github.com/taiki-e/portable-atomic/pull/90)) + - Optimize AArch64 outline-atomics on linux-musl. On linux-musl, outline-atomics is enabled by default only when dynamic linking is enabled. When static linking is enabled, this can be enabled by `--cfg portable_atomic_outline_atomics`. See the [`atomic128` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/atomic128/README.md#run-time-feature-detection) for more. ([8418235](https://github.com/taiki-e/portable-atomic/commit/84182354e4a149074e28bda4683d538e5fb617ce), [31d0862](https://github.com/taiki-e/portable-atomic/commit/31d08623d4e21af207ff2343f5553b9b5a030452)) + +## [1.2.0] - 2023-03-25 + +- Make 64-bit atomics lock-free on Arm Linux/Android targets that do not have 64-bit atomics (e.g., armv5te-unknown-linux-gnueabi, arm-linux-androideabi, etc.) when the kernel version is 3.1 or later. ([#82](https://github.com/taiki-e/portable-atomic/pull/82)) + +- Fix AArch64 128-bit atomics performance regression on Apple hardware. ([#89](https://github.com/taiki-e/portable-atomic/pull/89)) + +- Optimize 128-bit atomics on AArch64, x86_64, powerpc64, and s390x. + +## [1.1.0] - 2023-03-24 + +- Add `Atomic{I,U}*::bit_{set,clear,toggle}` and `AtomicPtr::bit_{set,clear,toggle}`. ([#72](https://github.com/taiki-e/portable-atomic/pull/72)) + + They correspond to x86's `lock bt{s,r,c}`, and the implementation calls them on x86/x86_64. + +- Add `AtomicU*::{fetch_neg,neg}` methods. Previously it was only available on `AtomicI*` and `AtomicF*`. + +- Add `as_ptr` method to all atomic types. ([#79](https://github.com/taiki-e/portable-atomic/pull/79)) + +- Make `AtomicF{32,64}::as_bits` `const fn` on Rust 1.58+. ([#79](https://github.com/taiki-e/portable-atomic/pull/79)) + +- Relax ordering in `Serialize` impl to reflect the [upstream change](https://github.com/serde-rs/serde/pull/2263). + +- Optimize x86_64 outline-atomics for 128-bit atomics. + - Support outline-atomics for cmpxchg16b on Rust 1.69+ (i.e., on Rust 1.69+, x86_64 128-bit atomics is lock-free on all Intel chips and almost all AMD chips, even if cmpxchg16b is not available at compile-time.). Previously it was only nightly. ([#80](https://github.com/taiki-e/portable-atomic/pull/80)) + - portable-atomic no longer enables outline-atomics on target where run-time CPU feature detection is not available. ([#80](https://github.com/taiki-e/portable-atomic/pull/80)) + +- Optimize AArch64 outline-atomics for 128-bit atomics. + - Support more targets and improve performance. ([#63](https://github.com/taiki-e/portable-atomic/pull/63), [#64](https://github.com/taiki-e/portable-atomic/pull/64), [#67](https://github.com/taiki-e/portable-atomic/pull/67), [#69](https://github.com/taiki-e/portable-atomic/pull/69), [#75](https://github.com/taiki-e/portable-atomic/pull/75), [#76](https://github.com/taiki-e/portable-atomic/pull/76), [#77](https://github.com/taiki-e/portable-atomic/pull/77)) + See the [`atomic128` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/atomic128/README.md#run-time-feature-detection) for a list of platforms that support outline-atomics. + Most of these improvements have already been [submitted and accepted in rust-lang/stdarch](https://github.com/rust-lang/stdarch/pulls?q=is%3Apr+author%3Ataiki-e+std_detect) and will soon be available in `std::arch::is_aarch64_feature_detected`. + - portable-atomic no longer enables outline-atomics on target where run-time CPU feature detection is not available. + +- Performance improvements. ([#70](https://github.com/taiki-e/portable-atomic/pull/70), [#81](https://github.com/taiki-e/portable-atomic/pull/81), [6c189ae](https://github.com/taiki-e/portable-atomic/commit/6c189ae1792ce0c08b4f56b6e6c256c223475ce2), [13c92b0](https://github.com/taiki-e/portable-atomic/commit/13c92b015a8e8646a4b885229157547354d03b9e), etc.) + +- Improve support for old nightly. ([#73](https://github.com/taiki-e/portable-atomic/pull/73), [872feb9](https://github.com/taiki-e/portable-atomic/commit/872feb9d7f3a4ca7cf9b63935265d46498fcae99)) + +- Documentation improvements. + +## [1.0.1] - 2023-01-21 + +- Optimize `Atomic{I,U}*::{fetch_not,not}` methods. ([#62](https://github.com/taiki-e/portable-atomic/pull/62)) + +## [1.0.0] - 2023-01-15 + +- Add `critical-section` feature to use [critical-section](https://github.com/rust-embedded/critical-section) on targets where atomic CAS is not natively available. ([#51](https://github.com/taiki-e/portable-atomic/pull/51), thanks @Dirbaio) + + This is useful to get atomic CAS when `--cfg portable_atomic_unsafe_assume_single_core` can't be used, such as multi-core targets, unprivileged code running under some RTOS, or environments where disabling interrupts needs extra care due to e.g. real-time requirements. + + See [documentation](https://github.com/taiki-e/portable-atomic#optional-features-critical-section) for more. + +- Remove `outline-atomics` feature. This was no-op since 0.3.19. + +- Documentation improvements. + +## [0.3.20] - 2023-05-07 + +The latest version of portable-atomic is 1.x. This release makes portable-atomic 0.3 is built on top of portable-atomic 1.x to make bug fixes and improvements such as [support for new targets](https://github.com/taiki-e/portable-atomic/pull/86) in 1.x available to the ecosystem that depends on older portable-atomic. portable-atomic 0.3 is still maintained passively, but upgrading to portable-atomic 1.x is recommended. (There are no breaking changes from 0.3, except that a deprecated no-op `outline-atomics` Cargo feature has been removed.) ([#99](https://github.com/taiki-e/portable-atomic/pull/99)) + +## [0.3.19] - 2022-12-25 + +- Add `AtomicI*::{fetch_neg,neg}` and `AtomicF*::fetch_neg` methods. ([#54](https://github.com/taiki-e/portable-atomic/pull/54)) + + `AtomicI*::neg` are equivalent to the corresponding `fetch_*` methods, but do not return the previous value. They are intended for optimization on platforms that have atomic instructions for the corresponding operation, such as x86's `lock neg`. + + Currently, optimizations by these methods (`neg`) are only guaranteed for x86/x86_64. + +- Add `Atomic{I,U}*::{fetch_not,not}` methods. ([#54](https://github.com/taiki-e/portable-atomic/pull/54)) + + `Atomic{I,U}*::not` are equivalent to the corresponding `fetch_*` methods, but do not return the previous value. They are intended for optimization on platforms that have atomic instructions for the corresponding operation, such as x86's `lock not`, MSP430's `inv`. + + Currently, optimizations by these methods (`not`) are only guaranteed for x86/x86_64 and MSP430. + + (Note: `AtomicBool` already has `fetch_not` and `not` methods.) + +- Enable outline-atomics for 128-bit atomics by default. ([#57](https://github.com/taiki-e/portable-atomic/pull/57)) See [#57](https://github.com/taiki-e/portable-atomic/pull/57) for more. + +- Improve support for old nightly compilers. + +## [0.3.18] - 2022-12-15 + +- Fix build error when not using `portable_atomic_unsafe_assume_single_core` cfg on AVR and MSP430 custom targets. ([#50](https://github.com/taiki-e/portable-atomic/pull/50)) + + Since 0.3.11, atomic CAS was supported without the cfg on AVR and MSP430 builtin targets, but that change was not applied to custom targets. + +## [0.3.17] - 2022-12-14 + +- Optimize x86_64 128-bit atomic load/store on AMD CPU with AVX. ([#49](https://github.com/taiki-e/portable-atomic/pull/49)) + +- Improve support for custom targets on old rustc. + +## [0.3.16] - 2022-12-09 + +- Add `Atomic{I,U}*::{add,sub,and,or,xor}` and `AtomicBool::{and,or,xor}` methods. ([#47](https://github.com/taiki-e/portable-atomic/pull/47)) + + They are equivalent to the corresponding `fetch_*` methods, but do not return the previous value. They are intended for optimization on platforms that implement atomics using inline assembly, such as the MSP430. + + Currently, optimizations by these methods (`add`,`sub`,`and`,`or`,`xor`) are only guaranteed for MSP430; on x86/x86_64, LLVM can optimize in most cases, so cases, where this would improve things, should be rare. + +- Various improvements to `portable_atomic_unsafe_assume_single_core` cfg. ([#44](https://github.com/taiki-e/portable-atomic/pull/44), [#40](https://github.com/taiki-e/portable-atomic/pull/40)) + + - Support disabling FIQs on pre-v6 Arm under `portable_atomic_disable_fiq` cfg. + - Support RISC-V supervisor mode under `portable_atomic_s_mode` cfg. + - Optimize interrupt restore on AVR and MSP430. ([#40](https://github.com/taiki-e/portable-atomic/pull/40)) + - Documentation improvements. + + See [#44](https://github.com/taiki-e/portable-atomic/pull/44) for more. + +## [0.3.15] - 2022-09-09 + +- Implement workaround for std cpuid bug due to LLVM bug ([rust-lang/rust#101346](https://github.com/rust-lang/rust/issues/101346), [llvm/llvm-project#57550](https://github.com/llvm/llvm-project/issues/57550)). + + - Our use case is likely not affected, but we implement this just in case. + - We've confirmed that the uses of inline assembly in this crate are not affected by this LLVM bug. + +## [0.3.14] - 2022-09-04 + +- Optimize atomic load/store on no-std pre-v6 Arm when `portable_atomic_unsafe_assume_single_core` cfg is used. ([#36](https://github.com/taiki-e/portable-atomic/pull/36)) + +- Support pre-power8 powerpc64le. powerpc64le's default cpu version is power8, but you can technically compile it for the old cpu using the unsafe `-C target-cpu` rustc flag. + +## [0.3.13] - 2022-08-15 + +- Use track_caller when debug assertions are enabled on Rust 1.46+. + +- Make powerpc64 128-bit atomics compatible with Miri and ThreadSanitizer on LLVM 15+. + +- Document that 128-bit atomics are compatible with Miri and ThreadSanitizer on recent nightly. + +## [0.3.12] - 2022-08-13 + +- Support atomic CAS on no-std pre-v6 Arm targets (e.g., thumbv4t-none-eabi) under unsafe cfg `portable_atomic_unsafe_assume_single_core`. ([#28](https://github.com/taiki-e/portable-atomic/pull/28)) + +## [0.3.11] - 2022-08-12 + +- Always provide atomic CAS for MSP430 and AVR. ([#31](https://github.com/taiki-e/portable-atomic/pull/31)) + + This previously required unsafe cfg `portable_atomic_unsafe_assume_single_core`, but since all MSP430 and AVR are single-core, we can safely provide atomic CAS based on disabling interrupts. + +- Support `fence` and `compiler_fence` on MSP430. (On MSP430, the standard library's fences are currently unavailable due to LLVM errors.) + +- Update safety requirements for unsafe cfg `portable_atomic_unsafe_assume_single_core` to mention use of privileged instructions to disable interrupts. + +- Atomic operations based on disabling interrupts on single-core systems are now considered lock-free. + + The previous behavior was inconsistent because we consider the pre-v6 Arm Linux's atomic operations provided in a similar way by the Linux kernel to be lock-free. + +- Respect `-Z allow-features`. + +## [0.3.10] - 2022-08-03 + +- Optimize AArch64 128-bit atomic load when the `lse` target feature is enabled at compile-time. ([#20](https://github.com/taiki-e/portable-atomic/pull/20)) + +## [0.3.9] - 2022-08-03 + +- Fix build error on old Miri. + +- Documentation improvements. + +## [0.3.8] - 2022-08-02 + +- Make AArch64 and s390x 128-bit atomics compatible with Miri and ThreadSanitizer. + +## [0.3.7] - 2022-07-31 + +- Provide stable equivalent of [`#![feature(strict_provenance_atomic_ptr)]`](https://github.com/rust-lang/rust/issues/99108). ([#23](https://github.com/taiki-e/portable-atomic/pull/23)) + + - `AtomicPtr::fetch_ptr_{add,sub}` + - `AtomicPtr::fetch_byte_{add,sub}` + - `AtomicPtr::fetch_{or,and,xor}` + + These APIs are compatible with strict-provenance on `cfg(miri)`. Otherwise, they are compatible with permissive-provenance. + Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, these APIs will be strict-provenance compatible in all cases from the version in which it is stabilized. + +- Provide stable equivalent of [`#![feature(atomic_bool_fetch_not)]`](https://github.com/rust-lang/rust/issues/98485). ([#24](https://github.com/taiki-e/portable-atomic/pull/24)) + + - `AtomicBool::fetch_not` + +- Optimize x86_64 128-bit RMWs. ([#22](https://github.com/taiki-e/portable-atomic/pull/22)) + +- Optimize x86_64 outline-atomics. + +- Optimize inline assemblies on Arm and AArch64. + +- Revert [thumbv6m atomic load/store changes made in 0.3.5](https://github.com/taiki-e/portable-atomic/pull/18). This is because [rust-lang/rust#99595](https://github.com/rust-lang/rust/pull/99595) has been reverted, so this is no longer needed. + +## [0.3.6] - 2022-07-26 + +- Fix build failure due to the existence of the `specs` directory. + +- Documentation improvements. + +- Optimize inline assemblies on x86_64, RISC-V, and MSP430. + +## [0.3.5] - 2022-07-23 + +**Note:** This release has been yanked due to a bug fixed in 0.3.6. + +- Provide thumbv6m atomic load/store which is planned to be removed from the standard library in [rust-lang/rust#99595](https://github.com/rust-lang/rust/pull/99595). ([#18](https://github.com/taiki-e/portable-atomic/pull/18)) + +- Optimize inline assemblies on AArch64, RISC-V, and powerpc64. + +## [0.3.4] - 2022-06-25 + +- Optimize x86_64 128-bit atomic store. + +## [0.3.3] - 2022-06-24 + +- Allow CAS failure ordering stronger than success ordering. ([#17](https://github.com/taiki-e/portable-atomic/pull/17)) + +## [0.3.2] - 2022-06-19 + +- Optimize x86_64 128-bit atomic load/store on Intel CPU with AVX. ([#16](https://github.com/taiki-e/portable-atomic/pull/16)) + +- Support native 128-bit atomic operations for powerpc64 (le or pwr8+, currently nightly-only). + +- Fix behavior differences between stable and nightly. ([#15](https://github.com/taiki-e/portable-atomic/pull/15)) + +## [0.3.1] - 2022-06-16 + +- Optimize AArch64 128-bit atomic load/store when the `lse2` target feature is enabled at compile-time. ([#11](https://github.com/taiki-e/portable-atomic/pull/11)) + +- Relax ordering in `Debug` impl to reflect std changes. ([#12](https://github.com/taiki-e/portable-atomic/pull/12)) + +## [0.3.0] - 2022-03-25 + +- Support native 128-bit atomic operations for s390x (currently nightly-only). + +- Add `AtomicF{32,64}::fetch_abs`. + +- Add `#[must_use]` to constructors. + +- Use 128-bit atomic operation mappings same as LLVM on AArch64. + +- Remove `parking_lot` optional feature to allow the use of this crate within global allocators. + +## [0.2.1] - 2022-03-17 + +- Implement AArch64 outline-atomics. + +## [0.2.0] - 2022-03-10 + +- Remove `i128` feature. `Atomic{I,U}128` are now always enabled. + +- Add `outline-atomics` feature. Currently, this is the same as the 0.1's `i128-dynamic`, except that `fallback` feature is not implicitly enabled. + +- Remove `i128-dynamic` feature in favor of `outline-atomics` feature. + +- Add `AtomicF{32,64}::as_bits`. + +## [0.1.4] - 2022-03-02 + +- Support native 128-bit atomic operations for AArch64 at Rust 1.59+. This was previously supported only on nightly. ([#6](https://github.com/taiki-e/portable-atomic/pull/6)) + +## [0.1.3] - 2022-02-28 + +- Fix inline assembly for RISC-V without A-extension. + +## [0.1.2] - 2022-02-26 + +**Note:** This release has been yanked due to a bug fixed in 0.1.3. + +- Add `parking_lot` feature to use parking_lot in global locks of fallback implementation. + +- Fix bug in cmpxchg16b support. ([#5](https://github.com/taiki-e/portable-atomic/pull/5)) + +## [0.1.1] - 2022-02-25 + +**Note:** This release has been yanked due to a bug fixed in 0.1.3. + +- Fix doc cfg on `Atomic{I,U}128`. + +## [0.1.0] - 2022-02-24 + +**Note:** This release has been yanked due to a bug fixed in 0.1.3. + +Initial release + +[Unreleased]: https://github.com/taiki-e/portable-atomic/compare/v1.9.0...HEAD +[1.9.0]: https://github.com/taiki-e/portable-atomic/compare/v1.8.0...v1.9.0 +[1.8.0]: https://github.com/taiki-e/portable-atomic/compare/v1.7.0...v1.8.0 +[1.7.0]: https://github.com/taiki-e/portable-atomic/compare/v1.6.0...v1.7.0 +[1.6.0]: https://github.com/taiki-e/portable-atomic/compare/v1.5.1...v1.6.0 +[1.5.1]: https://github.com/taiki-e/portable-atomic/compare/v1.5.0...v1.5.1 +[1.5.0]: https://github.com/taiki-e/portable-atomic/compare/v1.4.3...v1.5.0 +[1.4.3]: https://github.com/taiki-e/portable-atomic/compare/v1.4.2...v1.4.3 +[1.4.2]: https://github.com/taiki-e/portable-atomic/compare/v1.4.1...v1.4.2 +[1.4.1]: https://github.com/taiki-e/portable-atomic/compare/v1.4.0...v1.4.1 +[1.4.0]: https://github.com/taiki-e/portable-atomic/compare/v1.3.3...v1.4.0 +[1.3.3]: https://github.com/taiki-e/portable-atomic/compare/v1.3.2...v1.3.3 +[1.3.2]: https://github.com/taiki-e/portable-atomic/compare/v1.3.1...v1.3.2 +[1.3.1]: https://github.com/taiki-e/portable-atomic/compare/v1.3.0...v1.3.1 +[1.3.0]: https://github.com/taiki-e/portable-atomic/compare/v1.2.0...v1.3.0 +[1.2.0]: https://github.com/taiki-e/portable-atomic/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/taiki-e/portable-atomic/compare/v1.0.1...v1.1.0 +[1.0.1]: https://github.com/taiki-e/portable-atomic/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/taiki-e/portable-atomic/compare/v0.3.19...v1.0.0 +[0.3.20]: https://github.com/taiki-e/portable-atomic/compare/v0.3.19...v0.3.20 +[0.3.19]: https://github.com/taiki-e/portable-atomic/compare/v0.3.18...v0.3.19 +[0.3.18]: https://github.com/taiki-e/portable-atomic/compare/v0.3.17...v0.3.18 +[0.3.17]: https://github.com/taiki-e/portable-atomic/compare/v0.3.16...v0.3.17 +[0.3.16]: https://github.com/taiki-e/portable-atomic/compare/v0.3.15...v0.3.16 +[0.3.15]: https://github.com/taiki-e/portable-atomic/compare/v0.3.14...v0.3.15 +[0.3.14]: https://github.com/taiki-e/portable-atomic/compare/v0.3.13...v0.3.14 +[0.3.13]: https://github.com/taiki-e/portable-atomic/compare/v0.3.12...v0.3.13 +[0.3.12]: https://github.com/taiki-e/portable-atomic/compare/v0.3.11...v0.3.12 +[0.3.11]: https://github.com/taiki-e/portable-atomic/compare/v0.3.10...v0.3.11 +[0.3.10]: https://github.com/taiki-e/portable-atomic/compare/v0.3.9...v0.3.10 +[0.3.9]: https://github.com/taiki-e/portable-atomic/compare/v0.3.8...v0.3.9 +[0.3.8]: https://github.com/taiki-e/portable-atomic/compare/v0.3.7...v0.3.8 +[0.3.7]: https://github.com/taiki-e/portable-atomic/compare/v0.3.6...v0.3.7 +[0.3.6]: https://github.com/taiki-e/portable-atomic/compare/v0.3.5...v0.3.6 +[0.3.5]: https://github.com/taiki-e/portable-atomic/compare/v0.3.4...v0.3.5 +[0.3.4]: https://github.com/taiki-e/portable-atomic/compare/v0.3.3...v0.3.4 +[0.3.3]: https://github.com/taiki-e/portable-atomic/compare/v0.3.2...v0.3.3 +[0.3.2]: https://github.com/taiki-e/portable-atomic/compare/v0.3.1...v0.3.2 +[0.3.1]: https://github.com/taiki-e/portable-atomic/compare/v0.3.0...v0.3.1 +[0.3.0]: https://github.com/taiki-e/portable-atomic/compare/v0.2.1...v0.3.0 +[0.2.1]: https://github.com/taiki-e/portable-atomic/compare/v0.2.0...v0.2.1 +[0.2.0]: https://github.com/taiki-e/portable-atomic/compare/v0.1.4...v0.2.0 +[0.1.4]: https://github.com/taiki-e/portable-atomic/compare/v0.1.3...v0.1.4 +[0.1.3]: https://github.com/taiki-e/portable-atomic/compare/v0.1.2...v0.1.3 +[0.1.2]: https://github.com/taiki-e/portable-atomic/compare/v0.1.1...v0.1.2 +[0.1.1]: https://github.com/taiki-e/portable-atomic/compare/v0.1.0...v0.1.1 +[0.1.0]: https://github.com/taiki-e/portable-atomic/releases/tag/v0.1.0 diff --git a/bitbox02-bt/vendor/portable-atomic/Cargo.toml b/bitbox02-bt/vendor/portable-atomic/Cargo.toml new file mode 100644 index 0000000..ecba86b --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/Cargo.toml @@ -0,0 +1,224 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.34" +name = "portable-atomic" +version = "1.9.0" +build = "build.rs" +exclude = [ + "/.*", + "/tools", + "/target-specs", + "/DEVELOPMENT.md", +] +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = """ +Portable atomic types including support for 128-bit atomics, atomic float, etc. +""" +readme = "README.md" +keywords = ["atomic"] +categories = [ + "concurrency", + "embedded", + "hardware-support", + "no-std", + "no-std::no-alloc", +] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/taiki-e/portable-atomic" + +[package.metadata.cargo_check_external_types] +allowed_external_types = ["serde::*"] + +[package.metadata.docs.rs] +features = [ + "float", + "std", + "serde", + "critical-section", +] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +name = "portable_atomic" +path = "src/lib.rs" +doc-scrape-examples = false + +[dependencies.critical-section] +version = "1" +optional = true + +[dependencies.serde] +version = "1.0.60" +optional = true +default-features = false + +[dev-dependencies.build-context] +version = "0.1" + +[dev-dependencies.crossbeam-utils] +version = "=0.8.16" + +[dev-dependencies.fastrand] +version = "2" + +[dev-dependencies.paste] +version = "1" + +[dev-dependencies.sptr] +version = "0.3" + +[dev-dependencies.static_assertions] +version = "1" + +[features] +default = ["fallback"] +disable-fiq = [] +fallback = [] +float = [] +force-amo = [] +require-cas = [] +s-mode = [] +std = [] +unsafe-assume-single-core = [] + +[lints.clippy] +all = "warn" +as_ptr_cast_mut = "warn" +as_underscore = "warn" +default_union_representation = "warn" +inline_asm_x86_att_syntax = "warn" +pedantic = "warn" +trailing_empty_array = "warn" +transmute_undefined_repr = "warn" +undocumented_unsafe_blocks = "warn" + +[lints.clippy.bool_assert_comparison] +level = "allow" +priority = 1 + +[lints.clippy.borrow_as_ptr] +level = "allow" +priority = 1 + +[lints.clippy.cast_lossless] +level = "allow" +priority = 1 + +[lints.clippy.declare_interior_mutable_const] +level = "allow" +priority = 1 + +[lints.clippy.doc_markdown] +level = "allow" +priority = 1 + +[lints.clippy.float_cmp] +level = "allow" +priority = 1 + +[lints.clippy.incompatible_msrv] +level = "allow" +priority = 1 + +[lints.clippy.lint_groups_priority] +level = "allow" +priority = 1 + +[lints.clippy.manual_assert] +level = "allow" +priority = 1 + +[lints.clippy.manual_range_contains] +level = "allow" +priority = 1 + +[lints.clippy.missing_errors_doc] +level = "allow" +priority = 1 + +[lints.clippy.module_name_repetitions] +level = "allow" +priority = 1 + +[lints.clippy.naive_bytecount] +level = "allow" +priority = 1 + +[lints.clippy.nonminimal_bool] +level = "allow" +priority = 1 + +[lints.clippy.range_plus_one] +level = "allow" +priority = 1 + +[lints.clippy.similar_names] +level = "allow" +priority = 1 + +[lints.clippy.single_match] +level = "allow" +priority = 1 + +[lints.clippy.single_match_else] +level = "allow" +priority = 1 + +[lints.clippy.struct_excessive_bools] +level = "allow" +priority = 1 + +[lints.clippy.struct_field_names] +level = "allow" +priority = 1 + +[lints.clippy.too_many_arguments] +level = "allow" +priority = 1 + +[lints.clippy.too_many_lines] +level = "allow" +priority = 1 + +[lints.clippy.type_complexity] +level = "allow" +priority = 1 + +[lints.clippy.unreadable_literal] +level = "allow" +priority = 1 + +[lints.rust] +deprecated_safe = "warn" +improper_ctypes = "warn" +improper_ctypes_definitions = "warn" +non_ascii_idents = "warn" +rust_2018_idioms = "warn" +single_use_lifetimes = "warn" +unreachable_pub = "warn" + +[lints.rust.unexpected_cfgs] +level = "warn" +priority = 0 +check-cfg = [ + 'cfg(target_arch,values("xtensa"))', + 'cfg(target_feature,values("lse2","lse128","rcpc3"))', + 'cfg(target_feature,values("quadword-atomics"))', + 'cfg(target_pointer_width,values("128"))', + "cfg(portable_atomic_test_outline_atomics_detect_false,qemu,valgrind)", + "cfg(portable_atomic_no_outline_atomics,portable_atomic_outline_atomics)", +] diff --git a/bitbox02-bt/vendor/portable-atomic/LICENSE-APACHE b/bitbox02-bt/vendor/portable-atomic/LICENSE-APACHE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/portable-atomic/LICENSE-MIT b/bitbox02-bt/vendor/portable-atomic/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/portable-atomic/README.md b/bitbox02-bt/vendor/portable-atomic/README.md new file mode 100644 index 0000000..81b44c7 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/README.md @@ -0,0 +1,202 @@ +# portable-atomic + +[![crates.io](https://img.shields.io/crates/v/portable-atomic?style=flat-square&logo=rust)](https://crates.io/crates/portable-atomic) +[![docs.rs](https://img.shields.io/badge/docs.rs-portable--atomic-blue?style=flat-square&logo=docs.rs)](https://docs.rs/portable-atomic) +[![license](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue?style=flat-square)](#license) +[![msrv](https://img.shields.io/badge/msrv-1.34-blue?style=flat-square&logo=rust)](https://www.rust-lang.org) +[![github actions](https://img.shields.io/github/actions/workflow/status/taiki-e/portable-atomic/ci.yml?branch=main&style=flat-square&logo=github)](https://github.com/taiki-e/portable-atomic/actions) +[![cirrus ci](https://img.shields.io/cirrus/github/taiki-e/portable-atomic/main?style=flat-square&logo=cirrusci)](https://cirrus-ci.com/github/taiki-e/portable-atomic) + + +Portable atomic types including support for 128-bit atomics, atomic float, etc. + +- Provide all atomic integer types (`Atomic{I,U}{8,16,32,64}`) for all targets that can use atomic CAS. (i.e., all targets that can use `std`, and most no-std targets) +- Provide `AtomicI128` and `AtomicU128`. +- Provide `AtomicF32` and `AtomicF64`. ([optional, requires the `float` feature](#optional-features-float)) +- Provide atomic load/store for targets where atomic is not available at all in the standard library. (RISC-V without A-extension, MSP430, AVR) +- Provide atomic CAS for targets where atomic CAS is not available in the standard library. (thumbv6m, pre-v6 Arm, RISC-V without A-extension, MSP430, AVR, Xtensa, etc.) (always enabled for MSP430 and AVR, [optional](#optional-features-critical-section) otherwise) +- Provide stable equivalents of the standard library's atomic types' unstable APIs, such as [`AtomicPtr::fetch_*`](https://github.com/rust-lang/rust/issues/99108). +- Make features that require newer compilers, such as [`fetch_{max,min}`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.fetch_max), [`fetch_update`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.fetch_update), [`as_ptr`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.as_ptr), [`from_ptr`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.from_ptr), [`AtomicBool::fetch_not`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.fetch_not) and [stronger CAS failure ordering](https://github.com/rust-lang/rust/pull/98383) available on Rust 1.34+. +- Provide workaround for bugs in the standard library's atomic-related APIs, such as [rust-lang/rust#100650], `fence`/`compiler_fence` on MSP430 that cause LLVM error, etc. + + + +portable-atomic version of `std::sync::Arc` is provided by the [portable-atomic-util](https://github.com/taiki-e/portable-atomic/tree/HEAD/portable-atomic-util) crate. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +portable-atomic = "1" +``` + +The default features are mainly for users who use atomics larger than the pointer width. +If you don't need them, disabling the default features may reduce code size and compile time slightly. + +```toml +[dependencies] +portable-atomic = { version = "1", default-features = false } +``` + +If your crate supports no-std environment and requires atomic CAS, enabling the `require-cas` feature will allow the `portable-atomic` to display a [helpful error message](https://github.com/taiki-e/portable-atomic/pull/100) to users on targets requiring additional action on the user side to provide atomic CAS. + +```toml +[dependencies] +portable-atomic = { version = "1.3", default-features = false, features = ["require-cas"] } +``` + +## 128-bit atomics support + +Native 128-bit atomic operations are available on x86_64 (Rust 1.59+), AArch64 (Rust 1.59+), riscv64 (Rust 1.82+), powerpc64 (nightly only), s390x (nightly only), and Arm64EC (nightly only), otherwise the fallback implementation is used. + +On x86_64, even if `cmpxchg16b` is not available at compile-time (note: `cmpxchg16b` target feature is enabled by default only on Apple and Windows (except Windows 7) targets), run-time detection checks whether `cmpxchg16b` is available. If `cmpxchg16b` is not available at either compile-time or run-time detection, the fallback implementation is used. See also [`portable_atomic_no_outline_atomics`](#optional-cfg-no-outline-atomics) cfg. + +They are usually implemented using inline assembly, and when using Miri or ThreadSanitizer that do not support inline assembly, core intrinsics are used instead of inline assembly if possible. + +See the [`atomic128` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/atomic128/README.md) for details. + +## Optional features + +- **`fallback`** *(enabled by default)*
+ Enable fallback implementations. + + Disabling this allows only atomic types for which the platform natively supports atomic operations. + +-
**`float`**
+ Provide `AtomicF{32,64}`. + + Note that most of `fetch_*` operations of atomic floats are implemented using CAS loops, which can be slower than equivalent operations of atomic integers. ([GPU targets have atomic instructions for float, so we plan to use these instructions for GPU targets in the future.](https://github.com/taiki-e/portable-atomic/issues/34)) + +- **`std`**
+ Use `std`. + +- **`require-cas`**
+ Emit compile error if atomic CAS is not available. See [Usage](#usage) section and [#100](https://github.com/taiki-e/portable-atomic/pull/100) for more. + +- **`serde`**
+ Implement `serde::{Serialize,Deserialize}` for atomic types. + + Note: + - The MSRV when this feature is enabled depends on the MSRV of [serde]. + +- **`critical-section`**
+ When this feature is enabled, this crate uses [critical-section] to provide atomic CAS for targets where + it is not natively available. When enabling it, you should provide a suitable critical section implementation + for the current target, see the [critical-section] documentation for details on how to do so. + + `critical-section` support is useful to get atomic CAS when the [`unsafe-assume-single-core` feature](#optional-features-unsafe-assume-single-core) can't be used, + such as multi-core targets, unprivileged code running under some RTOS, or environments where disabling interrupts + needs extra care due to e.g. real-time requirements. + + Note that with the `critical-section` feature, critical sections are taken for all atomic operations, while with + [`unsafe-assume-single-core` feature](#optional-features-unsafe-assume-single-core) some operations don't require disabling interrupts (loads and stores, but + additionally on MSP430 `add`, `sub`, `and`, `or`, `xor`, `not`). Therefore, for better performance, if + all the `critical-section` implementation for your target does is disable interrupts, prefer using + `unsafe-assume-single-core` feature instead. + + Note: + - The MSRV when this feature is enabled depends on the MSRV of [critical-section]. + - It is usually *not* recommended to always enable this feature in dependencies of the library. + + Enabling this feature will prevent the end user from having the chance to take advantage of other (potentially) efficient implementations ([Implementations provided by `unsafe-assume-single-core` feature, default implementations on MSP430 and AVR](#optional-features-unsafe-assume-single-core), implementation proposed in [#60], etc. Other systems may also be supported in the future). + + The recommended approach for libraries is to leave it up to the end user whether or not to enable this feature. (However, it may make sense to enable this feature by default for libraries specific to a platform where other implementations are known not to work.) + + As an example, the end-user's `Cargo.toml` that uses a crate that provides a critical-section implementation and a crate that depends on portable-atomic as an option would be expected to look like this: + + ```toml + [dependencies] + portable-atomic = { version = "1", default-features = false, features = ["critical-section"] } + crate-provides-critical-section-impl = "..." + crate-uses-portable-atomic-as-feature = { version = "...", features = ["portable-atomic"] } + ``` + +- **`unsafe-assume-single-core`**
+ Assume that the target is single-core. + When this feature is enabled, this crate provides atomic CAS for targets where atomic CAS is not available in the standard library by disabling interrupts. + + This feature is `unsafe`, and note the following safety requirements: + - Enabling this feature for multi-core systems is always **unsound**. + - This uses privileged instructions to disable interrupts, so it usually doesn't work on unprivileged mode. + Enabling this feature in an environment where privileged instructions are not available, or if the instructions used are not sufficient to disable interrupts in the system, it is also usually considered **unsound**, although the details are system-dependent. + + The following are known cases: + - On pre-v6 Arm, this disables only IRQs by default. For many systems (e.g., GBA) this is enough. If the system need to disable both IRQs and FIQs, you need to enable the `disable-fiq` feature together. + - On RISC-V without A-extension, this generates code for machine-mode (M-mode) by default. If you enable the `s-mode` together, this generates code for supervisor-mode (S-mode). In particular, `qemu-system-riscv*` uses [OpenSBI](https://github.com/riscv-software-src/opensbi) as the default firmware. + + See also the [`interrupt` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/interrupt/README.md). + + Consider using the [`critical-section` feature](#optional-features-critical-section) for systems that cannot use this feature. + + It is **very strongly discouraged** to enable this feature in libraries that depend on `portable-atomic`. The recommended approach for libraries is to leave it up to the end user whether or not to enable this feature. (However, it may make sense to enable this feature by default for libraries specific to a platform where it is guaranteed to always be sound, for example in a hardware abstraction layer targeting a single-core chip.) + + Armv6-M (thumbv6m), pre-v6 Arm (e.g., thumbv4t, thumbv5te), RISC-V without A-extension, and Xtensa are currently supported. + + Since all MSP430 and AVR are single-core, we always provide atomic CAS for them without this feature. + + Enabling this feature for targets that have atomic CAS will result in a compile error. + + Feel free to submit an issue if your target is not supported yet. + +## Optional cfg + +One of the ways to enable cfg is to set [rustflags in the cargo config](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerustflags): + +```toml +# .cargo/config.toml +[target.] +rustflags = ["--cfg", "portable_atomic_no_outline_atomics"] +``` + +Or set environment variable: + +```sh +RUSTFLAGS="--cfg portable_atomic_no_outline_atomics" cargo ... +``` + +- **`--cfg portable_atomic_unsafe_assume_single_core`**
+ Since 1.4.0, this cfg is an alias of [`unsafe-assume-single-core` feature](#optional-features-unsafe-assume-single-core). + + Originally, we were providing these as cfgs instead of features, but based on a strong request from the embedded ecosystem, we have agreed to provide them as features as well. See [#94](https://github.com/taiki-e/portable-atomic/pull/94) for more. + +- **`--cfg portable_atomic_no_outline_atomics`**
+ Disable dynamic dispatching by run-time CPU feature detection. + + If dynamic dispatching by run-time CPU feature detection is enabled, it allows maintaining support for older CPUs while using features that are not supported on older CPUs, such as CMPXCHG16B (x86_64) and FEAT_LSE/FEAT_LSE2 (AArch64). + + Note: + - Dynamic detection is currently only enabled in Rust 1.59+ for x86_64 and AArch64, Rust 1.82+ for RISC-V (disabled by default), nightly only for powerpc64 (disabled by default) and Arm64EC, otherwise it works the same as when this cfg is set. + - If the required target features are enabled at compile-time, the atomic operations are inlined. + - This is compatible with no-std (as with all features except `std`). + - On some targets, run-time detection is disabled by default mainly for compatibility with older versions of operating systems or incomplete build environments, and can be enabled by `--cfg portable_atomic_outline_atomics`. (When both cfg are enabled, `*_no_*` cfg is preferred.) + - Some AArch64 targets enable LLVM's `outline-atomics` target feature by default, so if you set this cfg, you may want to disable that as well. (portable-atomic's outline-atomics does not depend on the compiler-rt symbols, so even if you need to disable LLVM's outline-atomics, you may not need to disable portable-atomic's outline-atomics.) + + See also the [`atomic128` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/atomic128/README.md). + +## Related Projects + +- [atomic-maybe-uninit]: Atomic operations on potentially uninitialized integers. +- [atomic-memcpy]: Byte-wise atomic memcpy. + +[#60]: https://github.com/taiki-e/portable-atomic/issues/60 +[atomic-maybe-uninit]: https://github.com/taiki-e/atomic-maybe-uninit +[atomic-memcpy]: https://github.com/taiki-e/atomic-memcpy +[critical-section]: https://github.com/rust-embedded/critical-section +[rust-lang/rust#100650]: https://github.com/rust-lang/rust/issues/100650 +[serde]: https://github.com/serde-rs/serde + + + +## License + +Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or +[MIT license](LICENSE-MIT) at your option. + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. diff --git a/bitbox02-bt/vendor/portable-atomic/build.rs b/bitbox02-bt/vendor/portable-atomic/build.rs new file mode 100644 index 0000000..d8ed4da --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/build.rs @@ -0,0 +1,514 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// The rustc-cfg emitted by the build script are *not* public API. + +#![allow(clippy::match_same_arms)] // https://github.com/rust-lang/rust-clippy/issues/12044 + +#[path = "version.rs"] +mod version; +use version::{rustc_version, Version}; + +use std::{env, str}; + +include!("no_atomic.rs"); + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=no_atomic.rs"); + println!("cargo:rerun-if-changed=version.rs"); + + #[cfg(feature = "unsafe-assume-single-core")] + println!("cargo:rustc-cfg=portable_atomic_unsafe_assume_single_core"); + #[cfg(feature = "s-mode")] + println!("cargo:rustc-cfg=portable_atomic_s_mode"); + #[cfg(feature = "force-amo")] + println!("cargo:rustc-cfg=portable_atomic_force_amo"); + #[cfg(feature = "disable-fiq")] + println!("cargo:rustc-cfg=portable_atomic_disable_fiq"); + + let target = &*env::var("TARGET").expect("TARGET not set"); + let target_arch = &*env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH not set"); + let target_os = &*env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS not set"); + + let version = match rustc_version() { + Some(version) => version, + None => { + if env::var_os("PORTABLE_ATOMIC_DENY_WARNINGS").is_some() { + panic!("unable to determine rustc version") + } + println!( + "cargo:warning={}: unable to determine rustc version; assuming latest stable rustc (1.{})", + env!("CARGO_PKG_NAME"), + Version::LATEST.minor + ); + Version::LATEST + } + }; + + if version.minor >= 80 { + println!( + r#"cargo:rustc-check-cfg=cfg(target_feature,values("zaamo","zabha","experimental-zacas","fast-serialization","load-store-on-cond","distinct-ops","miscellaneous-extensions-3"))"# + ); + + // Custom cfgs set by build script. Not public API. + // grep -F 'cargo:rustc-cfg=' build.rs | grep -Ev '^ *//' | sed -E 's/^.*cargo:rustc-cfg=//; s/(=\\)?".*$//' | LC_ALL=C sort -u | tr '\n' ',' | sed -E 's/,$/\n/' + println!( + "cargo:rustc-check-cfg=cfg(portable_atomic_disable_fiq,portable_atomic_force_amo,portable_atomic_ll_sc_rmw,portable_atomic_pre_llvm_15,portable_atomic_pre_llvm_16,portable_atomic_pre_llvm_18,portable_atomic_pre_llvm_19,portable_atomic_new_atomic_intrinsics,portable_atomic_no_asm,portable_atomic_no_asm_maybe_uninit,portable_atomic_no_atomic_64,portable_atomic_no_atomic_cas,portable_atomic_no_atomic_load_store,portable_atomic_no_atomic_min_max,portable_atomic_no_cfg_target_has_atomic,portable_atomic_no_cmpxchg16b_intrinsic,portable_atomic_no_cmpxchg16b_target_feature,portable_atomic_no_const_raw_ptr_deref,portable_atomic_no_const_transmute,portable_atomic_no_core_unwind_safe,portable_atomic_no_diagnostic_namespace,portable_atomic_no_stronger_failure_ordering,portable_atomic_no_track_caller,portable_atomic_no_unsafe_op_in_unsafe_fn,portable_atomic_s_mode,portable_atomic_sanitize_thread,portable_atomic_target_feature,portable_atomic_unsafe_assume_single_core,portable_atomic_unstable_asm,portable_atomic_unstable_asm_experimental_arch,portable_atomic_unstable_cfg_target_has_atomic,portable_atomic_unstable_isa_attribute)" + ); + // TODO: handle multi-line target_feature_fallback + // grep -F 'target_feature_fallback("' build.rs | grep -Ev '^ *//' | sed -E 's/^.*target_feature_fallback\(//; s/",.*$/"/' | LC_ALL=C sort -u | tr '\n' ',' | sed -E 's/,$/\n/' + println!( + r#"cargo:rustc-check-cfg=cfg(portable_atomic_target_feature,values("cmpxchg16b","distinct-ops","experimental-zacas","fast-serialization","load-store-on-cond","lse","lse128","lse2","mclass","miscellaneous-extensions-3","quadword-atomics","rcpc3","v6","zaamo","zabha"))"# + ); + } + + // https://github.com/rust-lang/rust/pull/123745 (includes https://github.com/rust-lang/cargo/pull/13560) merged in Rust 1.79 (nightly-2024-04-11). + if !version.probe(79, 2024, 4, 10) { + // HACK: If --target is specified, rustflags is not applied to the build + // script itself, so the build script will not be recompiled when rustflags + // is changed. That in itself is not a problem, but the old Cargo does + // not rerun the build script as well, which can be problematic. + // https://github.com/rust-lang/cargo/issues/13003 + // This problem has been fixed in 1.79 so only older versions need a workaround. + println!("cargo:rerun-if-env-changed=CARGO_ENCODED_RUSTFLAGS"); + println!("cargo:rerun-if-env-changed=RUSTFLAGS"); + println!("cargo:rerun-if-env-changed=CARGO_BUILD_RUSTFLAGS"); + let mut target_upper = target.replace(|c: char| c == '-' || c == '.', "_"); + target_upper.make_ascii_uppercase(); + println!("cargo:rerun-if-env-changed=CARGO_TARGET_{}_RUSTFLAGS", target_upper); + } + + // Note that cfgs are `no_`*, not `has_*`. This allows treating as the latest + // stable rustc is used when the build script doesn't run. This is useful + // for non-cargo build systems that don't run the build script. + + // atomic_min_max stabilized in Rust 1.45 (nightly-2020-05-30): https://github.com/rust-lang/rust/pull/72324 + if !version.probe(45, 2020, 5, 29) { + println!("cargo:rustc-cfg=portable_atomic_no_atomic_min_max"); + } + // track_caller stabilized in Rust 1.46 (nightly-2020-07-02): https://github.com/rust-lang/rust/pull/72445 + if !version.probe(46, 2020, 7, 1) { + println!("cargo:rustc-cfg=portable_atomic_no_track_caller"); + } + // unsafe_op_in_unsafe_fn stabilized in Rust 1.52 (nightly-2021-03-11): https://github.com/rust-lang/rust/pull/79208 + if !version.probe(52, 2021, 3, 10) { + println!("cargo:rustc-cfg=portable_atomic_no_unsafe_op_in_unsafe_fn"); + } + // const_transmute stabilized in Rust 1.56 (nightly-2021-07-29): https://github.com/rust-lang/rust/pull/85769 + if !version.probe(56, 2021, 7, 28) { + println!("cargo:rustc-cfg=portable_atomic_no_const_transmute"); + } + // https://github.com/rust-lang/rust/pull/84662 merged in Rust 1.56 (nightly-2021-08-02). + if !version.probe(56, 2021, 8, 1) { + println!("cargo:rustc-cfg=portable_atomic_no_core_unwind_safe"); + } + // const_raw_ptr_deref stabilized in Rust 1.58 (nightly-2021-11-15): https://github.com/rust-lang/rust/pull/89551 + if !version.probe(58, 2021, 11, 14) { + println!("cargo:rustc-cfg=portable_atomic_no_const_raw_ptr_deref"); + } + // https://github.com/rust-lang/rust/pull/98383 merged in Rust 1.64 (nightly-2022-07-19). + if !version.probe(64, 2022, 7, 18) { + println!("cargo:rustc-cfg=portable_atomic_no_stronger_failure_ordering"); + } + // https://github.com/rust-lang/rust/pull/114790 merged in nightly-2023-08-24 + if !version.probe(74, 2023, 8, 23) { + println!("cargo:rustc-cfg=portable_atomic_no_asm_maybe_uninit"); + } + // #[diagnostic] stabilized in Rust 1.78 (nightly-2024-03-09): https://github.com/rust-lang/rust/pull/119888 + if !version.probe(78, 2024, 3, 8) { + println!("cargo:rustc-cfg=portable_atomic_no_diagnostic_namespace"); + } + + // asm stabilized in Rust 1.59 (nightly-2021-12-16): https://github.com/rust-lang/rust/pull/91728 + let no_asm = !version.probe(59, 2021, 12, 15); + if no_asm { + if version.nightly + && version.probe(46, 2020, 6, 20) + && ((target_arch != "x86" && target_arch != "x86_64") || version.llvm >= 10) + && is_allowed_feature("asm") + { + // This feature was added in Rust 1.45 (nightly-2020-05-20), but + // concat! in asm! requires Rust 1.46 (nightly-2020-06-21). + // x86 intel syntax requires LLVM 10 (since Rust 1.53, the minimum + // external LLVM version is 10+: https://github.com/rust-lang/rust/pull/83387). + // The part of this feature we use has not been changed since nightly-2020-06-21 + // until it was stabilized in nightly-2021-12-16, so it can be safely enabled in + // nightly, which is older than nightly-2021-12-16. + println!("cargo:rustc-cfg=portable_atomic_unstable_asm"); + } + println!("cargo:rustc-cfg=portable_atomic_no_asm"); + } + + // feature(cfg_target_has_atomic) stabilized in Rust 1.60 (nightly-2022-02-11): https://github.com/rust-lang/rust/pull/93824 + if !version.probe(60, 2022, 2, 10) { + if version.nightly + && version.probe(40, 2019, 10, 13) + && is_allowed_feature("cfg_target_has_atomic") + { + // This feature has not been changed since the change in Rust 1.40 (nightly-2019-10-14) + // until it was stabilized in nightly-2022-02-11, so it can be safely enabled in + // nightly, which is older than nightly-2022-02-11. + println!("cargo:rustc-cfg=portable_atomic_unstable_cfg_target_has_atomic"); + } else { + println!("cargo:rustc-cfg=portable_atomic_no_cfg_target_has_atomic"); + let target = &*convert_custom_linux_target(target); + if NO_ATOMIC_CAS.contains(&target) { + println!("cargo:rustc-cfg=portable_atomic_no_atomic_cas"); + } + if NO_ATOMIC_64.contains(&target) { + println!("cargo:rustc-cfg=portable_atomic_no_atomic_64"); + } else { + // Otherwise, assuming `"max-atomic-width" == 64` or `"max-atomic-width" == 128`. + } + } + } + // We don't need to use convert_custom_linux_target here because all linux targets have atomics. + if NO_ATOMIC.contains(&target) { + println!("cargo:rustc-cfg=portable_atomic_no_atomic_load_store"); + } + + if version.llvm < 19 { + println!("cargo:rustc-cfg=portable_atomic_pre_llvm_19"); + if version.llvm < 18 { + println!("cargo:rustc-cfg=portable_atomic_pre_llvm_18"); + if version.llvm < 16 { + println!("cargo:rustc-cfg=portable_atomic_pre_llvm_16"); + if version.llvm < 15 { + println!("cargo:rustc-cfg=portable_atomic_pre_llvm_15"); + } + } + } + } + + if version.nightly { + // `cfg(sanitize = "..")` is not stabilized. + let sanitize = env::var("CARGO_CFG_SANITIZE").unwrap_or_default(); + if sanitize.contains("thread") { + // Most kinds of sanitizers are not compatible with asm + // (https://github.com/google/sanitizers/issues/192), + // but it seems that ThreadSanitizer is the only one that can cause + // false positives in our code. + println!("cargo:rustc-cfg=portable_atomic_sanitize_thread"); + } + + // https://github.com/rust-lang/rust/pull/93868 merged in Rust 1.60 (nightly-2022-02-13). + // https://github.com/rust-lang/rust/pull/111331 merged in Rust 1.71 (nightly-2023-05-09). + if !no_asm + && (target_arch == "powerpc64" && version.probe(60, 2022, 2, 12) + || target_arch == "s390x" && version.probe(71, 2023, 5, 8) + || target_arch == "arm64ec") + && is_allowed_feature("asm_experimental_arch") + { + println!("cargo:rustc-cfg=portable_atomic_unstable_asm_experimental_arch"); + } + } + + match target_arch { + "x86_64" => { + // cmpxchg16b_target_feature stabilized in Rust 1.69 (nightly-2023-03-01): https://github.com/rust-lang/rust/pull/106774 + if !version.probe(69, 2023, 2, 28) { + println!("cargo:rustc-cfg=portable_atomic_no_cmpxchg16b_target_feature"); + } + // For Miri and ThreadSanitizer. + // https://github.com/rust-lang/rust/pull/109359 (includes https://github.com/rust-lang/stdarch/pull/1358) merged in Rust 1.70 (nightly-2023-03-24). + if version.nightly && !version.probe(70, 2023, 3, 23) { + println!("cargo:rustc-cfg=portable_atomic_no_cmpxchg16b_intrinsic"); + } + + // cmpxchg16b_target_feature stabilized in Rust 1.69. + if needs_target_feature_fallback(&version, Some(69)) { + // x86_64 Apple targets always support CMPXCHG16B: + // https://github.com/rust-lang/rust/blob/1.68.0/compiler/rustc_target/src/spec/x86_64_apple_darwin.rs#L8 + // https://github.com/rust-lang/rust/blob/1.68.0/compiler/rustc_target/src/spec/apple_base.rs#L69-L70 + // (Since Rust 1.78, Windows (except Windows 7) targets also enable CMPXCHG16B, but + // this branch is only used on pre-1.69 that cmpxchg16b_target_feature is unstable.) + // Script to get builtin targets that support CMPXCHG16B by default: + // $ (for target in $(rustc --print target-list | grep -E '^x86_64'); do rustc --print cfg --target "${target}" | grep -Fq '"cmpxchg16b"' && printf '%s\n' "${target}"; done) + let is_apple = env::var("CARGO_CFG_TARGET_VENDOR").unwrap_or_default() == "apple"; + let has_cmpxchg16b = is_apple; + // LLVM recognizes this also as cx16 target feature: https://godbolt.org/z/KM3jz616j + // However, it is unlikely that rustc will support that name, so we ignore it. + target_feature_fallback("cmpxchg16b", has_cmpxchg16b); + } + } + "aarch64" | "arm64ec" => { + // For Miri and ThreadSanitizer. + // https://github.com/rust-lang/rust/pull/97423 merged in Rust 1.64 (nightly-2022-06-30). + if version.nightly && version.probe(64, 2022, 6, 29) { + println!("cargo:rustc-cfg=portable_atomic_new_atomic_intrinsics"); + } + + // target_feature "lse2"/"lse128"/"rcpc3" is unstable and available on rustc side since nightly-2024-08-30: https://github.com/rust-lang/rust/pull/128192 + if !version.probe(82, 2024, 8, 29) || needs_target_feature_fallback(&version, None) { + // FEAT_LSE2 doesn't imply FEAT_LSE. FEAT_LSE128 implies FEAT_LSE but not FEAT_LSE2. + // AArch64 macOS always supports FEAT_LSE and FEAT_LSE2 because M1 is Armv8.4 with all features of Armv8.5 except FEAT_BTI: + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/AArch64/AArch64Processors.td#L1203 + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/AArch64/AArch64Processors.td#L865 + // Script to get builtin targets that support FEAT_LSE/FEAT_LSE2 by default: + // $ (for target in $(rustc --print target-list | grep -E '^aarch64|^arm64'); do rustc --print cfg --target "${target}" | grep -Fq '"lse"' && printf '%s\n' "${target}"; done) + // $ (for target in $(rustc --print target-list | grep -E '^aarch64|^arm64'); do rustc --print cfg --target "${target}" | grep -Fq '"lse2"' && printf '%s\n' "${target}"; done) + let is_macos = target_os == "macos"; + let mut has_lse = is_macos; + target_feature_fallback("lse2", is_macos); + has_lse |= target_feature_fallback("lse128", false); + target_feature_fallback("rcpc3", false); + // aarch64_target_feature stabilized in Rust 1.61. + if needs_target_feature_fallback(&version, Some(61)) { + target_feature_fallback("lse", has_lse); + } + } + + // As of Apple M1/M1 Pro, on Apple hardware, CAS-loop-based RMW is much slower than + // LL/SC-loop-based RMW: https://github.com/taiki-e/portable-atomic/pull/89 + let is_apple = env::var("CARGO_CFG_TARGET_VENDOR").unwrap_or_default() == "apple"; + if is_apple || target_cpu().map_or(false, |cpu| cpu.starts_with("apple-")) { + println!("cargo:rustc-cfg=portable_atomic_ll_sc_rmw"); + } + } + "arm" => { + // For non-Linux/Android pre-v6 Arm (tier 3) with unsafe_assume_single_core enabled. + // feature(isa_attribute) stabilized in Rust 1.67 (nightly-2022-11-06): https://github.com/rust-lang/rust/pull/102458 + if version.nightly && !version.probe(67, 2022, 11, 5) { + println!("cargo:rustc-cfg=portable_atomic_unstable_isa_attribute"); + } + + if needs_target_feature_fallback(&version, None) { + // #[cfg(target_feature = "v7")] and others don't work on stable. + // armv7-unknown-linux-gnueabihf + // ^^ + let mut subarch = + strip_prefix(target, "arm").or_else(|| strip_prefix(target, "thumb")).unwrap(); + subarch = strip_prefix(subarch, "eb").unwrap_or(subarch); // ignore endianness + subarch = subarch.split('-').next().unwrap(); // ignore vender/os/env + subarch = subarch.split('.').next().unwrap(); // ignore .base/.main suffix + let mut known = true; + // See https://github.com/taiki-e/atomic-maybe-uninit/blob/HEAD/build.rs for details + let mut mclass = false; + match subarch { + "v7" | "v7a" | "v7neon" | "v7s" | "v7k" | "v8" | "v8a" | "v9" | "v9a" => {} // aclass + "v7r" | "v8r" | "v9r" => {} // rclass + "v6m" | "v7em" | "v7m" | "v8m" => mclass = true, + // arm-linux-androideabi is v5te + // https://github.com/rust-lang/rust/blob/1.80.0/compiler/rustc_target/src/spec/targets/arm_linux_androideabi.rs#L18 + _ if target == "arm-linux-androideabi" => subarch = "v5te", + // armeb-unknown-linux-gnueabi is v8 & aclass + // https://github.com/rust-lang/rust/blob/1.80.0/compiler/rustc_target/src/spec/targets/armeb_unknown_linux_gnueabi.rs#L18 + _ if target == "armeb-unknown-linux-gnueabi" => subarch = "v8", + // Legacy Arm architectures (pre-v7 except v6m) don't have *class target feature. + "" => subarch = "v6", + "v4t" | "v5te" | "v6" | "v6k" => {} + _ => { + known = false; + if env::var_os("PORTABLE_ATOMIC_DENY_WARNINGS").is_some() { + panic!("unrecognized Arm subarch: {}", target) + } + println!( + "cargo:warning={}: unrecognized Arm subarch: {}", + env!("CARGO_PKG_NAME"), + target + ); + } + } + let v6 = known + && (subarch.starts_with("v6") + || subarch.starts_with("v7") + || subarch.starts_with("v8") + || subarch.starts_with("v9")); + target_feature_fallback("v6", v6); + target_feature_fallback("mclass", mclass); + } + } + "riscv32" | "riscv64" => { + // As of rustc 1.80, target_feature "zaamo"/"zabha"/"zacas" is not available on rustc side: + // https://github.com/rust-lang/rust/blob/1.80.0/compiler/rustc_target/src/target_features.rs#L273 + // zabha and zacas imply zaamo in GCC, but do not in LLVM (but enabling them without zaamo is not allowed). + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/TargetParser/RISCVISAInfo.cpp#L772-L778 + // https://github.com/gcc-mirror/gcc/blob/08693e29ec186fd7941d0b73d4d466388971fe2f/gcc/config/riscv/arch-canonicalize#L45-L46 + if version.llvm >= 19 { + // amo*.{b,h} + // available since LLVM 19 https://github.com/llvm/llvm-project/commit/89f87c387627150d342722b79c78cea2311cddf7 / https://github.com/llvm/llvm-project/commit/6b7444964a8d028989beee554a1f5c61d16a1cac + target_feature_fallback("zabha", false); + } + if version.llvm == 19 { + // amocas.{w,d,q} (and amocas.{b,h} if zabha is also available) + // available as experimental since LLVM 17 https://github.com/llvm/llvm-project/commit/29f630a1ddcbb03caa31b5002f0cbc105ff3a869 + // attempted to make non-experimental in LLVM 19 https://github.com/llvm/llvm-project/commit/95aab69c109adf29e183090c25dc95c773215746 + // but reverted in https://github.com/llvm/llvm-project/commit/70e7d26e560173c8b9db4c75ab4a3004cd5f021a + // check == 19 instead of range 17..=19 because it is more experimental in LLVM 17/18. + // check == 19 instead of >= 19 because "experimental-zacas" feature + // may no longer exist when it is marked as non-experimental in LLVM 20. + target_feature_fallback("experimental-zacas", false); + } + // amo*.{w,d} + target_feature_fallback("zaamo", false); + } + "powerpc64" => { + // target_feature "quadword-atomics" is unstable and available on rustc side since nightly-2024-09-28: https://github.com/rust-lang/rust/pull/130873 + if !version.probe(83, 2024, 9, 27) || needs_target_feature_fallback(&version, None) { + let target_endian = + env::var("CARGO_CFG_TARGET_ENDIAN").expect("CARGO_CFG_TARGET_ENDIAN not set"); + // powerpc64le is pwr8+ by default https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/PowerPC/PPC.td#L702 + // See also https://github.com/rust-lang/rust/issues/59932 + let mut has_pwr8_features = target_endian == "little"; + // https://github.com/llvm/llvm-project/commit/549e118e93c666914a1045fde38a2cac33e1e445 + if let Some(cpu) = &target_cpu() { + if let Some(mut cpu_version) = strip_prefix(cpu, "pwr") { + cpu_version = strip_suffix(cpu_version, "x").unwrap_or(cpu_version); // for pwr5x and pwr6x + if let Ok(cpu_version) = cpu_version.parse::() { + has_pwr8_features = cpu_version >= 8; + } + } else { + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/PowerPC/PPC.td#L702 + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/PowerPC/PPC.td#L483 + // On the minimum external LLVM version of the oldest rustc version which we can use asm_experimental_arch + // on this target (see CI config for more), "future" is based on pwr10 features. + // https://github.com/llvm/llvm-project/blob/llvmorg-12.0.0/llvm/lib/Target/PowerPC/PPC.td#L370 + has_pwr8_features = cpu == "ppc64le" || cpu == "future"; + } + } + // lqarx and stqcx. + target_feature_fallback("quadword-atomics", has_pwr8_features); + } + } + "s390x" => { + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/SystemZ/SystemZFeatures.td + let mut arch9_features = false; // z196+ + let mut arch13_features = false; // z15+ + if let Some(cpu) = target_cpu() { + // LLVM and GCC recognize the same names: + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/SystemZ/SystemZProcessors.td + // https://github.com/gcc-mirror/gcc/blob/releases/gcc-14.2.0/gcc/config/s390/s390.opt#L58-L125 + match &*cpu { + "arch9" | "z196" | "arch10" | "zEC12" | "arch11" | "z13" | "arch12" | "z14" => { + arch9_features = true; + } + "arch13" | "z15" | "arch14" | "z16" => { + arch9_features = true; + arch13_features = true; + } + _ => {} + } + } + // As of rustc 1.80, target_feature "fast-serialization"/"load-store-on-cond"/"distinct-ops"/"miscellaneous-extensions-3" is not available on rustc side: + // https://github.com/rust-lang/rust/blob/1.80.0/compiler/rustc_target/src/target_features.rs + // bcr 14,0 + target_feature_fallback("fast-serialization", arch9_features); + // {l,st}oc{,g}{,r} + target_feature_fallback("load-store-on-cond", arch9_features); + // {al,sl,n,o,x}{,g}rk + target_feature_fallback("distinct-ops", arch9_features); + // nand (nnr{,g}k), select (sel{,g}r), etc. + target_feature_fallback("miscellaneous-extensions-3", arch13_features); + } + _ => {} + } +} + +// HACK: Currently, it seems that the only way to handle unstable target +// features on the stable is to parse the `-C target-feature` in RUSTFLAGS. +// +// - #[cfg(target_feature = "unstable_target_feature")] doesn't work on stable. +// - CARGO_CFG_TARGET_FEATURE excludes unstable target features on stable. +// +// As mentioned in the [RFC2045], unstable target features are also passed to LLVM +// (e.g., https://godbolt.org/z/4rr7rMcfG), so this hack works properly on stable. +// +// [RFC2045]: https://rust-lang.github.io/rfcs/2045-target-feature.html#backend-compilation-options +fn needs_target_feature_fallback(version: &Version, stable: Option) -> bool { + match stable { + // In these cases, cfg(target_feature = "...") would work, so skip emitting our own fallback target_feature cfg. + _ if version.nightly => false, + Some(stabilized) if version.minor >= stabilized => false, + _ => true, + } +} +fn target_feature_fallback(name: &str, mut has_target_feature: bool) -> bool { + if let Some(rustflags) = env::var_os("CARGO_ENCODED_RUSTFLAGS") { + for mut flag in rustflags.to_string_lossy().split('\x1f') { + flag = strip_prefix(flag, "-C").unwrap_or(flag); + if let Some(flag) = strip_prefix(flag, "target-feature=") { + for s in flag.split(',') { + // TODO: Handles cases where a specific target feature + // implicitly enables another target feature. + match (s.as_bytes().first(), s.as_bytes().get(1..)) { + (Some(b'+'), Some(f)) if f == name.as_bytes() => has_target_feature = true, + (Some(b'-'), Some(f)) if f == name.as_bytes() => has_target_feature = false, + _ => {} + } + } + } + } + } + if has_target_feature { + println!("cargo:rustc-cfg=portable_atomic_target_feature=\"{}\"", name); + } + has_target_feature +} + +fn target_cpu() -> Option { + let rustflags = env::var_os("CARGO_ENCODED_RUSTFLAGS")?; + let rustflags = rustflags.to_string_lossy(); + let mut cpu = None; + for mut flag in rustflags.split('\x1f') { + flag = strip_prefix(flag, "-C").unwrap_or(flag); + if let Some(flag) = strip_prefix(flag, "target-cpu=") { + cpu = Some(flag); + } + } + cpu.map(str::to_owned) +} + +fn is_allowed_feature(name: &str) -> bool { + // https://github.com/dtolnay/thiserror/pull/248 + if env::var_os("RUSTC_STAGE").is_some() { + return false; + } + + // allowed by default + let mut allowed = true; + if let Some(rustflags) = env::var_os("CARGO_ENCODED_RUSTFLAGS") { + for mut flag in rustflags.to_string_lossy().split('\x1f') { + flag = strip_prefix(flag, "-Z").unwrap_or(flag); + if let Some(flag) = strip_prefix(flag, "allow-features=") { + // If it is specified multiple times, the last value will be preferred. + allowed = flag.split(',').any(|allowed| allowed == name); + } + } + } + allowed +} + +// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.14/build-common.rs. +// +// The target triplets have the form of 'arch-vendor-system'. +// +// When building for Linux (e.g. the 'system' part is +// 'linux-something'), replace the vendor with 'unknown' +// so that mapping to rust standard targets happens correctly. +fn convert_custom_linux_target(target: &str) -> String { + let mut parts: Vec<&str> = target.split('-').collect(); + let system = parts.get(2); + if system == Some(&"linux") { + parts[1] = "unknown"; + } + parts.join("-") +} + +// str::strip_prefix requires Rust 1.45 +#[must_use] +fn strip_prefix<'a>(s: &'a str, pat: &str) -> Option<&'a str> { + if s.starts_with(pat) { + Some(&s[pat.len()..]) + } else { + None + } +} +// str::strip_suffix requires Rust 1.45 +#[must_use] +fn strip_suffix<'a>(s: &'a str, pat: &str) -> Option<&'a str> { + if s.ends_with(pat) { + Some(&s[..s.len() - pat.len()]) + } else { + None + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/no_atomic.rs b/bitbox02-bt/vendor/portable-atomic/no_atomic.rs new file mode 100644 index 0000000..dfbbb59 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/no_atomic.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +// This file is @generated by no_atomic.sh. +// It is not intended for manual editing. + +// Note: This is the list as of nightly-2022-02-10. We don't refer to this in +// nightly-2022-02-11+ because feature(cfg_target_has_atomic) stabilized. +#[rustfmt::skip] +static NO_ATOMIC_CAS: &[&str] = &[ + "avr-unknown-gnu-atmega328", + "bpfeb-unknown-none", + "bpfel-unknown-none", + "msp430-none-elf", + "riscv32i-unknown-none-elf", + "riscv32imc-unknown-none-elf", + "thumbv4t-none-eabi", + "thumbv6m-none-eabi", +]; + +// Note: This is the list as of nightly-2022-02-10. We don't refer to this in +// nightly-2022-02-11+ because feature(cfg_target_has_atomic) stabilized. +#[rustfmt::skip] +static NO_ATOMIC_64: &[&str] = &[ + "arm-linux-androideabi", + "armebv7r-none-eabi", + "armebv7r-none-eabihf", + "armv4t-unknown-linux-gnueabi", + "armv5te-unknown-linux-gnueabi", + "armv5te-unknown-linux-musleabi", + "armv5te-unknown-linux-uclibceabi", + "armv6k-nintendo-3ds", + "armv7r-none-eabi", + "armv7r-none-eabihf", + "avr-unknown-gnu-atmega328", + "hexagon-unknown-linux-musl", + "m68k-unknown-linux-gnu", + "mips-unknown-linux-gnu", + "mips-unknown-linux-musl", + "mips-unknown-linux-uclibc", + "mipsel-sony-psp", + "mipsel-unknown-linux-gnu", + "mipsel-unknown-linux-musl", + "mipsel-unknown-linux-uclibc", + "mipsel-unknown-none", + "mipsisa32r6-unknown-linux-gnu", + "mipsisa32r6el-unknown-linux-gnu", + "msp430-none-elf", + "powerpc-unknown-freebsd", + "powerpc-unknown-linux-gnu", + "powerpc-unknown-linux-gnuspe", + "powerpc-unknown-linux-musl", + "powerpc-unknown-netbsd", + "powerpc-unknown-openbsd", + "powerpc-wrs-vxworks", + "powerpc-wrs-vxworks-spe", + "riscv32gc-unknown-linux-gnu", + "riscv32gc-unknown-linux-musl", + "riscv32i-unknown-none-elf", + "riscv32imac-unknown-none-elf", + "riscv32imc-esp-espidf", + "riscv32imc-unknown-none-elf", + "thumbv4t-none-eabi", + "thumbv6m-none-eabi", + "thumbv7em-none-eabi", + "thumbv7em-none-eabihf", + "thumbv7m-none-eabi", + "thumbv8m.base-none-eabi", + "thumbv8m.main-none-eabi", + "thumbv8m.main-none-eabihf", +]; + +#[rustfmt::skip] +static NO_ATOMIC: &[&str] = &[ + "bpfeb-unknown-none", + "bpfel-unknown-none", + "mipsel-sony-psx", +]; diff --git a/bitbox02-bt/vendor/portable-atomic/src/cfgs.rs b/bitbox02-bt/vendor/portable-atomic/src/cfgs.rs new file mode 100644 index 0000000..7145ab5 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/cfgs.rs @@ -0,0 +1,633 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#![allow(missing_docs)] + +#[cfg(not(all( + portable_atomic_no_atomic_load_store, + not(any( + target_arch = "avr", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + )), +)))] +#[macro_use] +mod atomic_8_16_macros { + #[macro_export] + macro_rules! cfg_has_atomic_8 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[macro_export] + macro_rules! cfg_no_atomic_8 { + ($($tt:tt)*) => {}; + } + #[macro_export] + macro_rules! cfg_has_atomic_16 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[macro_export] + macro_rules! cfg_no_atomic_16 { + ($($tt:tt)*) => {}; + } +} +#[cfg(all( + portable_atomic_no_atomic_load_store, + not(any( + target_arch = "avr", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + )), +))] +#[macro_use] +mod atomic_8_16_macros { + #[macro_export] + macro_rules! cfg_has_atomic_8 { + ($($tt:tt)*) => {}; + } + #[macro_export] + macro_rules! cfg_no_atomic_8 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[macro_export] + macro_rules! cfg_has_atomic_16 { + ($($tt:tt)*) => {}; + } + #[macro_export] + macro_rules! cfg_no_atomic_16 { + ($($tt:tt)*) => { + $($tt)* + }; + } +} + +#[cfg(all( + any(not(target_pointer_width = "16"), feature = "fallback"), + not(all( + portable_atomic_no_atomic_load_store, + not(any( + target_arch = "avr", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + )), + )), +))] +#[macro_use] +mod atomic_32_macros { + #[macro_export] + macro_rules! cfg_has_atomic_32 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[macro_export] + macro_rules! cfg_no_atomic_32 { + ($($tt:tt)*) => {}; + } +} +#[cfg(not(all( + any(not(target_pointer_width = "16"), feature = "fallback"), + not(all( + portable_atomic_no_atomic_load_store, + not(any( + target_arch = "avr", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + )), + )), +)))] +#[macro_use] +mod atomic_32_macros { + #[macro_export] + macro_rules! cfg_has_atomic_32 { + ($($tt:tt)*) => {}; + } + #[macro_export] + macro_rules! cfg_no_atomic_32 { + ($($tt:tt)*) => { + $($tt)* + }; + } +} + +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(any( + all( + feature = "fallback", + any( + not(portable_atomic_no_atomic_cas), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ), + ), + not(portable_atomic_no_atomic_64), + not(any(target_pointer_width = "16", target_pointer_width = "32")), + )) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any( + all( + feature = "fallback", + any( + target_has_atomic = "ptr", + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ), + ), + target_has_atomic = "64", + not(any(target_pointer_width = "16", target_pointer_width = "32")), + all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + ), + ), + ), + )) +)] +#[macro_use] +mod atomic_64_macros { + #[macro_export] + macro_rules! cfg_has_atomic_64 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[macro_export] + macro_rules! cfg_no_atomic_64 { + ($($tt:tt)*) => {}; + } +} +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(any( + all( + feature = "fallback", + any( + not(portable_atomic_no_atomic_cas), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ), + ), + not(portable_atomic_no_atomic_64), + not(any(target_pointer_width = "16", target_pointer_width = "32")), + ))) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(not(any( + all( + feature = "fallback", + any( + target_has_atomic = "ptr", + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ), + ), + target_has_atomic = "64", + not(any(target_pointer_width = "16", target_pointer_width = "32")), + all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + ), + ), + ), + ))) +)] +#[macro_use] +mod atomic_64_macros { + #[macro_export] + macro_rules! cfg_has_atomic_64 { + ($($tt:tt)*) => {}; + } + #[macro_export] + macro_rules! cfg_no_atomic_64 { + ($($tt:tt)*) => { + $($tt)* + }; + } +} + +#[cfg_attr( + not(feature = "fallback"), + cfg(any( + all( + target_arch = "aarch64", + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + ), + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch), + all( + target_arch = "x86_64", + not(all( + any(miri, portable_atomic_sanitize_thread), + portable_atomic_no_cmpxchg16b_intrinsic, + )), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + not(any(target_env = "sgx", miri)), + ), + ), + ), + all( + target_arch = "riscv64", + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), + ), + all( + target_arch = "powerpc64", + portable_atomic_unstable_asm_experimental_arch, + any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + portable_atomic_outline_atomics, // TODO(powerpc64): currently disabled by default + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + all(target_os = "openbsd", portable_atomic_outline_atomics), + ), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), + ), + all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch), + )) +)] +#[cfg_attr( + all(feature = "fallback", portable_atomic_no_cfg_target_has_atomic), + cfg(any( + not(portable_atomic_no_atomic_cas), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + )) +)] +#[cfg_attr( + all(feature = "fallback", not(portable_atomic_no_cfg_target_has_atomic)), + cfg(any( + target_has_atomic = "ptr", + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + )) +)] +#[macro_use] +mod atomic_128_macros { + #[macro_export] + macro_rules! cfg_has_atomic_128 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[macro_export] + macro_rules! cfg_no_atomic_128 { + ($($tt:tt)*) => {}; + } +} +#[cfg_attr( + not(feature = "fallback"), + cfg(not(any( + all( + target_arch = "aarch64", + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + ), + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch), + all( + target_arch = "x86_64", + not(all( + any(miri, portable_atomic_sanitize_thread), + portable_atomic_no_cmpxchg16b_intrinsic, + )), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + not(any(target_env = "sgx", miri)), + ), + ), + ), + all( + target_arch = "riscv64", + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), + ), + all( + target_arch = "powerpc64", + portable_atomic_unstable_asm_experimental_arch, + any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + portable_atomic_outline_atomics, // TODO(powerpc64): currently disabled by default + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + all(target_os = "openbsd", portable_atomic_outline_atomics), + ), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), + ), + all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch), + ))) +)] +#[cfg_attr( + all(feature = "fallback", portable_atomic_no_cfg_target_has_atomic), + cfg(not(any( + not(portable_atomic_no_atomic_cas), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ))) +)] +#[cfg_attr( + all(feature = "fallback", not(portable_atomic_no_cfg_target_has_atomic)), + cfg(not(any( + target_has_atomic = "ptr", + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ))) +)] +#[macro_use] +mod atomic_128_macros { + #[macro_export] + macro_rules! cfg_has_atomic_128 { + ($($tt:tt)*) => {}; + } + #[macro_export] + macro_rules! cfg_no_atomic_128 { + ($($tt:tt)*) => { + $($tt)* + }; + } +} + +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(any( + not(portable_atomic_no_atomic_cas), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + )) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any( + target_has_atomic = "ptr", + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + )) +)] +#[macro_use] +mod atomic_cas_macros { + #[macro_export] + macro_rules! cfg_has_atomic_cas { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[macro_export] + macro_rules! cfg_no_atomic_cas { + ($($tt:tt)*) => {}; + } + // private + macro_rules! cfg_has_atomic_cas_or_amo32 { + ($($tt:tt)*) => { + $($tt)* + }; + } + macro_rules! cfg_has_atomic_cas_or_amo8 { + ($($tt:tt)*) => { + $($tt)* + }; + } +} +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(any( + not(portable_atomic_no_atomic_cas), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ))) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(not(any( + target_has_atomic = "ptr", + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ))) +)] +#[macro_use] +mod atomic_cas_macros { + #[macro_export] + macro_rules! cfg_has_atomic_cas { + ($($tt:tt)*) => {}; + } + #[macro_export] + macro_rules! cfg_no_atomic_cas { + ($($tt:tt)*) => { + $($tt)* + }; + } + // private + #[cfg_attr( + any(target_arch = "riscv32", target_arch = "riscv64"), + cfg(not(any(target_feature = "zaamo", portable_atomic_target_feature = "zaamo"))) + )] + macro_rules! cfg_has_atomic_cas_or_amo32 { + ($($tt:tt)*) => {}; + } + #[cfg_attr( + any(target_arch = "riscv32", target_arch = "riscv64"), + cfg(not(any(target_feature = "zaamo", portable_atomic_target_feature = "zaamo"))) + )] + macro_rules! cfg_no_atomic_cas_or_amo32 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[cfg(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + any(target_feature = "zaamo", portable_atomic_target_feature = "zaamo"), + ))] + macro_rules! cfg_has_atomic_cas_or_amo32 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[cfg(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + any(target_feature = "zaamo", portable_atomic_target_feature = "zaamo"), + ))] + macro_rules! cfg_no_atomic_cas_or_amo32 { + ($($tt:tt)*) => {}; + } + #[cfg_attr( + any(target_arch = "riscv32", target_arch = "riscv64"), + cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha"))) + )] + #[allow(unused_macros)] + macro_rules! cfg_has_atomic_cas_or_amo8 { + ($($tt:tt)*) => {}; + } + #[cfg_attr( + any(target_arch = "riscv32", target_arch = "riscv64"), + cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha"))) + )] + #[cfg_attr(target_arch = "bpf", allow(unused_macros))] + macro_rules! cfg_no_atomic_cas_or_amo8 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[cfg(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + any(target_feature = "zabha", portable_atomic_target_feature = "zabha"), + ))] + macro_rules! cfg_has_atomic_cas_or_amo8 { + ($($tt:tt)*) => { + $($tt)* + }; + } + #[cfg(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + any(target_feature = "zabha", portable_atomic_target_feature = "zabha"), + ))] + macro_rules! cfg_no_atomic_cas_or_amo8 { + ($($tt:tt)*) => {}; + } +} + +// Check that all cfg_ macros work. +mod check { + crate::cfg_has_atomic_8! { type _Atomic8 = (); } + crate::cfg_no_atomic_8! { type _Atomic8 = (); } + crate::cfg_has_atomic_16! { type _Atomic16 = (); } + crate::cfg_no_atomic_16! { type _Atomic16 = (); } + crate::cfg_has_atomic_32! { type _Atomic32 = (); } + crate::cfg_no_atomic_32! { type _Atomic32 = (); } + crate::cfg_has_atomic_64! { type _Atomic64 = (); } + crate::cfg_no_atomic_64! { type _Atomic64 = (); } + crate::cfg_has_atomic_128! { type _Atomic128 = (); } + crate::cfg_no_atomic_128! { type _Atomic128 = (); } + crate::cfg_has_atomic_ptr! { type _AtomicPtr = (); } + crate::cfg_no_atomic_ptr! { type _AtomicPtr = (); } + crate::cfg_has_atomic_cas! { type __AtomicPtr = (); } + crate::cfg_no_atomic_cas! { type __AtomicPtr = (); } + #[allow(unused_imports)] + use { + _Atomic128 as _, _Atomic16 as _, _Atomic32 as _, _Atomic64 as _, _Atomic8 as _, + _AtomicPtr as _, __AtomicPtr as _, + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/gen/utils.rs b/bitbox02-bt/vendor/portable-atomic/src/gen/utils.rs new file mode 100644 index 0000000..d04b3fc --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/gen/utils.rs @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +// This file is @generated by target_spec.sh. +// It is not intended for manual editing. + +#![allow(unused_macros)] + +// On AArch64, the base register of memory-related instructions must be 64-bit. +// Passing a 32-bit value to `in(reg)` on AArch64 results in the upper bits +// having an undefined value, but to work correctly with ILP32 ABI, the upper +// bits must be zero, which is handled here by casting to u64. Another way to +// handle this is to pass it as a pointer and clear the upper bits inside asm, +// but it is easier to overlook than cast, which can catch overlooks by +// asm_sub_register lint. +// See also https://github.com/ARM-software/abi-aa/blob/2024Q3/aapcs64/aapcs64.rst#pointers +// +// Except for x86_64, which can use 32-bit registers in the destination operand +// (on x86_64, we use the ptr_modifier macro to handle this), we need to do the +// same for ILP32 ABI on other 64-bit architectures. (At least, as far as I can +// see from the assembly generated by LLVM, this is also required for MIPS64 N32 +// ABI. I don't know about the RISC-V s64ilp32 ABI for which a patch was +// recently submitted to the kernel, but in any case, this should be a safe +// default for such ABIs). +// +// Known architectures that have such ABI are x86_64 (X32), AArch64 (ILP32), +// mips64 (N32), and riscv64 (s64ilp32, not merged yet though). (As of +// 2023-06-05, only the former two are supported by rustc.) However, we list all +// known 64-bit architectures because similar ABIs may exist or future added for +// other architectures. +#[cfg(all( + target_pointer_width = "32", + any( + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "bpf", + target_arch = "loongarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "nvptx64", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "sparc64", + target_arch = "wasm64", + target_arch = "x86_64", + ), +))] +macro_rules! ptr_reg { + ($ptr:ident) => {{ + let _: *const _ = $ptr; // ensure $ptr is a pointer (*mut _ or *const _) + #[cfg(not(portable_atomic_no_asm_maybe_uninit))] + #[allow(clippy::ptr_as_ptr)] + { + // If we cast to u64 here, the provenance will be lost, + // so we convert to MaybeUninit via zero extend helper. + crate::utils::zero_extend64_ptr($ptr as *mut ()) + } + #[cfg(portable_atomic_no_asm_maybe_uninit)] + { + // Use cast on old rustc because it does not support MaybeUninit + // registers. This is still permissive-provenance compatible and + // is sound. + $ptr as u64 + } + }}; +} +#[cfg(not(all( + target_pointer_width = "32", + any( + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "bpf", + target_arch = "loongarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "nvptx64", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "sparc64", + target_arch = "wasm64", + target_arch = "x86_64", + ), +)))] +macro_rules! ptr_reg { + ($ptr:ident) => {{ + let _: *const _ = $ptr; // ensure $ptr is a pointer (*mut _ or *const _) + $ptr // cast is unnecessary here. + }}; +} + +// Some 64-bit architectures have ABI with 32-bit pointer width (e.g., x86_64 X32 ABI, +// AArch64 ILP32 ABI, MIPS64 N32 ABI). On those targets, AtomicU64 is available +// and fast, so use it to implement normal sequence lock. +// +// See ptr_reg macro for the reason why all known 64-bit architectures are listed. +#[cfg(any( + not(any(target_pointer_width = "16", target_pointer_width = "32")), // i.e., 64-bit or greater + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "bpf", + target_arch = "loongarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "nvptx64", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "sparc64", + target_arch = "wasm64", + target_arch = "x86_64", +))] +#[macro_use] +mod fast_atomic_64_macros { + macro_rules! cfg_has_fast_atomic_64 { + ($($tt:tt)*) => { + $($tt)* + }; + } + macro_rules! cfg_no_fast_atomic_64 { + ($($tt:tt)*) => {}; + } +} +#[cfg(not(any( + not(any(target_pointer_width = "16", target_pointer_width = "32")), // i.e., 64-bit or greater + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "bpf", + target_arch = "loongarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "nvptx64", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "sparc64", + target_arch = "wasm64", + target_arch = "x86_64", +)))] +#[macro_use] +mod fast_atomic_64_macros { + macro_rules! cfg_has_fast_atomic_64 { + ($($tt:tt)*) => {}; + } + macro_rules! cfg_no_fast_atomic_64 { + ($($tt:tt)*) => { + $($tt)* + }; + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/README.md b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/README.md new file mode 100644 index 0000000..82d0419 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/README.md @@ -0,0 +1,36 @@ +# 128-bit atomic implementations on 64-bit architectures + +(See the [`atomic64` module](../atomic64) for 64-bit atomic implementations on 32-bit architectures.) + +## 128-bit atomic instructions + +Here is the table of targets that support 128-bit atomics and the instructions used: + +| target_arch | load | store | CAS | RMW | note | +| ----------- | ---- | ----- | --- | --- | ---- | +| x86_64 | cmpxchg16b or vmovdqa | cmpxchg16b or vmovdqa | cmpxchg16b | cmpxchg16b | cmpxchg16b target feature required. vmovdqa requires Intel, AMD, or Zhaoxin CPU with AVX.
Both compile-time and run-time detection are supported for cmpxchg16b. vmovdqa is currently run-time detection only.
Requires rustc 1.59+ | +| aarch64/arm64ec | ldxp/stxp or casp or ldp/ldiapp | ldxp/stxp or casp or stp/stilp/swpp | ldxp/stxp or casp | ldxp/stxp or casp/swpp/ldclrp/ldsetp | casp requires lse target feature, ldp/stp requires lse2 target feature, ldiapp/stilp requires lse2 and rcpc3 target features, swpp/ldclrp/ldsetp requires lse128 target feature.
Both compile-time and run-time detection are supported.
Requires rustc 1.59+ (aarch64) / nightly (arm64ec) | +| riscv64 | amocas.q | amocas.q | amocas.q | amocas.q | Experimental because LLVM marking the corresponding target feature as experimental. Requires experimental-zacas target feature. Both compile-time and run-time detection are supported (run-time detection is currently disabled by default).
Requires 1.82+ (LLVM 19+) | +| powerpc64 | lq | stq | lqarx/stqcx. | lqarx/stqcx. | Requires target-cpu pwr8+ (powerpc64le is pwr8 by default). Both compile-time and run-time detection are supported (run-time detection is currently disabled by default).
Requires nightly | +| s390x | lpq | stpq | cdsg | cdsg | Requires nightly | + +On compiler versions or platforms where these are not supported, the fallback implementation is used. + +See [aarch64.rs](aarch64.rs) module-level comments for more details on the instructions used on AArch64. + +## Comparison with core::intrinsics::atomic_\* (core::sync::atomic::Atomic{I,U}128) + +This directory has target-specific implementations with inline assembly ([x86_64.rs](x86_64.rs), [aarch64.rs](aarch64.rs), [riscv64.rs](riscv64.rs), [powerpc64.rs](powerpc64.rs), [s390x.rs](s390x.rs)) and an implementation without inline assembly ([intrinsics.rs](intrinsics.rs)). The latter currently always needs nightly compilers and is only used for Miri and ThreadSanitizer, which do not support inline assembly. + +Implementations with inline assembly generate assemblies almost equivalent to the `core::intrinsics::atomic_*` (used in `core::sync::atomic::Atomic{I,U}128`) for many operations, but some operations may or may not generate more efficient code. For example: + +- On x86_64 and AArch64, implementation with inline assembly contains additional optimizations (e.g., [#16](https://github.com/taiki-e/portable-atomic/pull/16), [#126](https://github.com/taiki-e/portable-atomic/pull/126)) and is much faster for some operations. +- On AArch64, implementation with inline assembly supports outline-atomics on more operating systems, and may be faster in environments where outline-atomics can improve performance. +- On powerpc64, LLVM does not support generating some 128-bit atomic operations (see [intrinsics.rs](intrinsics.rs) module-level comments), and we use CAS loop to implement them, so implementation with inline assembly may be faster for those operations. +- In implementations without inline assembly, the compiler may reuse condition flags that have changed as a result of the operation, or use immediate values instead of registers, depending on the situation. + +As 128-bit atomics-related APIs stabilize in the standard library, implementations with inline assembly are planned to be updated to get the benefits of both. + +## Run-time CPU feature detection + +See the [`detect` module's readme](../detect/README.md) for run-time CPU feature detection. diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/aarch64.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/aarch64.rs new file mode 100644 index 0000000..c23c044 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/aarch64.rs @@ -0,0 +1,2264 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +128-bit atomic implementation on AArch64. + +There are a few ways to implement 128-bit atomic operations in AArch64. + +- LDXP/STXP loop (DW LL/SC) +- CASP (DWCAS) added as Armv8.1 FEAT_LSE (optional from Armv8.0, mandatory from Armv8.1) +- LDP/STP (DW load/store) if Armv8.4 FEAT_LSE2 (optional from Armv8.2, mandatory from Armv8.4) is available +- LDIAPP/STILP (DW acquire-load/release-store) added as Armv8.9 FEAT_LRCPC3 (optional from Armv8.2) (if FEAT_LSE2 is also available) +- LDCLRP/LDSETP/SWPP (DW RMW) added as Armv9.4 FEAT_LSE128 (optional from Armv9.3) + +This module supports all of these instructions and attempts to select the best +one based on compile-time and run-time information about available CPU features +and platforms. For example: + +- If outline-atomics is not enabled and FEAT_LSE is not available at + compile-time, we use LDXP/STXP loop. +- If outline-atomics is enabled and FEAT_LSE is not available at + compile-time, we use CASP for CAS if FEAT_LSE is available + at run-time, otherwise, use LDXP/STXP loop. +- If FEAT_LSE is available at compile-time, we use CASP for load/store/CAS/RMW. + However, when portable_atomic_ll_sc_rmw cfg is set, use LDXP/STXP loop instead of CASP + loop for RMW (by default, it is set on Apple hardware where CASP is slow; + see build script for details). +- If outline-atomics is enabled and FEAT_LSE2 is not available at compile-time, + we use LDP/STP (and also LDIAPP/STILP/SWPP if FEAT_LRCPC3/FEAT_LSE128 is + available) for load/store if FEAT_LSE2 is available at run-time, otherwise, + use LDXP/STXP or CASP depending on whether FEAT_LSE is available. +- If FEAT_LSE2 is available at compile-time, we use LDP/STP for load/store. +- If FEAT_LSE128 is available at compile-time, we use LDCLRP/LDSETP/SWPP for fetch_and/fetch_or/swap/{release,seqcst}-store. +- If FEAT_LSE2 and FEAT_LRCPC3 are available at compile-time, we use LDIAPP/STILP for acquire-load/release-store. + +See each "Instruction selection flow for ..." comment in this file for the exact +instruction selection per operation. + +Note: FEAT_LSE2 doesn't imply FEAT_LSE. FEAT_LSE128 implies FEAT_LSE but not FEAT_LSE2. + +Note that we do not separate LL and SC into separate functions, but handle +them within a single asm block. This is because it is theoretically possible +for the compiler to insert operations that might clear the reservation between +LL and SC. Considering the type of operations we are providing and the fact +that [progress64](https://github.com/ARM-software/progress64) uses such code, +this is probably not a problem for AArch64, but it seems that AArch64 doesn't +guarantee it and hexagon is the only architecture with hardware guarantees +that such code works. See also: + +- https://yarchive.net/comp/linux/cmpxchg_ll_sc_portability.html +- https://lists.llvm.org/pipermail/llvm-dev/2016-May/099490.html +- https://lists.llvm.org/pipermail/llvm-dev/2018-June/123993.html + +Also, even when using a CAS loop to implement atomic RMW, include the loop itself +in the asm block because it is more efficient for some codegen backends. +https://github.com/rust-lang/compiler-builtins/issues/339#issuecomment-1191260474 + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use intrinsics.rs instead. + +Refs: +- Arm A-profile A64 Instruction Set Architecture + https://developer.arm.com/documentation/ddi0602/2024-06 +- Arm Compiler armasm User Guide + https://developer.arm.com/documentation/dui0801/latest +- Arm Architecture Reference Manual for A-profile architecture + https://developer.arm.com/documentation/ddi0487/latest (PDF) +- atomic-maybe-uninit https://github.com/taiki-e/atomic-maybe-uninit + +Generated asm: +- aarch64 https://godbolt.org/z/9Kq15oGs4 +- aarch64 msvc https://godbolt.org/z/hsWo8eYh4 +- aarch64 (+lse) https://godbolt.org/z/81TanrTGn +- aarch64 msvc (+lse) https://godbolt.org/z/KsannGvTY +- aarch64 (+lse,+lse2) https://godbolt.org/z/EzvodM6ca +- aarch64 (+lse,+lse2,+rcpc3) https://godbolt.org/z/3rEEs6KE6 +- aarch64 (+lse2,+lse128) https://godbolt.org/z/PWhsPjGa7 +- aarch64 (+lse2,+lse128,+rcpc3) https://godbolt.org/z/K8MMhfPT1 +*/ + +include!("macros.rs"); + +// On musl with static linking, it seems that getauxval is not always available. +// See detect/auxv.rs for more. +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any( + test, + not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + any(target_feature = "lse2", portable_atomic_target_feature = "lse2"), + )), +))] +#[cfg(any( + all( + target_os = "linux", + any( + target_env = "gnu", + all(any(target_env = "musl", target_env = "ohos"), not(target_feature = "crt-static")), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", +))] +#[path = "../detect/auxv.rs"] +mod detect; +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any( + test, + not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + any(target_feature = "lse2", portable_atomic_target_feature = "lse2"), + )), +))] +#[cfg(any(target_os = "netbsd", target_os = "openbsd"))] +#[path = "../detect/aarch64_aa64reg.rs"] +mod detect; +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any(test, portable_atomic_outline_atomics))] // TODO(aarch64-illumos): currently disabled by default +#[cfg(any( + test, + not(all( + any(target_feature = "lse2", portable_atomic_target_feature = "lse2"), + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + )), +))] +#[cfg(target_os = "illumos")] +#[path = "../detect/aarch64_illumos.rs"] +mod detect; +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any(test, not(any(target_feature = "lse", portable_atomic_target_feature = "lse"))))] +#[cfg(target_os = "fuchsia")] +#[path = "../detect/aarch64_fuchsia.rs"] +mod detect; +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any(test, not(any(target_feature = "lse", portable_atomic_target_feature = "lse"))))] +#[cfg(target_os = "windows")] +#[path = "../detect/aarch64_windows.rs"] +mod detect; + +// test only +#[cfg(test)] +#[cfg(not(qemu))] +#[cfg(not(valgrind))] +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] +#[path = "../detect/aarch64_aa64reg.rs"] +mod detect_aa64reg; +// TODO: OpenBSD 7.6+ +// #[cfg(test)] +// #[cfg(not(portable_atomic_no_outline_atomics))] +// #[cfg(target_os = "openbsd")] +// #[path = "../detect/auxv.rs"] +// mod detect_auxv; +#[cfg(test)] +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(target_vendor = "apple")] +#[path = "../detect/aarch64_apple.rs"] +mod detect_apple; + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; +use core::sync::atomic::Ordering; + +use crate::utils::{Pair, U128}; + +#[cfg(any( + target_feature = "lse", + portable_atomic_target_feature = "lse", + not(portable_atomic_no_outline_atomics), +))] +macro_rules! debug_assert_lse { + () => { + #[cfg(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + target_os = "fuchsia", + target_os = "windows", + ), + ))] + #[cfg(not(any(target_feature = "lse", portable_atomic_target_feature = "lse")))] + { + debug_assert!(detect::detect().has_lse()); + } + }; +} +#[rustfmt::skip] +#[cfg(any( + target_feature = "lse2", + portable_atomic_target_feature = "lse2", + not(portable_atomic_no_outline_atomics), +))] +macro_rules! debug_assert_lse2 { + () => { + #[cfg(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + // These don't support detection of FEAT_LSE2. + // target_os = "fuchsia", + // target_os = "windows", + ), + ))] + #[cfg(not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")))] + { + debug_assert!(detect::detect().has_lse2()); + } + }; +} +#[rustfmt::skip] +#[cfg(any( + target_feature = "lse128", + portable_atomic_target_feature = "lse128", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +macro_rules! debug_assert_lse128 { + () => { + #[cfg(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + // These don't support detection of FEAT_LSE128. + // target_os = "fuchsia", + // target_os = "windows", + ), + ))] + #[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] + { + debug_assert!(detect::detect().has_lse128()); + } + }; +} +#[rustfmt::skip] +#[cfg(any( + target_feature = "rcpc3", + portable_atomic_target_feature = "rcpc3", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +macro_rules! debug_assert_rcpc3 { + () => { + #[cfg(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + // These don't support detection of FEAT_LRCPC3. + // target_os = "fuchsia", + // target_os = "windows", + ), + ))] + #[cfg(not(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3")))] + { + debug_assert!(detect::detect().has_rcpc3()); + } + }; +} + +// Refs: https://developer.arm.com/documentation/100067/0611/armclang-Integrated-Assembler/AArch32-Target-selection-directives +// +// This is similar to #[target_feature(enable = "lse")], except that there are +// no compiler guarantees regarding (un)inlining, and the scope is within an asm +// block rather than a function. We use this directive to support outline-atomics +// on pre-1.61 rustc (aarch64_target_feature stabilized in Rust 1.61). +// +// The .arch_extension directive is effective until the end of the assembly block and +// is not propagated to subsequent code, so the end_lse macro is unneeded. +// https://godbolt.org/z/o6EPndP94 +// https://github.com/torvalds/linux/commit/e0d5896bd356cd577f9710a02d7a474cdf58426b +// https://github.com/torvalds/linux/commit/dd1f6308b28edf0452dd5dc7877992903ec61e69 +// (It seems GCC effectively ignores this directive and always allow FEAT_LSE instructions: https://godbolt.org/z/W9W6rensG) +// +// The .arch directive has a similar effect, but we don't use it due to the following issue: +// https://github.com/torvalds/linux/commit/dd1f6308b28edf0452dd5dc7877992903ec61e69 +// +// This is also needed for compatibility with rustc_codegen_cranelift: +// https://github.com/rust-lang/rustc_codegen_cranelift/issues/1400#issuecomment-1774599775 +// +// Note: If FEAT_LSE is not available at compile-time, we must guarantee that +// the function that uses it is not inlined into a function where it is not +// clear whether FEAT_LSE is available. Otherwise, (even if we checked whether +// FEAT_LSE is available at run-time) optimizations that reorder its +// instructions across the if condition might introduce undefined behavior. +// (see also https://rust-lang.github.io/rfcs/2045-target-feature.html#safely-inlining-target_feature-functions-on-more-contexts) +// However, our code uses the ifunc helper macro that works with function pointers, +// so we don't have to worry about this unless calling without helper macro. +#[cfg(any( + target_feature = "lse", + portable_atomic_target_feature = "lse", + not(portable_atomic_no_outline_atomics), +))] +macro_rules! start_lse { + () => { + ".arch_extension lse" + }; +} +#[cfg(not(portable_atomic_pre_llvm_16))] +#[cfg(any( + target_feature = "lse128", + portable_atomic_target_feature = "lse128", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +macro_rules! start_lse128 { + () => { + ".arch_extension lse128" + }; +} +#[cfg(not(portable_atomic_pre_llvm_16))] +#[cfg(any( + target_feature = "rcpc3", + portable_atomic_target_feature = "rcpc3", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +macro_rules! start_rcpc3 { + () => { + ".arch_extension rcpc3" + }; +} + +#[cfg(target_endian = "little")] +macro_rules! select_le_or_be { + ($le:expr, $be:expr) => { + $le + }; +} +#[cfg(target_endian = "big")] +macro_rules! select_le_or_be { + ($le:expr, $be:expr) => { + $be + }; +} + +macro_rules! atomic_rmw { + ($op:ident, $order:ident) => { + atomic_rmw!($op, $order, write = $order) + }; + ($op:ident, $order:ident, write = $write:ident) => { + match $order { + Ordering::Relaxed => $op!("", "", ""), + Ordering::Acquire => $op!("a", "", ""), + Ordering::Release => $op!("", "l", ""), + Ordering::AcqRel => $op!("a", "l", ""), + // In MSVC environments, SeqCst stores/writes needs fences after writes. + // https://reviews.llvm.org/D141748 + #[cfg(target_env = "msvc")] + Ordering::SeqCst if $write == Ordering::SeqCst => $op!("a", "l", "dmb ish"), + // AcqRel and SeqCst RMWs are equivalent in non-MSVC environments. + Ordering::SeqCst => $op!("a", "l", ""), + _ => unreachable!(), + } + }; +} +#[cfg(portable_atomic_pre_llvm_16)] +#[cfg(any( + target_feature = "lse128", + portable_atomic_target_feature = "lse128", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +macro_rules! atomic_rmw_inst { + ($op:ident, $order:ident) => { + atomic_rmw_inst!($op, $order, write = $order) + }; + ($op:ident, $order:ident, write = $write:ident) => { + match $order { + Ordering::Relaxed => $op!("2", ""), + Ordering::Acquire => $op!("a", ""), + Ordering::Release => $op!("6", ""), + Ordering::AcqRel => $op!("e", ""), + // In MSVC environments, SeqCst stores/writes needs fences after writes. + // https://reviews.llvm.org/D141748 + #[cfg(target_env = "msvc")] + Ordering::SeqCst if $write == Ordering::SeqCst => $op!("e", "dmb ish"), + // AcqRel and SeqCst RMWs are equivalent in non-MSVC environments. + Ordering::SeqCst => $op!("e", ""), + _ => unreachable!(), + } + }; +} + +// ----------------------------------------------------------------------------- +// load + +/* + +Instruction selection flow for load: +- if compile_time(FEAT_LSE2) => ldp: + - if compile_time(FEAT_LRCPC3) && order != relaxed => ldiapp + - else => ldp +- if platform_supports_detection_of(FEAT_LSE2): + - if detect(FEAT_LSE2) && detect(FEAT_LRCPC3) && order != relaxed => lse2_rcpc3 (ldiapp) + - if detect(FEAT_LSE2) => lse2 (ldp) +- else => no_lse2: + - if compile_time(FEAT_LSE) => casp + - else => ldxp_stxp + +Note: +- If FEAT_LSE2 is available at compile-time, we don't do run-time detection of + FEAT_LRCPC3 at this time, since FEAT_LRCPC3 is not yet available for most CPUs. + (macOS that doesn't have any FEAT_LRCPC3-enabled CPUs as of M4 is only a platform + that currently enables FEAT_LSE2 at compile-time by default.) +- If FEAT_LSE2 is not available at compile-time, we want to do run-time detection + of FEAT_LSE2, so we do run-time detection of FEAT_LRCPC3 at the same time. +- We don't do run-time detection of FEAT_LSE for load at this time, but since + load by CAS is wait-free, it would probably make sense to do run-time detection. (TODO) + +*/ + +// if compile_time(FEAT_LSE2) => ldp: +// cfg guarantee that the CPU supports FEAT_LSE2. +#[cfg(any(target_feature = "lse2", portable_atomic_target_feature = "lse2"))] +use _atomic_load_ldp as atomic_load; +#[cfg(not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")))] +#[inline] +unsafe fn atomic_load(src: *mut u128, order: Ordering) -> u128 { + #[inline] + unsafe fn atomic_load_no_lse2(src: *mut u128, order: Ordering) -> u128 { + // if compile_time(FEAT_LSE) => casp + #[cfg(any(target_feature = "lse", portable_atomic_target_feature = "lse"))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantee that the CPU supports FEAT_LSE. + unsafe { + _atomic_load_casp(src, order) + } + // else => ldxp_stxp + #[cfg(not(any(target_feature = "lse", portable_atomic_target_feature = "lse")))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + _atomic_load_ldxp_stxp(src, order) + } + } + // if platform_supports_detection_of(FEAT_LSE2): + #[cfg(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + // These don't support detection of FEAT_LSE2. + // target_os = "fuchsia", + // target_os = "windows", + ), + ))] + { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(src: *mut u128) -> u128; + atomic_load_lse2_relaxed = _atomic_load_ldp(Ordering::Relaxed); + atomic_load_lse2_acquire = _atomic_load_ldp(Ordering::Acquire); + atomic_load_lse2_seqcst = _atomic_load_ldp(Ordering::SeqCst); + atomic_load_lse2_rcpc3_acquire = _atomic_load_ldiapp(Ordering::Acquire); + atomic_load_lse2_rcpc3_seqcst = _atomic_load_ldiapp(Ordering::SeqCst); + } + fn_alias! { + unsafe fn(src: *mut u128) -> u128; + atomic_load_no_lse2_relaxed = atomic_load_no_lse2(Ordering::Relaxed); + atomic_load_no_lse2_acquire = atomic_load_no_lse2(Ordering::Acquire); + atomic_load_no_lse2_seqcst = atomic_load_no_lse2(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // and we've checked if FEAT_LSE2 is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + let cpuinfo = detect::detect(); + if cpuinfo.has_lse2() { + // if detect(FEAT_LSE2) => lse2 (ldp) + atomic_load_lse2_relaxed + } else { + // else => no_lse2: + atomic_load_no_lse2_relaxed + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + let cpuinfo = detect::detect(); + if cpuinfo.has_lse2() { + if cpuinfo.has_rcpc3() { + // if detect(FEAT_LSE2) && detect(FEAT_LRCPC3) && order != relaxed => lse2_rcpc3 (ldiapp) + atomic_load_lse2_rcpc3_acquire + } else { + // if detect(FEAT_LSE2) => lse2 (ldp) + atomic_load_lse2_acquire + } + } else { + // else => no_lse2: + atomic_load_no_lse2_acquire + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + let cpuinfo = detect::detect(); + if cpuinfo.has_lse2() { + if cpuinfo.has_rcpc3() { + // if detect(FEAT_LSE2) && detect(FEAT_LRCPC3) && order != relaxed => lse2_rcpc3 (ldiapp) + atomic_load_lse2_rcpc3_seqcst + } else { + // if detect(FEAT_LSE2) => lse2 (ldp) + atomic_load_lse2_seqcst + } + } else { + // else => no_lse2: + atomic_load_no_lse2_seqcst + } + }) + } + _ => unreachable!(), + } + } + } + // else => no_lse2: + #[cfg(not(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + // These don't support detection of FEAT_LSE2. + // target_os = "fuchsia", + // target_os = "windows", + ), + )))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_load_no_lse2(src, order) + } +} +// If CPU supports FEAT_LSE2, LDP/LDIAPP is single-copy atomic reads, +// otherwise it is two single-copy atomic reads. +// Refs: B2.2.1 of the Arm Architecture Reference Manual Armv8, for Armv8-A architecture profile +#[cfg(any( + target_feature = "lse2", + portable_atomic_target_feature = "lse2", + not(portable_atomic_no_outline_atomics), +))] +#[inline] +unsafe fn _atomic_load_ldp(src: *mut u128, order: Ordering) -> u128 { + debug_assert!(src as usize % 16 == 0); + debug_assert_lse2!(); + + // SAFETY: the caller must guarantee that `dst` is valid for reads, + // 16-byte aligned, that there are no concurrent non-atomic operations. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/LDP--Load-pair-of-registers- + unsafe { + let (out_lo, out_hi); + macro_rules! atomic_load_relaxed { + ($acquire:tt) => {{ + asm!( + "ldp {out_lo}, {out_hi}, [{src}]", + $acquire, + src = in(reg) ptr_reg!(src), + out_hi = lateout(reg) out_hi, + out_lo = lateout(reg) out_lo, + options(nostack, preserves_flags), + ); + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + }}; + } + match order { + // if compile_time(FEAT_LRCPC3) && order != relaxed => ldiapp + // SAFETY: cfg guarantee that the CPU supports FEAT_LRCPC3. + #[cfg(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3"))] + Ordering::Acquire | Ordering::SeqCst => _atomic_load_ldiapp(src, order), + + // else => ldp + Ordering::Relaxed => atomic_load_relaxed!(""), + #[cfg(not(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3")))] + Ordering::Acquire => atomic_load_relaxed!("dmb ishld"), + #[cfg(not(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3")))] + Ordering::SeqCst => { + asm!( + // ldar (or dmb ishld) is required to prevent reordering with preceding stlxp. + // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108891 for details. + "ldar {tmp}, [{src}]", + "ldp {out_lo}, {out_hi}, [{src}]", + "dmb ishld", + src = in(reg) ptr_reg!(src), + out_hi = lateout(reg) out_hi, + out_lo = lateout(reg) out_lo, + tmp = out(reg) _, + options(nostack, preserves_flags), + ); + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } + _ => unreachable!(), + } + } +} +#[cfg(any( + target_feature = "lse2", + portable_atomic_target_feature = "lse2", + not(portable_atomic_no_outline_atomics), +))] +#[cfg(any( + target_feature = "rcpc3", + portable_atomic_target_feature = "rcpc3", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +#[inline] +unsafe fn _atomic_load_ldiapp(src: *mut u128, order: Ordering) -> u128 { + debug_assert!(src as usize % 16 == 0); + debug_assert_lse2!(); + debug_assert_rcpc3!(); + + // SAFETY: the caller must guarantee that `dst` is valid for reads, + // 16-byte aligned, that there are no concurrent non-atomic operations. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/LDIAPP--Load-Acquire-RCpc-ordered-pair-of-registers- + unsafe { + let (out_lo, out_hi); + match order { + Ordering::Acquire => { + #[cfg(not(portable_atomic_pre_llvm_16))] + asm!( + start_rcpc3!(), + "ldiapp {out_lo}, {out_hi}, [{src}]", + src = in(reg) ptr_reg!(src), + out_hi = lateout(reg) out_hi, + out_lo = lateout(reg) out_lo, + options(nostack, preserves_flags), + ); + // LLVM supports FEAT_LRCPC3 instructions on LLVM 16+, so use .inst directive on old LLVM. + // https://github.com/llvm/llvm-project/commit/a6aaa969f7caec58a994142f8d855861cf3a1463 + #[cfg(portable_atomic_pre_llvm_16)] + asm!( + // 0: d9411800 ldiapp x0, x1, [x0] + ".inst 0xd9411800", + in("x0") ptr_reg!(src), + lateout("x1") out_hi, + lateout("x0") out_lo, + options(nostack, preserves_flags), + ); + } + Ordering::SeqCst => { + #[cfg(not(portable_atomic_pre_llvm_16))] + asm!( + start_rcpc3!(), + // ldar (or dmb ishld) is required to prevent reordering with preceding stlxp. + // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108891 for details. + "ldar {tmp}, [{src}]", + "ldiapp {out_lo}, {out_hi}, [{src}]", + src = in(reg) ptr_reg!(src), + out_hi = lateout(reg) out_hi, + out_lo = lateout(reg) out_lo, + tmp = out(reg) _, + options(nostack, preserves_flags), + ); + // LLVM supports FEAT_LRCPC3 instructions on LLVM 16+, so use .inst directive on old LLVM. + // https://github.com/llvm/llvm-project/commit/a6aaa969f7caec58a994142f8d855861cf3a1463 + #[cfg(portable_atomic_pre_llvm_16)] + asm!( + // ldar (or dmb ishld) is required to prevent reordering with preceding stlxp. + // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108891 for details. + "ldar {tmp}, [x0]", + // 0: d9411800 ldiapp x0, x1, [x0] + ".inst 0xd9411800", + tmp = out(reg) _, + in("x0") ptr_reg!(src), + lateout("x1") out_hi, + lateout("x0") out_lo, + options(nostack, preserves_flags), + ); + } + _ => unreachable!(), + } + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} +// Do not use _atomic_compare_exchange_casp because it needs extra MOV to implement load. +#[cfg(any(test, not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2"))))] +#[cfg(any(target_feature = "lse", portable_atomic_target_feature = "lse"))] +#[inline] +unsafe fn _atomic_load_casp(src: *mut u128, order: Ordering) -> u128 { + debug_assert!(src as usize % 16 == 0); + debug_assert_lse!(); + + // SAFETY: the caller must uphold the safety contract. + // cfg guarantee that the CPU supports FEAT_LSE. + unsafe { + let (out_lo, out_hi); + macro_rules! atomic_load { + ($acquire:tt, $release:tt) => { + asm!( + start_lse!(), + concat!("casp", $acquire, $release, " x2, x3, x2, x3, [{src}]"), + src = in(reg) ptr_reg!(src), + // must be allocated to even/odd register pair + inout("x2") 0_u64 => out_lo, + inout("x3") 0_u64 => out_hi, + options(nostack, preserves_flags), + ) + }; + } + match order { + Ordering::Relaxed => atomic_load!("", ""), + Ordering::Acquire => atomic_load!("a", ""), + Ordering::SeqCst => atomic_load!("a", "l"), + _ => unreachable!(), + } + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} +#[cfg(any( + test, + all( + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + not(any(target_feature = "lse", portable_atomic_target_feature = "lse")), + ), +))] +#[inline] +unsafe fn _atomic_load_ldxp_stxp(src: *mut u128, order: Ordering) -> u128 { + debug_assert!(src as usize % 16 == 0); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (mut out_lo, mut out_hi); + macro_rules! atomic_load { + ($acquire:tt, $release:tt) => { + asm!( + "2:", + concat!("ld", $acquire, "xp {out_lo}, {out_hi}, [{src}]"), + concat!("st", $release, "xp {r:w}, {out_lo}, {out_hi}, [{src}]"), + // 0 if the store was successful, 1 if no store was performed + "cbnz {r:w}, 2b", + src = in(reg) ptr_reg!(src), + out_lo = out(reg) out_lo, + out_hi = out(reg) out_hi, + r = out(reg) _, + options(nostack, preserves_flags), + ) + }; + } + match order { + Ordering::Relaxed => atomic_load!("", ""), + Ordering::Acquire => atomic_load!("a", ""), + Ordering::SeqCst => atomic_load!("a", "l"), + _ => unreachable!(), + } + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} + +// ----------------------------------------------------------------------------- +// store + +/* + +Instruction selection flow for store: +- if compile_time(FEAT_LSE2) => stp: + - if compile_time(FEAT_LSE128) && order == seqcst => swpp + - if compile_time(FEAT_LRCPC3) && order != relaxed => stilp + - if compile_time(FEAT_LSE128) && order != relaxed => swpp + - else => stp +- if platform_supports_detection_of(FEAT_LSE2): + - if detect(FEAT_LSE2) && detect(FEAT_LSE128) && order == seqcst => lse128 (swpp) + - if detect(FEAT_LSE2) && detect(FEAT_LRCPC3) && order != relaxed => lse2_rcpc3 (stilp) + - if detect(FEAT_LSE2) && detect(FEAT_LSE128) && order != relaxed => lse128 (swpp) + - if detect(FEAT_LSE2) => lse2 (stp) +- else => no_lse2: + - if compile_time(FEAT_LSE) && not(ll_sc_rmw) => casp + - else => ldxp_stxp + +Note: +- If FEAT_LSE2 is available at compile-time, we don't do run-time detection of + FEAT_LRCPC3/FEAT_LSE128 at this time, since FEAT_LRCPC3/FEAT_LSE128 is not yet available for most CPUs. + (macOS that doesn't have any FEAT_LRCPC3/FEAT_LSE128-enabled CPUs as of M4 is only a platform + that currently enables FEAT_LSE2 at compile-time by default.) +- If FEAT_LSE2 is not available at compile-time, we want to do run-time detection + of FEAT_LSE2, so we do run-time detection of FEAT_LRCPC3/FEAT_LSE128 at the same time. +- We don't do run-time detection of FEAT_LSE for store at this time. + +*/ + +// if compile_time(FEAT_LSE2) => stp: +// cfg guarantee that the CPU supports FEAT_LSE2. +#[cfg(any(target_feature = "lse2", portable_atomic_target_feature = "lse2"))] +use _atomic_store_stp as atomic_store; +#[cfg(not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")))] +#[inline] +unsafe fn atomic_store(dst: *mut u128, val: u128, order: Ordering) { + #[inline] + unsafe fn atomic_store_no_lse2(dst: *mut u128, val: u128, order: Ordering) { + // if compile_time(FEAT_LSE) && not(ll_sc_rmw) => casp + // If FEAT_LSE is available at compile-time and portable_atomic_ll_sc_rmw cfg is not set, + // we use CAS-based atomic RMW. + #[cfg(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + ))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantee that the CPU supports FEAT_LSE. + unsafe { + _atomic_swap_casp(dst, val, order); + } + // else => ldxp_stxp + #[cfg(not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + )))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + _atomic_store_ldxp_stxp(dst, val, order); + } + } + #[cfg(any( + target_feature = "lse128", + portable_atomic_target_feature = "lse128", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), + ))] + #[inline] + unsafe fn _atomic_store_swpp(dst: *mut u128, val: u128, order: Ordering) { + // SAFETY: the caller must uphold the safety contract. + unsafe { + _atomic_swap_swpp(dst, val, order); + } + } + // if platform_supports_detection_of(FEAT_LSE2): + #[cfg(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + // These don't support detection of FEAT_LSE2. + // target_os = "fuchsia", + // target_os = "windows", + ), + ))] + { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(dst: *mut u128, val: u128); + atomic_store_lse2_relaxed = _atomic_store_stp(Ordering::Relaxed); + atomic_store_lse2_release = _atomic_store_stp(Ordering::Release); + atomic_store_lse2_seqcst = _atomic_store_stp(Ordering::SeqCst); + atomic_store_lse2_rcpc3_release = _atomic_store_stilp(Ordering::Release); + atomic_store_lse2_rcpc3_seqcst = _atomic_store_stilp(Ordering::SeqCst); + atomic_store_lse128_release = _atomic_store_swpp(Ordering::Release); + atomic_store_lse128_seqcst = _atomic_store_swpp(Ordering::SeqCst); + } + fn_alias! { + unsafe fn(dst: *mut u128, val: u128); + atomic_store_no_lse2_relaxed = atomic_store_no_lse2(Ordering::Relaxed); + atomic_store_no_lse2_release = atomic_store_no_lse2(Ordering::Release); + atomic_store_no_lse2_seqcst = atomic_store_no_lse2(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // and we've checked if FEAT_LSE2 is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + let cpuinfo = detect::detect(); + if cpuinfo.has_lse2() { + // if detect(FEAT_LSE2) => lse2 (stp) + atomic_store_lse2_relaxed + } else { + // else => no_lse2: + atomic_store_no_lse2_relaxed + } + }); + } + Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + let cpuinfo = detect::detect(); + if cpuinfo.has_lse2() { + if cpuinfo.has_rcpc3() { + // if detect(FEAT_LSE2) && detect(FEAT_LRCPC3) && order != relaxed => lse2_rcpc3 (stilp) + atomic_store_lse2_rcpc3_release + } else if cpuinfo.has_lse128() { + // if detect(FEAT_LSE2) && detect(FEAT_LSE128) && order != relaxed => lse128 (swpp) + atomic_store_lse128_release + } else { + // if detect(FEAT_LSE2) => lse2 (stp) + atomic_store_lse2_release + } + } else { + // else => no_lse2: + atomic_store_no_lse2_release + } + }); + } + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + let cpuinfo = detect::detect(); + if cpuinfo.has_lse2() { + if cpuinfo.has_lse128() { + // if detect(FEAT_LSE2) && detect(FEAT_LSE128) && order == seqcst => lse128 (swpp) + atomic_store_lse128_seqcst + } else if cpuinfo.has_rcpc3() { + // if detect(FEAT_LSE2) && detect(FEAT_LRCPC3) && order != relaxed => lse2_rcpc3 (stilp) + atomic_store_lse2_rcpc3_seqcst + } else { + // if detect(FEAT_LSE2) => lse2 (stp) + atomic_store_lse2_seqcst + } + } else { + // else => no_lse2: + atomic_store_no_lse2_seqcst + } + }); + } + _ => unreachable!(), + } + } + } + // else => no_lse2: + #[cfg(not(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + // These don't support detection of FEAT_LSE2. + // target_os = "fuchsia", + // target_os = "windows", + ), + )))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_store_no_lse2(dst, val, order); + } +} +// If CPU supports FEAT_LSE2, STP/STILP is single-copy atomic writes, +// otherwise it is two single-copy atomic writes. +// Refs: B2.2.1 of the Arm Architecture Reference Manual Armv8, for Armv8-A architecture profile +#[cfg(any( + target_feature = "lse2", + portable_atomic_target_feature = "lse2", + not(portable_atomic_no_outline_atomics), +))] +#[inline] +unsafe fn _atomic_store_stp(dst: *mut u128, val: u128, order: Ordering) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_lse2!(); + + // SAFETY: the caller must guarantee that `dst` is valid for writes, + // 16-byte aligned, that there are no concurrent non-atomic operations. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/STP--Store-pair-of-registers- + unsafe { + #[rustfmt::skip] + macro_rules! atomic_store { + ($acquire:tt, $release:tt) => {{ + let val = U128 { whole: val }; + asm!( + $release, + "stp {val_lo}, {val_hi}, [{dst}]", + $acquire, + dst = in(reg) ptr_reg!(dst), + val_lo = in(reg) val.pair.lo, + val_hi = in(reg) val.pair.hi, + options(nostack, preserves_flags), + ); + }}; + } + match order { + // if compile_time(FEAT_LSE128) && order == seqcst => swpp + // Prefer swpp if stp requires fences. https://reviews.llvm.org/D143506 + // SAFETY: cfg guarantee that the CPU supports FEAT_LSE128. + #[cfg(any(target_feature = "lse128", portable_atomic_target_feature = "lse128"))] + Ordering::SeqCst => { + _atomic_swap_swpp(dst, val, order); + } + + // if compile_time(FEAT_LRCPC3) && order != relaxed: + // SAFETY: cfg guarantee that the CPU supports FEAT_LRCPC3. + #[cfg(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3"))] + Ordering::Release => _atomic_store_stilp(dst, val, order), + #[cfg(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3"))] + #[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] + Ordering::SeqCst => _atomic_store_stilp(dst, val, order), + + // if compile_time(FEAT_LSE128) && order != relaxed => swpp + // Prefer swpp if stp requires fences. https://reviews.llvm.org/D143506 + // SAFETY: cfg guarantee that the CPU supports FEAT_LSE128. + #[cfg(not(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3")))] + #[cfg(any(target_feature = "lse128", portable_atomic_target_feature = "lse128"))] + Ordering::Release => { + _atomic_swap_swpp(dst, val, order); + } + + // else => stp + Ordering::Relaxed => atomic_store!("", ""), + #[cfg(not(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3")))] + #[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] + Ordering::Release => atomic_store!("", "dmb ish"), + #[cfg(not(any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3")))] + #[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] + Ordering::SeqCst => atomic_store!("dmb ish", "dmb ish"), + _ => unreachable!(), + } + } +} +#[cfg(any( + target_feature = "lse2", + portable_atomic_target_feature = "lse2", + not(portable_atomic_no_outline_atomics), +))] +#[cfg(any( + target_feature = "rcpc3", + portable_atomic_target_feature = "rcpc3", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +#[inline] +unsafe fn _atomic_store_stilp(dst: *mut u128, val: u128, order: Ordering) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_lse2!(); + debug_assert_rcpc3!(); + + // SAFETY: the caller must guarantee that `dst` is valid for writes, + // 16-byte aligned, that there are no concurrent non-atomic operations. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/STILP--Store-release-ordered-pair-of-registers- + unsafe { + macro_rules! atomic_store { + ($acquire:tt) => {{ + let val = U128 { whole: val }; + #[cfg(not(portable_atomic_pre_llvm_16))] + asm!( + start_rcpc3!(), + "stilp {val_lo}, {val_hi}, [{dst}]", + $acquire, + dst = in(reg) ptr_reg!(dst), + val_lo = in(reg) val.pair.lo, + val_hi = in(reg) val.pair.hi, + options(nostack, preserves_flags), + ); + // LLVM supports FEAT_LRCPC3 instructions on LLVM 16+, so use .inst directive on old LLVM. + // https://github.com/llvm/llvm-project/commit/a6aaa969f7caec58a994142f8d855861cf3a1463 + #[cfg(portable_atomic_pre_llvm_16)] + asm!( + // 0: d9031802 stilp x2, x3, [x0] + ".inst 0xd9031802", + $acquire, + in("x0") ptr_reg!(dst), + in("x2") val.pair.lo, + in("x3") val.pair.hi, + options(nostack, preserves_flags), + ); + }}; + } + match order { + Ordering::Release => atomic_store!(""), + // LLVM uses store-release (dmb ish; stp); dmb ish, GCC (libatomic) + // uses store-release (stilp) without fence for SeqCst store + // (https://github.com/gcc-mirror/gcc/commit/7107574958e2bed11d916a1480ef1319f15e5ffe). + // Considering https://reviews.llvm.org/D141748, LLVM's lowing seems + // to be the safer option here (I'm not convinced that the libatomic's implementation is wrong). + Ordering::SeqCst => atomic_store!("dmb ish"), + _ => unreachable!(), + } + } +} +// Do not use _atomic_swap_ldxp_stxp because it needs extra registers to implement store. +#[cfg(any( + test, + not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + )) +))] +#[inline] +unsafe fn _atomic_store_ldxp_stxp(dst: *mut u128, val: u128, order: Ordering) { + debug_assert!(dst as usize % 16 == 0); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let val = U128 { whole: val }; + macro_rules! store { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + "2:", + concat!("ld", $acquire, "xp xzr, {tmp}, [{dst}]"), + concat!("st", $release, "xp {tmp:w}, {val_lo}, {val_hi}, [{dst}]"), + // 0 if the store was successful, 1 if no store was performed + "cbnz {tmp:w}, 2b", + $fence, + dst = in(reg) ptr_reg!(dst), + val_lo = in(reg) val.pair.lo, + val_hi = in(reg) val.pair.hi, + tmp = out(reg) _, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(store, order); + } +} + +// ----------------------------------------------------------------------------- +// compare_exchange + +/* + +Instruction selection flow for compare_exchange: +- if compile_time(FEAT_LSE) => casp +- if platform_supports_detection_of(FEAT_LSE): + - if detect(FEAT_LSE) => casp +- else => ldxp_stxp + +*/ + +#[inline] +unsafe fn atomic_compare_exchange( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> Result { + // if compile_time(FEAT_LSE) => casp + #[cfg(any(target_feature = "lse", portable_atomic_target_feature = "lse"))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantee that the CPU supports FEAT_LSE. + let prev = unsafe { _atomic_compare_exchange_casp(dst, old, new, success, failure) }; + // if platform_supports_detection_of(FEAT_LSE): + #[cfg(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + target_os = "fuchsia", + target_os = "windows", + ), + ))] + #[cfg(not(any(target_feature = "lse", portable_atomic_target_feature = "lse")))] + let prev = { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128; + atomic_compare_exchange_casp_relaxed + = _atomic_compare_exchange_casp(Ordering::Relaxed, Ordering::Relaxed); + atomic_compare_exchange_casp_acquire + = _atomic_compare_exchange_casp(Ordering::Acquire, Ordering::Acquire); + atomic_compare_exchange_casp_release + = _atomic_compare_exchange_casp(Ordering::Release, Ordering::Relaxed); + atomic_compare_exchange_casp_acqrel + = _atomic_compare_exchange_casp(Ordering::AcqRel, Ordering::Acquire); + // AcqRel and SeqCst RMWs are equivalent in non-MSVC environments. + #[cfg(target_env = "msvc")] + atomic_compare_exchange_casp_seqcst + = _atomic_compare_exchange_casp(Ordering::SeqCst, Ordering::SeqCst); + } + fn_alias! { + unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128; + atomic_compare_exchange_ldxp_stxp_relaxed + = _atomic_compare_exchange_ldxp_stxp(Ordering::Relaxed, Ordering::Relaxed); + atomic_compare_exchange_ldxp_stxp_acquire + = _atomic_compare_exchange_ldxp_stxp(Ordering::Acquire, Ordering::Acquire); + atomic_compare_exchange_ldxp_stxp_release + = _atomic_compare_exchange_ldxp_stxp(Ordering::Release, Ordering::Relaxed); + atomic_compare_exchange_ldxp_stxp_acqrel + = _atomic_compare_exchange_ldxp_stxp(Ordering::AcqRel, Ordering::Acquire); + // AcqRel and SeqCst RMWs are equivalent in non-MSVC environments. + #[cfg(target_env = "msvc")] + atomic_compare_exchange_ldxp_stxp_seqcst + = _atomic_compare_exchange_ldxp_stxp(Ordering::SeqCst, Ordering::SeqCst); + } + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, that there are no concurrent non-atomic operations, + // and we've checked if FEAT_LSE is available. + unsafe { + let success = crate::utils::upgrade_success_ordering(success, failure); + match success { + Ordering::Relaxed => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128 { + if detect::detect().has_lse() { + // if detect(FEAT_LSE) => casp + atomic_compare_exchange_casp_relaxed + } else { + // else => ldxp_stxp + atomic_compare_exchange_ldxp_stxp_relaxed + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128 { + if detect::detect().has_lse() { + // if detect(FEAT_LSE) => casp + atomic_compare_exchange_casp_acquire + } else { + // else => ldxp_stxp + atomic_compare_exchange_ldxp_stxp_acquire + } + }) + } + Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128 { + if detect::detect().has_lse() { + // if detect(FEAT_LSE) => casp + atomic_compare_exchange_casp_release + } else { + // else => ldxp_stxp + atomic_compare_exchange_ldxp_stxp_release + } + }) + } + // AcqRel and SeqCst RMWs are equivalent in both implementations in non-MSVC environments. + #[cfg(not(target_env = "msvc"))] + Ordering::AcqRel | Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128 { + if detect::detect().has_lse() { + // if detect(FEAT_LSE) => casp + atomic_compare_exchange_casp_acqrel + } else { + // else => ldxp_stxp + atomic_compare_exchange_ldxp_stxp_acqrel + } + }) + } + #[cfg(target_env = "msvc")] + Ordering::AcqRel => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128 { + if detect::detect().has_lse() { + // if detect(FEAT_LSE) => casp + atomic_compare_exchange_casp_acqrel + } else { + // else => ldxp_stxp + atomic_compare_exchange_ldxp_stxp_acqrel + } + }) + } + #[cfg(target_env = "msvc")] + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> u128 { + if detect::detect().has_lse() { + // if detect(FEAT_LSE) => casp + atomic_compare_exchange_casp_seqcst + } else { + // else => ldxp_stxp + atomic_compare_exchange_ldxp_stxp_seqcst + } + }) + } + _ => unreachable!(), + } + } + }; + // else => ldxp_stxp + #[cfg(not(all( + not(portable_atomic_no_outline_atomics), + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + all(target_os = "illumos", portable_atomic_outline_atomics), + target_os = "fuchsia", + target_os = "windows", + ), + )))] + #[cfg(not(any(target_feature = "lse", portable_atomic_target_feature = "lse")))] + // SAFETY: the caller must uphold the safety contract. + let prev = unsafe { _atomic_compare_exchange_ldxp_stxp(dst, old, new, success, failure) }; + if prev == old { + Ok(prev) + } else { + Err(prev) + } +} +#[cfg(any( + target_feature = "lse", + portable_atomic_target_feature = "lse", + not(portable_atomic_no_outline_atomics), +))] +#[inline] +unsafe fn _atomic_compare_exchange_casp( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_lse!(); + let order = crate::utils::upgrade_success_ordering(success, failure); + + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, that there are no concurrent non-atomic operations, + // and the CPU supports FEAT_LSE. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/CASP--CASPA--CASPAL--CASPL--Compare-and-swap-pair-of-words-or-doublewords-in-memory- + unsafe { + let old = U128 { whole: old }; + let new = U128 { whole: new }; + let (prev_lo, prev_hi); + macro_rules! cmpxchg { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + start_lse!(), + concat!("casp", $acquire, $release, " x6, x7, x4, x5, [{dst}]"), + $fence, + dst = in(reg) ptr_reg!(dst), + // must be allocated to even/odd register pair + inout("x6") old.pair.lo => prev_lo, + inout("x7") old.pair.hi => prev_hi, + // must be allocated to even/odd register pair + in("x4") new.pair.lo, + in("x5") new.pair.hi, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(cmpxchg, order, write = success); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} +#[cfg(any(test, not(any(target_feature = "lse", portable_atomic_target_feature = "lse"))))] +#[inline] +unsafe fn _atomic_compare_exchange_ldxp_stxp( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> u128 { + debug_assert!(dst as usize % 16 == 0); + let order = crate::utils::upgrade_success_ordering(success, failure); + + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, and that there are no concurrent non-atomic operations. + // + // Refs: + // - LDXP: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/LDXP--Load-exclusive-pair-of-registers- + // - LDAXP: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/LDAXP--Load-acquire-exclusive-pair-of-registers- + // - STXP: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/STXP--Store-exclusive-pair-of-registers- + // - STLXP: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/STLXP--Store-release-exclusive-pair-of-registers- + // + // Note: Load-Exclusive pair (by itself) does not guarantee atomicity; to complete an atomic + // operation (even load/store), a corresponding Store-Exclusive pair must succeed. + // See Arm Architecture Reference Manual for A-profile architecture + // Section B2.2.1 "Requirements for single-copy atomicity", and + // Section B2.9 "Synchronization and semaphores" for more. + unsafe { + let old = U128 { whole: old }; + let new = U128 { whole: new }; + let (mut prev_lo, mut prev_hi); + macro_rules! cmpxchg { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + "2:", + concat!("ld", $acquire, "xp {prev_lo}, {prev_hi}, [{dst}]"), + "cmp {prev_lo}, {old_lo}", + "cset {r:w}, ne", + "cmp {prev_hi}, {old_hi}", + "cinc {r:w}, {r:w}, ne", + "cbz {r:w}, 3f", + concat!("st", $release, "xp {r:w}, {prev_lo}, {prev_hi}, [{dst}]"), + // 0 if the store was successful, 1 if no store was performed + "cbnz {r:w}, 2b", + "b 4f", + "3:", + concat!("st", $release, "xp {r:w}, {new_lo}, {new_hi}, [{dst}]"), + // 0 if the store was successful, 1 if no store was performed + "cbnz {r:w}, 2b", + "4:", + $fence, + dst = in(reg) ptr_reg!(dst), + old_lo = in(reg) old.pair.lo, + old_hi = in(reg) old.pair.hi, + new_lo = in(reg) new.pair.lo, + new_hi = in(reg) new.pair.hi, + prev_lo = out(reg) prev_lo, + prev_hi = out(reg) prev_hi, + r = out(reg) _, + // Do not use `preserves_flags` because CMP modifies the condition flags. + options(nostack), + ) + }; + } + atomic_rmw!(cmpxchg, order, write = success); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} + +// casp is always strong, and ldxp requires a corresponding (succeed) stxp for +// its atomicity (see code comment in _atomic_compare_exchange_ldxp_stxp). +// (i.e., AArch64 doesn't have 128-bit weak CAS) +use self::atomic_compare_exchange as atomic_compare_exchange_weak; + +// ----------------------------------------------------------------------------- +// RMW + +/* + +Instruction selection flow for swap/fetch_and/fetch_or: +- if compile_time(FEAT_LSE128) => swpp/ldclrp/ldsetp +- if compile_time(FEAT_LSE) && not(ll_sc_rmw) => casp +- else => ldxp_stxp + +Instruction selection flow for other RMWs: +- if compile_time(FEAT_LSE) && not(ll_sc_rmw) => casp +- else => ldxp_stxp + +Note: +- We don't do run-time detection of FEAT_LSE128 at this time, because + FEAT_LSE128 is not yet available for most CPUs, but since + swpp/ldclrp/ldsetp is wait-free, it would make sense to do run-time + detection in the future. (TODO) +- We don't do run-time detection of FEAT_LSE for store at this time. + +*/ + +// If FEAT_LSE is available at compile-time and portable_atomic_ll_sc_rmw cfg is not set, +// we use CAS-based atomic RMW. +#[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] +#[cfg(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), +))] +use _atomic_swap_casp as atomic_swap; +#[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] +#[cfg(not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), +)))] +use _atomic_swap_ldxp_stxp as atomic_swap; +#[cfg(any(target_feature = "lse128", portable_atomic_target_feature = "lse128"))] +use _atomic_swap_swpp as atomic_swap; +#[cfg(any( + target_feature = "lse128", + portable_atomic_target_feature = "lse128", + all( + not(portable_atomic_no_outline_atomics), + not(any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + ), +))] +#[inline] +unsafe fn _atomic_swap_swpp(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_lse128!(); + + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, that there are no concurrent non-atomic operations, + // and the CPU supports FEAT_LSE128. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/SWPP--SWPPA--SWPPAL--SWPPL--Swap-quadword-in-memory- + unsafe { + let val = U128 { whole: val }; + let (prev_lo, prev_hi); + #[cfg(not(portable_atomic_pre_llvm_16))] + macro_rules! swap { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + start_lse128!(), + concat!("swpp", $acquire, $release, " {val_lo}, {val_hi}, [{dst}]"), + $fence, + dst = in(reg) ptr_reg!(dst), + val_lo = inout(reg) val.pair.lo => prev_lo, + val_hi = inout(reg) val.pair.hi => prev_hi, + options(nostack, preserves_flags), + ) + }; + } + #[cfg(not(portable_atomic_pre_llvm_16))] + atomic_rmw!(swap, order); + // LLVM supports FEAT_LSE128 instructions on LLVM 16+, so use .inst directive on old LLVM. + // https://github.com/llvm/llvm-project/commit/7fea6f2e0e606e5339c3359568f680eaf64aa306 + #[cfg(portable_atomic_pre_llvm_16)] + macro_rules! swap { + ($order:tt, $fence:tt) => { + asm!( + // 4: 19{2,a,6,e}18002 swpp{,a,l,al} x2, x1, [x0] + concat!(".inst 0x19", $order, "18002"), + $fence, + in("x0") ptr_reg!(dst), + inout("x2") val.pair.lo => prev_lo, + inout("x1") val.pair.hi => prev_hi, + options(nostack, preserves_flags), + ) + }; + } + #[cfg(portable_atomic_pre_llvm_16)] + atomic_rmw_inst!(swap, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} +// Do not use atomic_rmw_cas_3 because it needs extra MOV to implement swap. +#[cfg(any(test, not(portable_atomic_ll_sc_rmw)))] +#[cfg(any(target_feature = "lse", portable_atomic_target_feature = "lse"))] +#[inline] +unsafe fn _atomic_swap_casp(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_lse!(); + + // SAFETY: the caller must uphold the safety contract. + // cfg guarantee that the CPU supports FEAT_LSE. + unsafe { + let val = U128 { whole: val }; + let (mut prev_lo, mut prev_hi); + macro_rules! swap { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + start_lse!(), + // If FEAT_LSE2 is not supported, this works like byte-wise atomic. + // This is not single-copy atomic reads, but this is ok because subsequent + // CAS will check for consistency. + "ldp x4, x5, [{dst}]", + "2:", + // casp writes the current value to the first register pair, + // so copy the `out`'s value for later comparison. + "mov {tmp_lo}, x4", + "mov {tmp_hi}, x5", + concat!("casp", $acquire, $release, " x4, x5, x2, x3, [{dst}]"), + "cmp {tmp_hi}, x5", + "ccmp {tmp_lo}, x4, #0, eq", + "b.ne 2b", + $fence, + dst = in(reg) ptr_reg!(dst), + tmp_lo = out(reg) _, + tmp_hi = out(reg) _, + // must be allocated to even/odd register pair + out("x4") prev_lo, + out("x5") prev_hi, + // must be allocated to even/odd register pair + in("x2") val.pair.lo, + in("x3") val.pair.hi, + // Do not use `preserves_flags` because CMP and CCMP modify the condition flags. + options(nostack), + ) + }; + } + atomic_rmw!(swap, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} +// Do not use atomic_rmw_ll_sc_3 because it needs extra MOV to implement swap. +#[cfg(any( + test, + not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + )) +))] +#[inline] +unsafe fn _atomic_swap_ldxp_stxp(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let val = U128 { whole: val }; + let (mut prev_lo, mut prev_hi); + macro_rules! swap { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + "2:", + concat!("ld", $acquire, "xp {prev_lo}, {prev_hi}, [{dst}]"), + concat!("st", $release, "xp {r:w}, {val_lo}, {val_hi}, [{dst}]"), + // 0 if the store was successful, 1 if no store was performed + "cbnz {r:w}, 2b", + $fence, + dst = in(reg) ptr_reg!(dst), + val_lo = in(reg) val.pair.lo, + val_hi = in(reg) val.pair.hi, + prev_lo = out(reg) prev_lo, + prev_hi = out(reg) prev_hi, + r = out(reg) _, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(swap, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} + +/// Atomic RMW by LL/SC loop (3 arguments) +/// `unsafe fn(dst: *mut u128, val: u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - val_lo/val_hi pair: val argument (read-only for `$op`) +/// - prev_lo/prev_hi pair: previous value loaded by ll (read-only for `$op`) +/// - new_lo/new_hi pair: new value that will be stored by sc +macro_rules! atomic_rmw_ll_sc_3 { + ($name:ident as $reexport_name:ident $(($preserves_flags:tt))?, $($op:tt)*) => { + // If FEAT_LSE is available at compile-time and portable_atomic_ll_sc_rmw cfg is not set, + // we use CAS-based atomic RMW generated by atomic_rmw_cas_3! macro instead. + #[cfg(not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + )))] + use $name as $reexport_name; + #[cfg(any( + test, + not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + )) + ))] + #[inline] + unsafe fn $name(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + // SAFETY: the caller must uphold the safety contract. + unsafe { + let val = U128 { whole: val }; + let (mut prev_lo, mut prev_hi); + macro_rules! op { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + "2:", + concat!("ld", $acquire, "xp {prev_lo}, {prev_hi}, [{dst}]"), + $($op)* + concat!("st", $release, "xp {r:w}, {new_lo}, {new_hi}, [{dst}]"), + // 0 if the store was successful, 1 if no store was performed + "cbnz {r:w}, 2b", + $fence, + dst = in(reg) ptr_reg!(dst), + val_lo = in(reg) val.pair.lo, + val_hi = in(reg) val.pair.hi, + prev_lo = out(reg) prev_lo, + prev_hi = out(reg) prev_hi, + new_lo = out(reg) _, + new_hi = out(reg) _, + r = out(reg) _, + options(nostack $(, $preserves_flags)?), + ) + }; + } + atomic_rmw!(op, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } + } + }; +} +/// Atomic RMW by CAS loop (3 arguments) +/// `unsafe fn(dst: *mut u128, val: u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - val_lo/val_hi pair: val argument (read-only for `$op`) +/// - x6/x7 pair: previous value loaded (read-only for `$op`) +/// - x4/x5 pair: new value that will be stored +macro_rules! atomic_rmw_cas_3 { + ($name:ident as $reexport_name:ident, $($op:tt)*) => { + // If FEAT_LSE is not available at compile-time or portable_atomic_ll_sc_rmw cfg is set, + // we use LL/SC-based atomic RMW generated by atomic_rmw_ll_sc_3! macro instead. + #[cfg(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + ))] + use $name as $reexport_name; + #[cfg(any(test, not(portable_atomic_ll_sc_rmw)))] + #[cfg(any(target_feature = "lse", portable_atomic_target_feature = "lse"))] + #[inline] + unsafe fn $name(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_lse!(); + // SAFETY: the caller must uphold the safety contract. + // cfg guarantee that the CPU supports FEAT_LSE. + unsafe { + let val = U128 { whole: val }; + let (mut prev_lo, mut prev_hi); + macro_rules! op { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + start_lse!(), + // If FEAT_LSE2 is not supported, this works like byte-wise atomic. + // This is not single-copy atomic reads, but this is ok because subsequent + // CAS will check for consistency. + "ldp x6, x7, [{dst}]", + "2:", + // casp writes the current value to the first register pair, + // so copy the `out`'s value for later comparison. + "mov {tmp_lo}, x6", + "mov {tmp_hi}, x7", + $($op)* + concat!("casp", $acquire, $release, " x6, x7, x4, x5, [{dst}]"), + "cmp {tmp_hi}, x7", + "ccmp {tmp_lo}, x6, #0, eq", + "b.ne 2b", + $fence, + dst = in(reg) ptr_reg!(dst), + val_lo = in(reg) val.pair.lo, + val_hi = in(reg) val.pair.hi, + tmp_lo = out(reg) _, + tmp_hi = out(reg) _, + // must be allocated to even/odd register pair + out("x6") prev_lo, + out("x7") prev_hi, + // must be allocated to even/odd register pair + out("x4") _, + out("x5") _, + // Do not use `preserves_flags` because CMP and CCMP modify the condition flags. + options(nostack), + ) + }; + } + atomic_rmw!(op, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } + } + }; +} + +/// Atomic RMW by LL/SC loop (2 arguments) +/// `unsafe fn(dst: *mut u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - prev_lo/prev_hi pair: previous value loaded by ll (read-only for `$op`) +/// - new_lo/new_hi pair: new value that will be stored by sc +macro_rules! atomic_rmw_ll_sc_2 { + ($name:ident as $reexport_name:ident $(($preserves_flags:tt))?, $($op:tt)*) => { + // If FEAT_LSE is available at compile-time and portable_atomic_ll_sc_rmw cfg is not set, + // we use CAS-based atomic RMW generated by atomic_rmw_cas_2! macro instead. + #[cfg(not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + )))] + use $name as $reexport_name; + #[cfg(any( + test, + not(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + )) + ))] + #[inline] + unsafe fn $name(dst: *mut u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (mut prev_lo, mut prev_hi); + macro_rules! op { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + "2:", + concat!("ld", $acquire, "xp {prev_lo}, {prev_hi}, [{dst}]"), + $($op)* + concat!("st", $release, "xp {r:w}, {new_lo}, {new_hi}, [{dst}]"), + // 0 if the store was successful, 1 if no store was performed + "cbnz {r:w}, 2b", + $fence, + dst = in(reg) ptr_reg!(dst), + prev_lo = out(reg) prev_lo, + prev_hi = out(reg) prev_hi, + new_lo = out(reg) _, + new_hi = out(reg) _, + r = out(reg) _, + options(nostack $(, $preserves_flags)?), + ) + }; + } + atomic_rmw!(op, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } + } + }; +} +/// Atomic RMW by CAS loop (2 arguments) +/// `unsafe fn(dst: *mut u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - x6/x7 pair: previous value loaded (read-only for `$op`) +/// - x4/x5 pair: new value that will be stored +macro_rules! atomic_rmw_cas_2 { + ($name:ident as $reexport_name:ident, $($op:tt)*) => { + // If FEAT_LSE is not available at compile-time or portable_atomic_ll_sc_rmw cfg is set, + // we use LL/SC-based atomic RMW generated by atomic_rmw_ll_sc_3! macro instead. + #[cfg(all( + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + not(portable_atomic_ll_sc_rmw), + ))] + use $name as $reexport_name; + #[cfg(any(test, not(portable_atomic_ll_sc_rmw)))] + #[cfg(any(target_feature = "lse", portable_atomic_target_feature = "lse"))] + #[inline] + unsafe fn $name(dst: *mut u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_lse!(); + // SAFETY: the caller must uphold the safety contract. + // cfg guarantee that the CPU supports FEAT_LSE. + unsafe { + let (mut prev_lo, mut prev_hi); + macro_rules! op { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + start_lse!(), + // If FEAT_LSE2 is not supported, this works like byte-wise atomic. + // This is not single-copy atomic reads, but this is ok because subsequent + // CAS will check for consistency. + "ldp x6, x7, [{dst}]", + "2:", + // casp writes the current value to the first register pair, + // so copy the `out`'s value for later comparison. + "mov {tmp_lo}, x6", + "mov {tmp_hi}, x7", + $($op)* + concat!("casp", $acquire, $release, " x6, x7, x4, x5, [{dst}]"), + "cmp {tmp_hi}, x7", + "ccmp {tmp_lo}, x6, #0, eq", + "b.ne 2b", + $fence, + dst = in(reg) ptr_reg!(dst), + tmp_lo = out(reg) _, + tmp_hi = out(reg) _, + // must be allocated to even/odd register pair + out("x6") prev_lo, + out("x7") prev_hi, + // must be allocated to even/odd register pair + out("x4") _, + out("x5") _, + // Do not use `preserves_flags` because CMP and CCMP modify the condition flags. + options(nostack), + ) + }; + } + atomic_rmw!(op, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } + } + }; +} + +// Do not use `preserves_flags` because ADDS modifies the condition flags. +atomic_rmw_ll_sc_3! { + _atomic_add_ldxp_stxp as atomic_add, + select_le_or_be!("adds {new_lo}, {prev_lo}, {val_lo}", "adds {new_hi}, {prev_hi}, {val_hi}"), + select_le_or_be!("adc {new_hi}, {prev_hi}, {val_hi}", "adc {new_lo}, {prev_lo}, {val_lo}"), +} +atomic_rmw_cas_3! { + _atomic_add_casp as atomic_add, + select_le_or_be!("adds x4, x6, {val_lo}", "adds x5, x7, {val_hi}"), + select_le_or_be!("adc x5, x7, {val_hi}", "adc x4, x6, {val_lo}"), +} + +// Do not use `preserves_flags` because SUBS modifies the condition flags. +atomic_rmw_ll_sc_3! { + _atomic_sub_ldxp_stxp as atomic_sub, + select_le_or_be!("subs {new_lo}, {prev_lo}, {val_lo}", "subs {new_hi}, {prev_hi}, {val_hi}"), + select_le_or_be!("sbc {new_hi}, {prev_hi}, {val_hi}", "sbc {new_lo}, {prev_lo}, {val_lo}"), +} +atomic_rmw_cas_3! { + _atomic_sub_casp as atomic_sub, + select_le_or_be!("subs x4, x6, {val_lo}", "subs x5, x7, {val_hi}"), + select_le_or_be!("sbc x5, x7, {val_hi}", "sbc x4, x6, {val_lo}"), +} + +#[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] +atomic_rmw_ll_sc_3! { + _atomic_and_ldxp_stxp as atomic_and (preserves_flags), + "and {new_lo}, {prev_lo}, {val_lo}", + "and {new_hi}, {prev_hi}, {val_hi}", +} +#[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] +atomic_rmw_cas_3! { + _atomic_and_casp as atomic_and, + "and x4, x6, {val_lo}", + "and x5, x7, {val_hi}", +} +#[cfg(any(target_feature = "lse128", portable_atomic_target_feature = "lse128"))] +#[inline] +unsafe fn atomic_and(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, that there are no concurrent non-atomic operations, + // and the CPU supports FEAT_LSE128. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/LDCLRP--LDCLRPA--LDCLRPAL--LDCLRPL--Atomic-bit-clear-on-quadword-in-memory- + unsafe { + let val = U128 { whole: !val }; + let (prev_lo, prev_hi); + #[cfg(not(portable_atomic_pre_llvm_16))] + macro_rules! clear { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + start_lse128!(), + concat!("ldclrp", $acquire, $release, " {val_lo}, {val_hi}, [{dst}]"), + $fence, + dst = in(reg) ptr_reg!(dst), + val_lo = inout(reg) val.pair.lo => prev_lo, + val_hi = inout(reg) val.pair.hi => prev_hi, + options(nostack, preserves_flags), + ) + }; + } + #[cfg(not(portable_atomic_pre_llvm_16))] + atomic_rmw!(clear, order); + // LLVM supports FEAT_LSE128 instructions on LLVM 16+, so use .inst directive on old LLVM. + // https://github.com/llvm/llvm-project/commit/7fea6f2e0e606e5339c3359568f680eaf64aa306 + #[cfg(portable_atomic_pre_llvm_16)] + macro_rules! clear { + ($order:tt, $fence:tt) => { + asm!( + // 8: 19{2,a,6,e}11008 ldclrp{,a,l,al} x8, x1, [x0] + concat!(".inst 0x19", $order, "11008"), + $fence, + in("x0") ptr_reg!(dst), + inout("x8") val.pair.lo => prev_lo, + inout("x1") val.pair.hi => prev_hi, + options(nostack, preserves_flags), + ) + }; + } + #[cfg(portable_atomic_pre_llvm_16)] + atomic_rmw_inst!(clear, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} + +atomic_rmw_ll_sc_3! { + _atomic_nand_ldxp_stxp as atomic_nand (preserves_flags), + "and {new_lo}, {prev_lo}, {val_lo}", + "mvn {new_lo}, {new_lo}", + "and {new_hi}, {prev_hi}, {val_hi}", + "mvn {new_hi}, {new_hi}", +} +atomic_rmw_cas_3! { + _atomic_nand_casp as atomic_nand, + "and x4, x6, {val_lo}", + "mvn x4, x4", + "and x5, x7, {val_hi}", + "mvn x5, x5", +} + +#[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] +atomic_rmw_ll_sc_3! { + _atomic_or_ldxp_stxp as atomic_or (preserves_flags), + "orr {new_lo}, {prev_lo}, {val_lo}", + "orr {new_hi}, {prev_hi}, {val_hi}", +} +#[cfg(not(any(target_feature = "lse128", portable_atomic_target_feature = "lse128")))] +atomic_rmw_cas_3! { + _atomic_or_casp as atomic_or, + "orr x4, x6, {val_lo}", + "orr x5, x7, {val_hi}", +} +#[cfg(any(target_feature = "lse128", portable_atomic_target_feature = "lse128"))] +#[inline] +unsafe fn atomic_or(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, that there are no concurrent non-atomic operations, + // and the CPU supports FEAT_LSE128. + // + // Refs: https://developer.arm.com/documentation/ddi0602/2024-06/Base-Instructions/LDSETP--LDSETPA--LDSETPAL--LDSETPL--Atomic-bit-set-on-quadword-in-memory- + unsafe { + let val = U128 { whole: val }; + let (prev_lo, prev_hi); + #[cfg(not(portable_atomic_pre_llvm_16))] + macro_rules! or { + ($acquire:tt, $release:tt, $fence:tt) => { + asm!( + start_lse128!(), + concat!("ldsetp", $acquire, $release, " {val_lo}, {val_hi}, [{dst}]"), + $fence, + dst = in(reg) ptr_reg!(dst), + val_lo = inout(reg) val.pair.lo => prev_lo, + val_hi = inout(reg) val.pair.hi => prev_hi, + options(nostack, preserves_flags), + ) + }; + } + #[cfg(not(portable_atomic_pre_llvm_16))] + atomic_rmw!(or, order); + // LLVM supports FEAT_LSE128 instructions on LLVM 16+, so use .inst directive on old LLVM. + // https://github.com/llvm/llvm-project/commit/7fea6f2e0e606e5339c3359568f680eaf64aa306 + #[cfg(portable_atomic_pre_llvm_16)] + macro_rules! or { + ($order:tt, $fence:tt) => { + asm!( + // 4: 19{2,a,6,e}13002 ldsetp{,a,l,al} x2, x1, [x0] + concat!(".inst 0x19", $order, "13002"), + $fence, + in("x0") ptr_reg!(dst), + inout("x2") val.pair.lo => prev_lo, + inout("x1") val.pair.hi => prev_hi, + options(nostack, preserves_flags), + ) + }; + } + #[cfg(portable_atomic_pre_llvm_16)] + atomic_rmw_inst!(or, order); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} + +atomic_rmw_ll_sc_3! { + _atomic_xor_ldxp_stxp as atomic_xor (preserves_flags), + "eor {new_lo}, {prev_lo}, {val_lo}", + "eor {new_hi}, {prev_hi}, {val_hi}", +} +atomic_rmw_cas_3! { + _atomic_xor_casp as atomic_xor, + "eor x4, x6, {val_lo}", + "eor x5, x7, {val_hi}", +} + +atomic_rmw_ll_sc_2! { + _atomic_not_ldxp_stxp as atomic_not (preserves_flags), + "mvn {new_lo}, {prev_lo}", + "mvn {new_hi}, {prev_hi}", +} +atomic_rmw_cas_2! { + _atomic_not_casp as atomic_not, + "mvn x4, x6", + "mvn x5, x7", +} + +// Do not use `preserves_flags` because NEGS modifies the condition flags. +atomic_rmw_ll_sc_2! { + _atomic_neg_ldxp_stxp as atomic_neg, + select_le_or_be!("negs {new_lo}, {prev_lo}", "negs {new_hi}, {prev_hi}"), + select_le_or_be!("ngc {new_hi}, {prev_hi}", "ngc {new_lo}, {prev_lo}"), +} +atomic_rmw_cas_2! { + _atomic_neg_casp as atomic_neg, + select_le_or_be!("negs x4, x6", "negs x5, x7"), + select_le_or_be!("ngc x5, x7", "ngc x4, x6"), +} + +// Do not use `preserves_flags` because CMP and SBCS modify the condition flags. +atomic_rmw_ll_sc_3! { + _atomic_max_ldxp_stxp as atomic_max, + select_le_or_be!("cmp {val_lo}, {prev_lo}", "cmp {val_hi}, {prev_hi}"), + select_le_or_be!("sbcs xzr, {val_hi}, {prev_hi}", "sbcs xzr, {val_lo}, {prev_lo}"), + "csel {new_hi}, {prev_hi}, {val_hi}, lt", // select hi 64-bit + "csel {new_lo}, {prev_lo}, {val_lo}, lt", // select lo 64-bit +} +atomic_rmw_cas_3! { + _atomic_max_casp as atomic_max, + select_le_or_be!("cmp {val_lo}, x6", "cmp {val_hi}, x7"), + select_le_or_be!("sbcs xzr, {val_hi}, x7", "sbcs xzr, {val_lo}, x6"), + "csel x5, x7, {val_hi}, lt", // select hi 64-bit + "csel x4, x6, {val_lo}, lt", // select lo 64-bit +} + +// Do not use `preserves_flags` because CMP and SBCS modify the condition flags. +atomic_rmw_ll_sc_3! { + _atomic_umax_ldxp_stxp as atomic_umax, + select_le_or_be!("cmp {val_lo}, {prev_lo}", "cmp {val_hi}, {prev_hi}"), + select_le_or_be!("sbcs xzr, {val_hi}, {prev_hi}", "sbcs xzr, {val_lo}, {prev_lo}"), + "csel {new_hi}, {prev_hi}, {val_hi}, lo", // select hi 64-bit + "csel {new_lo}, {prev_lo}, {val_lo}, lo", // select lo 64-bit +} +atomic_rmw_cas_3! { + _atomic_umax_casp as atomic_umax, + select_le_or_be!("cmp {val_lo}, x6", "cmp {val_hi}, x7"), + select_le_or_be!("sbcs xzr, {val_hi}, x7", "sbcs xzr, {val_lo}, x6"), + "csel x5, x7, {val_hi}, lo", // select hi 64-bit + "csel x4, x6, {val_lo}, lo", // select lo 64-bit +} + +// Do not use `preserves_flags` because CMP and SBCS modify the condition flags. +atomic_rmw_ll_sc_3! { + _atomic_min_ldxp_stxp as atomic_min, + select_le_or_be!("cmp {val_lo}, {prev_lo}", "cmp {val_hi}, {prev_hi}"), + select_le_or_be!("sbcs xzr, {val_hi}, {prev_hi}", "sbcs xzr, {val_lo}, {prev_lo}"), + "csel {new_hi}, {prev_hi}, {val_hi}, ge", // select hi 64-bit + "csel {new_lo}, {prev_lo}, {val_lo}, ge", // select lo 64-bit +} +atomic_rmw_cas_3! { + _atomic_min_casp as atomic_min, + select_le_or_be!("cmp {val_lo}, x6", "cmp {val_hi}, x7"), + select_le_or_be!("sbcs xzr, {val_hi}, x7", "sbcs xzr, {val_lo}, x6"), + "csel x5, x7, {val_hi}, ge", // select hi 64-bit + "csel x4, x6, {val_lo}, ge", // select lo 64-bit +} + +// Do not use `preserves_flags` because CMP and SBCS modify the condition flags. +atomic_rmw_ll_sc_3! { + _atomic_umin_ldxp_stxp as atomic_umin, + select_le_or_be!("cmp {val_lo}, {prev_lo}", "cmp {val_hi}, {prev_hi}"), + select_le_or_be!("sbcs xzr, {val_hi}, {prev_hi}", "sbcs xzr, {val_lo}, {prev_lo}"), + "csel {new_hi}, {prev_hi}, {val_hi}, hs", // select hi 64-bit + "csel {new_lo}, {prev_lo}, {val_lo}, hs", // select lo 64-bit +} +atomic_rmw_cas_3! { + _atomic_umin_casp as atomic_umin, + select_le_or_be!("cmp {val_lo}, x6", "cmp {val_hi}, x7"), + select_le_or_be!("sbcs xzr, {val_hi}, x7", "sbcs xzr, {val_lo}, x6"), + "csel x5, x7, {val_hi}, hs", // select hi 64-bit + "csel x4, x6, {val_lo}, hs", // select lo 64-bit +} + +#[inline] +const fn is_lock_free() -> bool { + IS_ALWAYS_LOCK_FREE +} +const IS_ALWAYS_LOCK_FREE: bool = true; + +atomic128!(AtomicI128, i128, atomic_max, atomic_min); +atomic128!(AtomicU128, u128, atomic_umax, atomic_umin); + +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_int!(i128); + test_atomic_int!(u128); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u128); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/intrinsics.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/intrinsics.rs new file mode 100644 index 0000000..816ac67 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/intrinsics.rs @@ -0,0 +1,515 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +128-bit atomic implementation without inline assembly. + +Adapted from https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs. + +Note: This module is currently only enabled on Miri and ThreadSanitizer which +do not support inline assembly. + +This uses `core::arch::x86_64::cmpxchg16b` on x86_64 and +`core::intrinsics::atomic_*` on aarch64, powerpc64, and s390x. + +See README.md of this directory for performance comparison with the +implementation with inline assembly. + +Note: +- This currently needs Rust 1.70 on x86_64, otherwise nightly compilers. +- On powerpc64, this requires LLVM 15+ and pwr8+ (quadword-atomics LLVM target feature): + https://github.com/llvm/llvm-project/commit/549e118e93c666914a1045fde38a2cac33e1e445 +- On s390x, old LLVM (pre-18) generates libcalls for operations other than load/store/cmpxchg: + https://github.com/llvm/llvm-project/commit/c568927f3e2e7d9804ea74ecbf11c16c014ddcbc +- On aarch64 big-endian, LLVM (as of 17) generates broken code. (wrong result in stress test) + (on cfg(miri)/cfg(sanitize) it may be fine though) +- On powerpc64, LLVM (as of 17) doesn't support 128-bit atomic min/max: + https://github.com/llvm/llvm-project/issues/68390 +- On powerpc64le, LLVM (as of 17) generates broken code. (wrong result from fetch_add) +*/ + +include!("macros.rs"); + +#[allow(dead_code)] // we only use compare_exchange. +#[cfg(target_arch = "x86_64")] +#[cfg(not(target_feature = "cmpxchg16b"))] +#[path = "../fallback/outline_atomics.rs"] +mod fallback; + +#[cfg(target_arch = "x86_64")] +#[cfg(not(target_feature = "cmpxchg16b"))] +#[path = "../detect/x86_64.rs"] +mod detect; + +use core::sync::atomic::Ordering; +#[cfg(not(target_arch = "x86_64"))] +use core::{ + intrinsics, + sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release, SeqCst}, +}; + +// https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L3267 +#[cfg(target_arch = "x86_64")] +#[inline] +fn strongest_failure_ordering(order: Ordering) -> Ordering { + match order { + Ordering::Release | Ordering::Relaxed => Ordering::Relaxed, + Ordering::SeqCst => Ordering::SeqCst, + Ordering::Acquire | Ordering::AcqRel => Ordering::Acquire, + _ => unreachable!(), + } +} + +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_load(src: *mut u128, order: Ordering) -> u128 { + #[cfg(target_arch = "x86_64")] + // SAFETY: the caller must uphold the safety contract. + unsafe { + let fail_order = strongest_failure_ordering(order); + match atomic_compare_exchange(src, 0, 0, order, fail_order) { + Ok(v) | Err(v) => v, + } + } + #[cfg(not(target_arch = "x86_64"))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_load_acquire(src), + Relaxed => intrinsics::atomic_load_relaxed(src), + SeqCst => intrinsics::atomic_load_seqcst(src), + _ => unreachable!(), + } + } +} + +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_store(dst: *mut u128, val: u128, order: Ordering) { + #[cfg(target_arch = "x86_64")] + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_swap(dst, val, order); + } + #[cfg(not(target_arch = "x86_64"))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Release => intrinsics::atomic_store_release(dst, val), + Relaxed => intrinsics::atomic_store_relaxed(dst, val), + SeqCst => intrinsics::atomic_store_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_compare_exchange( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> Result { + #[cfg(target_arch = "x86_64")] + let (val, ok) = { + #[target_feature(enable = "cmpxchg16b")] + #[cfg_attr(target_feature = "cmpxchg16b", inline)] + #[cfg_attr(not(target_feature = "cmpxchg16b"), inline(never))] + unsafe fn cmpxchg16b( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, + ) -> (u128, bool) { + debug_assert!(dst as usize % 16 == 0); + #[cfg(not(target_feature = "cmpxchg16b"))] + { + debug_assert!(detect::detect().has_cmpxchg16b()); + } + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned (required by CMPXCHG16B), that there are no + // concurrent non-atomic operations, and that the CPU supports CMPXCHG16B. + let prev = unsafe { core::arch::x86_64::cmpxchg16b(dst, old, new, success, failure) }; + (prev, prev == old) + } + #[cfg(target_feature = "cmpxchg16b")] + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, that there are no concurrent non-atomic operations, + // and cfg guarantees that CMPXCHG16B is available at compile-time. + unsafe { + cmpxchg16b(dst, old, new, success, failure) + } + #[cfg(not(target_feature = "cmpxchg16b"))] + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, and that there are no different kinds of concurrent accesses. + unsafe { + ifunc!(unsafe fn( + dst: *mut u128, old: u128, new: u128, success: Ordering, failure: Ordering + ) -> (u128, bool) { + if detect::detect().has_cmpxchg16b() { + cmpxchg16b + } else { + fallback::atomic_compare_exchange + } + }) + } + }; + #[cfg(not(target_arch = "x86_64"))] + // SAFETY: the caller must uphold the safety contract. + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => intrinsics::atomic_cxchg_relaxed_relaxed(dst, old, new), + (Relaxed, Acquire) => intrinsics::atomic_cxchg_relaxed_acquire(dst, old, new), + (Relaxed, SeqCst) => intrinsics::atomic_cxchg_relaxed_seqcst(dst, old, new), + (Acquire, Relaxed) => intrinsics::atomic_cxchg_acquire_relaxed(dst, old, new), + (Acquire, Acquire) => intrinsics::atomic_cxchg_acquire_acquire(dst, old, new), + (Acquire, SeqCst) => intrinsics::atomic_cxchg_acquire_seqcst(dst, old, new), + (Release, Relaxed) => intrinsics::atomic_cxchg_release_relaxed(dst, old, new), + (Release, Acquire) => intrinsics::atomic_cxchg_release_acquire(dst, old, new), + (Release, SeqCst) => intrinsics::atomic_cxchg_release_seqcst(dst, old, new), + (AcqRel, Relaxed) => intrinsics::atomic_cxchg_acqrel_relaxed(dst, old, new), + (AcqRel, Acquire) => intrinsics::atomic_cxchg_acqrel_acquire(dst, old, new), + (AcqRel, SeqCst) => intrinsics::atomic_cxchg_acqrel_seqcst(dst, old, new), + (SeqCst, Relaxed) => intrinsics::atomic_cxchg_seqcst_relaxed(dst, old, new), + (SeqCst, Acquire) => intrinsics::atomic_cxchg_seqcst_acquire(dst, old, new), + (SeqCst, SeqCst) => intrinsics::atomic_cxchg_seqcst_seqcst(dst, old, new), + _ => unreachable!(), + } + }; + if ok { + Ok(val) + } else { + Err(val) + } +} + +#[cfg(target_arch = "x86_64")] +use atomic_compare_exchange as atomic_compare_exchange_weak; +#[cfg(not(target_arch = "x86_64"))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_compare_exchange_weak( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> Result { + // SAFETY: the caller must uphold the safety contract. + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => intrinsics::atomic_cxchgweak_relaxed_relaxed(dst, old, new), + (Relaxed, Acquire) => intrinsics::atomic_cxchgweak_relaxed_acquire(dst, old, new), + (Relaxed, SeqCst) => intrinsics::atomic_cxchgweak_relaxed_seqcst(dst, old, new), + (Acquire, Relaxed) => intrinsics::atomic_cxchgweak_acquire_relaxed(dst, old, new), + (Acquire, Acquire) => intrinsics::atomic_cxchgweak_acquire_acquire(dst, old, new), + (Acquire, SeqCst) => intrinsics::atomic_cxchgweak_acquire_seqcst(dst, old, new), + (Release, Relaxed) => intrinsics::atomic_cxchgweak_release_relaxed(dst, old, new), + (Release, Acquire) => intrinsics::atomic_cxchgweak_release_acquire(dst, old, new), + (Release, SeqCst) => intrinsics::atomic_cxchgweak_release_seqcst(dst, old, new), + (AcqRel, Relaxed) => intrinsics::atomic_cxchgweak_acqrel_relaxed(dst, old, new), + (AcqRel, Acquire) => intrinsics::atomic_cxchgweak_acqrel_acquire(dst, old, new), + (AcqRel, SeqCst) => intrinsics::atomic_cxchgweak_acqrel_seqcst(dst, old, new), + (SeqCst, Relaxed) => intrinsics::atomic_cxchgweak_seqcst_relaxed(dst, old, new), + (SeqCst, Acquire) => intrinsics::atomic_cxchgweak_seqcst_acquire(dst, old, new), + (SeqCst, SeqCst) => intrinsics::atomic_cxchgweak_seqcst_seqcst(dst, old, new), + _ => unreachable!(), + } + }; + if ok { + Ok(val) + } else { + Err(val) + } +} + +#[inline(always)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_update(dst: *mut u128, order: Ordering, mut f: F) -> u128 +where + F: FnMut(u128) -> u128, +{ + // SAFETY: the caller must uphold the safety contract. + unsafe { + // This is a private function and all instances of `f` only operate on the value + // loaded, so there is no need to synchronize the first load/failed CAS. + let mut prev = atomic_load(dst, Ordering::Relaxed); + loop { + let next = f(prev); + match atomic_compare_exchange_weak(dst, prev, next, order, Ordering::Relaxed) { + Ok(x) => return x, + Err(x) => prev = x, + } + } + } +} + +// On x86_64, we use core::arch::x86_64::cmpxchg16b instead of core::intrinsics. +// - On s390x, old LLVM (pre-18) generates libcalls for operations other than load/store/cmpxchg (see also module-level comment). +#[cfg(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18)))] +atomic_rmw_by_atomic_update!(); +// On powerpc64, LLVM doesn't support 128-bit atomic min/max (see also module-level comment). +#[cfg(target_arch = "powerpc64")] +atomic_rmw_by_atomic_update!(cmp); + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_swap(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_xchg_acquire(dst, val), + Release => intrinsics::atomic_xchg_release(dst, val), + AcqRel => intrinsics::atomic_xchg_acqrel(dst, val), + Relaxed => intrinsics::atomic_xchg_relaxed(dst, val), + SeqCst => intrinsics::atomic_xchg_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_add(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_xadd_acquire(dst, val), + Release => intrinsics::atomic_xadd_release(dst, val), + AcqRel => intrinsics::atomic_xadd_acqrel(dst, val), + Relaxed => intrinsics::atomic_xadd_relaxed(dst, val), + SeqCst => intrinsics::atomic_xadd_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_sub(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_xsub_acquire(dst, val), + Release => intrinsics::atomic_xsub_release(dst, val), + AcqRel => intrinsics::atomic_xsub_acqrel(dst, val), + Relaxed => intrinsics::atomic_xsub_relaxed(dst, val), + SeqCst => intrinsics::atomic_xsub_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_and(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_and_acquire(dst, val), + Release => intrinsics::atomic_and_release(dst, val), + AcqRel => intrinsics::atomic_and_acqrel(dst, val), + Relaxed => intrinsics::atomic_and_relaxed(dst, val), + SeqCst => intrinsics::atomic_and_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_nand(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_nand_acquire(dst, val), + Release => intrinsics::atomic_nand_release(dst, val), + AcqRel => intrinsics::atomic_nand_acqrel(dst, val), + Relaxed => intrinsics::atomic_nand_relaxed(dst, val), + SeqCst => intrinsics::atomic_nand_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_or(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_or_acquire(dst, val), + Release => intrinsics::atomic_or_release(dst, val), + AcqRel => intrinsics::atomic_or_acqrel(dst, val), + Relaxed => intrinsics::atomic_or_relaxed(dst, val), + SeqCst => intrinsics::atomic_or_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_xor(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_xor_acquire(dst, val), + Release => intrinsics::atomic_xor_release(dst, val), + AcqRel => intrinsics::atomic_xor_acqrel(dst, val), + Relaxed => intrinsics::atomic_xor_relaxed(dst, val), + SeqCst => intrinsics::atomic_xor_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any( + target_arch = "x86_64", + target_arch = "powerpc64", + all(target_arch = "s390x", portable_atomic_pre_llvm_18), +)))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_max(dst: *mut u128, val: u128, order: Ordering) -> i128 { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_max_acquire(dst.cast::(), val as i128), + Release => intrinsics::atomic_max_release(dst.cast::(), val as i128), + AcqRel => intrinsics::atomic_max_acqrel(dst.cast::(), val as i128), + Relaxed => intrinsics::atomic_max_relaxed(dst.cast::(), val as i128), + SeqCst => intrinsics::atomic_max_seqcst(dst.cast::(), val as i128), + _ => unreachable!(), + } + } +} + +#[cfg(not(any( + target_arch = "x86_64", + target_arch = "powerpc64", + all(target_arch = "s390x", portable_atomic_pre_llvm_18), +)))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_min(dst: *mut u128, val: u128, order: Ordering) -> i128 { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_min_acquire(dst.cast::(), val as i128), + Release => intrinsics::atomic_min_release(dst.cast::(), val as i128), + AcqRel => intrinsics::atomic_min_acqrel(dst.cast::(), val as i128), + Relaxed => intrinsics::atomic_min_relaxed(dst.cast::(), val as i128), + SeqCst => intrinsics::atomic_min_seqcst(dst.cast::(), val as i128), + _ => unreachable!(), + } + } +} + +#[cfg(not(any( + target_arch = "x86_64", + target_arch = "powerpc64", + all(target_arch = "s390x", portable_atomic_pre_llvm_18), +)))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_umax(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_umax_acquire(dst, val), + Release => intrinsics::atomic_umax_release(dst, val), + AcqRel => intrinsics::atomic_umax_acqrel(dst, val), + Relaxed => intrinsics::atomic_umax_relaxed(dst, val), + SeqCst => intrinsics::atomic_umax_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any( + target_arch = "x86_64", + target_arch = "powerpc64", + all(target_arch = "s390x", portable_atomic_pre_llvm_18), +)))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_umin(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + match order { + Acquire => intrinsics::atomic_umin_acquire(dst, val), + Release => intrinsics::atomic_umin_release(dst, val), + AcqRel => intrinsics::atomic_umin_acqrel(dst, val), + Relaxed => intrinsics::atomic_umin_relaxed(dst, val), + SeqCst => intrinsics::atomic_umin_seqcst(dst, val), + _ => unreachable!(), + } + } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_not(dst: *mut u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_xor(dst, !0, order) } +} + +#[cfg(not(any(target_arch = "x86_64", all(target_arch = "s390x", portable_atomic_pre_llvm_18))))] +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +unsafe fn atomic_neg(dst: *mut u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, u128::wrapping_neg) } +} + +#[cfg(not(target_arch = "x86_64"))] +#[inline] +const fn is_lock_free() -> bool { + IS_ALWAYS_LOCK_FREE +} +#[cfg(not(target_arch = "x86_64"))] +const IS_ALWAYS_LOCK_FREE: bool = true; + +#[cfg(target_arch = "x86_64")] +#[inline] +fn is_lock_free() -> bool { + #[cfg(target_feature = "cmpxchg16b")] + { + // CMPXCHG16B is available at compile-time. + true + } + #[cfg(not(target_feature = "cmpxchg16b"))] + { + detect::detect().has_cmpxchg16b() + } +} +#[cfg(target_arch = "x86_64")] +const IS_ALWAYS_LOCK_FREE: bool = cfg!(target_feature = "cmpxchg16b"); + +atomic128!(AtomicI128, i128, atomic_max, atomic_min); +atomic128!(AtomicU128, u128, atomic_umax, atomic_umin); + +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_int!(i128); + test_atomic_int!(u128); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u128); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/macros.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/macros.rs new file mode 100644 index 0000000..98cb1a1 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/macros.rs @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +macro_rules! atomic128 { + ($atomic_type:ident, $int_type:ident, $atomic_max:ident, $atomic_min:ident) => { + #[repr(C, align(16))] + pub(crate) struct $atomic_type { + v: core::cell::UnsafeCell<$int_type>, + } + + // Send is implicitly implemented. + // SAFETY: any data races are prevented by atomic intrinsics. + unsafe impl Sync for $atomic_type {} + + impl_default_no_fetch_ops!($atomic_type, $int_type); + impl_default_bit_opts!($atomic_type, $int_type); + impl $atomic_type { + #[inline] + pub(crate) const fn new(v: $int_type) -> Self { + Self { v: core::cell::UnsafeCell::new(v) } + } + + #[inline] + pub(crate) fn is_lock_free() -> bool { + is_lock_free() + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = IS_ALWAYS_LOCK_FREE; + + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $int_type { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.v.get() } + } + + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn load(&self, order: Ordering) -> $int_type { + crate::utils::assert_load_ordering(order); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_load(self.v.get().cast::(), order) as $int_type + } + } + + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn store(&self, val: $int_type, order: Ordering) { + crate::utils::assert_store_ordering(order); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_store(self.v.get().cast::(), val as u128, order) + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn swap(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_swap(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + match atomic_compare_exchange( + self.v.get().cast::(), + current as u128, + new as u128, + success, + failure, + ) { + Ok(v) => Ok(v as $int_type), + Err(v) => Err(v as $int_type), + } + } + } + + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + match atomic_compare_exchange_weak( + self.v.get().cast::(), + current as u128, + new as u128, + success, + failure, + ) { + Ok(v) => Ok(v as $int_type), + Err(v) => Err(v as $int_type), + } + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_add(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_sub(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_and(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_nand(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_or(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_xor(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + $atomic_max(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + $atomic_min(self.v.get().cast::(), val as u128, order) as $int_type + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_not(&self, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_not(self.v.get().cast::(), order) as $int_type + } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_neg(&self, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_neg(self.v.get().cast::(), order) as $int_type + } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } + + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut $int_type { + self.v.get() + } + } + }; +} + +#[cfg(any(target_arch = "powerpc64", target_arch = "s390x", target_arch = "x86_64"))] +#[allow(unused_macros)] // also used by intrinsics.rs +macro_rules! atomic_rmw_by_atomic_update { + () => { + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_swap(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |_| val) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_add(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| x.wrapping_add(val)) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_sub(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| x.wrapping_sub(val)) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_and(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| x & val) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_nand(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| !(x & val)) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_or(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| x | val) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_xor(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| x ^ val) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_not(dst: *mut u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| !x) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_neg(dst: *mut u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, u128::wrapping_neg) } + } + atomic_rmw_by_atomic_update!(cmp); + }; + (cmp) => { + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_max(dst: *mut u128, val: u128, order: Ordering) -> u128 { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_update(dst, order, |x| core::cmp::max(x as i128, val as i128) as u128) + } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_umax(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| core::cmp::max(x, val)) } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_min(dst: *mut u128, val: u128, order: Ordering) -> u128 { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_update(dst, order, |x| core::cmp::min(x as i128, val as i128) as u128) + } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + unsafe fn atomic_umin(dst: *mut u128, val: u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update(dst, order, |x| core::cmp::min(x, val)) } + } + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/mod.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/mod.rs new file mode 100644 index 0000000..6c98be2 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/mod.rs @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +128-bit atomic implementations on 64-bit architectures + +See README.md for details. +*/ + +// AArch64 +#[cfg(any( + all(target_arch = "aarch64", any(not(portable_atomic_no_asm), portable_atomic_unstable_asm)), + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch) +))] +// Use intrinsics.rs on Miri and Sanitizer that do not support inline assembly. +#[cfg_attr( + all(any(miri, portable_atomic_sanitize_thread), portable_atomic_new_atomic_intrinsics), + path = "intrinsics.rs" +)] +pub(super) mod aarch64; + +// powerpc64 +#[cfg(all( + target_arch = "powerpc64", + portable_atomic_unstable_asm_experimental_arch, + any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(powerpc64): currently disabled by default + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + all(target_os = "openbsd", portable_atomic_outline_atomics), + ), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), +))] +// Use intrinsics.rs on Miri and Sanitizer that do not support inline assembly. +#[cfg_attr( + all(any(miri, portable_atomic_sanitize_thread), not(portable_atomic_pre_llvm_15)), + path = "intrinsics.rs" +)] +pub(super) mod powerpc64; + +// riscv64 +#[cfg(all( + target_arch = "riscv64", + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), +))] +// Use intrinsics.rs on Miri and Sanitizer that do not support inline assembly. +#[cfg_attr(any(miri, portable_atomic_sanitize_thread), path = "intrinsics.rs")] +pub(super) mod riscv64; + +// s390x +#[cfg(all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch))] +// Use intrinsics.rs on Miri and Sanitizer that do not support inline assembly. +#[cfg_attr(any(miri, portable_atomic_sanitize_thread), path = "intrinsics.rs")] +pub(super) mod s390x; + +// x86_64 +#[cfg(all( + target_arch = "x86_64", + not(all(any(miri, portable_atomic_sanitize_thread), portable_atomic_no_cmpxchg16b_intrinsic)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + not(any(target_env = "sgx", miri)), + ), + ), +))] +// Use intrinsics.rs on Miri and Sanitizer that do not support inline assembly. +#[cfg_attr(any(miri, portable_atomic_sanitize_thread), path = "intrinsics.rs")] +pub(super) mod x86_64; diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/powerpc64.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/powerpc64.rs new file mode 100644 index 0000000..47da45d --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/powerpc64.rs @@ -0,0 +1,945 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +128-bit atomic implementation on PowerPC64. + +powerpc64 on pwr8+ support 128-bit atomics (load/store/LL/SC): +https://github.com/llvm/llvm-project/commit/549e118e93c666914a1045fde38a2cac33e1e445 +https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/test/CodeGen/PowerPC/atomics-i128-ldst.ll +https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/test/CodeGen/PowerPC/atomics-i128.ll + +powerpc64le is pwr8+ by default https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/PowerPC/PPC.td#L702 +See also https://github.com/rust-lang/rust/issues/59932 + +Note that we do not separate LL and SC into separate functions, but handle +them within a single asm block. This is because it is theoretically possible +for the compiler to insert operations that might clear the reservation between +LL and SC. See aarch64.rs for details. + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use intrinsics.rs instead. + +Refs: +- Power ISA https://openpowerfoundation.org/specifications/isa +- AIX Assembler language reference https://www.ibm.com/docs/en/aix/7.3?topic=aix-assembler-language-reference +- atomic-maybe-uninit https://github.com/taiki-e/atomic-maybe-uninit + +Generated asm: +- powerpc64 (pwr8) https://godbolt.org/z/71xGhY9qf +- powerpc64le https://godbolt.org/z/4TexcjGEz +*/ + +include!("macros.rs"); + +#[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +)))] +#[path = "../fallback/outline_atomics.rs"] +mod fallback; + +// On musl with static linking, it seems that getauxval is not always available. +// See detect/auxv.rs for more. +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any(test, portable_atomic_outline_atomics))] // TODO(powerpc64): currently disabled by default +#[cfg(any( + test, + not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + )), +))] +#[cfg(any( + all( + target_os = "linux", + any( + target_env = "gnu", + all(any(target_env = "musl", target_env = "ohos"), not(target_feature = "crt-static")), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + all(target_os = "openbsd", portable_atomic_outline_atomics), +))] +#[path = "../detect/auxv.rs"] +mod detect; + +use core::{arch::asm, sync::atomic::Ordering}; + +use crate::utils::{Pair, U128}; + +macro_rules! debug_assert_pwr8 { + () => { + #[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + )))] + { + debug_assert!(detect::detect().has_quadword_atomics()); + } + }; +} + +// Refs: https://www.ibm.com/docs/en/aix/7.3?topic=ops-machine-pseudo-op +// +// This is similar to #[target_feature(enable = "quadword-atomics")], except that there are +// no compiler guarantees regarding (un)inlining, and the scope is within an asm +// block rather than a function. We use this directive because #[target_feature(enable = "quadword-atomics")] +// is not supported as of Rust 1.70-nightly. +// +// start_pwr8 and end_pwr8 must be used in pairs. +// +// Note: If power8 instructions are not available at compile-time, we must guarantee that +// the function that uses it is not inlined into a function where it is not +// clear whether power8 instructions are available. Otherwise, (even if we checked whether +// power8 instructions are available at run-time) optimizations that reorder its +// instructions across the if condition might introduce undefined behavior. +// (see also https://rust-lang.github.io/rfcs/2045-target-feature.html#safely-inlining-target_feature-functions-on-more-contexts) +// However, our code uses the ifunc helper macro that works with function pointers, +// so we don't have to worry about this unless calling without helper macro. +macro_rules! start_pwr8 { + () => { + ".machine push\n.machine power8" + }; +} +macro_rules! end_pwr8 { + () => { + ".machine pop" + }; +} + +macro_rules! atomic_rmw { + ($op:ident, $order:ident) => { + match $order { + Ordering::Relaxed => $op!("", ""), + Ordering::Acquire => $op!("lwsync", ""), + Ordering::Release => $op!("", "lwsync"), + Ordering::AcqRel => $op!("lwsync", "lwsync"), + Ordering::SeqCst => $op!("lwsync", "sync"), + _ => unreachable!(), + } + }; +} + +// Extracts and checks the EQ bit of cr0. +#[inline(always)] +fn extract_cr0(r: u64) -> bool { + r & 0x20000000 != 0 +} + +// If quadword-atomics is available at compile-time, we can always use pwr8_fn. +#[cfg(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +))] +use atomic_load_pwr8 as atomic_load; +// Otherwise, we need to do run-time detection and can use pwr8_fn only if quadword-atomics is available. +#[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +)))] +#[inline] +unsafe fn atomic_load(src: *mut u128, order: Ordering) -> u128 { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(src: *mut u128) -> u128; + atomic_load_pwr8_relaxed = atomic_load_pwr8(Ordering::Relaxed); + atomic_load_pwr8_acquire = atomic_load_pwr8(Ordering::Acquire); + atomic_load_pwr8_seqcst = atomic_load_pwr8(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls atomic_load_pwr8 if quadword-atomics is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + if detect::detect().has_quadword_atomics() { + atomic_load_pwr8_relaxed + } else { + fallback::atomic_load_non_seqcst + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + if detect::detect().has_quadword_atomics() { + atomic_load_pwr8_acquire + } else { + fallback::atomic_load_non_seqcst + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + if detect::detect().has_quadword_atomics() { + atomic_load_pwr8_seqcst + } else { + fallback::atomic_load_seqcst + } + }) + } + _ => unreachable!(), + } + } +} +#[inline] +unsafe fn atomic_load_pwr8(src: *mut u128, order: Ordering) -> u128 { + debug_assert!(src as usize % 16 == 0); + debug_assert_pwr8!(); + + // SAFETY: the caller must uphold the safety contract. + // + // Refs: "3.3.4 Fixed Point Load and Store Quadword Instructions" of Power ISA + unsafe { + let (out_hi, out_lo); + macro_rules! atomic_load_acquire { + ($release:tt) => { + asm!( + start_pwr8!(), + $release, + "lq %r4, 0({src})", + // Lightweight acquire sync + // Refs: https://github.com/boostorg/atomic/blob/boost-1.79.0/include/boost/atomic/detail/core_arch_ops_gcc_ppc.hpp#L47-L62 + "cmpd %cr7, %r4, %r4", + "bne- %cr7, 2f", + "2:", + "isync", + end_pwr8!(), + src = in(reg_nonzero) ptr_reg!(src), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + out("r4") out_hi, + out("r5") out_lo, + out("cr7") _, + options(nostack, preserves_flags), + ) + }; + } + match order { + Ordering::Relaxed => { + asm!( + start_pwr8!(), + "lq %r4, 0({src})", + end_pwr8!(), + src = in(reg_nonzero) ptr_reg!(src), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + out("r4") out_hi, + out("r5") out_lo, + options(nostack, preserves_flags), + ); + } + Ordering::Acquire => atomic_load_acquire!(""), + Ordering::SeqCst => atomic_load_acquire!("sync"), + _ => unreachable!(), + } + U128 { pair: Pair { hi: out_hi, lo: out_lo } }.whole + } +} + +// If quadword-atomics is available at compile-time, we can always use pwr8_fn. +#[cfg(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +))] +use atomic_store_pwr8 as atomic_store; +// Otherwise, we need to do run-time detection and can use pwr8_fn only if quadword-atomics is available. +#[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +)))] +#[inline] +unsafe fn atomic_store(dst: *mut u128, val: u128, order: Ordering) { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(dst: *mut u128, val: u128); + atomic_store_pwr8_relaxed = atomic_store_pwr8(Ordering::Relaxed); + atomic_store_pwr8_release = atomic_store_pwr8(Ordering::Release); + atomic_store_pwr8_seqcst = atomic_store_pwr8(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls atomic_store_pwr8 if quadword-atomics is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + if detect::detect().has_quadword_atomics() { + atomic_store_pwr8_relaxed + } else { + fallback::atomic_store_non_seqcst + } + }); + } + Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + if detect::detect().has_quadword_atomics() { + atomic_store_pwr8_release + } else { + fallback::atomic_store_non_seqcst + } + }); + } + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + if detect::detect().has_quadword_atomics() { + atomic_store_pwr8_seqcst + } else { + fallback::atomic_store_seqcst + } + }); + } + _ => unreachable!(), + } + } +} +#[inline] +unsafe fn atomic_store_pwr8(dst: *mut u128, val: u128, order: Ordering) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_pwr8!(); + + // SAFETY: the caller must uphold the safety contract. + // + // Refs: "3.3.4 Fixed Point Load and Store Quadword Instructions" of Power ISA + unsafe { + let val = U128 { whole: val }; + macro_rules! atomic_store { + ($release:tt) => { + asm!( + start_pwr8!(), + $release, + "stq %r4, 0({dst})", + end_pwr8!(), + dst = in(reg_nonzero) ptr_reg!(dst), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + in("r4") val.pair.hi, + in("r5") val.pair.lo, + options(nostack, preserves_flags), + ) + }; + } + match order { + Ordering::Relaxed => atomic_store!(""), + Ordering::Release => atomic_store!("lwsync"), + Ordering::SeqCst => atomic_store!("sync"), + _ => unreachable!(), + } + } +} + +#[inline] +unsafe fn atomic_compare_exchange( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> Result { + let success = crate::utils::upgrade_success_ordering(success, failure); + + #[cfg(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + ))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantees that quadword atomics instructions are available at compile-time. + let (prev, ok) = unsafe { atomic_compare_exchange_pwr8(dst, old, new, success) }; + #[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + )))] + // SAFETY: the caller must uphold the safety contract. + let (prev, ok) = unsafe { atomic_compare_exchange_ifunc(dst, old, new, success) }; + if ok { + Ok(prev) + } else { + Err(prev) + } +} +#[inline] +unsafe fn atomic_compare_exchange_pwr8( + dst: *mut u128, + old: u128, + new: u128, + order: Ordering, +) -> (u128, bool) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_pwr8!(); + + // SAFETY: the caller must uphold the safety contract. + // + // Refs: "4.6.2.2 128-bit Load And Reserve and Store Conditional Instructions" of Power ISA + unsafe { + let old = U128 { whole: old }; + let new = U128 { whole: new }; + let (mut prev_hi, mut prev_lo); + let mut r; + macro_rules! cmpxchg { + ($acquire:tt, $release:tt) => { + asm!( + start_pwr8!(), + $release, + "2:", + "lqarx %r8, 0, {dst}", + "xor {tmp_lo}, %r9, {old_lo}", + "xor {tmp_hi}, %r8, {old_hi}", + "or. {tmp_lo}, {tmp_lo}, {tmp_hi}", + "bne %cr0, 3f", // jump if compare failed + "stqcx. %r6, 0, {dst}", + "bne %cr0, 2b", // continue loop if store failed + "3:", + // if compare failed EQ bit is cleared, if stqcx succeeds EQ bit is set. + "mfcr {tmp_lo}", + $acquire, + end_pwr8!(), + dst = in(reg_nonzero) ptr_reg!(dst), + old_hi = in(reg) old.pair.hi, + old_lo = in(reg) old.pair.lo, + tmp_hi = out(reg) _, + tmp_lo = out(reg) r, + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + in("r6") new.pair.hi, + in("r7") new.pair.lo, + out("r8") prev_hi, + out("r9") prev_lo, + out("cr0") _, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(cmpxchg, order); + (U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole, extract_cr0(r)) + } +} + +// Always use strong CAS for outline-atomics. +#[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +)))] +use atomic_compare_exchange as atomic_compare_exchange_weak; +#[cfg(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +))] +#[inline] +unsafe fn atomic_compare_exchange_weak( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> Result { + let success = crate::utils::upgrade_success_ordering(success, failure); + + // SAFETY: the caller must uphold the safety contract. + // cfg guarantees that quadword atomics instructions are available at compile-time. + let (prev, ok) = unsafe { atomic_compare_exchange_weak_pwr8(dst, old, new, success) }; + if ok { + Ok(prev) + } else { + Err(prev) + } +} +#[cfg(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +))] +#[inline] +unsafe fn atomic_compare_exchange_weak_pwr8( + dst: *mut u128, + old: u128, + new: u128, + order: Ordering, +) -> (u128, bool) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_pwr8!(); + + // SAFETY: the caller must uphold the safety contract. + // + // Refs: "4.6.2.2 128-bit Load And Reserve and Store Conditional Instructions" of Power ISA + unsafe { + let old = U128 { whole: old }; + let new = U128 { whole: new }; + let (mut prev_hi, mut prev_lo); + let mut r; + macro_rules! cmpxchg_weak { + ($acquire:tt, $release:tt) => { + asm!( + start_pwr8!(), + $release, + "lqarx %r8, 0, {dst}", + "xor {tmp_lo}, %r9, {old_lo}", + "xor {tmp_hi}, %r8, {old_hi}", + "or. {tmp_lo}, {tmp_lo}, {tmp_hi}", + "bne %cr0, 3f", // jump if compare failed + "stqcx. %r6, 0, {dst}", + "3:", + // if compare or stqcx failed EQ bit is cleared, if stqcx succeeds EQ bit is set. + "mfcr {tmp_lo}", + $acquire, + end_pwr8!(), + dst = in(reg_nonzero) ptr_reg!(dst), + old_hi = in(reg) old.pair.hi, + old_lo = in(reg) old.pair.lo, + tmp_hi = out(reg) _, + tmp_lo = out(reg) r, + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + in("r6") new.pair.hi, + in("r7") new.pair.lo, + out("r8") prev_hi, + out("r9") prev_lo, + out("cr0") _, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(cmpxchg_weak, order); + (U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole, extract_cr0(r)) + } +} + +// Do not use atomic_rmw_ll_sc_3 because it needs extra MR to implement swap. +#[inline] +unsafe fn atomic_swap_pwr8(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_pwr8!(); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let val = U128 { whole: val }; + let (mut prev_hi, mut prev_lo); + macro_rules! swap { + ($acquire:tt, $release:tt) => { + asm!( + start_pwr8!(), + $release, + "2:", + "lqarx %r6, 0, {dst}", + "stqcx. %r8, 0, {dst}", + "bne %cr0, 2b", + $acquire, + end_pwr8!(), + dst = in(reg_nonzero) ptr_reg!(dst), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + out("r6") prev_hi, + out("r7") prev_lo, + in("r8") val.pair.hi, + in("r9") val.pair.lo, + out("cr0") _, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(swap, order); + U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole + } +} + +/// Atomic RMW by LL/SC loop (3 arguments) +/// `unsafe fn(dst: *mut u128, val: u128, order: Ordering) -> u128;` +/// +/// $op can use the following registers: +/// - val_hi/val_lo pair: val argument (read-only for `$op`) +/// - r6/r7 pair: previous value loaded by ll (read-only for `$op`) +/// - r8/r9 pair: new value that will be stored by sc +macro_rules! atomic_rmw_ll_sc_3 { + ($name:ident, [$($reg:tt)*], $($op:tt)*) => { + #[inline] + unsafe fn $name(dst: *mut u128, val: u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_pwr8!(); + // SAFETY: the caller must uphold the safety contract. + unsafe { + let val = U128 { whole: val }; + let (mut prev_hi, mut prev_lo); + macro_rules! op { + ($acquire:tt, $release:tt) => { + asm!( + start_pwr8!(), + $release, + "2:", + "lqarx %r6, 0, {dst}", + $($op)* + "stqcx. %r8, 0, {dst}", + "bne %cr0, 2b", + $acquire, + end_pwr8!(), + dst = in(reg_nonzero) ptr_reg!(dst), + val_hi = in(reg) val.pair.hi, + val_lo = in(reg) val.pair.lo, + $($reg)* + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + out("r6") prev_hi, + out("r7") prev_lo, + out("r8") _, // new (hi) + out("r9") _, // new (lo) + out("cr0") _, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(op, order); + U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole + } + } + }; +} +/// Atomic RMW by LL/SC loop (2 arguments) +/// `unsafe fn(dst: *mut u128, order: Ordering) -> u128;` +/// +/// $op can use the following registers: +/// - r6/r7 pair: previous value loaded by ll (read-only for `$op`) +/// - r8/r9 pair: new value that will be stored by sc +macro_rules! atomic_rmw_ll_sc_2 { + ($name:ident, [$($reg:tt)*], $($op:tt)*) => { + #[inline] + unsafe fn $name(dst: *mut u128, order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_pwr8!(); + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (mut prev_hi, mut prev_lo); + macro_rules! op { + ($acquire:tt, $release:tt) => { + asm!( + start_pwr8!(), + $release, + "2:", + "lqarx %r6, 0, {dst}", + $($op)* + "stqcx. %r8, 0, {dst}", + "bne %cr0, 2b", + $acquire, + end_pwr8!(), + dst = in(reg_nonzero) ptr_reg!(dst), + $($reg)* + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + // We cannot use r1 (sp) and r2 (system reserved), so start with r4 or grater. + out("r6") prev_hi, + out("r7") prev_lo, + out("r8") _, // new (hi) + out("r9") _, // new (lo) + out("cr0") _, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw!(op, order); + U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole + } + } + }; +} + +atomic_rmw_ll_sc_3! { + atomic_add_pwr8, [out("xer") _,], + "addc %r9, {val_lo}, %r7", + "adde %r8, {val_hi}, %r6", +} +atomic_rmw_ll_sc_3! { + atomic_sub_pwr8, [out("xer") _,], + "subc %r9, %r7, {val_lo}", + "subfe %r8, {val_hi}, %r6", +} +atomic_rmw_ll_sc_3! { + atomic_and_pwr8, [], + "and %r9, {val_lo}, %r7", + "and %r8, {val_hi}, %r6", +} +atomic_rmw_ll_sc_3! { + atomic_nand_pwr8, [], + "nand %r9, {val_lo}, %r7", + "nand %r8, {val_hi}, %r6", +} +atomic_rmw_ll_sc_3! { + atomic_or_pwr8, [], + "or %r9, {val_lo}, %r7", + "or %r8, {val_hi}, %r6", +} +atomic_rmw_ll_sc_3! { + atomic_xor_pwr8, [], + "xor %r9, {val_lo}, %r7", + "xor %r8, {val_hi}, %r6", +} +atomic_rmw_ll_sc_3! { + atomic_max_pwr8, [out("cr1") _,], + "cmpld %r7, {val_lo}", // (unsigned) compare lo 64-bit, store result to cr0 + "iselgt %r9, %r7, {val_lo}", // select lo 64-bit based on GT bit in cr0 + "cmpd %cr1, %r6, {val_hi}", // (signed) compare hi 64-bit, store result to cr1 + "isel %r8, %r7, {val_lo}, 5", // select lo 64-bit based on GT bit in cr1 + "cmpld %r6, {val_hi}", // (unsigned) compare hi 64-bit, store result to cr0 + "iseleq %r9, %r9, %r8", // select lo 64-bit based on EQ bit in cr0 + "isel %r8, %r6, {val_hi}, 5", // select hi 64-bit based on GT bit in cr1 +} +atomic_rmw_ll_sc_3! { + atomic_umax_pwr8, [], + "cmpld %r7, {val_lo}", // compare lo 64-bit, store result to cr0 + "iselgt %r9, %r7, {val_lo}", // select lo 64-bit based on GT bit in cr0 + "cmpld %r6, {val_hi}", // compare hi 64-bit, store result to cr0 + "iselgt %r8, %r7, {val_lo}", // select lo 64-bit based on GT bit in cr0 + "iseleq %r9, %r9, %r8", // select lo 64-bit based on EQ bit in cr0 + "iselgt %r8, %r6, {val_hi}", // select hi 64-bit based on GT bit in cr0 +} +atomic_rmw_ll_sc_3! { + atomic_min_pwr8, [out("cr1") _,], + "cmpld %r7, {val_lo}", // (unsigned) compare lo 64-bit, store result to cr0 + "isellt %r9, %r7, {val_lo}", // select lo 64-bit based on LT bit in cr0 + "cmpd %cr1, %r6, {val_hi}", // (signed) compare hi 64-bit, store result to cr1 + "isel %r8, %r7, {val_lo}, 4", // select lo 64-bit based on LT bit in cr1 + "cmpld %r6, {val_hi}", // (unsigned) compare hi 64-bit, store result to cr0 + "iseleq %r9, %r9, %r8", // select lo 64-bit based on EQ bit in cr0 + "isel %r8, %r6, {val_hi}, 4", // select hi 64-bit based on LT bit in cr1 +} +atomic_rmw_ll_sc_3! { + atomic_umin_pwr8, [], + "cmpld %r7, {val_lo}", // compare lo 64-bit, store result to cr0 + "isellt %r9, %r7, {val_lo}", // select lo 64-bit based on LT bit in cr0 + "cmpld %r6, {val_hi}", // compare hi 64-bit, store result to cr0 + "isellt %r8, %r7, {val_lo}", // select lo 64-bit based on LT bit in cr0 + "iseleq %r9, %r9, %r8", // select lo 64-bit based on EQ bit in cr0 + "isellt %r8, %r6, {val_hi}", // select hi 64-bit based on LT bit in cr0 +} + +#[inline] +unsafe fn atomic_not_pwr8(dst: *mut u128, order: Ordering) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_xor_pwr8(dst, !0, order) } +} + +#[cfg(not(portable_atomic_pre_llvm_16))] +atomic_rmw_ll_sc_2! { + atomic_neg_pwr8, [out("xer") _,], + "subfic %r9, %r7, 0", + "subfze %r8, %r6", +} +// LLVM 15 miscompiles subfic. +#[cfg(portable_atomic_pre_llvm_16)] +atomic_rmw_ll_sc_2! { + atomic_neg_pwr8, [zero = in(reg) 0_u64, out("xer") _,], + "subc %r9, {zero}, %r7", + "subfze %r8, %r6", +} + +macro_rules! select_atomic_rmw { + ( + unsafe fn $name:ident($($arg:tt)*) $(-> $ret_ty:ty)?; + pwr8 = $pwr8_fn:ident; + non_seqcst_fallback = $non_seqcst_fallback_fn:ident; + seqcst_fallback = $seqcst_fallback_fn:ident; + ) => { + // If quadword-atomics is available at compile-time, we can always use pwr8_fn. + #[cfg(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + ))] + use $pwr8_fn as $name; + // Otherwise, we need to do run-time detection and can use pwr8_fn only if quadword-atomics is available. + #[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + )))] + #[inline] + unsafe fn $name($($arg)*, order: Ordering) $(-> $ret_ty)? { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn($($arg)*) $(-> $ret_ty)?; + pwr8_relaxed_fn = $pwr8_fn(Ordering::Relaxed); + pwr8_acquire_fn = $pwr8_fn(Ordering::Acquire); + pwr8_release_fn = $pwr8_fn(Ordering::Release); + pwr8_acqrel_fn = $pwr8_fn(Ordering::AcqRel); + pwr8_seqcst_fn = $pwr8_fn(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls pwr8_fn if quadword-atomics is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn($($arg)*) $(-> $ret_ty)? { + if detect::detect().has_quadword_atomics() { + pwr8_relaxed_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn($($arg)*) $(-> $ret_ty)? { + if detect::detect().has_quadword_atomics() { + pwr8_acquire_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::Release => { + ifunc!(unsafe fn($($arg)*) $(-> $ret_ty)? { + if detect::detect().has_quadword_atomics() { + pwr8_release_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::AcqRel => { + ifunc!(unsafe fn($($arg)*) $(-> $ret_ty)? { + if detect::detect().has_quadword_atomics() { + pwr8_acqrel_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn($($arg)*) $(-> $ret_ty)? { + if detect::detect().has_quadword_atomics() { + pwr8_seqcst_fn + } else { + fallback::$seqcst_fallback_fn + } + }) + } + _ => unreachable!(), + } + } + } + }; +} + +#[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +)))] +select_atomic_rmw! { + unsafe fn atomic_compare_exchange_ifunc(dst: *mut u128, old: u128, new: u128) -> (u128, bool); + pwr8 = atomic_compare_exchange_pwr8; + non_seqcst_fallback = atomic_compare_exchange_non_seqcst; + seqcst_fallback = atomic_compare_exchange_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_swap(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_swap_pwr8; + non_seqcst_fallback = atomic_swap_non_seqcst; + seqcst_fallback = atomic_swap_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_add(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_add_pwr8; + non_seqcst_fallback = atomic_add_non_seqcst; + seqcst_fallback = atomic_add_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_sub(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_sub_pwr8; + non_seqcst_fallback = atomic_sub_non_seqcst; + seqcst_fallback = atomic_sub_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_and(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_and_pwr8; + non_seqcst_fallback = atomic_and_non_seqcst; + seqcst_fallback = atomic_and_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_nand(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_nand_pwr8; + non_seqcst_fallback = atomic_nand_non_seqcst; + seqcst_fallback = atomic_nand_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_or(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_or_pwr8; + non_seqcst_fallback = atomic_or_non_seqcst; + seqcst_fallback = atomic_or_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_xor(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_xor_pwr8; + non_seqcst_fallback = atomic_xor_non_seqcst; + seqcst_fallback = atomic_xor_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_max(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_max_pwr8; + non_seqcst_fallback = atomic_max_non_seqcst; + seqcst_fallback = atomic_max_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umax(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_umax_pwr8; + non_seqcst_fallback = atomic_umax_non_seqcst; + seqcst_fallback = atomic_umax_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_min(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_min_pwr8; + non_seqcst_fallback = atomic_min_non_seqcst; + seqcst_fallback = atomic_min_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umin(dst: *mut u128, val: u128) -> u128; + pwr8 = atomic_umin_pwr8; + non_seqcst_fallback = atomic_umin_non_seqcst; + seqcst_fallback = atomic_umin_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_not(dst: *mut u128) -> u128; + pwr8 = atomic_not_pwr8; + non_seqcst_fallback = atomic_not_non_seqcst; + seqcst_fallback = atomic_not_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_neg(dst: *mut u128) -> u128; + pwr8 = atomic_neg_pwr8; + non_seqcst_fallback = atomic_neg_non_seqcst; + seqcst_fallback = atomic_neg_seqcst; +} + +#[inline] +fn is_lock_free() -> bool { + #[cfg(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + ))] + { + // lqarx and stqcx. instructions are statically available. + true + } + #[cfg(not(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + )))] + { + detect::detect().has_quadword_atomics() + } +} +const IS_ALWAYS_LOCK_FREE: bool = cfg!(any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", +)); + +atomic128!(AtomicI128, i128, atomic_max, atomic_min); +atomic128!(AtomicU128, u128, atomic_umax, atomic_umin); + +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_int!(i128); + test_atomic_int!(u128); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u128); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/riscv64.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/riscv64.rs new file mode 100644 index 0000000..bac83d5 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/riscv64.rs @@ -0,0 +1,651 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +128-bit atomic implementation on riscv64 using amocas.q (DWCAS). + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use intrinsics.rs instead. + +Refs: +- RISC-V Instruction Set Manual + https://github.com/riscv/riscv-isa-manual/tree/riscv-isa-release-8b9dc50-2024-08-30 + "Zacas" Extension for Atomic Compare-and-Swap (CAS) Instructions + https://github.com/riscv/riscv-isa-manual/blob/riscv-isa-release-8b9dc50-2024-08-30/src/zacas.adoc +- RISC-V Atomics ABI Specification + https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/draft-20240829-13bfa9f54634cb60d86b9b333e109f077805b4b3/riscv-atomic.adoc + +Generated asm: +- riscv64 (+experimental-zacas) https://godbolt.org/z/5Kc17T1W8 +*/ + +include!("macros.rs"); + +#[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +)))] +#[path = "../fallback/outline_atomics.rs"] +mod fallback; + +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any(test, portable_atomic_outline_atomics))] // TODO(riscv): currently disabled by default +#[cfg(any( + test, + not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )), +))] +#[cfg(any(target_os = "linux", target_os = "android"))] +#[path = "../detect/riscv_linux.rs"] +mod detect; + +use core::{arch::asm, sync::atomic::Ordering}; + +use crate::utils::{Pair, U128}; + +macro_rules! debug_assert_zacas { + () => { + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + { + debug_assert!(detect::detect().has_zacas()); + } + }; +} + +// LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. +// So, we currently always using .insn directive. +// `.insn ` directive requires LLVM 19. +// https://github.com/llvm/llvm-project/commit/2a086dce691e3cc34a2fc27f4fb255bb2cbbfac9 +// // https://github.com/riscv-non-isa/riscv-asm-manual/blob/ad0de8c004e29c9a7ac33cfd054f4d4f9392f2fb/src/asm-manual.adoc#arch +// macro_rules! start_zacas { +// () => { +// ".option push\n.option arch, +zacas" +// }; +// } +// macro_rules! end_zacas { +// () => { +// ".option pop" +// }; +// } + +// LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. +// So, we currently always using .insn directive. +// macro_rules! atomic_rmw_amocas_order { +// ($op:ident, $order:ident) => { +// atomic_rmw_amocas_order!($op, $order, failure = $order) +// }; +// ($op:ident, $order:ident, failure = $failure:ident) => { +// match $order { +// Ordering::Relaxed => $op!("", ""), +// Ordering::Acquire => $op!("", ".aq"), +// Ordering::Release => $op!("", ".rl"), +// Ordering::AcqRel => $op!("", ".aqrl"), +// Ordering::SeqCst if $failure == Ordering::SeqCst => $op!("fence rw,rw", ".aqrl"), +// Ordering::SeqCst => $op!("", ".aqrl"), +// _ => unreachable!(), +// } +// }; +// } +macro_rules! atomic_rmw_amocas_order_insn { + ($op:ident, $order:ident) => { + atomic_rmw_amocas_order_insn!($op, $order, failure = $order) + }; + ($op:ident, $order:ident, failure = $failure:ident) => { + match $order { + Ordering::Relaxed => $op!("", "8"), + Ordering::Acquire => $op!("", "c"), + Ordering::Release => $op!("", "a"), + Ordering::AcqRel => $op!("", "e"), + Ordering::SeqCst if $failure == Ordering::SeqCst => $op!("fence rw,rw", "e"), + Ordering::SeqCst => $op!("", "e"), + _ => unreachable!(), + } + }; +} + +// If zacas is available at compile-time, we can always use zacas_fn. +#[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +))] +use atomic_load_zacas as atomic_load; +// Otherwise, we need to do run-time detection and can use zacas_fn only if zacas is available. +#[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +)))] +#[inline] +unsafe fn atomic_load(src: *mut u128, order: Ordering) -> u128 { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(src: *mut u128) -> u128; + atomic_load_zacas_relaxed = atomic_load_zacas(Ordering::Relaxed); + atomic_load_zacas_acquire = atomic_load_zacas(Ordering::Acquire); + atomic_load_zacas_seqcst = atomic_load_zacas(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls atomic_load_zacas if zacas is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + if detect::detect().has_zacas() { + atomic_load_zacas_relaxed + } else { + fallback::atomic_load_non_seqcst + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + if detect::detect().has_zacas() { + atomic_load_zacas_acquire + } else { + fallback::atomic_load_non_seqcst + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + if detect::detect().has_zacas() { + atomic_load_zacas_seqcst + } else { + fallback::atomic_load_seqcst + } + }) + } + _ => unreachable!(), + } + } +} +#[inline] +unsafe fn atomic_load_zacas(src: *mut u128, order: Ordering) -> u128 { + debug_assert!(src as usize % 16 == 0); + debug_assert_zacas!(); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (out_lo, out_hi); + // LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. + // So, we currently always using .insn directive. + // macro_rules! load { + // ($fence:tt, $asm_order:tt) => { + // asm!( + // start_zacas!(), + // $fence, + // concat!("amocas.q", $asm_order, " a2, a2, 0({src})"), + // end_zacas!(), + // src = in(reg) ptr_reg!(src), + // inout("a2") 0_u64 => out_lo, + // inout("a3") 0_u64 => out_hi, + // options(nostack, preserves_flags), + // ) + // }; + // } + // atomic_rmw_amocas_order!(load, order); + macro_rules! load { + ($fence:tt, $insn_order:tt) => { + asm!( + $fence, + // 4: 2{8,c,a,e}c5462f amocas.q{,.aq,.rl,.aqrl} a2, a2, (a0) + concat!(".insn 0x2", $insn_order, "c5462f"), + in("a0") ptr_reg!(src), + inout("a2") 0_u64 => out_lo, + inout("a3") 0_u64 => out_hi, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw_amocas_order_insn!(load, order); + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} + +#[inline] +unsafe fn atomic_store(dst: *mut u128, val: u128, order: Ordering) { + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_swap(dst, val, order); + } +} + +#[inline] +unsafe fn atomic_compare_exchange( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> Result { + #[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantees that zacas instructions are available at compile-time. + let (prev, ok) = unsafe { atomic_compare_exchange_zacas(dst, old, new, success, failure) }; + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + let (prev, ok) = { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(dst: *mut u128, old: u128, new: u128) -> (u128, bool); + zacas_relaxed_fn = atomic_compare_exchange_zacas(Ordering::Relaxed, Ordering::Relaxed); + zacas_acquire_fn = atomic_compare_exchange_zacas(Ordering::Acquire, Ordering::Acquire); + zacas_release_fn = atomic_compare_exchange_zacas(Ordering::Release, Ordering::Relaxed); + zacas_acqrel_fn = atomic_compare_exchange_zacas(Ordering::AcqRel, Ordering::Acquire); + zacas_seqcst_fn = atomic_compare_exchange_zacas(Ordering::SeqCst, Ordering::SeqCst); + } + let order = crate::utils::upgrade_success_ordering(success, failure); + // SAFETY: the caller must uphold the safety contract. + // we only calls atomic_compare_exchange_zacas if zacas is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> (u128, bool) { + if detect::detect().has_zacas() { + zacas_relaxed_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> (u128, bool) { + if detect::detect().has_zacas() { + zacas_acquire_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> (u128, bool) { + if detect::detect().has_zacas() { + zacas_release_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::AcqRel => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> (u128, bool) { + if detect::detect().has_zacas() { + zacas_acqrel_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> (u128, bool) { + if detect::detect().has_zacas() { + zacas_seqcst_fn + } else { + fallback::atomic_compare_exchange_seqcst + } + }) + } + _ => unreachable!(), + } + } + }; + if ok { + Ok(prev) + } else { + Err(prev) + } +} +#[inline] +unsafe fn atomic_compare_exchange_zacas( + dst: *mut u128, + old: u128, + new: u128, + success: Ordering, + failure: Ordering, +) -> (u128, bool) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_zacas!(); + let order = crate::utils::upgrade_success_ordering(success, failure); + + // SAFETY: the caller must uphold the safety contract. + let prev = unsafe { + let old = U128 { whole: old }; + let new = U128 { whole: new }; + let (prev_lo, prev_hi); + // LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. + // So, we currently always using .insn directive. + // macro_rules! cmpxchg { + // ($fence:tt, $asm_order:tt) => { + // asm!( + // start_zacas!(), + // $fence, + // concat!("amocas.q", $asm_order, " a4, a2, 0({dst})"), + // end_zacas!(), + // dst = in(reg) ptr_reg!(dst), + // // must be allocated to even/odd register pair + // inout("a4") old.pair.lo => prev_lo, + // inout("a5") old.pair.hi => prev_hi, + // // must be allocated to even/odd register pair + // in("a2") new.pair.lo, + // in("a3") new.pair.hi, + // options(nostack, preserves_flags), + // ) + // }; + // } + // atomic_rmw_amocas_order!(cmpxchg, order, failure = failure); + macro_rules! cmpxchg { + ($fence:tt, $insn_order:tt) => { + asm!( + $fence, + // c: 2{8,c,a,e}c5472f amocas.q{,.aq,.rl,.aqrl} a4, a2, (a0) + concat!(".insn 0x2", $insn_order, "c5472f"), + in("a0") ptr_reg!(dst), + // must be allocated to even/odd register pair + inout("a4") old.pair.lo => prev_lo, + inout("a5") old.pair.hi => prev_hi, + // must be allocated to even/odd register pair + in("a2") new.pair.lo, + in("a3") new.pair.hi, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw_amocas_order_insn!(cmpxchg, order, failure = failure); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + }; + (prev, prev == old) +} + +// amocas is always strong. +use atomic_compare_exchange as atomic_compare_exchange_weak; + +// 128-bit atomic load by two 64-bit atomic loads. (see arm_linux.rs for more) +#[inline] +unsafe fn byte_wise_atomic_load(src: *const u128) -> u128 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (out_lo, out_hi); + asm!( + "ld {out_lo}, ({src})", + "ld {out_hi}, 8({src})", + src = in(reg) ptr_reg!(src), + out_lo = out(reg) out_lo, + out_hi = out(reg) out_hi, + options(pure, nostack, preserves_flags, readonly), + ); + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} + +#[inline(always)] +unsafe fn atomic_update_zacas(dst: *mut u128, order: Ordering, mut f: F) -> u128 +where + F: FnMut(u128) -> u128, +{ + // SAFETY: the caller must uphold the safety contract. + unsafe { + let mut prev = byte_wise_atomic_load(dst); + loop { + let next = f(prev); + match atomic_compare_exchange_weak(dst, prev, next, order, Ordering::Relaxed) { + Ok(x) => return x, + Err(x) => prev = x, + } + } + } +} + +macro_rules! select_atomic_rmw { + ( + unsafe fn $name:ident(dst: *mut u128 $(, $($arg:tt)*)?) $(-> $ret_ty:ty)? { + $($zacas_fn_body:tt)* + } + zacas = $zacas_fn:ident; + non_seqcst_fallback = $non_seqcst_fallback_fn:ident; + seqcst_fallback = $seqcst_fallback_fn:ident; + ) => { + #[inline] + unsafe fn $zacas_fn(dst: *mut u128 $(, $($arg)*)?, order: Ordering) $(-> $ret_ty)? { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_zacas(dst, order, $($zacas_fn_body)*) } + } + // If zacas is available at compile-time, we can always use zacas_fn. + #[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ))] + use $zacas_fn as $name; + // Otherwise, we need to do run-time detection and can use zacas_fn only if zacas is available. + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + #[inline] + unsafe fn $name(dst: *mut u128 $(, $($arg)*)?, order: Ordering) $(-> $ret_ty)? { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(dst: *mut u128 $(, $($arg)*)?) $(-> $ret_ty)?; + zacas_relaxed_fn = $zacas_fn(Ordering::Relaxed); + zacas_acquire_fn = $zacas_fn(Ordering::Acquire); + zacas_release_fn = $zacas_fn(Ordering::Release); + zacas_acqrel_fn = $zacas_fn(Ordering::AcqRel); + zacas_seqcst_fn = $zacas_fn(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls zacas_fn if zacas is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(dst: *mut u128 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_relaxed_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(dst: *mut u128 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_acquire_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u128 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_release_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::AcqRel => { + ifunc!(unsafe fn(dst: *mut u128 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_acqrel_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u128 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_seqcst_fn + } else { + fallback::$seqcst_fallback_fn + } + }) + } + _ => unreachable!(), + } + } + } + }; +} + +select_atomic_rmw! { + unsafe fn atomic_swap(dst: *mut u128, val: u128) -> u128 { + |_| val + } + zacas = atomic_swap_zacas; + non_seqcst_fallback = atomic_swap_non_seqcst; + seqcst_fallback = atomic_swap_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_add(dst: *mut u128, val: u128) -> u128 { + |x| x.wrapping_add(val) + } + zacas = atomic_add_zacas; + non_seqcst_fallback = atomic_add_non_seqcst; + seqcst_fallback = atomic_add_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_sub(dst: *mut u128, val: u128) -> u128 { + |x| x.wrapping_sub(val) + } + zacas = atomic_sub_zacas; + non_seqcst_fallback = atomic_sub_non_seqcst; + seqcst_fallback = atomic_sub_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_and(dst: *mut u128, val: u128) -> u128 { + |x| x & val + } + zacas = atomic_and_zacas; + non_seqcst_fallback = atomic_and_non_seqcst; + seqcst_fallback = atomic_and_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_nand(dst: *mut u128, val: u128) -> u128 { + |x| !(x & val) + } + zacas = atomic_nand_zacas; + non_seqcst_fallback = atomic_nand_non_seqcst; + seqcst_fallback = atomic_nand_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_or(dst: *mut u128, val: u128) -> u128 { + |x| x | val + } + zacas = atomic_or_zacas; + non_seqcst_fallback = atomic_or_non_seqcst; + seqcst_fallback = atomic_or_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_xor(dst: *mut u128, val: u128) -> u128 { + |x| x ^ val + } + zacas = atomic_xor_zacas; + non_seqcst_fallback = atomic_xor_non_seqcst; + seqcst_fallback = atomic_xor_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_max(dst: *mut u128, val: u128) -> u128 { + |x| { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + { core::cmp::max(x as i128, val as i128) as u128 } + } + } + zacas = atomic_max_zacas; + non_seqcst_fallback = atomic_max_non_seqcst; + seqcst_fallback = atomic_max_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umax(dst: *mut u128, val: u128) -> u128 { + |x| core::cmp::max(x, val) + } + zacas = atomic_umax_zacas; + non_seqcst_fallback = atomic_umax_non_seqcst; + seqcst_fallback = atomic_umax_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_min(dst: *mut u128, val: u128) -> u128 { + |x| { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + { core::cmp::min(x as i128, val as i128) as u128 } + } + } + zacas = atomic_min_zacas; + non_seqcst_fallback = atomic_min_non_seqcst; + seqcst_fallback = atomic_min_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umin(dst: *mut u128, val: u128) -> u128 { + |x| core::cmp::min(x, val) + } + zacas = atomic_umin_zacas; + non_seqcst_fallback = atomic_umin_non_seqcst; + seqcst_fallback = atomic_umin_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_not(dst: *mut u128) -> u128 { + |x| !x + } + zacas = atomic_not_zacas; + non_seqcst_fallback = atomic_not_non_seqcst; + seqcst_fallback = atomic_not_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_neg(dst: *mut u128) -> u128 { + u128::wrapping_neg + } + zacas = atomic_neg_zacas; + non_seqcst_fallback = atomic_neg_non_seqcst; + seqcst_fallback = atomic_neg_seqcst; +} + +#[inline] +fn is_lock_free() -> bool { + #[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ))] + { + // zacas is available at compile-time. + true + } + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + { + detect::detect().has_zacas() + } +} +const IS_ALWAYS_LOCK_FREE: bool = cfg!(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +)); + +atomic128!(AtomicI128, i128, atomic_max, atomic_min); +atomic128!(AtomicU128, u128, atomic_umax, atomic_umin); + +#[allow(clippy::undocumented_unsafe_blocks, clippy::wildcard_imports)] +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_int!(i128); + test_atomic_int!(u128); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u128); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/s390x.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/s390x.rs new file mode 100644 index 0000000..92be6f7 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/s390x.rs @@ -0,0 +1,466 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +128-bit atomic implementation on s390x. + +s390x has 128-bit atomic load/store/CAS instructions and other operations are emulated by CAS loop. +https://github.com/llvm/llvm-project/commit/a11f63a952664f700f076fd754476a2b9eb158cc +https://github.com/llvm/llvm-project/commit/c568927f3e2e7d9804ea74ecbf11c16c014ddcbc + +128-bit atomic instructions (lpq,stpq,cdsg) has been present since +[the First Edition of the Principles of Operation](https://publibfp.dhe.ibm.com/epubs/pdf/dz9zr000.pdf). +LLVM's minimal supported architecture level is z10 (the Eighth Edition of the PoP): +https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/SystemZ/SystemZProcessors.td#L16-L17 +This does not appear to have changed since the current s390x backend was added in LLVM 3.3: +https://github.com/llvm/llvm-project/commit/5f613dfd1f7edb0ae95d521b7107b582d9df5103#diff-cbaef692b3958312e80fd5507a7e2aff071f1acb086f10e8a96bc06a7bb289db + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use intrinsics.rs instead. + +Refs: +- z/Architecture Principles of Operation https://publibfp.dhe.ibm.com/epubs/pdf/a227832d.pdf +- z/Architecture Reference Summary https://www.ibm.com/support/pages/zarchitecture-reference-summary +- atomic-maybe-uninit https://github.com/taiki-e/atomic-maybe-uninit + +Generated asm: +- s390x https://godbolt.org/z/sbvhjKrMT +- s390x (z196) https://godbolt.org/z/Erbqazhv7 +- s390x (z15) https://godbolt.org/z/GEaePbbsT +*/ + +include!("macros.rs"); + +use core::{arch::asm, sync::atomic::Ordering}; + +use crate::utils::{Pair, U128}; + +// Use distinct operands on z196 or later, otherwise split to lgr and $op. +#[cfg(any(target_feature = "distinct-ops", portable_atomic_target_feature = "distinct-ops"))] +macro_rules! distinct_op { + ($op:tt, $a0:tt, $a1:tt, $a2:tt) => { + concat!($op, "k ", $a0, ", ", $a1, ", ", $a2) + }; +} +#[cfg(not(any(target_feature = "distinct-ops", portable_atomic_target_feature = "distinct-ops")))] +macro_rules! distinct_op { + ($op:tt, $a0:tt, $a1:tt, $a2:tt) => { + concat!("lgr ", $a0, ", ", $a1, "\n", $op, " ", $a0, ", ", $a2) + }; +} + +// Use selgr$cond on z15 or later, otherwise split to locgr$cond and $op. +#[cfg(any( + target_feature = "miscellaneous-extensions-3", + portable_atomic_target_feature = "miscellaneous-extensions-3", +))] +#[cfg(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +))] +macro_rules! select_op { + ($cond:tt, $a0:tt, $a1:tt, $a2:tt) => { + concat!("selgr", $cond, " ", $a0, ", ", $a1, ", ", $a2) + }; +} +#[cfg(not(any( + target_feature = "miscellaneous-extensions-3", + portable_atomic_target_feature = "miscellaneous-extensions-3", +)))] +#[cfg(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +))] +macro_rules! select_op { + ($cond:tt, $a0:tt, $a1:tt, $a2:tt) => { + concat!("lgr ", $a0, ", ", $a2, "\n", "locgr", $cond, " ", $a0, ", ", $a1) + }; +} + +#[inline] +unsafe fn atomic_load(src: *mut u128, _order: Ordering) -> u128 { + debug_assert!(src as usize % 16 == 0); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + // atomic load is always SeqCst. + let (out_hi, out_lo); + asm!( + "lpq %r0, 0({src})", + src = in(reg) ptr_reg!(src), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + out("r0") out_hi, + out("r1") out_lo, + options(nostack, preserves_flags), + ); + U128 { pair: Pair { hi: out_hi, lo: out_lo } }.whole + } +} + +#[inline] +unsafe fn atomic_store(dst: *mut u128, val: u128, order: Ordering) { + debug_assert!(dst as usize % 16 == 0); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let val = U128 { whole: val }; + macro_rules! atomic_store { + ($fence:tt) => { + asm!( + "stpq %r0, 0({dst})", + $fence, + dst = in(reg) ptr_reg!(dst), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + in("r0") val.pair.hi, + in("r1") val.pair.lo, + options(nostack, preserves_flags), + ) + }; + } + match order { + // Relaxed and Release stores are equivalent. + Ordering::Relaxed | Ordering::Release => atomic_store!(""), + // bcr 14,0 (fast-BCR-serialization) requires z196 or later. + #[cfg(any( + target_feature = "fast-serialization", + portable_atomic_target_feature = "fast-serialization", + ))] + Ordering::SeqCst => atomic_store!("bcr 14, 0"), + #[cfg(not(any( + target_feature = "fast-serialization", + portable_atomic_target_feature = "fast-serialization", + )))] + Ordering::SeqCst => atomic_store!("bcr 15, 0"), + _ => unreachable!(), + } + } +} + +#[inline] +unsafe fn atomic_compare_exchange( + dst: *mut u128, + old: u128, + new: u128, + _success: Ordering, + _failure: Ordering, +) -> Result { + debug_assert!(dst as usize % 16 == 0); + + // SAFETY: the caller must uphold the safety contract. + let prev = unsafe { + // atomic CAS is always SeqCst. + let old = U128 { whole: old }; + let new = U128 { whole: new }; + let (prev_hi, prev_lo); + asm!( + "cdsg %r0, %r12, 0({dst})", + dst = in(reg) ptr_reg!(dst), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + inout("r0") old.pair.hi => prev_hi, + inout("r1") old.pair.lo => prev_lo, + in("r12") new.pair.hi, + in("r13") new.pair.lo, + // Do not use `preserves_flags` because CDSG modifies the condition code. + options(nostack), + ); + U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole + }; + if prev == old { + Ok(prev) + } else { + Err(prev) + } +} + +// cdsg is always strong. +use atomic_compare_exchange as atomic_compare_exchange_weak; + +#[cfg(not(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +)))] +#[inline(always)] +unsafe fn atomic_update(dst: *mut u128, order: Ordering, mut f: F) -> u128 +where + F: FnMut(u128) -> u128, +{ + // SAFETY: the caller must uphold the safety contract. + unsafe { + // This is a private function and all instances of `f` only operate on the value + // loaded, so there is no need to synchronize the first load/failed CAS. + let mut prev = atomic_load(dst, Ordering::Relaxed); + loop { + let next = f(prev); + match atomic_compare_exchange_weak(dst, prev, next, order, Ordering::Relaxed) { + Ok(x) => return x, + Err(x) => prev = x, + } + } + } +} + +#[inline] +unsafe fn atomic_swap(dst: *mut u128, val: u128, _order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + + // SAFETY: the caller must uphold the safety contract. + // + // We could use atomic_update here, but using an inline assembly allows omitting + // the comparison of results and the storing/comparing of condition flags. + // + // Do not use atomic_rmw_cas_3 because it needs extra LGR to implement swap. + unsafe { + // atomic swap is always SeqCst. + let val = U128 { whole: val }; + let (mut prev_hi, mut prev_lo); + asm!( + "lpq %r0, 0({dst})", + "2:", + "cdsg %r0, %r12, 0({dst})", + "jl 2b", + dst = in(reg) ptr_reg!(dst), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + out("r0") prev_hi, + out("r1") prev_lo, + in("r12") val.pair.hi, + in("r13") val.pair.lo, + // Do not use `preserves_flags` because CDSG modifies the condition code. + options(nostack), + ); + U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole + } +} + +/// Atomic RMW by CAS loop (3 arguments) +/// `unsafe fn(dst: *mut u128, val: u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - val_hi/val_lo pair: val argument (read-only for `$op`) +/// - r0/r1 pair: previous value loaded (read-only for `$op`) +/// - r12/r13 pair: new value that will be stored +// We could use atomic_update here, but using an inline assembly allows omitting +// the comparison of results and the storing/comparing of condition flags. +macro_rules! atomic_rmw_cas_3 { + ($name:ident, [$($reg:tt)*], $($op:tt)*) => { + #[inline] + unsafe fn $name(dst: *mut u128, val: u128, _order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + // SAFETY: the caller must uphold the safety contract. + unsafe { + // atomic RMW is always SeqCst. + let val = U128 { whole: val }; + let (mut prev_hi, mut prev_lo); + asm!( + "lpq %r0, 0({dst})", + "2:", + $($op)* + "cdsg %r0, %r12, 0({dst})", + "jl 2b", + dst = in(reg) ptr_reg!(dst), + val_hi = in(reg) val.pair.hi, + val_lo = in(reg) val.pair.lo, + $($reg)* + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + out("r0") prev_hi, + out("r1") prev_lo, + out("r12") _, + out("r13") _, + // Do not use `preserves_flags` because CDSG modifies the condition code. + options(nostack), + ); + U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole + } + } + }; +} +/// Atomic RMW by CAS loop (2 arguments) +/// `unsafe fn(dst: *mut u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - r0/r1 pair: previous value loaded (read-only for `$op`) +/// - r12/r13 pair: new value that will be stored +// We could use atomic_update here, but using an inline assembly allows omitting +// the comparison of results and the storing/comparing of condition flags. +macro_rules! atomic_rmw_cas_2 { + ($name:ident, $($op:tt)*) => { + #[inline] + unsafe fn $name(dst: *mut u128, _order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + // SAFETY: the caller must uphold the safety contract. + unsafe { + // atomic RMW is always SeqCst. + let (mut prev_hi, mut prev_lo); + asm!( + "lpq %r0, 0({dst})", + "2:", + $($op)* + "cdsg %r0, %r12, 0({dst})", + "jl 2b", + dst = in(reg) ptr_reg!(dst), + // Quadword atomic instructions work with even/odd pair of specified register and subsequent register. + out("r0") prev_hi, + out("r1") prev_lo, + out("r12") _, + out("r13") _, + // Do not use `preserves_flags` because CDSG modifies the condition code. + options(nostack), + ); + U128 { pair: Pair { hi: prev_hi, lo: prev_lo } }.whole + } + } + }; +} + +atomic_rmw_cas_3! { + atomic_add, [], + distinct_op!("algr", "%r13", "%r1", "{val_lo}"), + "lgr %r12, %r0", + "alcgr %r12, {val_hi}", +} +atomic_rmw_cas_3! { + atomic_sub, [], + distinct_op!("slgr", "%r13", "%r1", "{val_lo}"), + "lgr %r12, %r0", + "slbgr %r12, {val_hi}", +} +atomic_rmw_cas_3! { + atomic_and, [], + distinct_op!("ngr", "%r13", "%r1", "{val_lo}"), + distinct_op!("ngr", "%r12", "%r0", "{val_hi}"), +} + +// Use nngrk on z15 or later. +#[cfg(any( + target_feature = "miscellaneous-extensions-3", + portable_atomic_target_feature = "miscellaneous-extensions-3", +))] +atomic_rmw_cas_3! { + atomic_nand, [], + "nngrk %r13, %r1, {val_lo}", + "nngrk %r12, %r0, {val_hi}", +} +#[cfg(not(any( + target_feature = "miscellaneous-extensions-3", + portable_atomic_target_feature = "miscellaneous-extensions-3", +)))] +atomic_rmw_cas_3! { + atomic_nand, [], + distinct_op!("ngr", "%r13", "%r1", "{val_lo}"), + "xihf %r13, 4294967295", + "xilf %r13, 4294967295", + distinct_op!("ngr", "%r12", "%r0", "{val_hi}"), + "xihf %r12, 4294967295", + "xilf %r12, 4294967295", +} + +atomic_rmw_cas_3! { + atomic_or, [], + distinct_op!("ogr", "%r13", "%r1", "{val_lo}"), + distinct_op!("ogr", "%r12", "%r0", "{val_hi}"), +} +atomic_rmw_cas_3! { + atomic_xor, [], + distinct_op!("xgr", "%r13", "%r1", "{val_lo}"), + distinct_op!("xgr", "%r12", "%r0", "{val_hi}"), +} + +#[cfg(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +))] +atomic_rmw_cas_3! { + atomic_max, [], + "clgr %r1, {val_lo}", + select_op!("h", "%r12", "%r1", "{val_lo}"), + "cgr %r0, {val_hi}", + select_op!("h", "%r13", "%r1", "{val_lo}"), + "locgre %r13, %r12", + select_op!("h", "%r12", "%r0", "{val_hi}"), +} +#[cfg(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +))] +atomic_rmw_cas_3! { + atomic_umax, [tmp = out(reg) _,], + "clgr %r1, {val_lo}", + select_op!("h", "{tmp}", "%r1", "{val_lo}"), + "clgr %r0, {val_hi}", + select_op!("h", "%r12", "%r0", "{val_hi}"), + select_op!("h", "%r13", "%r1", "{val_lo}"), + "cgr %r0, {val_hi}", + "locgre %r13, {tmp}", +} +#[cfg(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +))] +atomic_rmw_cas_3! { + atomic_min, [], + "clgr %r1, {val_lo}", + select_op!("l", "%r12", "%r1", "{val_lo}"), + "cgr %r0, {val_hi}", + select_op!("l", "%r13", "%r1", "{val_lo}"), + "locgre %r13, %r12", + select_op!("l", "%r12", "%r0", "{val_hi}"), +} +#[cfg(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +))] +atomic_rmw_cas_3! { + atomic_umin, [tmp = out(reg) _,], + "clgr %r1, {val_lo}", + select_op!("l", "{tmp}", "%r1", "{val_lo}"), + "clgr %r0, {val_hi}", + select_op!("l", "%r12", "%r0", "{val_hi}"), + select_op!("l", "%r13", "%r1", "{val_lo}"), + "cgr %r0, {val_hi}", + "locgre %r13, {tmp}", +} +// We use atomic_update for atomic min/max on pre-z196 because +// z10 doesn't seem to have a good way to implement 128-bit min/max. +// loc{,g}r requires z196 or later. +// https://godbolt.org/z/EqoMEP8b3 +#[cfg(not(any( + target_feature = "load-store-on-cond", + portable_atomic_target_feature = "load-store-on-cond", +)))] +atomic_rmw_by_atomic_update!(cmp); + +atomic_rmw_cas_2! { + atomic_not, + "lgr %r13, %r1", + "xihf %r13, 4294967295", + "xilf %r13, 4294967295", + "lgr %r12, %r0", + "xihf %r12, 4294967295", + "xilf %r12, 4294967295", +} +atomic_rmw_cas_2! { + atomic_neg, + "lghi %r13, 0", + "slgr %r13, %r1", + "lghi %r12, 0", + "slbgr %r12, %r0", +} + +#[inline] +const fn is_lock_free() -> bool { + IS_ALWAYS_LOCK_FREE +} +const IS_ALWAYS_LOCK_FREE: bool = true; + +atomic128!(AtomicI128, i128, atomic_max, atomic_min); +atomic128!(AtomicU128, u128, atomic_umax, atomic_umin); + +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_int!(i128); + test_atomic_int!(u128); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u128); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/x86_64.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/x86_64.rs new file mode 100644 index 0000000..5116d40 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic128/x86_64.rs @@ -0,0 +1,879 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +128-bit atomic implementation on x86_64 using CMPXCHG16B (DWCAS). + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use intrinsics.rs instead. + +Refs: +- x86 and amd64 instruction reference https://www.felixcloutier.com/x86 +- atomic-maybe-uninit https://github.com/taiki-e/atomic-maybe-uninit + +Generated asm: +- x86_64 (+cmpxchg16b) https://godbolt.org/z/r5x9M8PdK +*/ + +// TODO: use core::arch::x86_64::cmpxchg16b where available and efficient than asm + +include!("macros.rs"); + +#[cfg(not(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b")))] +#[path = "../fallback/outline_atomics.rs"] +mod fallback; + +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(not(target_env = "sgx"))] +#[cfg_attr( + not(target_feature = "sse"), + cfg(not(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"))) +)] +#[path = "../detect/x86_64.rs"] +mod detect; + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; +use core::sync::atomic::Ordering; + +use crate::utils::{Pair, U128}; + +// Asserts that the function is called in the correct context. +macro_rules! debug_assert_cmpxchg16b { + () => { + #[cfg(not(any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + )))] + { + debug_assert!(detect::detect().has_cmpxchg16b()); + } + }; +} +#[cfg(not(any(portable_atomic_no_outline_atomics, target_env = "sgx")))] +#[cfg(target_feature = "sse")] +macro_rules! debug_assert_vmovdqa_atomic { + () => {{ + debug_assert_cmpxchg16b!(); + debug_assert!(detect::detect().has_vmovdqa_atomic()); + }}; +} + +#[cfg(not(any(portable_atomic_no_outline_atomics, target_env = "sgx")))] +#[cfg(target_feature = "sse")] +#[cfg(target_pointer_width = "32")] +macro_rules! ptr_modifier { + () => { + ":e" + }; +} +#[cfg(not(any(portable_atomic_no_outline_atomics, target_env = "sgx")))] +#[cfg(target_feature = "sse")] +#[cfg(target_pointer_width = "64")] +macro_rules! ptr_modifier { + () => { + "" + }; +} + +// Unlike AArch64 and RISC-V, x86's assembler doesn't check instruction +// requirements for the currently enabled target features. In the first place, +// there is no option in the x86 assembly for such case, like Arm .arch_extension, +// RISC-V .option arch, PowerPC .machine, etc. +// However, we set target_feature(enable) when available (Rust 1.69+) in case a +// new codegen backend is added that checks for it in the future, or an option +// is added to the assembler to check for it. +#[cfg_attr( + not(portable_atomic_no_cmpxchg16b_target_feature), + target_feature(enable = "cmpxchg16b") +)] +#[inline] +unsafe fn cmpxchg16b(dst: *mut u128, old: u128, new: u128) -> (u128, bool) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_cmpxchg16b!(); + + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned (required by CMPXCHG16B), that there are no + // concurrent non-atomic operations, and that the CPU supports CMPXCHG16B. + // + // If the value at `dst` (destination operand) and rdx:rax are equal, the + // 128-bit value in rcx:rbx is stored in the `dst`, otherwise the value at + // `dst` is loaded to rdx:rax. + // + // The ZF flag is set if the value at `dst` and rdx:rax are equal, + // otherwise it is cleared. Other flags are unaffected. + // + // Refs: https://www.felixcloutier.com/x86/cmpxchg8b:cmpxchg16b + unsafe { + // cmpxchg16b is always SeqCst. + let r: u8; + let old = U128 { whole: old }; + let new = U128 { whole: new }; + let (prev_lo, prev_hi); + macro_rules! cmpxchg16b { + ($rdi:tt) => { + asm!( + "xchg {rbx_tmp}, rbx", // save rbx which is reserved by LLVM + concat!("lock cmpxchg16b xmmword ptr [", $rdi, "]"), + "sete cl", + "mov rbx, {rbx_tmp}", // restore rbx + rbx_tmp = inout(reg) new.pair.lo => _, + in("rcx") new.pair.hi, + inout("rax") old.pair.lo => prev_lo, + inout("rdx") old.pair.hi => prev_hi, + in($rdi) dst, + lateout("cl") r, + // Do not use `preserves_flags` because CMPXCHG16B modifies the ZF flag. + options(nostack), + ) + }; + } + #[cfg(target_pointer_width = "32")] + cmpxchg16b!("edi"); + #[cfg(target_pointer_width = "64")] + cmpxchg16b!("rdi"); + crate::utils::assert_unchecked(r == 0 || r == 1); // needed to remove extra test + (U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole, r != 0) + } +} + +// VMOVDQA is atomic on Intel, AMD, and Zhaoxin CPUs with AVX. +// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104688 for details. +// +// Refs: https://www.felixcloutier.com/x86/movdqa:vmovdqa32:vmovdqa64 +// +// Use cfg(target_feature = "sse") here -- SSE is included in the x86_64 +// baseline and is always available, but the SSE target feature is disabled for +// use cases such as kernels and firmware that should not use vector registers. +// So, do not use vector registers unless SSE target feature is enabled. +// See also https://github.com/rust-lang/rust/blob/1.80.0/src/doc/rustc/src/platform-support/x86_64-unknown-none.md. +#[cfg(not(any(portable_atomic_no_outline_atomics, target_env = "sgx")))] +#[cfg(target_feature = "sse")] +#[target_feature(enable = "avx")] +#[inline] +unsafe fn atomic_load_vmovdqa(src: *mut u128) -> u128 { + debug_assert!(src as usize % 16 == 0); + debug_assert_vmovdqa_atomic!(); + + // SAFETY: the caller must uphold the safety contract. + // + // atomic load by vmovdqa is always SeqCst. + unsafe { + let out: core::arch::x86_64::__m128i; + asm!( + concat!("vmovdqa {out}, xmmword ptr [{src", ptr_modifier!(), "}]"), + src = in(reg) src, + out = out(xmm_reg) out, + options(nostack, preserves_flags), + ); + core::mem::transmute(out) + } +} +#[cfg(not(any(portable_atomic_no_outline_atomics, target_env = "sgx")))] +#[cfg(target_feature = "sse")] +#[target_feature(enable = "avx")] +#[inline] +unsafe fn atomic_store_vmovdqa(dst: *mut u128, val: u128, order: Ordering) { + debug_assert!(dst as usize % 16 == 0); + debug_assert_vmovdqa_atomic!(); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let val: core::arch::x86_64::__m128i = core::mem::transmute(val); + match order { + // Relaxed and Release stores are equivalent. + Ordering::Relaxed | Ordering::Release => { + asm!( + concat!("vmovdqa xmmword ptr [{dst", ptr_modifier!(), "}], {val}"), + dst = in(reg) dst, + val = in(xmm_reg) val, + options(nostack, preserves_flags), + ); + } + Ordering::SeqCst => { + let p = core::cell::UnsafeCell::new(core::mem::MaybeUninit::::uninit()); + asm!( + concat!("vmovdqa xmmword ptr [{dst", ptr_modifier!(), "}], {val}"), + // Equivalent to mfence, but is up to 3.1x faster on Coffee Lake and up to 2.4x faster on Raptor Lake-H at least in simple cases. + // - https://github.com/taiki-e/portable-atomic/pull/156 + // - LLVM uses lock or for x86_32 64-bit atomic SeqCst store using SSE https://godbolt.org/z/9sKEr8YWc + // - Windows uses xchg for x86_32 for MemoryBarrier https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-memorybarrier + // - MSVC STL uses lock inc https://github.com/microsoft/STL/pull/740 + // - boost uses lock or https://github.com/boostorg/atomic/commit/559eba81af71386cedd99f170dc6101c6ad7bf22 + concat!("xchg qword ptr [{p", ptr_modifier!(), "}], {tmp}"), + dst = in(reg) dst, + val = in(xmm_reg) val, + p = inout(reg) p.get() => _, + tmp = lateout(reg) _, + options(nostack, preserves_flags), + ); + } + _ => unreachable!(), + } + } +} + +#[cfg(not(all( + any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"), + any(portable_atomic_no_outline_atomics, target_env = "sgx", not(target_feature = "sse")), +)))] +macro_rules! load_store_detect { + ( + vmovdqa = $vmovdqa:ident + cmpxchg16b = $cmpxchg16b:ident + fallback = $fallback:ident + ) => {{ + let cpuid = detect::detect(); + #[cfg(not(any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + )))] + { + // Check CMPXCHG16B first to prevent mixing atomic and non-atomic access. + if cpuid.has_cmpxchg16b() { + // We only use VMOVDQA when SSE is enabled. See atomic_load_vmovdqa() for more. + #[cfg(target_feature = "sse")] + { + if cpuid.has_vmovdqa_atomic() { + $vmovdqa + } else { + $cmpxchg16b + } + } + #[cfg(not(target_feature = "sse"))] + { + $cmpxchg16b + } + } else { + fallback::$fallback + } + } + #[cfg(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"))] + { + if cpuid.has_vmovdqa_atomic() { + $vmovdqa + } else { + $cmpxchg16b + } + } + }}; +} + +#[inline] +unsafe fn atomic_load(src: *mut u128, _order: Ordering) -> u128 { + // We only use VMOVDQA when SSE is enabled. See atomic_load_vmovdqa() for more. + // SGX doesn't support CPUID. + #[cfg(all( + any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"), + any(portable_atomic_no_outline_atomics, target_env = "sgx", not(target_feature = "sse")), + ))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantees that CMPXCHG16B is available at compile-time. + unsafe { + // cmpxchg16b is always SeqCst. + atomic_load_cmpxchg16b(src) + } + #[cfg(not(all( + any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"), + any(portable_atomic_no_outline_atomics, target_env = "sgx", not(target_feature = "sse")), + )))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + ifunc!(unsafe fn(src: *mut u128) -> u128 { + load_store_detect! { + vmovdqa = atomic_load_vmovdqa + cmpxchg16b = atomic_load_cmpxchg16b + // Use SeqCst because cmpxchg16b and atomic load by vmovdqa is always SeqCst. + fallback = atomic_load_seqcst + } + }) + } +} +// See cmpxchg16b() for target_feature(enable). +#[cfg_attr( + not(portable_atomic_no_cmpxchg16b_target_feature), + target_feature(enable = "cmpxchg16b") +)] +#[inline] +unsafe fn atomic_load_cmpxchg16b(src: *mut u128) -> u128 { + debug_assert!(src as usize % 16 == 0); + debug_assert_cmpxchg16b!(); + + // SAFETY: the caller must guarantee that `src` is valid for both writes and + // reads, 16-byte aligned, and that there are no concurrent non-atomic operations. + // cfg guarantees that the CPU supports CMPXCHG16B. + // + // See cmpxchg16b function for more. + // + // We could use CAS loop by atomic_compare_exchange here, but using an inline assembly allows + // omitting the storing of condition flags and avoid use of xchg to handle rbx. + unsafe { + // cmpxchg16b is always SeqCst. + let (out_lo, out_hi); + macro_rules! cmpxchg16b { + ($rdi:tt) => { + asm!( + "mov {rbx_tmp}, rbx", // save rbx which is reserved by LLVM + "xor rbx, rbx", // zeroed rbx + concat!("lock cmpxchg16b xmmword ptr [", $rdi, "]"), + "mov rbx, {rbx_tmp}", // restore rbx + // set old/new args of cmpxchg16b to 0 (rbx is zeroed after saved to rbx_tmp, to avoid xchg) + rbx_tmp = out(reg) _, + in("rcx") 0_u64, + inout("rax") 0_u64 => out_lo, + inout("rdx") 0_u64 => out_hi, + in($rdi) src, + // Do not use `preserves_flags` because CMPXCHG16B modifies the ZF flag. + options(nostack), + ) + }; + } + #[cfg(target_pointer_width = "32")] + cmpxchg16b!("edi"); + #[cfg(target_pointer_width = "64")] + cmpxchg16b!("rdi"); + U128 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} + +#[inline] +unsafe fn atomic_store(dst: *mut u128, val: u128, order: Ordering) { + // We only use VMOVDQA when SSE is enabled. See atomic_load_vmovdqa() for more. + // SGX doesn't support CPUID. + #[cfg(all( + any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"), + any(portable_atomic_no_outline_atomics, target_env = "sgx", not(target_feature = "sse")), + ))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantees that CMPXCHG16B is available at compile-time. + unsafe { + // cmpxchg16b is always SeqCst. + let _ = order; + atomic_store_cmpxchg16b(dst, val); + } + #[cfg(not(all( + any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"), + any(portable_atomic_no_outline_atomics, target_env = "sgx", not(target_feature = "sse")), + )))] + // SAFETY: the caller must uphold the safety contract. + unsafe { + #[cfg(target_feature = "sse")] + fn_alias! { + #[target_feature(enable = "avx")] + unsafe fn(dst: *mut u128, val: u128); + // atomic store by vmovdqa has at least release semantics. + atomic_store_vmovdqa_non_seqcst = atomic_store_vmovdqa(Ordering::Release); + atomic_store_vmovdqa_seqcst = atomic_store_vmovdqa(Ordering::SeqCst); + } + match order { + // Relaxed and Release stores are equivalent in all implementations + // that may be called here (vmovdqa, asm-based cmpxchg16b, and fallback). + // core::arch's cmpxchg16b will never called here. + Ordering::Relaxed | Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + load_store_detect! { + vmovdqa = atomic_store_vmovdqa_non_seqcst + cmpxchg16b = atomic_store_cmpxchg16b + fallback = atomic_store_non_seqcst + } + }); + } + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u128, val: u128) { + load_store_detect! { + vmovdqa = atomic_store_vmovdqa_seqcst + cmpxchg16b = atomic_store_cmpxchg16b + fallback = atomic_store_seqcst + } + }); + } + _ => unreachable!(), + } + } +} +// See cmpxchg16b() for target_feature(enable). +#[cfg_attr( + not(portable_atomic_no_cmpxchg16b_target_feature), + target_feature(enable = "cmpxchg16b") +)] +#[inline] +unsafe fn atomic_store_cmpxchg16b(dst: *mut u128, val: u128) { + // SAFETY: the caller must uphold the safety contract. + unsafe { + // cmpxchg16b is always SeqCst. + atomic_swap_cmpxchg16b(dst, val, Ordering::SeqCst); + } +} + +#[inline] +unsafe fn atomic_compare_exchange( + dst: *mut u128, + old: u128, + new: u128, + _success: Ordering, + _failure: Ordering, +) -> Result { + #[cfg(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"))] + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, that there are no concurrent non-atomic operations, + // and cfg guarantees that CMPXCHG16B is available at compile-time. + let (prev, ok) = unsafe { cmpxchg16b(dst, old, new) }; + #[cfg(not(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b")))] + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, and that there are no different kinds of concurrent accesses. + let (prev, ok) = unsafe { + ifunc!(unsafe fn(dst: *mut u128, old: u128, new: u128) -> (u128, bool) { + if detect::detect().has_cmpxchg16b() { + cmpxchg16b + } else { + // Use SeqCst because cmpxchg16b is always SeqCst. + fallback::atomic_compare_exchange_seqcst + } + }) + }; + if ok { + Ok(prev) + } else { + Err(prev) + } +} + +// cmpxchg16b is always strong. +use atomic_compare_exchange as atomic_compare_exchange_weak; + +// See cmpxchg16b() for target_feature(enable). +#[cfg_attr( + not(portable_atomic_no_cmpxchg16b_target_feature), + target_feature(enable = "cmpxchg16b") +)] +#[inline] +unsafe fn atomic_swap_cmpxchg16b(dst: *mut u128, val: u128, _order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_cmpxchg16b!(); + + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, and that there are no concurrent non-atomic operations. + // cfg guarantees that the CPU supports CMPXCHG16B. + // + // See cmpxchg16b function for more. + // + // We could use CAS loop by atomic_compare_exchange here, but using an inline assembly allows + // omitting the storing/comparing of condition flags and reducing uses of xchg/mov to handle rbx. + // + // Do not use atomic_rmw_cas_3 because it needs extra MOV to implement swap. + unsafe { + // cmpxchg16b is always SeqCst. + let val = U128 { whole: val }; + let (mut prev_lo, mut prev_hi); + macro_rules! cmpxchg16b { + ($rdi:tt) => { + asm!( + "xchg {rbx_tmp}, rbx", // save rbx which is reserved by LLVM + // This is not single-copy atomic reads, but this is ok because subsequent + // CAS will check for consistency. + // + // This is based on the code generated for the first load in DW RMWs by LLVM. + // + // Note that the C++20 memory model does not allow mixed-sized atomic access, + // so we must use inline assembly to implement this. + // (i.e., byte-wise atomic based on the standard library's atomic types + // cannot be used here). + concat!("mov rax, qword ptr [", $rdi, "]"), + concat!("mov rdx, qword ptr [", $rdi, " + 8]"), + "2:", + concat!("lock cmpxchg16b xmmword ptr [", $rdi, "]"), + "jne 2b", + "mov rbx, {rbx_tmp}", // restore rbx + rbx_tmp = inout(reg) val.pair.lo => _, + in("rcx") val.pair.hi, + out("rax") prev_lo, + out("rdx") prev_hi, + in($rdi) dst, + // Do not use `preserves_flags` because CMPXCHG16B modifies the ZF flag. + options(nostack), + ) + }; + } + #[cfg(target_pointer_width = "32")] + cmpxchg16b!("edi"); + #[cfg(target_pointer_width = "64")] + cmpxchg16b!("rdi"); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } +} + +/// Atomic RMW by CAS loop (3 arguments) +/// `unsafe fn(dst: *mut u128, val: u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - rsi/r8 pair: val argument (read-only for `$op`) +/// - rax/rdx pair: previous value loaded (read-only for `$op`) +/// - rbx/rcx pair: new value that will be stored +// We could use CAS loop by atomic_compare_exchange here, but using an inline assembly allows +// omitting the storing/comparing of condition flags and reducing uses of xchg/mov to handle rbx. +macro_rules! atomic_rmw_cas_3 { + ($name:ident, $($op:tt)*) => { + // See cmpxchg16b() for target_feature(enable). + #[cfg_attr( + not(portable_atomic_no_cmpxchg16b_target_feature), + target_feature(enable = "cmpxchg16b") + )] + #[inline] + unsafe fn $name(dst: *mut u128, val: u128, _order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_cmpxchg16b!(); + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, and that there are no concurrent non-atomic operations. + // cfg guarantees that the CPU supports CMPXCHG16B. + // + // See cmpxchg16b function for more. + unsafe { + // cmpxchg16b is always SeqCst. + let val = U128 { whole: val }; + let (mut prev_lo, mut prev_hi); + macro_rules! cmpxchg16b { + ($rdi:tt) => { + asm!( + "mov {rbx_tmp}, rbx", // save rbx which is reserved by LLVM + // This is not single-copy atomic reads, but this is ok because subsequent + // CAS will check for consistency. + // + // This is based on the code generated for the first load in DW RMWs by LLVM. + // + // Note that the C++20 memory model does not allow mixed-sized atomic access, + // so we must use inline assembly to implement this. + // (i.e., byte-wise atomic based on the standard library's atomic types + // cannot be used here). + concat!("mov rax, qword ptr [", $rdi, "]"), + concat!("mov rdx, qword ptr [", $rdi, " + 8]"), + "2:", + $($op)* + concat!("lock cmpxchg16b xmmword ptr [", $rdi, "]"), + "jne 2b", + "mov rbx, {rbx_tmp}", // restore rbx + rbx_tmp = out(reg) _, + out("rcx") _, + out("rax") prev_lo, + out("rdx") prev_hi, + in($rdi) dst, + in("rsi") val.pair.lo, + in("r8") val.pair.hi, + // Do not use `preserves_flags` because CMPXCHG16B modifies the ZF flag. + options(nostack), + ) + }; + } + #[cfg(target_pointer_width = "32")] + cmpxchg16b!("edi"); + #[cfg(target_pointer_width = "64")] + cmpxchg16b!("rdi"); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } + } + }; +} +/// Atomic RMW by CAS loop (2 arguments) +/// `unsafe fn(dst: *mut u128, order: Ordering) -> u128;` +/// +/// `$op` can use the following registers: +/// - rax/rdx pair: previous value loaded (read-only for `$op`) +/// - rbx/rcx pair: new value that will be stored +// We could use CAS loop by atomic_compare_exchange here, but using an inline assembly allows +// omitting the storing of condition flags and avoid use of xchg to handle rbx. +macro_rules! atomic_rmw_cas_2 { + ($name:ident, $($op:tt)*) => { + // See cmpxchg16b() for target_feature(enable). + #[cfg_attr( + not(portable_atomic_no_cmpxchg16b_target_feature), + target_feature(enable = "cmpxchg16b") + )] + #[inline] + unsafe fn $name(dst: *mut u128, _order: Ordering) -> u128 { + debug_assert!(dst as usize % 16 == 0); + debug_assert_cmpxchg16b!(); + // SAFETY: the caller must guarantee that `dst` is valid for both writes and + // reads, 16-byte aligned, and that there are no concurrent non-atomic operations. + // cfg guarantees that the CPU supports CMPXCHG16B. + // + // See cmpxchg16b function for more. + unsafe { + // cmpxchg16b is always SeqCst. + let (mut prev_lo, mut prev_hi); + macro_rules! cmpxchg16b { + ($rdi:tt) => { + asm!( + "mov {rbx_tmp}, rbx", // save rbx which is reserved by LLVM + // This is not single-copy atomic reads, but this is ok because subsequent + // CAS will check for consistency. + // + // This is based on the code generated for the first load in DW RMWs by LLVM. + // + // Note that the C++20 memory model does not allow mixed-sized atomic access, + // so we must use inline assembly to implement this. + // (i.e., byte-wise atomic based on the standard library's atomic types + // cannot be used here). + concat!("mov rax, qword ptr [", $rdi, "]"), + concat!("mov rdx, qword ptr [", $rdi, " + 8]"), + "2:", + $($op)* + concat!("lock cmpxchg16b xmmword ptr [", $rdi, "]"), + "jne 2b", + "mov rbx, {rbx_tmp}", // restore rbx + rbx_tmp = out(reg) _, + out("rcx") _, + out("rax") prev_lo, + out("rdx") prev_hi, + in($rdi) dst, + // Do not use `preserves_flags` because CMPXCHG16B modifies the ZF flag. + options(nostack), + ) + }; + } + #[cfg(target_pointer_width = "32")] + cmpxchg16b!("edi"); + #[cfg(target_pointer_width = "64")] + cmpxchg16b!("rdi"); + U128 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + } + } + }; +} + +atomic_rmw_cas_3! { + atomic_add_cmpxchg16b, + "mov rbx, rax", + "add rbx, rsi", + "mov rcx, rdx", + "adc rcx, r8", +} +atomic_rmw_cas_3! { + atomic_sub_cmpxchg16b, + "mov rbx, rax", + "sub rbx, rsi", + "mov rcx, rdx", + "sbb rcx, r8", +} +atomic_rmw_cas_3! { + atomic_and_cmpxchg16b, + "mov rbx, rax", + "and rbx, rsi", + "mov rcx, rdx", + "and rcx, r8", +} +atomic_rmw_cas_3! { + atomic_nand_cmpxchg16b, + "mov rbx, rax", + "and rbx, rsi", + "not rbx", + "mov rcx, rdx", + "and rcx, r8", + "not rcx", +} +atomic_rmw_cas_3! { + atomic_or_cmpxchg16b, + "mov rbx, rax", + "or rbx, rsi", + "mov rcx, rdx", + "or rcx, r8", +} +atomic_rmw_cas_3! { + atomic_xor_cmpxchg16b, + "mov rbx, rax", + "xor rbx, rsi", + "mov rcx, rdx", + "xor rcx, r8", +} + +atomic_rmw_cas_2! { + atomic_not_cmpxchg16b, + "mov rbx, rax", + "not rbx", + "mov rcx, rdx", + "not rcx", +} +atomic_rmw_cas_2! { + atomic_neg_cmpxchg16b, + "mov rbx, rax", + "neg rbx", + "mov rcx, 0", + "sbb rcx, rdx", +} + +atomic_rmw_cas_3! { + atomic_max_cmpxchg16b, + "cmp rsi, rax", + "mov rcx, r8", + "sbb rcx, rdx", + "mov rcx, r8", + "cmovl rcx, rdx", + "mov rbx, rsi", + "cmovl rbx, rax", +} +atomic_rmw_cas_3! { + atomic_umax_cmpxchg16b, + "cmp rsi, rax", + "mov rcx, r8", + "sbb rcx, rdx", + "mov rcx, r8", + "cmovb rcx, rdx", + "mov rbx, rsi", + "cmovb rbx, rax", +} +atomic_rmw_cas_3! { + atomic_min_cmpxchg16b, + "cmp rsi, rax", + "mov rcx, r8", + "sbb rcx, rdx", + "mov rcx, r8", + "cmovge rcx, rdx", + "mov rbx, rsi", + "cmovge rbx, rax", +} +atomic_rmw_cas_3! { + atomic_umin_cmpxchg16b, + "cmp rsi, rax", + "mov rcx, r8", + "sbb rcx, rdx", + "mov rcx, r8", + "cmovae rcx, rdx", + "mov rbx, rsi", + "cmovae rbx, rax", +} + +macro_rules! select_atomic_rmw { + ( + unsafe fn $name:ident($($arg:tt)*) $(-> $ret_ty:ty)?; + cmpxchg16b = $cmpxchg16b_fn:ident; + fallback = $seqcst_fallback_fn:ident; + ) => { + // If cmpxchg16b is available at compile-time, we can always use cmpxchg16b_fn. + #[cfg(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"))] + use $cmpxchg16b_fn as $name; + // Otherwise, we need to do run-time detection and can use cmpxchg16b_fn only if cmpxchg16b is available. + #[cfg(not(any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + )))] + #[inline] + unsafe fn $name($($arg)*, _order: Ordering) $(-> $ret_ty)? { + fn_alias! { + // See cmpxchg16b() for target_feature(enable). + #[cfg_attr( + not(portable_atomic_no_cmpxchg16b_target_feature), + target_feature(enable = "cmpxchg16b") + )] + unsafe fn($($arg)*) $(-> $ret_ty)?; + // cmpxchg16b is always SeqCst. + cmpxchg16b_seqcst_fn = $cmpxchg16b_fn(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls cmpxchg16b_fn if cmpxchg16b is available. + unsafe { + ifunc!(unsafe fn($($arg)*) $(-> $ret_ty)? { + if detect::detect().has_cmpxchg16b() { + cmpxchg16b_seqcst_fn + } else { + // Use SeqCst because cmpxchg16b is always SeqCst. + fallback::$seqcst_fallback_fn + } + }) + } + } + }; +} + +select_atomic_rmw! { + unsafe fn atomic_swap(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_swap_cmpxchg16b; + fallback = atomic_swap_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_add(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_add_cmpxchg16b; + fallback = atomic_add_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_sub(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_sub_cmpxchg16b; + fallback = atomic_sub_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_and(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_and_cmpxchg16b; + fallback = atomic_and_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_nand(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_nand_cmpxchg16b; + fallback = atomic_nand_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_or(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_or_cmpxchg16b; + fallback = atomic_or_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_xor(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_xor_cmpxchg16b; + fallback = atomic_xor_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_max(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_max_cmpxchg16b; + fallback = atomic_max_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umax(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_umax_cmpxchg16b; + fallback = atomic_umax_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_min(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_min_cmpxchg16b; + fallback = atomic_min_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umin(dst: *mut u128, val: u128) -> u128; + cmpxchg16b = atomic_umin_cmpxchg16b; + fallback = atomic_umin_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_not(dst: *mut u128) -> u128; + cmpxchg16b = atomic_not_cmpxchg16b; + fallback = atomic_not_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_neg(dst: *mut u128) -> u128; + cmpxchg16b = atomic_neg_cmpxchg16b; + fallback = atomic_neg_seqcst; +} + +#[inline] +fn is_lock_free() -> bool { + #[cfg(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"))] + { + // CMPXCHG16B is available at compile-time. + true + } + #[cfg(not(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b")))] + { + detect::detect().has_cmpxchg16b() + } +} +const IS_ALWAYS_LOCK_FREE: bool = + cfg!(any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b")); + +atomic128!(AtomicI128, i128, atomic_max, atomic_min); +atomic128!(AtomicU128, u128, atomic_umax, atomic_umin); + +#[allow(clippy::undocumented_unsafe_blocks, clippy::wildcard_imports)] +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_int!(i128); + test_atomic_int!(u128); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u128); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/README.md b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/README.md new file mode 100644 index 0000000..66280e6 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/README.md @@ -0,0 +1,20 @@ +# 64-bit atomic implementations on 32-bit architectures + +(See the [`atomic128` module](../atomic128) for 128-bit atomic implementations on 64-bit architectures.) + +## 64-bit atomic instructions + +Here is the table of targets that support 64-bit atomics and the instructions used: + +| target_arch | load | store | CAS | RMW | note | +| ----------- | ---- | ----- | --- | --- | ---- | +| x86 | cmpxchg8b or fild or movlps or movq | cmpxchg8b or fistp or movlps | cmpxchg8b | cmpxchg8b | provided by `core::sync::atomic` | +| arm | ldrexd | ldrexd/strexd | ldrexd/strexd | ldrexd/strexd | provided by `core::sync::atomic` for Armv6+, otherwise provided by us for Linux/Android using kuser_cmpxchg64 (see [arm_linux.rs](arm_linux.rs) for more) | +| riscv32 | amocas.d | amocas.d | amocas.d | amocas.d | Experimental because LLVM marking the corresponding target feature as experimental. Requires experimental-zacas target feature. Both compile-time and run-time detection are supported (run-time detection is currently disabled by default).
Requires 1.82+ (LLVM 19+) | + +If `core::sync::atomic` provides 64-bit atomics, we use them. +On compiler versions or platforms where these are not supported, the fallback implementation is used. + +## Run-time CPU feature detection + +See the [`detect` module's readme](../detect/README.md) for run-time CPU feature detection. diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/arm_linux.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/arm_linux.rs new file mode 100644 index 0000000..4456115 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/arm_linux.rs @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +64-bit atomic implementation using kuser_cmpxchg64 on pre-v6 Arm Linux/Android. + +Refs: +- https://github.com/torvalds/linux/blob/v6.11/Documentation/arch/arm/kernel_user_helpers.rst +- https://github.com/rust-lang/compiler-builtins/blob/compiler_builtins-v0.1.124/src/arm_linux.rs + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use fallback implementation instead. +*/ + +// TODO: Since Rust 1.64, the Linux kernel requirement for Rust when using std is 3.2+, so it should +// be possible to omit the dynamic kernel version check if the std feature is enabled on Rust 1.64+. +// https://blog.rust-lang.org/2022/08/01/Increasing-glibc-kernel-requirements.html + +include!("macros.rs"); + +#[path = "../fallback/outline_atomics.rs"] +mod fallback; + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; +use core::{mem, sync::atomic::Ordering}; + +use crate::utils::{Pair, U64}; + +// https://github.com/torvalds/linux/blob/v6.11/Documentation/arch/arm/kernel_user_helpers.rst +const KUSER_HELPER_VERSION: usize = 0xFFFF0FFC; +// __kuser_helper_version >= 5 (kernel version 3.1+) +const KUSER_CMPXCHG64: usize = 0xFFFF0F60; +#[inline] +fn __kuser_helper_version() -> i32 { + use core::sync::atomic::AtomicI32; + + static CACHE: AtomicI32 = AtomicI32::new(0); + let mut v = CACHE.load(Ordering::Relaxed); + if v != 0 { + return v; + } + // SAFETY: core assumes that at least __kuser_memory_barrier (__kuser_helper_version >= 3, + // kernel version 2.6.15+) is available on this platform. __kuser_helper_version + // is always available on such a platform. + v = unsafe { (KUSER_HELPER_VERSION as *const i32).read() }; + CACHE.store(v, Ordering::Relaxed); + v +} +#[inline] +fn has_kuser_cmpxchg64() -> bool { + // Note: detect_false cfg is intended to make it easy for portable-atomic developers to + // test cases such as has_cmpxchg16b == false, has_lse == false, + // __kuser_helper_version < 5, etc., and is not a public API. + if cfg!(portable_atomic_test_outline_atomics_detect_false) { + return false; + } + __kuser_helper_version() >= 5 +} +#[inline] +unsafe fn __kuser_cmpxchg64(old_val: *const u64, new_val: *const u64, ptr: *mut u64) -> bool { + // SAFETY: the caller must uphold the safety contract. + unsafe { + let f: extern "C" fn(*const u64, *const u64, *mut u64) -> u32 = + mem::transmute(KUSER_CMPXCHG64 as *const ()); + f(old_val, new_val, ptr) == 0 + } +} + +// 64-bit atomic load by two 32-bit atomic loads. +#[inline] +unsafe fn byte_wise_atomic_load(src: *const u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (out_lo, out_hi); + asm!( + "ldr {out_lo}, [{src}]", + "ldr {out_hi}, [{src}, #4]", + src = in(reg) src, + out_lo = out(reg) out_lo, + out_hi = out(reg) out_hi, + options(pure, nostack, preserves_flags, readonly), + ); + U64 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} + +#[inline(always)] +unsafe fn atomic_update_kuser_cmpxchg64(dst: *mut u64, mut f: F) -> u64 +where + F: FnMut(u64) -> u64, +{ + debug_assert!(dst as usize % 8 == 0); + debug_assert!(has_kuser_cmpxchg64()); + // SAFETY: the caller must uphold the safety contract. + unsafe { + loop { + // This is not single-copy atomic reads, but this is ok because subsequent + // CAS will check for consistency. + // + // Arm's memory model allow mixed-sized atomic access. + // https://github.com/rust-lang/unsafe-code-guidelines/issues/345#issuecomment-1172891466 + // + // Note that the C++20 memory model does not allow mixed-sized atomic access, + // so we must use inline assembly to implement byte_wise_atomic_load. + // (i.e., byte-wise atomic based on the standard library's atomic types + // cannot be used here). + let prev = byte_wise_atomic_load(dst); + let next = f(prev); + if __kuser_cmpxchg64(&prev, &next, dst) { + return prev; + } + } + } +} + +macro_rules! atomic_with_ifunc { + ( + unsafe fn $name:ident($($arg:tt)*) $(-> $ret_ty:ty)? { $($kuser_cmpxchg64_fn_body:tt)* } + fallback = $seqcst_fallback_fn:ident + ) => { + #[inline] + unsafe fn $name($($arg)*, _: Ordering) $(-> $ret_ty)? { + unsafe fn kuser_cmpxchg64_fn($($arg)*) $(-> $ret_ty)? { + $($kuser_cmpxchg64_fn_body)* + } + // SAFETY: the caller must uphold the safety contract. + // we only calls __kuser_cmpxchg64 if it is available. + unsafe { + ifunc!(unsafe fn($($arg)*) $(-> $ret_ty)? { + if has_kuser_cmpxchg64() { + kuser_cmpxchg64_fn + } else { + // Use SeqCst because __kuser_cmpxchg64 is always SeqCst. + // https://github.com/torvalds/linux/blob/v6.11/arch/arm/kernel/entry-armv.S#L692-L699 + fallback::$seqcst_fallback_fn + } + }) + } + } + }; +} + +atomic_with_ifunc! { + unsafe fn atomic_load(src: *mut u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(src, |old| old) } + } + fallback = atomic_load_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_store(dst: *mut u64, val: u64) { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |_| val); } + } + fallback = atomic_store_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_swap(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |_| val) } + } + fallback = atomic_swap_seqcst +} +#[inline] +unsafe fn atomic_compare_exchange( + dst: *mut u64, + old: u64, + new: u64, + _: Ordering, + _: Ordering, +) -> Result { + unsafe fn kuser_cmpxchg64_fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool) { + // SAFETY: the caller must uphold the safety contract. + let prev = + unsafe { atomic_update_kuser_cmpxchg64(dst, |v| if v == old { new } else { v }) }; + (prev, prev == old) + } + // SAFETY: the caller must uphold the safety contract. + // we only calls __kuser_cmpxchg64 if it is available. + let (prev, ok) = unsafe { + ifunc!(unsafe fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool) { + if has_kuser_cmpxchg64() { + kuser_cmpxchg64_fn + } else { + // Use SeqCst because __kuser_cmpxchg64 is always SeqCst. + // https://github.com/torvalds/linux/blob/v6.11/arch/arm/kernel/entry-armv.S#L692-L699 + fallback::atomic_compare_exchange_seqcst + } + }) + }; + if ok { + Ok(prev) + } else { + Err(prev) + } +} +use self::atomic_compare_exchange as atomic_compare_exchange_weak; +atomic_with_ifunc! { + unsafe fn atomic_add(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| x.wrapping_add(val)) } + } + fallback = atomic_add_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_sub(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| x.wrapping_sub(val)) } + } + fallback = atomic_sub_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_and(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| x & val) } + } + fallback = atomic_and_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_nand(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| !(x & val)) } + } + fallback = atomic_nand_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_or(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| x | val) } + } + fallback = atomic_or_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_xor(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| x ^ val) } + } + fallback = atomic_xor_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_max(dst: *mut u64, val: u64) -> u64 { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_update_kuser_cmpxchg64(dst, |x| core::cmp::max(x as i64, val as i64) as u64) + } + } + fallback = atomic_max_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_umax(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| core::cmp::max(x, val)) } + } + fallback = atomic_umax_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_min(dst: *mut u64, val: u64) -> u64 { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_update_kuser_cmpxchg64(dst, |x| core::cmp::min(x as i64, val as i64) as u64) + } + } + fallback = atomic_min_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_umin(dst: *mut u64, val: u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| core::cmp::min(x, val)) } + } + fallback = atomic_umin_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_not(dst: *mut u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, |x| !x) } + } + fallback = atomic_not_seqcst +} +atomic_with_ifunc! { + unsafe fn atomic_neg(dst: *mut u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_kuser_cmpxchg64(dst, u64::wrapping_neg) } + } + fallback = atomic_neg_seqcst +} + +#[inline] +fn is_lock_free() -> bool { + has_kuser_cmpxchg64() +} +const IS_ALWAYS_LOCK_FREE: bool = false; + +atomic64!(AtomicI64, i64, atomic_max, atomic_min); +atomic64!(AtomicU64, u64, atomic_umax, atomic_umin); + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kuser_helper_version() { + let version = __kuser_helper_version(); + assert!(version >= 5, "{:?}", version); + assert_eq!(version, unsafe { (KUSER_HELPER_VERSION as *const i32).read() }); + } + + test_atomic_int!(i64); + test_atomic_int!(u64); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u64); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/macros.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/macros.rs new file mode 100644 index 0000000..f953185 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/macros.rs @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +macro_rules! atomic64 { + ($atomic_type:ident, $int_type:ident, $atomic_max:ident, $atomic_min:ident) => { + #[repr(C, align(8))] + pub(crate) struct $atomic_type { + v: core::cell::UnsafeCell<$int_type>, + } + + // Send is implicitly implemented. + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock. + unsafe impl Sync for $atomic_type {} + + impl_default_no_fetch_ops!($atomic_type, $int_type); + impl_default_bit_opts!($atomic_type, $int_type); + impl $atomic_type { + #[inline] + pub(crate) const fn new(v: $int_type) -> Self { + Self { v: core::cell::UnsafeCell::new(v) } + } + + #[inline] + pub(crate) fn is_lock_free() -> bool { + is_lock_free() + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = IS_ALWAYS_LOCK_FREE; + + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $int_type { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.v.get() } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn load(&self, order: Ordering) -> $int_type { + crate::utils::assert_load_ordering(order); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_load(self.v.get().cast::(), order) as $int_type + } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn store(&self, val: $int_type, order: Ordering) { + crate::utils::assert_store_ordering(order); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_store(self.v.get().cast::(), val as u64, order) + } + } + + #[inline] + pub(crate) fn swap(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_swap(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + match atomic_compare_exchange( + self.v.get().cast::(), + current as u64, + new as u64, + success, + failure, + ) { + Ok(v) => Ok(v as $int_type), + Err(v) => Err(v as $int_type), + } + } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + match atomic_compare_exchange_weak( + self.v.get().cast::(), + current as u64, + new as u64, + success, + failure, + ) { + Ok(v) => Ok(v as $int_type), + Err(v) => Err(v as $int_type), + } + } + } + + #[inline] + pub(crate) fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_add(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_sub(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_and(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_nand(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_or(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_xor(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + $atomic_max(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + $atomic_min(self.v.get().cast::(), val as u64, order) as $int_type + } + } + + #[inline] + pub(crate) fn fetch_not(&self, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_not(self.v.get().cast::(), order) as $int_type + } + } + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + + #[inline] + pub(crate) fn fetch_neg(&self, order: Ordering) -> $int_type { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + // SAFETY: any data races are prevented by atomic intrinsics, the kernel user helper, or the lock + // and the raw pointer passed in is valid because we got it from a reference. + unsafe { + atomic_neg(self.v.get().cast::(), order) as $int_type + } + } + #[inline] + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } + + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut $int_type { + self.v.get() + } + } + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/mod.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/mod.rs new file mode 100644 index 0000000..6138dbc --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/mod.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +64-bit atomic implementations on 32-bit architectures + +See README.md for details. +*/ + +// pre-v6 Arm Linux +#[cfg(feature = "fallback")] +// Miri and Sanitizer do not support inline assembly. +#[cfg(all( + target_arch = "arm", + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any(target_os = "linux", target_os = "android"), + not(any(target_feature = "v6", portable_atomic_target_feature = "v6")), + not(portable_atomic_no_outline_atomics), +))] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(portable_atomic_no_atomic_64))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(not(target_has_atomic = "64")))] +pub(super) mod arm_linux; + +// riscv32 +// Miri and Sanitizer do not support inline assembly. +#[cfg(all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + ), + ), +))] +pub(super) mod riscv32; diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/riscv32.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/riscv32.rs new file mode 100644 index 0000000..209e4ef --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/atomic64/riscv32.rs @@ -0,0 +1,653 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +64-bit atomic implementation on riscv32 using amocas.d (DWCAS). + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use fallback implementation instead. + +Refs: +- RISC-V Instruction Set Manual + https://github.com/riscv/riscv-isa-manual/tree/riscv-isa-release-8b9dc50-2024-08-30 + "Zacas" Extension for Atomic Compare-and-Swap (CAS) Instructions + https://github.com/riscv/riscv-isa-manual/blob/riscv-isa-release-8b9dc50-2024-08-30/src/zacas.adoc +- RISC-V Atomics ABI Specification + https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/draft-20240829-13bfa9f54634cb60d86b9b333e109f077805b4b3/riscv-atomic.adoc + +Generated asm: +- riscv32 (+experimental-zacas) https://godbolt.org/z/d3f6EsG3f +*/ + +// TODO: merge duplicated code with atomic128/riscv64.rs + +include!("macros.rs"); + +#[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +)))] +#[path = "../fallback/outline_atomics.rs"] +mod fallback; + +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any(test, portable_atomic_outline_atomics))] // TODO(riscv): currently disabled by default +#[cfg(any( + test, + not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )), +))] +#[cfg(any(target_os = "linux", target_os = "android"))] +#[path = "../detect/riscv_linux.rs"] +mod detect; + +use core::{arch::asm, sync::atomic::Ordering}; + +use crate::utils::{Pair, U64}; + +macro_rules! debug_assert_zacas { + () => { + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + { + debug_assert!(detect::detect().has_zacas()); + } + }; +} + +// LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. +// So, we currently always using .insn directive. +// `.insn ` directive requires LLVM 19. +// https://github.com/llvm/llvm-project/commit/2a086dce691e3cc34a2fc27f4fb255bb2cbbfac9 +// // https://github.com/riscv-non-isa/riscv-asm-manual/blob/ad0de8c004e29c9a7ac33cfd054f4d4f9392f2fb/src/asm-manual.adoc#arch +// macro_rules! start_zacas { +// () => { +// ".option push\n.option arch, +zacas" +// }; +// } +// macro_rules! end_zacas { +// () => { +// ".option pop" +// }; +// } + +// LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. +// So, we currently always using .insn directive. +// macro_rules! atomic_rmw_amocas_order { +// ($op:ident, $order:ident) => { +// atomic_rmw_amocas_order!($op, $order, failure = $order) +// }; +// ($op:ident, $order:ident, failure = $failure:ident) => { +// match $order { +// Ordering::Relaxed => $op!("", ""), +// Ordering::Acquire => $op!("", ".aq"), +// Ordering::Release => $op!("", ".rl"), +// Ordering::AcqRel => $op!("", ".aqrl"), +// Ordering::SeqCst if $failure == Ordering::SeqCst => $op!("fence rw,rw", ".aqrl"), +// Ordering::SeqCst => $op!("", ".aqrl"), +// _ => unreachable!(), +// } +// }; +// } +macro_rules! atomic_rmw_amocas_order_insn { + ($op:ident, $order:ident) => { + atomic_rmw_amocas_order_insn!($op, $order, failure = $order) + }; + ($op:ident, $order:ident, failure = $failure:ident) => { + match $order { + Ordering::Relaxed => $op!("", "8"), + Ordering::Acquire => $op!("", "c"), + Ordering::Release => $op!("", "a"), + Ordering::AcqRel => $op!("", "e"), + Ordering::SeqCst if $failure == Ordering::SeqCst => $op!("fence rw,rw", "e"), + Ordering::SeqCst => $op!("", "e"), + _ => unreachable!(), + } + }; +} + +// If zacas is available at compile-time, we can always use zacas_fn. +#[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +))] +use atomic_load_zacas as atomic_load; +// Otherwise, we need to do run-time detection and can use zacas_fn only if zacas is available. +#[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +)))] +#[inline] +unsafe fn atomic_load(src: *mut u64, order: Ordering) -> u64 { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(src: *mut u64) -> u64; + atomic_load_zacas_relaxed = atomic_load_zacas(Ordering::Relaxed); + atomic_load_zacas_acquire = atomic_load_zacas(Ordering::Acquire); + atomic_load_zacas_seqcst = atomic_load_zacas(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls atomic_load_zacas if zacas is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(src: *mut u64) -> u64 { + if detect::detect().has_zacas() { + atomic_load_zacas_relaxed + } else { + fallback::atomic_load_non_seqcst + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(src: *mut u64) -> u64 { + if detect::detect().has_zacas() { + atomic_load_zacas_acquire + } else { + fallback::atomic_load_non_seqcst + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(src: *mut u64) -> u64 { + if detect::detect().has_zacas() { + atomic_load_zacas_seqcst + } else { + fallback::atomic_load_seqcst + } + }) + } + _ => unreachable!(), + } + } +} +#[inline] +unsafe fn atomic_load_zacas(src: *mut u64, order: Ordering) -> u64 { + debug_assert!(src as usize % 8 == 0); + debug_assert_zacas!(); + + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (out_lo, out_hi); + // LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. + // So, we currently always using .insn directive. + // macro_rules! load { + // ($fence:tt, $asm_order:tt) => { + // asm!( + // start_zacas!(), + // $fence, + // concat!("amocas.d", $asm_order, " a2, a2, 0({src})"), + // end_zacas!(), + // src = in(reg) ptr_reg!(src), + // inout("a2") 0_u32 => out_lo, + // inout("a3") 0_u32 => out_hi, + // options(nostack, preserves_flags), + // ) + // }; + // } + // atomic_rmw_amocas_order!(load, order); + macro_rules! load { + ($fence:tt, $insn_order:tt) => { + asm!( + $fence, + // 4: 2{8,c,a,e}c5362f amocas.d{,.aq,.rl,.aqrl} a2, a2, (a0) + concat!(".insn 0x2", $insn_order, "c5362f"), + in("a0") ptr_reg!(src), + inout("a2") 0_u32 => out_lo, + inout("a3") 0_u32 => out_hi, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw_amocas_order_insn!(load, order); + U64 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} + +#[inline] +unsafe fn atomic_store(dst: *mut u64, val: u64, order: Ordering) { + // SAFETY: the caller must uphold the safety contract. + unsafe { + atomic_swap(dst, val, order); + } +} + +#[inline] +unsafe fn atomic_compare_exchange( + dst: *mut u64, + old: u64, + new: u64, + success: Ordering, + failure: Ordering, +) -> Result { + #[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ))] + // SAFETY: the caller must uphold the safety contract. + // cfg guarantees that zacas instructions are available at compile-time. + let (prev, ok) = unsafe { atomic_compare_exchange_zacas(dst, old, new, success, failure) }; + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + let (prev, ok) = { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool); + zacas_relaxed_fn = atomic_compare_exchange_zacas(Ordering::Relaxed, Ordering::Relaxed); + zacas_acquire_fn = atomic_compare_exchange_zacas(Ordering::Acquire, Ordering::Acquire); + zacas_release_fn = atomic_compare_exchange_zacas(Ordering::Release, Ordering::Relaxed); + zacas_acqrel_fn = atomic_compare_exchange_zacas(Ordering::AcqRel, Ordering::Acquire); + zacas_seqcst_fn = atomic_compare_exchange_zacas(Ordering::SeqCst, Ordering::SeqCst); + } + let order = crate::utils::upgrade_success_ordering(success, failure); + // SAFETY: the caller must uphold the safety contract. + // we only calls atomic_compare_exchange_zacas if zacas is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool) { + if detect::detect().has_zacas() { + zacas_relaxed_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool) { + if detect::detect().has_zacas() { + zacas_acquire_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool) { + if detect::detect().has_zacas() { + zacas_release_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::AcqRel => { + ifunc!(unsafe fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool) { + if detect::detect().has_zacas() { + zacas_acqrel_fn + } else { + fallback::atomic_compare_exchange_non_seqcst + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u64, old: u64, new: u64) -> (u64, bool) { + if detect::detect().has_zacas() { + zacas_seqcst_fn + } else { + fallback::atomic_compare_exchange_seqcst + } + }) + } + _ => unreachable!(), + } + } + }; + if ok { + Ok(prev) + } else { + Err(prev) + } +} +#[inline] +unsafe fn atomic_compare_exchange_zacas( + dst: *mut u64, + old: u64, + new: u64, + success: Ordering, + failure: Ordering, +) -> (u64, bool) { + debug_assert!(dst as usize % 8 == 0); + debug_assert_zacas!(); + let order = crate::utils::upgrade_success_ordering(success, failure); + + // SAFETY: the caller must uphold the safety contract. + let prev = unsafe { + let old = U64 { whole: old }; + let new = U64 { whole: new }; + let (prev_lo, prev_hi); + // LLVM doesn't support `.option arch, +zabha` directive as of LLVM 19 because it is experimental. + // So, we currently always using .insn directive. + // macro_rules! cmpxchg { + // ($fence:tt, $asm_order:tt) => { + // asm!( + // start_zacas!(), + // $fence, + // concat!("amocas.d", $asm_order, " a4, a2, 0({dst})"), + // end_zacas!(), + // dst = in(reg) ptr_reg!(dst), + // // must be allocated to even/odd register pair + // inout("a4") old.pair.lo => prev_lo, + // inout("a5") old.pair.hi => prev_hi, + // // must be allocated to even/odd register pair + // in("a2") new.pair.lo, + // in("a3") new.pair.hi, + // options(nostack, preserves_flags), + // ) + // }; + // } + // atomic_rmw_amocas_order!(cmpxchg, order, failure = failure); + macro_rules! cmpxchg { + ($fence:tt, $insn_order:tt) => { + asm!( + $fence, + // 10: 2{8,c,a,e}c5372f amocas.d{,.aq,.rl,.aqrl} a4, a2, (a0) + concat!(".insn 0x2", $insn_order, "c5372f"), + in("a0") ptr_reg!(dst), + // must be allocated to even/odd register pair + inout("a4") old.pair.lo => prev_lo, + inout("a5") old.pair.hi => prev_hi, + // must be allocated to even/odd register pair + in("a2") new.pair.lo, + in("a3") new.pair.hi, + options(nostack, preserves_flags), + ) + }; + } + atomic_rmw_amocas_order_insn!(cmpxchg, order, failure = failure); + U64 { pair: Pair { lo: prev_lo, hi: prev_hi } }.whole + }; + (prev, prev == old) +} + +// amocas is always strong. +use atomic_compare_exchange as atomic_compare_exchange_weak; + +// 64-bit atomic load by two 32-bit atomic loads. (see arm_linux.rs for more) +#[inline] +unsafe fn byte_wise_atomic_load(src: *const u64) -> u64 { + // SAFETY: the caller must uphold the safety contract. + unsafe { + let (out_lo, out_hi); + asm!( + "lw {out_lo}, ({src})", + "lw {out_hi}, 4({src})", + src = in(reg) ptr_reg!(src), + out_lo = out(reg) out_lo, + out_hi = out(reg) out_hi, + options(pure, nostack, preserves_flags, readonly), + ); + U64 { pair: Pair { lo: out_lo, hi: out_hi } }.whole + } +} + +#[inline(always)] +unsafe fn atomic_update_zacas(dst: *mut u64, order: Ordering, mut f: F) -> u64 +where + F: FnMut(u64) -> u64, +{ + // SAFETY: the caller must uphold the safety contract. + unsafe { + let mut prev = byte_wise_atomic_load(dst); + loop { + let next = f(prev); + match atomic_compare_exchange_weak(dst, prev, next, order, Ordering::Relaxed) { + Ok(x) => return x, + Err(x) => prev = x, + } + } + } +} + +macro_rules! select_atomic_rmw { + ( + unsafe fn $name:ident(dst: *mut u64 $(, $($arg:tt)*)?) $(-> $ret_ty:ty)? { + $($zacas_fn_body:tt)* + } + zacas = $zacas_fn:ident; + non_seqcst_fallback = $non_seqcst_fallback_fn:ident; + seqcst_fallback = $seqcst_fallback_fn:ident; + ) => { + #[inline] + unsafe fn $zacas_fn(dst: *mut u64 $(, $($arg)*)?, order: Ordering) $(-> $ret_ty)? { + // SAFETY: the caller must uphold the safety contract. + unsafe { atomic_update_zacas(dst, order, $($zacas_fn_body)*) } + } + // If zacas is available at compile-time, we can always use zacas_fn. + #[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ))] + use $zacas_fn as $name; + // Otherwise, we need to do run-time detection and can use zacas_fn only if zacas is available. + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + #[inline] + unsafe fn $name(dst: *mut u64 $(, $($arg)*)?, order: Ordering) $(-> $ret_ty)? { + fn_alias! { + // inline(never) is just a hint and also not strictly necessary + // because we use ifunc helper macro, but used for clarity. + #[inline(never)] + unsafe fn(dst: *mut u64 $(, $($arg)*)?) $(-> $ret_ty)?; + zacas_relaxed_fn = $zacas_fn(Ordering::Relaxed); + zacas_acquire_fn = $zacas_fn(Ordering::Acquire); + zacas_release_fn = $zacas_fn(Ordering::Release); + zacas_acqrel_fn = $zacas_fn(Ordering::AcqRel); + zacas_seqcst_fn = $zacas_fn(Ordering::SeqCst); + } + // SAFETY: the caller must uphold the safety contract. + // we only calls zacas_fn if zacas is available. + unsafe { + match order { + Ordering::Relaxed => { + ifunc!(unsafe fn(dst: *mut u64 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_relaxed_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::Acquire => { + ifunc!(unsafe fn(dst: *mut u64 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_acquire_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::Release => { + ifunc!(unsafe fn(dst: *mut u64 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_release_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::AcqRel => { + ifunc!(unsafe fn(dst: *mut u64 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_acqrel_fn + } else { + fallback::$non_seqcst_fallback_fn + } + }) + } + Ordering::SeqCst => { + ifunc!(unsafe fn(dst: *mut u64 $(, $($arg)*)?) $(-> $ret_ty)? { + if detect::detect().has_zacas() { + zacas_seqcst_fn + } else { + fallback::$seqcst_fallback_fn + } + }) + } + _ => unreachable!(), + } + } + } + }; +} + +select_atomic_rmw! { + unsafe fn atomic_swap(dst: *mut u64, val: u64) -> u64 { + |_| val + } + zacas = atomic_swap_zacas; + non_seqcst_fallback = atomic_swap_non_seqcst; + seqcst_fallback = atomic_swap_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_add(dst: *mut u64, val: u64) -> u64 { + |x| x.wrapping_add(val) + } + zacas = atomic_add_zacas; + non_seqcst_fallback = atomic_add_non_seqcst; + seqcst_fallback = atomic_add_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_sub(dst: *mut u64, val: u64) -> u64 { + |x| x.wrapping_sub(val) + } + zacas = atomic_sub_zacas; + non_seqcst_fallback = atomic_sub_non_seqcst; + seqcst_fallback = atomic_sub_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_and(dst: *mut u64, val: u64) -> u64 { + |x| x & val + } + zacas = atomic_and_zacas; + non_seqcst_fallback = atomic_and_non_seqcst; + seqcst_fallback = atomic_and_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_nand(dst: *mut u64, val: u64) -> u64 { + |x| !(x & val) + } + zacas = atomic_nand_zacas; + non_seqcst_fallback = atomic_nand_non_seqcst; + seqcst_fallback = atomic_nand_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_or(dst: *mut u64, val: u64) -> u64 { + |x| x | val + } + zacas = atomic_or_zacas; + non_seqcst_fallback = atomic_or_non_seqcst; + seqcst_fallback = atomic_or_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_xor(dst: *mut u64, val: u64) -> u64 { + |x| x ^ val + } + zacas = atomic_xor_zacas; + non_seqcst_fallback = atomic_xor_non_seqcst; + seqcst_fallback = atomic_xor_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_max(dst: *mut u64, val: u64) -> u64 { + |x| { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + { core::cmp::max(x as i64, val as i64) as u64 } + } + } + zacas = atomic_max_zacas; + non_seqcst_fallback = atomic_max_non_seqcst; + seqcst_fallback = atomic_max_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umax(dst: *mut u64, val: u64) -> u64 { + |x| core::cmp::max(x, val) + } + zacas = atomic_umax_zacas; + non_seqcst_fallback = atomic_umax_non_seqcst; + seqcst_fallback = atomic_umax_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_min(dst: *mut u64, val: u64) -> u64 { + |x| { + #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] + { core::cmp::min(x as i64, val as i64) as u64 } + } + } + zacas = atomic_min_zacas; + non_seqcst_fallback = atomic_min_non_seqcst; + seqcst_fallback = atomic_min_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_umin(dst: *mut u64, val: u64) -> u64 { + |x| core::cmp::min(x, val) + } + zacas = atomic_umin_zacas; + non_seqcst_fallback = atomic_umin_non_seqcst; + seqcst_fallback = atomic_umin_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_not(dst: *mut u64) -> u64 { + |x| !x + } + zacas = atomic_not_zacas; + non_seqcst_fallback = atomic_not_non_seqcst; + seqcst_fallback = atomic_not_seqcst; +} +select_atomic_rmw! { + unsafe fn atomic_neg(dst: *mut u64) -> u64 { + u64::wrapping_neg + } + zacas = atomic_neg_zacas; + non_seqcst_fallback = atomic_neg_non_seqcst; + seqcst_fallback = atomic_neg_seqcst; +} + +#[inline] +fn is_lock_free() -> bool { + #[cfg(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ))] + { + // zacas is available at compile-time. + true + } + #[cfg(not(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + )))] + { + detect::detect().has_zacas() + } +} +const IS_ALWAYS_LOCK_FREE: bool = cfg!(any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", +)); + +atomic64!(AtomicI64, i64, atomic_max, atomic_min); +atomic64!(AtomicU64, u64, atomic_umax, atomic_umin); + +#[allow(clippy::undocumented_unsafe_blocks, clippy::wildcard_imports)] +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_int!(i64); + test_atomic_int!(u64); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + stress_test!(u64); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/core_atomic.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/core_atomic.rs new file mode 100644 index 0000000..b87c95b --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/core_atomic.rs @@ -0,0 +1,439 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Wrap the standard library's atomic types in newtype. + +This is not a reexport, because we want to backport changes like +https://github.com/rust-lang/rust/pull/98383 to old compilers. +*/ + +use core::{cell::UnsafeCell, marker::PhantomData, sync::atomic::Ordering}; + +// core::panic::RefUnwindSafe is only available on Rust 1.56+, so on pre-1.56 +// Rust, we implement RefUnwindSafe when "std" feature is enabled. +// However, on pre-1.56 Rust, the standard library's atomic types implement +// RefUnwindSafe when "linked to std", and that's behavior that our other atomic +// implementations can't emulate, so use PhantomData to match +// conditions where our other atomic implementations implement RefUnwindSafe. +// +// If we do not do this, for example, downstream that is only tested on x86_64 +// may incorrectly assume that AtomicU64 always implements RefUnwindSafe even on +// older rustc, and may be broken on platforms where std AtomicU64 is not available. +struct NotRefUnwindSafe(UnsafeCell<()>); +// SAFETY: this is a marker type and we'll never access the value. +unsafe impl Sync for NotRefUnwindSafe {} + +#[repr(transparent)] +pub(crate) struct AtomicPtr { + inner: core::sync::atomic::AtomicPtr, + // Prevent RefUnwindSafe from being propagated from the std atomic type. See NotRefUnwindSafe for more. + _not_ref_unwind_safe: PhantomData, +} +impl AtomicPtr { + #[inline] + pub(crate) const fn new(v: *mut T) -> Self { + Self { inner: core::sync::atomic::AtomicPtr::new(v), _not_ref_unwind_safe: PhantomData } + } + #[inline] + pub(crate) fn is_lock_free() -> bool { + Self::IS_ALWAYS_LOCK_FREE + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = true; + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut *mut T { + self.inner.get_mut() + } + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn load(&self, order: Ordering) -> *mut T { + crate::utils::assert_load_ordering(order); // for track_caller (compiler can omit double check) + self.inner.load(order) + } + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn store(&self, ptr: *mut T, order: Ordering) { + crate::utils::assert_store_ordering(order); // for track_caller (compiler can omit double check) + self.inner.store(ptr, order); + } + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_raw_ptr_deref))]; + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut *mut T { + // SAFETY: Self is #[repr(C)] and internally UnsafeCell<*mut T>. + // See also https://github.com/rust-lang/rust/pull/66705 and + // https://github.com/rust-lang/rust/issues/66136#issuecomment-557867116. + unsafe { (*(self as *const Self as *const UnsafeCell<*mut T>)).get() } + } + } +} +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(not(portable_atomic_no_atomic_cas)))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(target_has_atomic = "ptr"))] +impl AtomicPtr { + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + crate::utils::assert_compare_exchange_ordering(success, failure); // for track_caller (compiler can omit double check) + #[cfg(portable_atomic_no_stronger_failure_ordering)] + let success = crate::utils::upgrade_success_ordering(success, failure); + self.inner.compare_exchange(current, new, success, failure) + } + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange_weak( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + crate::utils::assert_compare_exchange_ordering(success, failure); // for track_caller (compiler can omit double check) + #[cfg(portable_atomic_no_stronger_failure_ordering)] + let success = crate::utils::upgrade_success_ordering(success, failure); + self.inner.compare_exchange_weak(current, new, success, failure) + } +} +impl core::ops::Deref for AtomicPtr { + type Target = core::sync::atomic::AtomicPtr; + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +macro_rules! atomic_int { + ($atomic_type:ident, $int_type:ident) => { + #[repr(transparent)] + pub(crate) struct $atomic_type { + inner: core::sync::atomic::$atomic_type, + // Prevent RefUnwindSafe from being propagated from the std atomic type. See NotRefUnwindSafe for more. + _not_ref_unwind_safe: PhantomData, + } + #[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(portable_atomic_no_atomic_cas)) + )] + #[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(target_has_atomic = "ptr"))] + impl_default_no_fetch_ops!($atomic_type, $int_type); + #[cfg(not(all( + any(target_arch = "x86", target_arch = "x86_64"), + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + )))] + #[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(portable_atomic_no_atomic_cas)) + )] + #[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(target_has_atomic = "ptr"))] + impl_default_bit_opts!($atomic_type, $int_type); + impl $atomic_type { + #[inline] + pub(crate) const fn new(v: $int_type) -> Self { + Self { + inner: core::sync::atomic::$atomic_type::new(v), + _not_ref_unwind_safe: PhantomData, + } + } + #[inline] + pub(crate) fn is_lock_free() -> bool { + Self::IS_ALWAYS_LOCK_FREE + } + // ESP-IDF targets' 64-bit atomics are not lock-free. + // https://github.com/rust-lang/rust/pull/115577#issuecomment-1732259297 + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = cfg!(not(all( + any(target_arch = "riscv32", target_arch = "xtensa"), + target_os = "espidf", + ))) | (core::mem::size_of::<$int_type>() + < 8); + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $int_type { + self.inner.get_mut() + } + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn load(&self, order: Ordering) -> $int_type { + crate::utils::assert_load_ordering(order); // for track_caller (compiler can omit double check) + self.inner.load(order) + } + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn store(&self, val: $int_type, order: Ordering) { + crate::utils::assert_store_ordering(order); // for track_caller (compiler can omit double check) + self.inner.store(val, order); + } + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_raw_ptr_deref))]; + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut $int_type { + // SAFETY: Self is #[repr(C)] and internally UnsafeCell<$int_type>. + // See also https://github.com/rust-lang/rust/pull/66705 and + // https://github.com/rust-lang/rust/issues/66136#issuecomment-557867116. + unsafe { + (*(self as *const Self as *const UnsafeCell<$int_type>)).get() + } + } + } + } + #[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(portable_atomic_no_atomic_cas)) + )] + #[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(target_has_atomic = "ptr"))] + impl $atomic_type { + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); // for track_caller (compiler can omit double check) + #[cfg(portable_atomic_no_stronger_failure_ordering)] + let success = crate::utils::upgrade_success_ordering(success, failure); + self.inner.compare_exchange(current, new, success, failure) + } + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); // for track_caller (compiler can omit double check) + #[cfg(portable_atomic_no_stronger_failure_ordering)] + let success = crate::utils::upgrade_success_ordering(success, failure); + self.inner.compare_exchange_weak(current, new, success, failure) + } + #[allow(dead_code)] + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + fn fetch_update_(&self, order: Ordering, mut f: F) -> $int_type + where + F: FnMut($int_type) -> $int_type, + { + // This is a private function and all instances of `f` only operate on the value + // loaded, so there is no need to synchronize the first load/failed CAS. + let mut prev = self.load(Ordering::Relaxed); + loop { + let next = f(prev); + match self.compare_exchange_weak(prev, next, order, Ordering::Relaxed) { + Ok(x) => return x, + Err(next_prev) => prev = next_prev, + } + } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { + #[cfg(not(portable_atomic_no_atomic_min_max))] + { + #[cfg(any( + all( + any(target_arch = "aarch64", target_arch = "arm64ec"), + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + ), + all( + target_arch = "arm", + not(any( + target_feature = "v6", + portable_atomic_target_feature = "v6", + )), + ), + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "powerpc", + target_arch = "powerpc64", + ))] + { + // HACK: the following operations are currently broken (at least on qemu-user): + // - aarch64's `AtomicI{8,16}::fetch_{max,min}` (release mode + lse) + // - armv5te's `Atomic{I,U}{8,16}::fetch_{max,min}` + // - mips's `AtomicI8::fetch_{max,min}` (release mode) + // - mipsel's `AtomicI{8,16}::fetch_{max,min}` (debug mode, at least) + // - mips64's `AtomicI8::fetch_{max,min}` (release mode) + // - mips64el's `AtomicI{8,16}::fetch_{max,min}` (debug mode, at least) + // - powerpc's `AtomicI{8,16}::fetch_{max,min}` + // - powerpc64's `AtomicI{8,16}::fetch_{max,min}` (debug mode, at least) + // - powerpc64le's `AtomicU{8,16}::fetch_{max,min}` (release mode + fat LTO) + // See also: + // https://github.com/llvm/llvm-project/issues/61880 + // https://github.com/llvm/llvm-project/issues/61881 + // https://github.com/llvm/llvm-project/issues/61882 + // https://github.com/taiki-e/portable-atomic/issues/2 + // https://github.com/rust-lang/rust/issues/100650 + if core::mem::size_of::<$int_type>() <= 2 { + return self.fetch_update_(order, |x| core::cmp::max(x, val)); + } + } + self.inner.fetch_max(val, order) + } + #[cfg(portable_atomic_no_atomic_min_max)] + { + self.fetch_update_(order, |x| core::cmp::max(x, val)) + } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { + #[cfg(not(portable_atomic_no_atomic_min_max))] + { + #[cfg(any( + all( + any(target_arch = "aarch64", target_arch = "arm64ec"), + any(target_feature = "lse", portable_atomic_target_feature = "lse"), + ), + all( + target_arch = "arm", + not(any( + target_feature = "v6", + portable_atomic_target_feature = "v6", + )), + ), + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "powerpc", + target_arch = "powerpc64", + ))] + { + // HACK: the following operations are currently broken (at least on qemu-user): + // - aarch64's `AtomicI{8,16}::fetch_{max,min}` (release mode + lse) + // - armv5te's `Atomic{I,U}{8,16}::fetch_{max,min}` + // - mips's `AtomicI8::fetch_{max,min}` (release mode) + // - mipsel's `AtomicI{8,16}::fetch_{max,min}` (debug mode, at least) + // - mips64's `AtomicI8::fetch_{max,min}` (release mode) + // - mips64el's `AtomicI{8,16}::fetch_{max,min}` (debug mode, at least) + // - powerpc's `AtomicI{8,16}::fetch_{max,min}` + // - powerpc64's `AtomicI{8,16}::fetch_{max,min}` (debug mode, at least) + // - powerpc64le's `AtomicU{8,16}::fetch_{max,min}` (release mode + fat LTO) + // See also: + // https://github.com/llvm/llvm-project/issues/61880 + // https://github.com/llvm/llvm-project/issues/61881 + // https://github.com/llvm/llvm-project/issues/61882 + // https://github.com/taiki-e/portable-atomic/issues/2 + // https://github.com/rust-lang/rust/issues/100650 + if core::mem::size_of::<$int_type>() <= 2 { + return self.fetch_update_(order, |x| core::cmp::min(x, val)); + } + } + self.inner.fetch_min(val, order) + } + #[cfg(portable_atomic_no_atomic_min_max)] + { + self.fetch_update_(order, |x| core::cmp::min(x, val)) + } + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_not(&self, order: Ordering) -> $int_type { + self.fetch_xor(!0, order) + } + #[cfg(not(all( + any(target_arch = "x86", target_arch = "x86_64"), + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + )))] + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + // TODO: provide asm-based implementation on AArch64, Armv7, RISC-V, etc. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_neg(&self, order: Ordering) -> $int_type { + self.fetch_update_(order, $int_type::wrapping_neg) + } + #[cfg(not(all( + any(target_arch = "x86", target_arch = "x86_64"), + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + )))] + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } + } + impl core::ops::Deref for $atomic_type { + type Target = core::sync::atomic::$atomic_type; + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + fn deref(&self) -> &Self::Target { + &self.inner + } + } + }; +} + +atomic_int!(AtomicIsize, isize); +atomic_int!(AtomicUsize, usize); +#[cfg(not(portable_atomic_no_atomic_load_store))] +atomic_int!(AtomicI8, i8); +#[cfg(not(portable_atomic_no_atomic_load_store))] +atomic_int!(AtomicU8, u8); +#[cfg(not(portable_atomic_no_atomic_load_store))] +atomic_int!(AtomicI16, i16); +#[cfg(not(portable_atomic_no_atomic_load_store))] +atomic_int!(AtomicU16, u16); +#[cfg(not(portable_atomic_no_atomic_load_store))] +#[cfg(not(target_pointer_width = "16"))] +atomic_int!(AtomicI32, i32); +#[cfg(not(portable_atomic_no_atomic_load_store))] +#[cfg(not(target_pointer_width = "16"))] +atomic_int!(AtomicU32, u32); +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(not(portable_atomic_no_atomic_64)))] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any( + target_has_atomic = "64", + not(any(target_pointer_width = "16", target_pointer_width = "32")), + )) +)] +atomic_int!(AtomicI64, i64); +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(not(portable_atomic_no_atomic_64)))] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any( + target_has_atomic = "64", + not(any(target_pointer_width = "16", target_pointer_width = "32")), + )) +)] +atomic_int!(AtomicU64, u64); diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/README.md b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/README.md new file mode 100644 index 0000000..ea7750e --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/README.md @@ -0,0 +1,33 @@ +# Run-time CPU feature detection + +This module has run-time CPU feature detection implementations. + +Here is the table of targets that support run-time CPU feature detection and the instruction or API used: + +| target_arch | target_os/target_env | instruction/API | features | note | +| ----------- | -------------------- | --------------- | -------- | ---- | +| x86_64 | all (except for sgx) | cpuid | all | Enabled by default | +| aarch64 | linux | getauxval | all | Only enabled by default on `*-linux-gnu*`, and `*-linux-musl*"` (default is static linking)/`*-linux-ohos*` (default is dynamic linking) with dynamic linking enabled. | +| aarch64 | android | getauxval | all | Enabled by default | +| aarch64 | freebsd | elf_aux_info | lse, lse2 | Enabled by default | +| aarch64 | netbsd | sysctlbyname | all | Enabled by default | +| aarch64 | openbsd | sysctl | all | Enabled by default | +| aarch64 | macos/ios/tvos/watchos/visionos | sysctlbyname | all | Currently only used in tests (see [aarch64_apple.rs](aarch64_apple.rs)). | +| aarch64 | illumos | getisax | lse, lse2 | Disabled by default | +| aarch64/arm64ec | windows | IsProcessorFeaturePresent | lse | Enabled by default | +| aarch64 | fuchsia | zx_system_get_features | lse | Enabled by default | +| riscv32 | linux | riscv_hwprobe | all | Disabled by default | +| riscv64 | linux | riscv_hwprobe | all | Disabled by default | +| powerpc64 | linux | getauxval | all | Disabled by default | +| powerpc64 | freebsd | elf_aux_info | all | Disabled by default | +| powerpc64 | openbsd | elf_aux_info | all | Disabled by default | + +Run-time detection is enabled by default on most targets and can be disabled with `--cfg portable_atomic_no_outline_atomics`. + +On some targets, run-time detection is disabled by default mainly for compatibility with older versions of operating systems or incomplete build environments, and can be enabled by `--cfg portable_atomic_outline_atomics`. (When both cfg are enabled, `*_no_*` cfg is preferred.) + +For targets not included in the above table, run-time detection is always disabled and works the same as when `--cfg portable_atomic_no_outline_atomics` is set. + +See [auxv.rs](auxv.rs) module-level comments for more details on Linux/Android/FreeBSD/OpenBSD. + +See also [docs on `portable_atomic_no_outline_atomics`](https://github.com/taiki-e/portable-atomic/blob/HEAD/README.md#optional-cfg-no-outline-atomics) in the top-level readme. diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_aa64reg.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_aa64reg.rs new file mode 100644 index 0000000..c5bc491 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_aa64reg.rs @@ -0,0 +1,586 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on AArch64 Linux/Android/FreeBSD/NetBSD/OpenBSD by parsing system registers. + +As of nightly-2024-09-07, is_aarch64_feature_detected doesn't support run-time detection on NetBSD. +https://github.com/rust-lang/stdarch/blob/d9466edb4c53cece8686ee6e17b028436ddf4151/crates/std_detect/src/detect/mod.rs +Run-time detection on OpenBSD by is_aarch64_feature_detected is supported on Rust 1.70+. +https://github.com/rust-lang/stdarch/pull/1374 + +Refs: +- https://developer.arm.com/documentation/ddi0601/2024-06/AArch64-Registers +- https://github.com/torvalds/linux/blob/v6.11/Documentation/arch/arm64/cpu-feature-registers.rst +- https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/std_detect/src/detect/os/aarch64.rs + +Supported platforms: +- Linux 4.11+ (emulate mrs instruction) + https://github.com/torvalds/linux/commit/77c97b4ee21290f5f083173d957843b615abbff2 +- FreeBSD 12.0+ (emulate mrs instruction) + https://github.com/freebsd/freebsd-src/commit/398810619cb32abf349f8de23f29510b2ee0839b +- NetBSD 9.0+ (through sysctl/sysctlbyname) + https://github.com/NetBSD/src/commit/0e9d25528729f7fea53e78275d1bc5039dfe8ffb +- OpenBSD 7.1+ (through sysctl) + https://github.com/openbsd/src/commit/d335af936b9d7dd9cf655cae1ce19560c45de6c8 + +For now, this module is only used on NetBSD/OpenBSD. + +On Linux/Android/FreeBSD, we use auxv.rs and this module is test-only because: +- On Linux/Android, this approach requires a higher kernel version than Rust supports, + and also does not work with qemu-user (as of 7.2) and Valgrind (as of 3.19). + (Looking into HWCAP_CPUID in auxvec, it appears that Valgrind is setting it + to false correctly, but qemu-user is setting it to true.) +- On FreeBSD, this approach does not work on FreeBSD 12 on QEMU (confirmed on + FreeBSD 12.{2,3,4}), and we got SIGILL (worked on FreeBSD 13 and 14). +*/ + +include!("common.rs"); + +#[cfg_attr(test, derive(Debug, PartialEq))] +struct AA64Reg { + aa64isar0: u64, + aa64isar1: u64, + aa64mmfr2: u64, +} + +#[cold] +fn _detect(info: &mut CpuInfo) { + let AA64Reg { aa64isar0, aa64isar1, aa64mmfr2 } = imp::aa64reg(); + + // ID_AA64ISAR0_EL1, AArch64 Instruction Set Attribute Register 0 + // https://developer.arm.com/documentation/ddi0601/2024-06/AArch64-Registers/ID-AA64ISAR0-EL1--AArch64-Instruction-Set-Attribute-Register-0 + let atomic = extract(aa64isar0, 23, 20); + if atomic >= 0b0010 { + info.set(CpuInfo::HAS_LSE); + if atomic >= 0b0011 { + info.set(CpuInfo::HAS_LSE128); + } + } + // ID_AA64ISAR1_EL1, AArch64 Instruction Set Attribute Register 1 + // https://developer.arm.com/documentation/ddi0601/2024-06/AArch64-Registers/ID-AA64ISAR1-EL1--AArch64-Instruction-Set-Attribute-Register-1 + if extract(aa64isar1, 23, 20) >= 0b0011 { + info.set(CpuInfo::HAS_RCPC3); + } + // ID_AA64MMFR2_EL1, AArch64 Memory Model Feature Register 2 + // https://developer.arm.com/documentation/ddi0601/2024-06/AArch64-Registers/ID-AA64MMFR2-EL1--AArch64-Memory-Model-Feature-Register-2 + if extract(aa64mmfr2, 35, 32) >= 0b0001 { + info.set(CpuInfo::HAS_LSE2); + } +} + +fn extract(x: u64, high: usize, low: usize) -> u64 { + (x >> low) & ((1 << (high - low + 1)) - 1) +} + +#[cfg(not(any(target_os = "netbsd", target_os = "openbsd")))] +mod imp { + // This module is test-only. See parent module docs for details. + + #[cfg(not(portable_atomic_no_asm))] + use core::arch::asm; + + use super::AA64Reg; + + pub(super) fn aa64reg() -> AA64Reg { + // SAFETY: This is safe on FreeBSD 12.0+. FreeBSD 11 was EoL on 2021-09-30. + // Note that stdarch has been doing the same thing since before FreeBSD 11 was EoL. + // https://github.com/rust-lang/stdarch/pull/611 + unsafe { + let aa64isar0: u64; + asm!( + "mrs {0}, ID_AA64ISAR0_EL1", + out(reg) aa64isar0, + options(pure, nomem, nostack, preserves_flags), + ); + let aa64isar1: u64; + asm!( + "mrs {0}, ID_AA64ISAR1_EL1", + out(reg) aa64isar1, + options(pure, nomem, nostack, preserves_flags), + ); + let aa64mmfr2: u64; + asm!( + "mrs {0}, ID_AA64MMFR2_EL1", + out(reg) aa64mmfr2, + options(pure, nomem, nostack, preserves_flags), + ); + AA64Reg { aa64isar0, aa64isar1, aa64mmfr2 } + } + } +} +#[cfg(target_os = "netbsd")] +mod imp { + // NetBSD doesn't trap the mrs instruction, but exposes the system registers through sysctl. + // https://github.com/NetBSD/src/commit/0e9d25528729f7fea53e78275d1bc5039dfe8ffb + // https://github.com/golang/sys/commit/ef9fd89ba245e184bdd308f7f2b4f3c551fa5b0f + + use core::ptr; + + use super::AA64Reg; + + // core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 + #[allow(non_camel_case_types)] + pub(super) mod ffi { + pub(crate) use super::super::c_types::{c_char, c_int, c_size_t, c_void}; + + // Defined in aarch64/armreg.h. + // https://github.com/NetBSD/src/blob/432a1357026b10c184d8a0ddb683008a23cc7cd9/sys/arch/aarch64/include/armreg.h#L1863 + #[derive(Clone, Copy)] + #[repr(C)] + pub(crate) struct aarch64_sysctl_cpu_id { + // NetBSD 9.0+ + // https://github.com/NetBSD/src/commit/0e9d25528729f7fea53e78275d1bc5039dfe8ffb + pub(crate) midr: u64, + pub(crate) revidr: u64, + pub(crate) mpidr: u64, + pub(crate) aa64dfr0: u64, + pub(crate) aa64dfr1: u64, + pub(crate) aa64isar0: u64, + pub(crate) aa64isar1: u64, + pub(crate) aa64mmfr0: u64, + pub(crate) aa64mmfr1: u64, + pub(crate) aa64mmfr2: u64, + pub(crate) aa64pfr0: u64, + pub(crate) aa64pfr1: u64, + pub(crate) aa64zfr0: u64, + pub(crate) mvfr0: u32, + pub(crate) mvfr1: u32, + pub(crate) mvfr2: u32, + // NetBSD 10.0+ + // https://github.com/NetBSD/src/commit/0c7bdc13f0e332cccec56e307f023b4888638973 + pub(crate) pad: u32, + pub(crate) clidr: u64, + pub(crate) ctr: u64, + } + + extern "C" { + // Defined in sys/sysctl.h. + // https://man.netbsd.org/sysctl.3 + // https://github.com/NetBSD/src/blob/432a1357026b10c184d8a0ddb683008a23cc7cd9/sys/sys/sysctl.h + pub(crate) fn sysctlbyname( + name: *const c_char, + old_p: *mut c_void, + old_len_p: *mut c_size_t, + new_p: *const c_void, + new_len: c_size_t, + ) -> c_int; + } + } + + pub(super) unsafe fn sysctl_cpu_id(name: &[u8]) -> Option { + const OUT_LEN: ffi::c_size_t = + core::mem::size_of::() as ffi::c_size_t; + + debug_assert_eq!(name.last(), Some(&0), "{:?}", name); + debug_assert_eq!(name.iter().filter(|&&v| v == 0).count(), 1, "{:?}", name); + + // SAFETY: all fields of aarch64_sysctl_cpu_id are zero-able and we use + // the result when machdep.cpuN.cpu_id sysctl was successful. + let mut buf: ffi::aarch64_sysctl_cpu_id = unsafe { core::mem::zeroed() }; + let mut out_len = OUT_LEN; + // SAFETY: + // - the caller must guarantee that `name` is ` machdep.cpuN.cpu_id` in a C string. + // - `out_len` does not exceed the size of the value at `buf`. + // - `sysctlbyname` is thread-safe. + let res = unsafe { + ffi::sysctlbyname( + name.as_ptr().cast::(), + (&mut buf as *mut ffi::aarch64_sysctl_cpu_id).cast::(), + &mut out_len, + ptr::null_mut(), + 0, + ) + }; + if res != 0 { + return None; + } + Some(AA64Reg { + aa64isar0: buf.aa64isar0, + aa64isar1: buf.aa64isar1, + aa64mmfr2: buf.aa64mmfr2, + }) + } + + pub(super) fn aa64reg() -> AA64Reg { + // Get system registers for cpu0. + // If failed, returns default because machdep.cpuN.cpu_id sysctl is not available. + // machdep.cpuN.cpu_id sysctl was added in NetBSD 9.0 so it is not available on older versions. + // SAFETY: we passed a valid name in a C string. + // It is ok to check only cpu0, even if there are more CPUs. + // https://github.com/NetBSD/src/commit/bd9707e06ea7d21b5c24df6dfc14cb37c2819416 + // https://github.com/golang/sys/commit/ef9fd89ba245e184bdd308f7f2b4f3c551fa5b0f + match unsafe { sysctl_cpu_id(b"machdep.cpu0.cpu_id\0") } { + Some(cpu_id) => cpu_id, + None => AA64Reg { aa64isar0: 0, aa64isar1: 0, aa64mmfr2: 0 }, + } + } +} +#[cfg(target_os = "openbsd")] +mod imp { + // OpenBSD doesn't trap the mrs instruction, but exposes the system registers through sysctl. + // https://github.com/openbsd/src/commit/d335af936b9d7dd9cf655cae1ce19560c45de6c8 + // https://github.com/golang/go/commit/cd54ef1f61945459486e9eea2f016d99ef1da925 + + use core::ptr; + + use super::AA64Reg; + + // core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 + #[allow(non_camel_case_types)] + pub(super) mod ffi { + pub(crate) use super::super::c_types::{c_int, c_size_t, c_uint, c_void}; + + // Defined in sys/sysctl.h. + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/sys/sysctl.h#L82 + pub(crate) const CTL_MACHDEP: c_int = 7; + + // Defined in machine/cpu.h. + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/arch/arm64/include/cpu.h#L25-L40 + // OpenBSD 7.1+ + // https://github.com/openbsd/src/commit/d335af936b9d7dd9cf655cae1ce19560c45de6c8 + pub(crate) const CPU_ID_AA64ISAR0: c_int = 2; + pub(crate) const CPU_ID_AA64ISAR1: c_int = 3; + // OpenBSD 7.3+ + // https://github.com/openbsd/src/commit/c7654cd65262d532212f65123ee3905ba200365c + // However, on OpenBSD 7.3-7.5, querying CPU_ID_AA64MMFR2 always returns 0. + // https://github.com/openbsd/src/commit/e8331b74e5c20302d4bd948c9db722af688ccfc1 + pub(crate) const CPU_ID_AA64MMFR2: c_int = 7; + + extern "C" { + // Defined in sys/sysctl.h. + // https://man.openbsd.org/sysctl.2 + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/sys/sysctl.h + pub(crate) fn sysctl( + name: *const c_int, + name_len: c_uint, + old_p: *mut c_void, + old_len_p: *mut c_size_t, + new_p: *mut c_void, + new_len: c_size_t, + ) -> c_int; + } + } + + // sysctl returns an unsupported error if operation is not supported, + // so we can safely use this function on older versions of OpenBSD. + pub(super) fn aa64reg() -> AA64Reg { + let aa64isar0 = sysctl64(&[ffi::CTL_MACHDEP, ffi::CPU_ID_AA64ISAR0]).unwrap_or(0); + let aa64isar1 = sysctl64(&[ffi::CTL_MACHDEP, ffi::CPU_ID_AA64ISAR1]).unwrap_or(0); + let aa64mmfr2 = sysctl64(&[ffi::CTL_MACHDEP, ffi::CPU_ID_AA64MMFR2]).unwrap_or(0); + AA64Reg { aa64isar0, aa64isar1, aa64mmfr2 } + } + + fn sysctl64(mib: &[ffi::c_int]) -> Option { + const OUT_LEN: ffi::c_size_t = core::mem::size_of::() as ffi::c_size_t; + let mut out = 0_u64; + let mut out_len = OUT_LEN; + #[allow(clippy::cast_possible_truncation)] + let mib_len = mib.len() as ffi::c_uint; + // SAFETY: + // - `mib.len()` does not exceed the size of `mib`. + // - `out_len` does not exceed the size of `out`. + // - `sysctl` is thread-safe. + let res = unsafe { + ffi::sysctl( + mib.as_ptr(), + mib_len, + (&mut out as *mut u64).cast::(), + &mut out_len, + ptr::null_mut(), + 0, + ) + }; + if res == -1 { + return None; + } + debug_assert_eq!(out_len, OUT_LEN); + Some(out) + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use std::{ + process::Command, + string::{String, ToString}, + }; + + use super::*; + + #[test] + fn test_aa64reg() { + let AA64Reg { aa64isar0, aa64isar1, aa64mmfr2 } = imp::aa64reg(); + std::eprintln!("aa64isar0={}", aa64isar0); + std::eprintln!("aa64isar1={}", aa64isar1); + std::eprintln!("aa64mmfr2={}", aa64mmfr2); + if cfg!(target_os = "openbsd") { + let output = Command::new("sysctl").arg("machdep").output().unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + // OpenBSD 7.1+ + assert_eq!( + stdout.lines().find_map(|s| s.strip_prefix("machdep.id_aa64isar0=")).unwrap_or("0"), + aa64isar0.to_string(), + ); + assert_eq!( + stdout.lines().find_map(|s| s.strip_prefix("machdep.id_aa64isar1=")).unwrap_or("0"), + aa64isar1.to_string(), + ); + // OpenBSD 7.3+ + assert_eq!( + stdout.lines().find_map(|s| s.strip_prefix("machdep.id_aa64mmfr2=")).unwrap_or("0"), + aa64mmfr2.to_string(), + ); + } + if detect().test(CpuInfo::HAS_LSE) { + let atomic = extract(aa64isar0, 23, 20); + if detect().test(CpuInfo::HAS_LSE128) { + assert_eq!(atomic, 3); + } else { + assert_eq!(atomic, 2); + } + } + if detect().test(CpuInfo::HAS_LSE2) { + assert_eq!(extract(aa64mmfr2, 35, 32), 1); + } + if detect().test(CpuInfo::HAS_RCPC3) { + assert_eq!(extract(aa64isar1, 23, 20), 3); + } + } + + #[allow(clippy::cast_possible_wrap)] + #[cfg(target_os = "netbsd")] + #[test] + fn test_netbsd() { + use c_types::*; + use imp::ffi; + #[cfg(not(portable_atomic_no_asm))] + use std::arch::asm; + use std::{mem, ptr, vec, vec::Vec}; + use test_helper::sys; + + // Call syscall using asm instead of libc. + // Note that NetBSD does not guarantee the stability of raw syscall as + // much as Linux does (It may actually be stable enough, though: https://lists.llvm.org/pipermail/llvm-dev/2019-June/133393.html). + // + // This is currently used only for testing. + unsafe fn sysctl_cpu_id_asm_syscall(name: &[&[u8]]) -> Result { + // https://github.com/golang/go/blob/4badad8d477ffd7a6b762c35bc69aed82faface7/src/syscall/asm_netbsd_arm64.s + #[inline] + unsafe fn sysctl( + name: *const c_int, + name_len: c_uint, + old_p: *mut c_void, + old_len_p: *mut c_size_t, + new_p: *const c_void, + new_len: c_size_t, + ) -> Result { + // SAFETY: the caller must uphold the safety contract. + unsafe { + let mut n = sys::SYS___sysctl as u64; + let r: i64; + asm!( + "svc 0", + "b.cc 2f", + "mov x17, x0", + "mov x0, #-1", + "2:", + inout("x17") n, + inout("x0") ptr_reg!(name) => r, + inout("x1") name_len as u64 => _, + in("x2") ptr_reg!(old_p), + in("x3") ptr_reg!(old_len_p), + in("x4") ptr_reg!(new_p), + in("x5") new_len as u64, + options(nostack), + ); + #[allow(clippy::cast_possible_truncation)] + if r as c_int == -1 { + Err(n as c_int) + } else { + Ok(r as c_int) + } + } + } + + // https://github.com/golang/sys/blob/4badad8d477ffd7a6b762c35bc69aed82faface7/cpu/cpu_netbsd_arm64.go. + fn sysctl_nodes(mib: &mut Vec) -> Result, i32> { + mib.push(sys::CTL_QUERY); + let mut q_node = sys::sysctlnode { + sysctl_flags: sys::SYSCTL_VERS_1, + ..unsafe { mem::zeroed() } + }; + let qp = (&mut q_node as *mut sys::sysctlnode).cast::(); + let sz = mem::size_of::(); + let mut olen = 0; + #[allow(clippy::cast_possible_truncation)] + let mib_len = mib.len() as c_uint; + unsafe { + sysctl(mib.as_ptr(), mib_len, ptr::null_mut(), &mut olen, qp, sz)?; + } + + let mut nodes = Vec::::with_capacity(olen / sz); + let np = nodes.as_mut_ptr().cast::(); + unsafe { + sysctl(mib.as_ptr(), mib_len, np, &mut olen, qp, sz)?; + nodes.set_len(olen / sz); + } + + mib.pop(); // pop CTL_QUERY + Ok(nodes) + } + fn name_to_mib(parts: &[&[u8]]) -> Result, i32> { + let mut mib = vec![]; + for (part_no, &part) in parts.iter().enumerate() { + let nodes = sysctl_nodes(&mut mib)?; + for node in nodes { + let mut n = vec![]; + for b in node.sysctl_name { + if b != 0 { + n.push(b); + } + } + if n == part { + mib.push(node.sysctl_num); + break; + } + } + if mib.len() != part_no + 1 { + return Err(0); + } + } + + Ok(mib) + } + + const OUT_LEN: ffi::c_size_t = + core::mem::size_of::() as ffi::c_size_t; + + let mib = name_to_mib(name)?; + + let mut buf: ffi::aarch64_sysctl_cpu_id = unsafe { core::mem::zeroed() }; + let mut out_len = OUT_LEN; + #[allow(clippy::cast_possible_truncation)] + let mib_len = mib.len() as c_uint; + unsafe { + sysctl( + mib.as_ptr(), + mib_len, + (&mut buf as *mut ffi::aarch64_sysctl_cpu_id).cast::(), + &mut out_len, + ptr::null_mut(), + 0, + )?; + } + Ok(AA64Reg { + aa64isar0: buf.aa64isar0, + aa64isar1: buf.aa64isar1, + aa64mmfr2: buf.aa64mmfr2, + }) + } + + unsafe { + assert_eq!( + imp::sysctl_cpu_id(b"machdep.cpu0.cpu_id\0").unwrap(), + sysctl_cpu_id_asm_syscall(&[b"machdep", b"cpu0", b"cpu_id"]).unwrap() + ); + } + } + + // Static assertions for FFI bindings. + // This checks that FFI bindings defined in this crate, FFI bindings defined + // in libc, and FFI bindings generated for the platform's latest header file + // using bindgen have compatible signatures (or the same values if constants). + // Since this is static assertion, we can detect problems with + // `cargo check --tests --target ` run in CI (via TESTS=1 build.sh) + // without actually running tests on these platforms. + // See also tools/codegen/src/ffi.rs. + // TODO(codegen): auto-generate this test + #[cfg(target_os = "netbsd")] + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::no_effect_underscore_binding, + clippy::used_underscore_binding + )] + const _: fn() = || { + use imp::ffi; + use std::mem; + use test_helper::{libc, sys}; + let mut _sysctlbyname: unsafe extern "C" fn( + *const ffi::c_char, + *mut ffi::c_void, + *mut ffi::c_size_t, + *const ffi::c_void, + ffi::c_size_t, + ) -> ffi::c_int = ffi::sysctlbyname; + _sysctlbyname = libc::sysctlbyname; + _sysctlbyname = sys::sysctlbyname; + // libc doesn't have this + // static_assert!( + // mem::size_of::() + // == mem::size_of::() + // ); + static_assert!( + mem::size_of::() + == mem::size_of::() + ); + let ffi: ffi::aarch64_sysctl_cpu_id = unsafe { mem::zeroed() }; + let _ = sys::aarch64_sysctl_cpu_id { + ac_midr: ffi.midr, + ac_revidr: ffi.revidr, + ac_mpidr: ffi.mpidr, + ac_aa64dfr0: ffi.aa64dfr0, + ac_aa64dfr1: ffi.aa64dfr1, + ac_aa64isar0: ffi.aa64isar0, + ac_aa64isar1: ffi.aa64isar1, + ac_aa64mmfr0: ffi.aa64mmfr0, + ac_aa64mmfr1: ffi.aa64mmfr1, + ac_aa64mmfr2: ffi.aa64mmfr2, + ac_aa64pfr0: ffi.aa64pfr0, + ac_aa64pfr1: ffi.aa64pfr1, + ac_aa64zfr0: ffi.aa64zfr0, + ac_mvfr0: ffi.mvfr0, + ac_mvfr1: ffi.mvfr1, + ac_mvfr2: ffi.mvfr2, + ac_pad: ffi.pad, + ac_clidr: ffi.clidr, + ac_ctr: ffi.ctr, + }; + }; + #[cfg(target_os = "openbsd")] + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::no_effect_underscore_binding + )] + const _: fn() = || { + use imp::ffi; + use test_helper::{libc, sys}; + let mut _sysctl: unsafe extern "C" fn( + *const ffi::c_int, + ffi::c_uint, + *mut ffi::c_void, + *mut ffi::c_size_t, + *mut ffi::c_void, + ffi::c_size_t, + ) -> ffi::c_int = ffi::sysctl; + _sysctl = libc::sysctl; + _sysctl = sys::sysctl; + static_assert!(ffi::CTL_MACHDEP == libc::CTL_MACHDEP); + static_assert!(ffi::CTL_MACHDEP == sys::CTL_MACHDEP as ffi::c_int); + // static_assert!(ffi::CPU_ID_AA64ISAR0 == libc::CPU_ID_AA64ISAR0); // libc doesn't have this + static_assert!(ffi::CPU_ID_AA64ISAR0 == sys::CPU_ID_AA64ISAR0 as ffi::c_int); + // static_assert!(ffi::CPU_ID_AA64ISAR1 == libc::CPU_ID_AA64ISAR1); // libc doesn't have this + static_assert!(ffi::CPU_ID_AA64ISAR1 == sys::CPU_ID_AA64ISAR1 as ffi::c_int); + // static_assert!(ffi::CPU_ID_AA64MMFR2 == libc::CPU_ID_AA64MMFR2); // libc doesn't have this + static_assert!(ffi::CPU_ID_AA64MMFR2 == sys::CPU_ID_AA64MMFR2 as ffi::c_int); + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_apple.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_apple.rs new file mode 100644 index 0000000..dbece1c --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_apple.rs @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on AArch64 Apple targets by using sysctlbyname. + +On macOS, this module is currently only enabled on tests because AArch64 macOS +always supports FEAT_LSE and FEAT_LSE2 (see build script for more). + +If macOS supporting FEAT_LSE128/FEAT_LRCPC3 becomes popular in the future, this module will +be used to support outline-atomics for FEAT_LSE128/FEAT_LRCPC3. +M4 is Armv9.2 and it doesn't support FEAT_LSE128/FEAT_LRCPC3. + +Refs: https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_instruction_set_characteristics + +TODO: non-macOS targets doesn't always supports FEAT_LSE2, but sysctl on them on the App Store is...? +- https://developer.apple.com/forums/thread/9440 +- https://nabla-c0d3.github.io/blog/2015/06/16/ios9-security-privacy +- https://github.com/rust-lang/stdarch/pull/1636 +*/ + +include!("common.rs"); + +use core::ptr; + +// core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 +#[allow(non_camel_case_types)] +mod ffi { + pub(crate) use super::c_types::{c_char, c_int, c_size_t, c_void}; + + extern "C" { + // https://developer.apple.com/documentation/kernel/1387446-sysctlbyname + // https://github.com/apple-oss-distributions/xnu/blob/5c2921b07a2480ab43ec66f5b9e41cb872bc554f/bsd/sys/sysctl.h + pub(crate) fn sysctlbyname( + name: *const c_char, + old_p: *mut c_void, + old_len_p: *mut c_size_t, + new_p: *mut c_void, + new_len: c_size_t, + ) -> c_int; + } +} + +unsafe fn sysctlbyname32(name: &[u8]) -> Option { + const OUT_LEN: ffi::c_size_t = core::mem::size_of::() as ffi::c_size_t; + + debug_assert_eq!(name.last(), Some(&0), "{:?}", name); + debug_assert_eq!(name.iter().filter(|&&v| v == 0).count(), 1, "{:?}", name); + + let mut out = 0_u32; + let mut out_len = OUT_LEN; + // SAFETY: + // - the caller must guarantee that `name` a valid C string. + // - `out_len` does not exceed the size of `out`. + // - `sysctlbyname` is thread-safe. + let res = unsafe { + ffi::sysctlbyname( + name.as_ptr().cast::(), + (&mut out as *mut u32).cast::(), + &mut out_len, + ptr::null_mut(), + 0, + ) + }; + if res != 0 { + return None; + } + debug_assert_eq!(out_len, OUT_LEN); + Some(out) +} + +#[cold] +fn _detect(info: &mut CpuInfo) { + // hw.optional.armv8_1_atomics is available on macOS 11+ (note: AArch64 support was added in macOS 11), + // hw.optional.arm.FEAT_* are only available on macOS 12+. + // Query both names in case future versions of macOS remove the old name. + // https://github.com/golang/go/commit/c15593197453b8bf90fc3a9080ba2afeaf7934ea + // https://github.com/google/boringssl/commit/91e0b11eba517d83b910b20fe3740eeb39ecb37e + // SAFETY: we passed a valid C string. + if unsafe { + sysctlbyname32(b"hw.optional.arm.FEAT_LSE\0").unwrap_or(0) != 0 + || sysctlbyname32(b"hw.optional.armv8_1_atomics\0").unwrap_or(0) != 0 + } { + info.set(CpuInfo::HAS_LSE); + } + // SAFETY: we passed a valid C string. + if unsafe { sysctlbyname32(b"hw.optional.arm.FEAT_LSE2\0").unwrap_or(0) != 0 } { + info.set(CpuInfo::HAS_LSE2); + } + // SAFETY: we passed a valid C string. + if unsafe { sysctlbyname32(b"hw.optional.arm.FEAT_LSE128\0").unwrap_or(0) != 0 } { + info.set(CpuInfo::HAS_LSE128); + } + // SAFETY: we passed a valid C string. + if unsafe { sysctlbyname32(b"hw.optional.arm.FEAT_LRCPC3\0").unwrap_or(0) != 0 } { + info.set(CpuInfo::HAS_RCPC3); + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_macos() { + unsafe { + assert_eq!(sysctlbyname32(b"hw.optional.armv8_1_atomics\0"), Some(1)); + assert_eq!(sysctlbyname32(b"hw.optional.arm.FEAT_LSE\0"), Some(1)); + assert_eq!(sysctlbyname32(b"hw.optional.arm.FEAT_LSE2\0"), Some(1)); + assert_eq!(sysctlbyname32(b"hw.optional.arm.FEAT_LSE128\0"), None); + assert_eq!(std::io::Error::last_os_error().kind(), std::io::ErrorKind::NotFound); + assert_eq!(sysctlbyname32(b"hw.optional.arm.FEAT_LRCPC\0"), Some(1)); + assert_eq!(sysctlbyname32(b"hw.optional.arm.FEAT_LRCPC2\0"), Some(1)); + assert_eq!(sysctlbyname32(b"hw.optional.arm.FEAT_LRCPC3\0"), None); + assert_eq!(std::io::Error::last_os_error().kind(), std::io::ErrorKind::NotFound); + } + } + + // Static assertions for FFI bindings. + // This checks that FFI bindings defined in this crate, FFI bindings defined + // in libc, and FFI bindings generated for the platform's latest header file + // using bindgen have compatible signatures (or the same values if constants). + // Since this is static assertion, we can detect problems with + // `cargo check --tests --target ` run in CI (via TESTS=1 build.sh) + // without actually running tests on these platforms. + // See also tools/codegen/src/ffi.rs. + // TODO(codegen): auto-generate this test + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::no_effect_underscore_binding + )] + const _: fn() = || { + use test_helper::{libc, sys}; + let mut _sysctlbyname: unsafe extern "C" fn( + *const ffi::c_char, + *mut ffi::c_void, + *mut ffi::c_size_t, + *mut ffi::c_void, + ffi::c_size_t, + ) -> ffi::c_int = ffi::sysctlbyname; + _sysctlbyname = libc::sysctlbyname; + _sysctlbyname = sys::sysctlbyname; + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_fuchsia.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_fuchsia.rs new file mode 100644 index 0000000..a5f1437 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_fuchsia.rs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on AArch64 Fuchsia by using zx_system_get_features. + +As of nightly-2024-09-07, is_aarch64_feature_detected doesn't support run-time detection on Fuchsia. +https://github.com/rust-lang/stdarch/blob/d9466edb4c53cece8686ee6e17b028436ddf4151/crates/std_detect/src/detect/mod.rs + +Refs: +- https://fuchsia.dev/reference/syscalls/system_get_features +- https://github.com/llvm/llvm-project/commit/4e731abc55681751b5d736b613f7720e50eb1ad4 +*/ + +include!("common.rs"); + +#[allow(non_camel_case_types)] +mod ffi { + // https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/zircon/system/public/zircon/types.h + pub(crate) type zx_status_t = i32; + + // https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/zircon/system/public/zircon/errors.h + pub(crate) const ZX_OK: zx_status_t = 0; + + // https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/zircon/system/public/zircon/features.h + pub(crate) const ZX_FEATURE_KIND_CPU: u32 = 0; + pub(crate) const ZX_ARM64_FEATURE_ISA_ATOMICS: u32 = 1 << 8; + + #[link(name = "zircon")] + extern "C" { + // https://fuchsia.dev/reference/syscalls/system_get_features + pub(crate) fn zx_system_get_features(kind: u32, features: *mut u32) -> zx_status_t; + } +} + +fn zx_system_get_features(kind: u32) -> u32 { + let mut out = 0_u32; + // SAFETY: the pointer is valid because we got it from a reference. + let res = unsafe { ffi::zx_system_get_features(kind, &mut out) }; + if res != ffi::ZX_OK { + return 0; + } + out +} + +#[cold] +fn _detect(info: &mut CpuInfo) { + let features = zx_system_get_features(ffi::ZX_FEATURE_KIND_CPU); + if features & ffi::ZX_ARM64_FEATURE_ISA_ATOMICS != 0 { + info.set(CpuInfo::HAS_LSE); + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_fuchsia() { + let features = zx_system_get_features(ffi::ZX_FEATURE_KIND_CPU); + assert_ne!(features, 0); + std::eprintln!("features: {:b}", features); + } + + // Static assertions for FFI bindings. + // This checks that FFI bindings defined in this crate and FFI bindings + // generated for the platform's latest header file using bindgen have + // compatible signatures (or the same values if constants). + // Since this is static assertion, we can detect problems with + // `cargo check --tests --target ` run in CI (via TESTS=1 build.sh) + // without actually running tests on these platforms. + // See also tools/codegen/src/ffi.rs. + // TODO(codegen): auto-generate this test + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::cast_possible_truncation, + clippy::no_effect_underscore_binding + )] + const _: fn() = || { + use test_helper::sys; + // TODO(codegen): zx_system_get_features + let _: ffi::zx_status_t = 0 as sys::zx_status_t; + static_assert!(ffi::ZX_OK == sys::ZX_OK as ffi::zx_status_t); + static_assert!(ffi::ZX_FEATURE_KIND_CPU == sys::ZX_FEATURE_KIND_CPU); + static_assert!(ffi::ZX_ARM64_FEATURE_ISA_ATOMICS == sys::ZX_ARM64_FEATURE_ISA_ATOMICS); + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_illumos.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_illumos.rs new file mode 100644 index 0000000..f1bc357 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_illumos.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on AArch64 illumos by using getisax. + +As of nightly-2024-09-07, is_aarch64_feature_detected doesn't support run-time detection on illumos. +https://github.com/rust-lang/stdarch/blob/d9466edb4c53cece8686ee6e17b028436ddf4151/crates/std_detect/src/detect/mod.rs + +Run-time detection on AArch64 illumos is currently disabled by default as AArch64 port is experimental. +*/ + +include!("common.rs"); + +// core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 +#[allow(non_camel_case_types)] +mod ffi { + pub(crate) use super::c_types::c_uint; + + // Defined in sys/auxv_aarch64.h. + // https://github.com/richlowe/illumos-gate/blob/arm64-gate/usr/src/uts/common/sys/auxv_aarch64.h + pub(crate) const AV_AARCH64_LSE: u32 = 1 << 15; + pub(crate) const AV_AARCH64_2_LSE2: u32 = 1 << 2; + + extern "C" { + // Defined in sys/auxv.h. + // https://illumos.org/man/2/getisax + // https://github.com/richlowe/illumos-gate/blob/arm64-gate/usr/src/uts/common/sys/auxv.h + pub(crate) fn getisax(array: *mut u32, n: c_uint) -> c_uint; + } +} + +#[cold] +fn _detect(info: &mut CpuInfo) { + let mut out = [0_u32; 2]; + // SAFETY: the pointer is valid because we got it from a reference. + unsafe { + ffi::getisax(out.as_mut_ptr(), 2); + } + if out[0] & ffi::AV_AARCH64_LSE != 0 { + info.set(CpuInfo::HAS_LSE); + } + if out[1] & ffi::AV_AARCH64_2_LSE2 != 0 { + info.set(CpuInfo::HAS_LSE2); + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use super::*; + + // Static assertions for FFI bindings. + // This checks that FFI bindings defined in this crate and FFI bindings + // generated for the platform's latest header file using bindgen have + // compatible signatures (or the same values if constants). + // Since this is static assertion, we can detect problems with + // `cargo check --tests --target ` run in CI (via TESTS=1 build.sh) + // without actually running tests on these platforms. + // See also tools/codegen/src/ffi.rs. + // TODO(codegen): auto-generate this test + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::cast_possible_truncation, + clippy::no_effect_underscore_binding + )] + const _: fn() = || { + use test_helper::sys; + let mut _getisax: unsafe extern "C" fn(*mut u32, ffi::c_uint) -> ffi::c_uint = ffi::getisax; + _getisax = sys::getisax; + // static_assert!(ffi::AV_AARCH64_LSE == libc::AV_AARCH64_LSE); + static_assert!(ffi::AV_AARCH64_LSE == sys::AV_AARCH64_LSE); + // static_assert!(ffi::AV_AARCH64_2_LSE2 == libc::AV_AARCH64_2_LSE2); + static_assert!(ffi::AV_AARCH64_2_LSE2 == sys::AV_AARCH64_2_LSE2); + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_windows.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_windows.rs new file mode 100644 index 0000000..2fbcf6b --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/aarch64_windows.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on AArch64 Windows by using IsProcessorFeaturePresent. + +Run-time detection of FEAT_LSE on Windows by is_aarch64_feature_detected is supported on Rust 1.70+. +https://github.com/rust-lang/stdarch/pull/1373 + +Refs: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-isprocessorfeaturepresent +*/ + +include!("common.rs"); + +// windows-sys requires Rust 1.60 +#[allow(clippy::upper_case_acronyms)] +mod ffi { + pub(crate) type DWORD = u32; + pub(crate) type BOOL = i32; + + pub(crate) const FALSE: BOOL = 0; + + // Defined in winnt.h of Windows SDK. + pub(crate) const PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE: DWORD = 34; + + extern "system" { + // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-isprocessorfeaturepresent + pub(crate) fn IsProcessorFeaturePresent(ProcessorFeature: DWORD) -> BOOL; + } +} + +#[cold] +fn _detect(info: &mut CpuInfo) { + // SAFETY: calling IsProcessorFeaturePresent is safe, and FALSE is also + // returned if the HAL does not support detection of the specified feature. + if unsafe { + ffi::IsProcessorFeaturePresent(ffi::PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE) != ffi::FALSE + } { + info.set(CpuInfo::HAS_LSE); + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use super::*; + + // Static assertions for FFI bindings. + // This checks that FFI bindings defined in this crate and FFI bindings defined + // in windows-sys have compatible signatures (or the same values if constants). + // Since this is static assertion, we can detect problems with + // `cargo check --tests --target ` run in CI (via TESTS=1 build.sh) + // without actually running tests on these platforms. + // (Unlike libc, windows-sys programmatically generates bindings from Windows + // API metadata, so it should be enough to check compatibility with the + // windows-sys' signatures/values.) + // See also tools/codegen/src/ffi.rs. + // TODO(codegen): auto-generate this test + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::cast_possible_truncation, + clippy::no_effect_underscore_binding + )] + const _: fn() = || { + use test_helper::windows_sys; + let _: ffi::DWORD = 0 as windows_sys::Win32::System::Threading::PROCESSOR_FEATURE_ID; + let _: ffi::BOOL = 0 as windows_sys::Win32::Foundation::BOOL; + let mut _is_processor_feature_present: unsafe extern "system" fn(ffi::DWORD) -> ffi::BOOL = + ffi::IsProcessorFeaturePresent; + _is_processor_feature_present = + windows_sys::Win32::System::Threading::IsProcessorFeaturePresent; + static_assert!(ffi::FALSE == windows_sys::Win32::Foundation::FALSE); + static_assert!( + ffi::PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE + == windows_sys::Win32::System::Threading::PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE + ); + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/auxv.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/auxv.rs new file mode 100644 index 0000000..27bd8b4 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/auxv.rs @@ -0,0 +1,853 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on AArch64/PowerPC64 Linux/Android/FreeBSD/OpenBSD by parsing ELF auxiliary vectors. + +Supported platforms: +- Linux 6.4+ (through prctl) + https://github.com/torvalds/linux/commit/ddc65971bb677aa9f6a4c21f76d3133e106f88eb + prctl returns an unsupported error if operation is not supported, + so we can safely use this on older versions. +- glibc 2.16+ (through getauxval) + https://github.com/bminor/glibc/commit/c7683a6d02f3ed59f5cd119b3e8547f45a15912f + Always available on: + - aarch64 (glibc 2.17+ https://github.com/bminor/glibc/blob/glibc-2.17/NEWS#L35) + Not always available on: + - powerpc64 (glibc 2.3+ https://github.com/bminor/glibc/blob/glibc-2.3/NEWS#L55) + Since Rust 1.64, std requires glibc 2.17+ https://blog.rust-lang.org/2022/08/01/Increasing-glibc-kernel-requirements.html +- musl 1.1.0+ (through getauxval) + https://github.com/bminor/musl/commit/21ada94c4b8c01589367cea300916d7db8461ae7 + Always available on: + - aarch64 (musl 1.1.7+ https://github.com/bminor/musl/blob/v1.1.7/WHATSNEW#L1422) + - powerpc64 (musl 1.1.15+ https://github.com/bminor/musl/blob/v1.1.15/WHATSNEW#L1702) + Since Rust 1.31, std requires musl 1.1.20+ https://github.com/rust-lang/rust/pull/54430 + Since Rust 1.37, std requires musl 1.1.22+ https://github.com/rust-lang/rust/pull/61252 + Since Rust 1.46, std requires musl 1.1.24+ https://github.com/rust-lang/rust/pull/73089 + Since Rust 1.71, std requires musl 1.2.3+ https://blog.rust-lang.org/2023/05/09/Updating-musl-targets.html +- uClibc-ng 1.0.43+ (through getauxval) + https://github.com/wbx-github/uclibc-ng/commit/d869bb1600942c01a77539128f9ba5b5b55ad647 +- Picolibc 1.4.6+ (through getauxval) + https://github.com/picolibc/picolibc/commit/19bfe51d62ad7e32533c7f664b5bca8e26286e31 +- Android 4.3+ (API level 18+) (through getauxval) + https://github.com/aosp-mirror/platform_bionic/blob/d3ebc2f7c49a9893b114124d4a6b315f3a328764/libc/include/sys/auxv.h#L49 + Always available on 64-bit architectures, which is supported on Android 5.0+ (API level 21+) https://android-developers.googleblog.com/2014/10/whats-new-in-android-50-lollipop.html +- FreeBSD 12.0+ and 11.4+ (through elf_aux_info) + https://github.com/freebsd/freebsd-src/commit/0b08ae2120cdd08c20a2b806e2fcef4d0a36c470 + https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/sys/auxv.h + Not always available on: + - aarch64 (FreeBSD 11.0+ https://www.freebsd.org/releases/11.0R/announce) + - powerpc64 (FreeBSD 9.0+ https://www.freebsd.org/releases/9.0R/announce) + Since Rust 1.75, std requires FreeBSD 12+ https://github.com/rust-lang/rust/pull/114521 +- OpenBSD 7.6+ (through elf_aux_info) + https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d + +# Linux/Android + +As of Rust 1.69, is_aarch64_feature_detected always uses dlsym by default +on AArch64 Linux/Android, but on the following platforms, we can safely assume +getauxval is linked to the binary. + +- On glibc (*-linux-gnu*), [AArch64 support is available on glibc 2.17+](https://github.com/bminor/glibc/blob/glibc-2.17/NEWS#L35) +- On musl (*-linux-musl*, *-linux-ohos*), [AArch64 support is available on musl 1.1.7+](https://github.com/bminor/musl/blob/v1.1.7/WHATSNEW#L1422) +- On bionic (*-android*), [64-bit architecture support is available on Android 5.0+ (API level 21+)](https://android-developers.googleblog.com/2014/10/whats-new-in-android-50-lollipop.html) + +However, on musl with static linking, it seems that getauxval is not always available, independent of version requirements: https://github.com/rust-lang/rust/issues/89626 +(That problem may have been fixed in https://github.com/rust-lang/rust/commit/9a04ae4997493e9260352064163285cddc43de3c, +but even in the version containing that patch, [there is report](https://github.com/rust-lang/rust/issues/89626#issuecomment-1242636038) +of the same error.) + +On other Linux targets, we cannot assume that getauxval is always available, so we don't enable +run-time detection by default (can be enabled by `--cfg portable_atomic_outline_atomics`). + +- musl with static linking. See the above for more. + Also, dlsym(getauxval) always returns null when statically linked. +- uClibc-ng (*-linux-uclibc*, *-l4re-uclibc*). getauxval was recently added (See the above list). +- Picolibc. getauxval was recently added (See the above list). + +See also https://github.com/rust-lang/stdarch/pull/1375 + +See tests::test_linux_like and aarch64_aa64reg.rs for (test-only) alternative implementations. + +# FreeBSD + +As of nightly-2024-09-07, is_aarch64_feature_detected always uses mrs on +AArch64 FreeBSD. However, they do not work on FreeBSD 12 on QEMU (confirmed +on FreeBSD 12.{2,3,4}), and we got SIGILL (worked on FreeBSD 13 and 14). + +So use elf_aux_info instead of mrs like compiler-rt does. +https://reviews.llvm.org/D109330 + +elf_aux_info is available on FreeBSD 12.0+ and 11.4+: +https://github.com/freebsd/freebsd-src/commit/0b08ae2120cdd08c20a2b806e2fcef4d0a36c470 +https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/sys/auxv.h +On FreeBSD, [AArch64 support is available on FreeBSD 11.0+](https://www.freebsd.org/releases/11.0R/announce), +but FreeBSD 11 (11.4) was EoL on 2021-09-30, and FreeBSD 11.3 was EoL on 2020-09-30: +https://www.freebsd.org/security/unsupported +See also https://github.com/rust-lang/stdarch/pull/611#issuecomment-445464613 + +See tests::test_freebsd and aarch64_aa64reg.rs for (test-only) alternative implementations. + +# OpenBSD + +elf_aux_info is available on OpenBSD 7.6+: +https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d + +On AArch64, there is an alternative that available on older version, +so we use it (see aarch64_aa64reg.rs). + +# PowerPC64 + +On PowerPC64, run-time detection is currently disabled by default mainly for +compatibility with older versions of operating systems +(can be enabled by `--cfg portable_atomic_outline_atomics`). + +- On glibc, [powerpc64 support is available on glibc 2.3+](https://github.com/bminor/glibc/blob/glibc-2.3/NEWS#L55) +- On musl, [powerpc64 support is available on musl 1.1.15+](https://github.com/bminor/musl/blob/v1.1.15/WHATSNEW#L1702) +- On FreeBSD, [powerpc64 support is available on FreeBSD 9.0+](https://www.freebsd.org/releases/9.0R/announce) + +(On uClibc-ng, [powerpc64 is not supported](https://github.com/wbx-github/uclibc-ng/commit/d4d4f37fda7fa57e57132ff2f0d735ce7cc2178e)) +*/ + +include!("common.rs"); + +use os::ffi; +#[cfg(any(target_os = "linux", target_os = "android"))] +mod os { + // core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 + #[cfg_attr(test, allow(dead_code))] + pub(super) mod ffi { + pub(crate) use super::super::c_types::c_ulong; + #[cfg(all(target_arch = "aarch64", target_os = "android"))] + pub(crate) use super::super::c_types::{c_char, c_int}; + + // https://github.com/torvalds/linux/blob/v6.11/include/uapi/linux/auxvec.h + #[cfg(any(test, target_arch = "aarch64"))] + pub(crate) const AT_HWCAP: c_ulong = 16; + #[cfg(any( + test, + all(target_arch = "aarch64", target_pointer_width = "64"), + target_arch = "powerpc64", + ))] + pub(crate) const AT_HWCAP2: c_ulong = 26; + + // Defined in sys/system_properties.h. + // https://github.com/aosp-mirror/platform_bionic/blob/d3ebc2f7c49a9893b114124d4a6b315f3a328764/libc/include/sys/system_properties.h + #[cfg(all(target_arch = "aarch64", target_os = "android"))] + pub(crate) const PROP_VALUE_MAX: c_int = 92; + + extern "C" { + // Defined in sys/auxv.h. + // https://man7.org/linux/man-pages/man3/getauxval.3.html + // https://github.com/bminor/glibc/blob/glibc-2.40/misc/sys/auxv.h + // https://github.com/bminor/musl/blob/v1.2.5/include/sys/auxv.h + // https://github.com/wbx-github/uclibc-ng/blob/v1.0.47/include/sys/auxv.h + // https://github.com/aosp-mirror/platform_bionic/blob/d3ebc2f7c49a9893b114124d4a6b315f3a328764/libc/include/sys/auxv.h + // https://github.com/picolibc/picolibc/blob/1.8.6/newlib/libc/include/sys/auxv.h + pub(crate) fn getauxval(type_: c_ulong) -> c_ulong; + + // Defined in sys/system_properties.h. + // https://github.com/aosp-mirror/platform_bionic/blob/d3ebc2f7c49a9893b114124d4a6b315f3a328764/libc/include/sys/system_properties.h + #[cfg(all(target_arch = "aarch64", target_os = "android"))] + pub(crate) fn __system_property_get(name: *const c_char, value: *mut c_char) -> c_int; + } + } + + pub(super) fn getauxval(type_: ffi::c_ulong) -> ffi::c_ulong { + #[cfg(all(target_arch = "aarch64", target_os = "android"))] + { + // Samsung Exynos 9810 has a bug that big and little cores have different + // ISAs. And on older Android (pre-9), the kernel incorrectly reports + // that features available only on some cores are available on all cores. + // https://reviews.llvm.org/D114523 + let mut arch = [0_u8; ffi::PROP_VALUE_MAX as usize]; + // SAFETY: we've passed a valid C string and a buffer with max length. + let len = unsafe { + ffi::__system_property_get( + b"ro.arch\0".as_ptr().cast::(), + arch.as_mut_ptr().cast::(), + ) + }; + // On Exynos, ro.arch is not available on Android 12+, but it is fine + // because Android 9+ includes the fix. + if len > 0 && arch.starts_with(b"exynos9810") { + return 0; + } + } + + // SAFETY: `getauxval` is thread-safe. See also the module level docs. + unsafe { ffi::getauxval(type_) } + } +} +#[cfg(any(target_os = "freebsd", target_os = "openbsd"))] +mod os { + // core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 + #[cfg_attr(test, allow(dead_code))] + pub(super) mod ffi { + pub(crate) use super::super::c_types::{c_int, c_ulong, c_void}; + + // FreeBSD + // Defined in sys/elf_common.h. + // https://github.com/freebsd/freebsd-src/blob/release/14.1.0/sys/sys/elf_common.h + // OpenBSD + // Defined in sys/auxv.h. + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/sys/auxv.h + #[cfg(any(test, target_arch = "aarch64"))] + pub(crate) const AT_HWCAP: c_int = 25; + #[cfg(any(test, target_arch = "powerpc64"))] + pub(crate) const AT_HWCAP2: c_int = 26; + + extern "C" { + // FreeBSD + // Defined in sys/auxv.h. + // https://man.freebsd.org/elf_aux_info(3) + // https://github.com/freebsd/freebsd-src/blob/release/14.1.0/sys/sys/auxv.h + // OpenBSD + // Defined in sys/auxv.h. + // https://man.openbsd.org/elf_aux_info.3 + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/sys/auxv.h + pub(crate) fn elf_aux_info(aux: c_int, buf: *mut c_void, buf_len: c_int) -> c_int; + } + } + + pub(super) fn getauxval(aux: ffi::c_int) -> ffi::c_ulong { + #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)] + const OUT_LEN: ffi::c_int = core::mem::size_of::() as ffi::c_int; + let mut out: ffi::c_ulong = 0; + // SAFETY: + // - the pointer is valid because we got it from a reference. + // - `OUT_LEN` is the same as the size of `out`. + // - `elf_aux_info` is thread-safe. + unsafe { + let res = ffi::elf_aux_info( + aux, + (&mut out as *mut ffi::c_ulong).cast::(), + OUT_LEN, + ); + // If elf_aux_info fails, `out` will be left at zero (which is the proper default value). + debug_assert!(res == 0 || out == 0); + } + out + } +} + +// Basically, Linux/FreeBSD/OpenBSD use the same hwcap values. +// FreeBSD/OpenBSD supports a subset of the hwcap values supported by Linux. +use arch::_detect; +#[cfg(target_arch = "aarch64")] +mod arch { + use super::{ffi, os, CpuInfo}; + + // Linux + // https://github.com/torvalds/linux/blob/v6.11/arch/arm64/include/uapi/asm/hwcap.h + // https://github.com/torvalds/linux/blob/v6.11/Documentation/arch/arm64/elf_hwcaps.rst + // FreeBSD + // Defined in machine/elf.h. + // https://github.com/freebsd/freebsd-src/blob/release/14.1.0/sys/arm64/include/elf.h + // OpenBSD + // Defined in machine/elf.h. + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/arch/arm64/include/elf.h + // Linux 4.3+ + // https://github.com/torvalds/linux/commit/40a1db2434a1b62332b1af25cfa14d7b8c0301fe + // FreeBSD 13.0+/12.2+ + // https://github.com/freebsd/freebsd-src/blob/release/13.0.0/sys/arm64/include/elf.h + // https://github.com/freebsd/freebsd-src/blob/release/12.2.0/sys/arm64/include/elf.h + // OpenBSD 7.6+ + // https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d + pub(super) const HWCAP_ATOMICS: ffi::c_ulong = 1 << 8; + // Linux 4.17+ + // https://github.com/torvalds/linux/commit/7206dc93a58fb76421c4411eefa3c003337bcb2d + // FreeBSD 13.0+/12.2+ + // https://github.com/freebsd/freebsd-src/blob/release/13.0.0/sys/arm64/include/elf.h + // https://github.com/freebsd/freebsd-src/blob/release/12.2.0/sys/arm64/include/elf.h + // OpenBSD 7.6+ + // https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d + pub(super) const HWCAP_USCAT: ffi::c_ulong = 1 << 25; + // Linux 6.7+ + // https://github.com/torvalds/linux/commit/338a835f40a849cd89b993e342bd9fbd5684825c + #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(target_pointer_width = "64")] + pub(super) const HWCAP2_LRCPC3: ffi::c_ulong = 1 << 46; + // Linux 6.7+ + // https://github.com/torvalds/linux/commit/94d0657f9f0d311489606589133ebf49e28104d8 + #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(target_pointer_width = "64")] + pub(super) const HWCAP2_LSE128: ffi::c_ulong = 1 << 47; + + #[cold] + pub(super) fn _detect(info: &mut CpuInfo) { + let hwcap = os::getauxval(ffi::AT_HWCAP); + + if hwcap & HWCAP_ATOMICS != 0 { + info.set(CpuInfo::HAS_LSE); + } + if hwcap & HWCAP_USCAT != 0 { + info.set(CpuInfo::HAS_LSE2); + } + #[cfg(any(target_os = "linux", target_os = "android"))] + // HWCAP2 is not yet available on ILP32: https://git.kernel.org/pub/scm/linux/kernel/git/arm64/linux.git/tree/arch/arm64/include/uapi/asm/hwcap.h?h=staging/ilp32-5.1 + #[cfg(target_pointer_width = "64")] + { + let hwcap2 = os::getauxval(ffi::AT_HWCAP2); + if hwcap2 & HWCAP2_LRCPC3 != 0 { + info.set(CpuInfo::HAS_RCPC3); + } + if hwcap2 & HWCAP2_LSE128 != 0 { + info.set(CpuInfo::HAS_LSE128); + } + } + } +} +#[cfg(target_arch = "powerpc64")] +mod arch { + use super::{ffi, os, CpuInfo}; + + // Linux + // https://github.com/torvalds/linux/blob/v6.11/arch/powerpc/include/uapi/asm/cputable.h + // https://github.com/torvalds/linux/blob/v6.11/Documentation/arch/powerpc/elf_hwcaps.rst + // FreeBSD + // Defined in machine/cpu.h. + // https://github.com/freebsd/freebsd-src/blob/release/14.1.0/sys/powerpc/include/cpu.h + // OpenBSD + // Defined in machine/elf.h. + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/arch/powerpc64/include/elf.h + // Linux 3.10+ + // https://github.com/torvalds/linux/commit/cbbc6f1b1433ef553d57826eee87a84ca49645ce + // FreeBSD 11.0+ + // https://github.com/freebsd/freebsd-src/commit/b0bf7fcd298133457991b27625bbed766e612730 + // OpenBSD 7.6+ + // https://github.com/openbsd/src/commit/0b0568a19fc4c197871ceafbabc91fabf17ca152 + pub(super) const PPC_FEATURE2_ARCH_2_07: ffi::c_ulong = 0x80000000; + // Linux 4.5+ + // https://github.com/torvalds/linux/commit/e708c24cd01ce80b1609d8baccee40ccc3608a01 + // FreeBSD 12.0+ + // https://github.com/freebsd/freebsd-src/commit/18f48e0c72f91bc2d4373078a3f1ab1bcab4d8b3 + // OpenBSD 7.6+ + // https://github.com/openbsd/src/commit/0b0568a19fc4c197871ceafbabc91fabf17ca152 + pub(super) const PPC_FEATURE2_ARCH_3_00: ffi::c_ulong = 0x00800000; + // Linux 5.8+ + // https://github.com/torvalds/linux/commit/ee988c11acf6f9464b7b44e9a091bf6afb3b3a49 + #[cfg(any(target_os = "linux", target_os = "android"))] + pub(super) const PPC_FEATURE2_ARCH_3_1: ffi::c_ulong = 0x00040000; + + #[cold] + pub(super) fn _detect(info: &mut CpuInfo) { + let hwcap2 = os::getauxval(ffi::AT_HWCAP2); + + // power8 + // Check both 2_07 (power8) and later ISAs (which are superset of 2_07) because + // OpenBSD currently doesn't set 2_07 even when 3_00 (power9) is set. + // https://github.com/openbsd/src/blob/ed8f5e8d82ace15e4cefca2c82941b15cb1a7830/sys/arch/powerpc64/powerpc64/cpu.c#L224-L243 + // Other OSes should be fine, but check all OSs in the same way just in case. + #[cfg(any(target_os = "linux", target_os = "android"))] + let power8_or_later = + PPC_FEATURE2_ARCH_2_07 | PPC_FEATURE2_ARCH_3_00 | PPC_FEATURE2_ARCH_3_1; + #[cfg(not(any(target_os = "linux", target_os = "android")))] + let power8_or_later = PPC_FEATURE2_ARCH_2_07 | PPC_FEATURE2_ARCH_3_00; + if hwcap2 & power8_or_later != 0 { + info.set(CpuInfo::HAS_QUADWORD_ATOMICS); + } + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(target_pointer_width = "64")] + #[test] + fn test_linux_like() { + use c_types::*; + #[cfg(not(portable_atomic_no_asm))] + use std::arch::asm; + use std::{mem, vec}; + use test_helper::{libc, sys}; + + // Linux kernel 6.4 has added a way to read auxv without depending on either libc or mrs trap. + // https://github.com/torvalds/linux/commit/ddc65971bb677aa9f6a4c21f76d3133e106f88eb + // + // This is currently used only for testing. + fn getauxval_pr_get_auxv(type_: ffi::c_ulong) -> Result { + #[cfg(target_arch = "aarch64")] + unsafe fn prctl_get_auxv(out: *mut c_void, len: usize) -> Result { + let r: i64; + unsafe { + asm!( + "svc 0", + in("x8") sys::__NR_prctl as u64, + inout("x0") sys::PR_GET_AUXV as u64 => r, + in("x1") ptr_reg!(out), + in("x2") len as u64, + // arg4 and arg5 must be zero. + in("x3") 0_u64, + in("x4") 0_u64, + options(nostack, preserves_flags), + ); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + if (r as c_int) < 0 { + Err(r as c_int) + } else { + Ok(r as usize) + } + } + #[cfg(target_arch = "powerpc64")] + unsafe fn prctl_get_auxv(out: *mut c_void, len: usize) -> Result { + let r: i64; + unsafe { + asm!( + "sc", + "bns+ 2f", + "neg %r3, %r3", + "2:", + inout("r0") sys::__NR_prctl as u64 => _, + inout("r3") sys::PR_GET_AUXV as u64 => r, + inout("r4") ptr_reg!(out) => _, + inout("r5") len as u64 => _, + // arg4 and arg5 must be zero. + inout("r6") 0_u64 => _, + inout("r7") 0_u64 => _, + out("r8") _, + out("r9") _, + out("r10") _, + out("r11") _, + out("r12") _, + out("cr0") _, + options(nostack, preserves_flags), + ); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + if (r as c_int) < 0 { + Err(r as c_int) + } else { + Ok(r as usize) + } + } + + let mut auxv = vec![unsafe { mem::zeroed::() }; 38]; + + let old_len = auxv.len() * mem::size_of::(); + + // SAFETY: + // - `out_len` does not exceed the size of `auxv`. + let _len = unsafe { prctl_get_auxv(auxv.as_mut_ptr().cast::(), old_len)? }; + + for aux in &auxv { + if aux.a_type == type_ { + // SAFETY: aux.a_un is #[repr(C)] union and all fields have + // the same size and can be safely transmuted to integers. + return Ok(unsafe { aux.a_un.a_val }); + } + } + Err(0) + } + + unsafe { + let mut u = mem::zeroed(); + assert_eq!(libc::uname(&mut u), 0); + let release = std::ffi::CStr::from_ptr(u.release.as_ptr()); + let release = core::str::from_utf8(release.to_bytes()).unwrap(); + let mut digits = release.split('.'); + let major = digits.next().unwrap().parse::().unwrap(); + let minor = digits.next().unwrap().parse::().unwrap(); + // TODO: qemu-user bug? + if (major, minor) < (6, 4) || cfg!(qemu) { + std::eprintln!("kernel version: {}.{} (no pr_get_auxv)", major, minor); + assert_eq!(getauxval_pr_get_auxv(ffi::AT_HWCAP).unwrap_err(), -22); + assert_eq!(getauxval_pr_get_auxv(ffi::AT_HWCAP2).unwrap_err(), -22); + } else { + std::eprintln!("kernel version: {}.{} (has pr_get_auxv)", major, minor); + assert_eq!( + os::getauxval(ffi::AT_HWCAP), + getauxval_pr_get_auxv(ffi::AT_HWCAP).unwrap() + ); + assert_eq!( + os::getauxval(ffi::AT_HWCAP2), + getauxval_pr_get_auxv(ffi::AT_HWCAP2).unwrap() + ); + } + } + } + + #[allow(clippy::cast_sign_loss)] + #[cfg(all(target_arch = "aarch64", target_os = "android"))] + #[test] + fn test_android() { + unsafe { + let mut arch = [1; ffi::PROP_VALUE_MAX as usize]; + let len = ffi::__system_property_get( + b"ro.arch\0".as_ptr().cast::(), + arch.as_mut_ptr().cast::(), + ); + assert!(len >= 0); + std::eprintln!("len={}", len); + std::eprintln!("arch={:?}", arch); + std::eprintln!( + "arch={:?}", + core::str::from_utf8(core::slice::from_raw_parts(arch.as_ptr(), len as usize)) + .unwrap() + ); + } + } + + #[allow(clippy::cast_possible_wrap)] + #[cfg(target_os = "freebsd")] + #[test] + fn test_freebsd() { + use c_types::*; + #[cfg(not(portable_atomic_no_asm))] + use std::arch::asm; + use std::{mem, ptr}; + use test_helper::sys; + + // This is almost equivalent to what elf_aux_info does. + // https://man.freebsd.org/elf_aux_info(3) + // On FreeBSD, [AArch64 support is available on FreeBSD 11.0+](https://www.freebsd.org/releases/11.0R/announce), + // but elf_aux_info is available on FreeBSD 12.0+ and 11.4+: + // https://github.com/freebsd/freebsd-src/commit/0b08ae2120cdd08c20a2b806e2fcef4d0a36c470 + // https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/sys/auxv.h + // so use sysctl instead of elf_aux_info. + // Note that FreeBSD 11 (11.4) was EoL on 2021-09-30, and FreeBSD 11.3 was EoL on 2020-09-30: + // https://www.freebsd.org/security/unsupported + // + // std_detect uses this way, but it appears to be somewhat incorrect + // (the type of arg4 of sysctl, auxv is smaller than AT_COUNT, etc.). + // https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/std_detect/src/detect/os/freebsd/auxvec.rs#L52 + // + // This is currently used only for testing. + // If you want us to use this implementation for compatibility with the older FreeBSD + // version that came to EoL a few years ago, please open an issue. + fn getauxval_sysctl_libc(type_: ffi::c_int) -> ffi::c_ulong { + let mut auxv: [sys::Elf64_Auxinfo; sys::AT_COUNT as usize] = unsafe { mem::zeroed() }; + + let mut len = core::mem::size_of_val(&auxv) as c_size_t; + + // SAFETY: calling getpid is safe. + let pid = unsafe { sys::getpid() }; + let mib = [ + sys::CTL_KERN as c_int, + sys::KERN_PROC as c_int, + sys::KERN_PROC_AUXV as c_int, + pid, + ]; + + #[allow(clippy::cast_possible_truncation)] + // SAFETY: + // - `mib.len()` does not exceed the size of `mib`. + // - `len` does not exceed the size of `auxv`. + // - `sysctl` is thread-safe. + let res = unsafe { + sys::sysctl( + mib.as_ptr(), + mib.len() as c_uint, + auxv.as_mut_ptr().cast::(), + &mut len, + ptr::null_mut(), + 0, + ) + }; + + if res != -1 { + for aux in &auxv { + if aux.a_type == type_ as c_long { + // SAFETY: aux.a_un is #[repr(C)] union and all fields have + // the same size and can be safely transmuted to integers. + return unsafe { aux.a_un.a_val as c_ulong }; + } + } + } + 0 + } + // Similar to the above, but call syscall using asm instead of libc. + // Note that FreeBSD does not guarantee the stability of raw syscall as + // much as Linux does (It may actually be stable enough, though: + // https://lists.llvm.org/pipermail/llvm-dev/2019-June/133393.html, + // https://github.com/ziglang/zig/issues/16590). + // + // This is currently used only for testing. + fn getauxval_sysctl_asm_syscall(type_: ffi::c_int) -> Result { + #[allow(non_camel_case_types)] + type pid_t = c_int; + + // https://github.com/freebsd/freebsd-src/blob/release/14.1.0/lib/libc/aarch64/SYS.h + // https://github.com/golang/go/blob/4badad8d477ffd7a6b762c35bc69aed82faface7/src/syscall/asm_freebsd_arm64.s + #[cfg(target_arch = "aarch64")] + #[inline] + fn getpid() -> pid_t { + #[allow(clippy::cast_possible_truncation)] + // SAFETY: calling getpid is safe. + unsafe { + let n = sys::SYS_getpid; + let r: i64; + asm!( + "svc 0", + in("x8") n as u64, + out("x0") r, + options(nostack, readonly), + ); + r as pid_t + } + } + #[cfg(target_arch = "aarch64")] + #[inline] + unsafe fn sysctl( + name: *const c_int, + name_len: c_uint, + old_p: *mut c_void, + old_len_p: *mut c_size_t, + new_p: *const c_void, + new_len: c_size_t, + ) -> Result { + #[allow(clippy::cast_possible_truncation)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + let mut n = sys::SYS___sysctl as u64; + let r: i64; + asm!( + "svc 0", + "b.cc 2f", + "mov x8, x0", + "mov x0, #-1", + "2:", + inout("x8") n, + inout("x0") ptr_reg!(name) => r, + inout("x1") name_len as u64 => _, + in("x2") ptr_reg!(old_p), + in("x3") ptr_reg!(old_len_p), + in("x4") ptr_reg!(new_p), + in("x5") new_len as u64, + options(nostack), + ); + if r as c_int == -1 { + Err(n as c_int) + } else { + Ok(r as c_int) + } + } + } + + // https://github.com/freebsd/freebsd-src/blob/release/14.1.0/lib/libc/powerpc64/SYS.h + #[cfg(target_arch = "powerpc64")] + #[inline] + fn getpid() -> pid_t { + #[allow(clippy::cast_possible_truncation)] + // SAFETY: calling getpid is safe. + unsafe { + let n = sys::SYS_getpid; + let r: i64; + asm!( + "sc", + inout("r0") n as u64 => _, + out("r3") r, + out("r4") _, + out("r5") _, + out("r6") _, + out("r7") _, + out("r8") _, + out("r9") _, + out("r10") _, + out("r11") _, + out("r12") _, + out("cr0") _, + options(nostack, preserves_flags, readonly), + ); + r as pid_t + } + } + #[cfg(target_arch = "powerpc64")] + #[inline] + unsafe fn sysctl( + name: *const c_int, + name_len: c_uint, + old_p: *mut c_void, + old_len_p: *mut c_size_t, + new_p: *const c_void, + new_len: c_size_t, + ) -> Result { + #[allow(clippy::cast_possible_truncation)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + let mut n = sys::SYS___sysctl as u64; + let r: i64; + asm!( + "sc", + "bns+ 2f", + "mr %r0, %r3", + "li %r3, -1", + "2:", + inout("r0") n, + inout("r3") ptr_reg!(name) => r, + inout("r4") name_len as u64 => _, + inout("r5") ptr_reg!(old_p) => _, + inout("r6") ptr_reg!(old_len_p) => _, + inout("r7") ptr_reg!(new_p) => _, + inout("r8") new_len as u64 => _, + out("r9") _, + out("r10") _, + out("r11") _, + out("r12") _, + out("cr0") _, + options(nostack, preserves_flags), + ); + if r as c_int == -1 { + Err(n as c_int) + } else { + Ok(r as c_int) + } + } + } + + let mut auxv: [sys::Elf64_Auxinfo; sys::AT_COUNT as usize] = unsafe { mem::zeroed() }; + + let mut len = core::mem::size_of_val(&auxv) as c_size_t; + + let pid = getpid(); + let mib = [ + sys::CTL_KERN as c_int, + sys::KERN_PROC as c_int, + sys::KERN_PROC_AUXV as c_int, + pid, + ]; + + #[allow(clippy::cast_possible_truncation)] + // SAFETY: + // - `mib.len()` does not exceed the size of `mib`. + // - `len` does not exceed the size of `auxv`. + // - `sysctl` is thread-safe. + unsafe { + sysctl( + mib.as_ptr(), + mib.len() as c_uint, + auxv.as_mut_ptr().cast::(), + &mut len, + ptr::null_mut(), + 0, + )?; + } + + for aux in &auxv { + if aux.a_type == type_ as c_long { + // SAFETY: aux.a_un is #[repr(C)] union and all fields have + // the same size and can be safely transmuted to integers. + return Ok(unsafe { aux.a_un.a_val as c_ulong }); + } + } + Err(0) + } + + assert_eq!(os::getauxval(ffi::AT_HWCAP), getauxval_sysctl_libc(ffi::AT_HWCAP)); + assert_eq!(os::getauxval(ffi::AT_HWCAP2), getauxval_sysctl_libc(ffi::AT_HWCAP2)); + assert_eq!( + os::getauxval(ffi::AT_HWCAP), + getauxval_sysctl_asm_syscall(ffi::AT_HWCAP).unwrap() + ); + assert_eq!( + os::getauxval(ffi::AT_HWCAP2), + // AT_HWCAP2 is only available on FreeBSD 13+, at least on AArch64. + getauxval_sysctl_asm_syscall(ffi::AT_HWCAP2).unwrap_or(0) + ); + } + + // Static assertions for FFI bindings. + // This checks that FFI bindings defined in this crate, FFI bindings defined + // in libc, and FFI bindings generated for the platform's latest header file + // using bindgen have compatible signatures (or the same values if constants). + // Since this is static assertion, we can detect problems with + // `cargo check --tests --target ` run in CI (via TESTS=1 build.sh) + // without actually running tests on these platforms. + // See also tools/codegen/src/ffi.rs. + // TODO(codegen): auto-generate this test + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::cast_possible_truncation, + clippy::no_effect_underscore_binding + )] + const _: fn() = || { + #[cfg(not(target_os = "openbsd"))] + use test_helper::libc; + use test_helper::sys; + #[cfg(not(any(target_os = "freebsd", target_os = "openbsd")))] + type AtType = ffi::c_ulong; + #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] + type AtType = ffi::c_int; + #[cfg(any(target_os = "linux", target_os = "android"))] + { + let mut _getauxval: unsafe extern "C" fn(ffi::c_ulong) -> ffi::c_ulong = ffi::getauxval; + _getauxval = libc::getauxval; + _getauxval = sys::getauxval; + } + #[cfg(all(target_arch = "aarch64", target_os = "android"))] + { + let mut ___system_property_get: unsafe extern "C" fn( + *const ffi::c_char, + *mut ffi::c_char, + ) -> ffi::c_int = ffi::__system_property_get; + ___system_property_get = libc::__system_property_get; + ___system_property_get = sys::__system_property_get; + static_assert!(ffi::PROP_VALUE_MAX == libc::PROP_VALUE_MAX); + static_assert!(ffi::PROP_VALUE_MAX == sys::PROP_VALUE_MAX as ffi::c_int); + } + #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] + { + let mut _elf_aux_info: unsafe extern "C" fn( + ffi::c_int, + *mut ffi::c_void, + ffi::c_int, + ) -> ffi::c_int = ffi::elf_aux_info; + #[cfg(not(target_os = "openbsd"))] // libc doesn't have this on OpenBSD + { + _elf_aux_info = libc::elf_aux_info; + } + _elf_aux_info = sys::elf_aux_info; + } + #[cfg(not(target_os = "openbsd"))] // libc doesn't have this on OpenBSD + static_assert!(ffi::AT_HWCAP == libc::AT_HWCAP); + static_assert!(ffi::AT_HWCAP == sys::AT_HWCAP as AtType); + #[cfg(not(target_os = "openbsd"))] // libc doesn't have this on OpenBSD + static_assert!(ffi::AT_HWCAP2 == libc::AT_HWCAP2); + static_assert!(ffi::AT_HWCAP2 == sys::AT_HWCAP2 as AtType); + #[cfg(target_arch = "aarch64")] + { + #[cfg(any(target_os = "linux", target_os = "android"))] // libc doesn't have this on BSDs + static_assert!(arch::HWCAP_ATOMICS == libc::HWCAP_ATOMICS); + static_assert!(arch::HWCAP_ATOMICS == sys::HWCAP_ATOMICS as ffi::c_ulong); + #[cfg(any(target_os = "linux", target_os = "android"))] // libc doesn't have this on BSDs + static_assert!(arch::HWCAP_USCAT == libc::HWCAP_USCAT); + static_assert!(arch::HWCAP_USCAT == sys::HWCAP_USCAT as ffi::c_ulong); + #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(target_pointer_width = "64")] + { + // static_assert!(HWCAP2_LRCPC3 == libc::HWCAP2_LRCPC3); // libc doesn't have this + static_assert!(arch::HWCAP2_LRCPC3 == sys::HWCAP2_LRCPC3 as ffi::c_ulong); + // static_assert!(HWCAP2_LSE128 == libc::HWCAP2_LSE128); // libc doesn't have this + static_assert!(arch::HWCAP2_LSE128 == sys::HWCAP2_LSE128 as ffi::c_ulong); + } + } + #[cfg(target_arch = "powerpc64")] + { + // static_assert!(arch::PPC_FEATURE2_ARCH_2_07 == libc::PPC_FEATURE2_ARCH_2_07); // libc doesn't have this + static_assert!( + arch::PPC_FEATURE2_ARCH_2_07 == sys::PPC_FEATURE2_ARCH_2_07 as ffi::c_ulong + ); + // static_assert!(arch::PPC_FEATURE2_ARCH_3_00 == libc::PPC_FEATURE2_ARCH_3_00); // libc doesn't have this + static_assert!( + arch::PPC_FEATURE2_ARCH_3_00 == sys::PPC_FEATURE2_ARCH_3_00 as ffi::c_ulong + ); + #[cfg(any(target_os = "linux", target_os = "android"))] + { + // static_assert!(arch::PPC_FEATURE2_ARCH_3_1 == libc::PPC_FEATURE2_ARCH_3_1); // libc doesn't have this + static_assert!( + arch::PPC_FEATURE2_ARCH_3_1 == sys::PPC_FEATURE2_ARCH_3_1 as ffi::c_ulong + ); + } + } + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/common.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/common.rs new file mode 100644 index 0000000..6d43511 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/common.rs @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#[derive(Clone, Copy)] +pub(crate) struct CpuInfo(u32); + +impl CpuInfo { + const INIT: u32 = 0; + + #[inline] + fn set(&mut self, bit: u32) { + self.0 = set(self.0, bit); + } + #[inline] + fn test(self, bit: u32) -> bool { + test(self.0, bit) + } +} + +#[inline] +fn set(x: u32, bit: u32) -> u32 { + x | 1 << bit +} +#[inline] +fn test(x: u32, bit: u32) -> bool { + x & (1 << bit) != 0 +} + +#[inline] +pub(crate) fn detect() -> CpuInfo { + use core::sync::atomic::{AtomicU32, Ordering}; + + static CACHE: AtomicU32 = AtomicU32::new(0); + let mut info = CpuInfo(CACHE.load(Ordering::Relaxed)); + if info.0 != 0 { + return info; + } + info.set(CpuInfo::INIT); + // Note: detect_false cfg is intended to make it easy for portable-atomic developers to + // test cases such as has_cmpxchg16b == false, has_lse == false, + // __kuser_helper_version < 5, etc., and is not a public API. + if !cfg!(portable_atomic_test_outline_atomics_detect_false) { + _detect(&mut info); + } + CACHE.store(info.0, Ordering::Relaxed); + info +} + +macro_rules! flags { + ($( + $(#[$attr:meta])* + $flag:ident ($shift:literal, $func:ident, $name:literal, $cfg:meta), + )*) => { + impl CpuInfo { + $( + $(#[$attr])* + const $flag: u32 = $shift; + $(#[$attr])* + #[cfg(any(test, not($cfg)))] + #[inline] + pub(crate) fn $func(self) -> bool { + self.test(Self::$flag) + } + )* + #[cfg(test)] // for test + const ALL_FLAGS: &'static [(&'static str, u32, bool)] = &[$( + ($name, Self::$flag, cfg!($cfg)), + )*]; + } + }; +} + +#[cfg(any(target_arch = "aarch64", target_arch = "arm64ec"))] +flags! { + // FEAT_LSE, Large System Extensions + // https://developer.arm.com/documentation/109697/0100/Feature-descriptions/The-Armv8-1-architecture-extension + // > This feature is supported in AArch64 state only. + // > FEAT_LSE is OPTIONAL from Armv8.0. + // > FEAT_LSE is mandatory from Armv8.1. + HAS_LSE(1, has_lse, "lse", any(target_feature = "lse", portable_atomic_target_feature = "lse")), + // FEAT_LSE2, Large System Extensions version 2 + // https://developer.arm.com/documentation/109697/0100/Feature-descriptions/The-Armv8-4-architecture-extension + // > This feature is supported in AArch64 state only. + // > FEAT_LSE2 is OPTIONAL from Armv8.2. + // > FEAT_LSE2 is mandatory from Armv8.4. + #[cfg_attr(not(test), allow(dead_code))] + HAS_LSE2(2, has_lse2, "lse2", any(target_feature = "lse2", portable_atomic_target_feature = "lse2")), + // FEAT_LRCPC3, Load-Acquire RCpc instructions version 3 + // https://developer.arm.com/documentation/109697/0100/Feature-descriptions/The-Armv8-9-architecture-extension + // > This feature is supported in AArch64 state only. + // > FEAT_LRCPC3 is OPTIONAL from Armv8.2. + // > If FEAT_LRCPC3 is implemented, then FEAT_LRCPC2 is implemented. + #[cfg_attr(not(test), allow(dead_code))] + HAS_RCPC3(3, has_rcpc3, "rcpc3", any(target_feature = "rcpc3", portable_atomic_target_feature = "rcpc3")), + // FEAT_LSE128, 128-bit Atomics + // https://developer.arm.com/documentation/109697/0100/Feature-descriptions/The-Armv9-4-architecture-extension + // > This feature is supported in AArch64 state only. + // > FEAT_LSE128 is OPTIONAL from Armv9.3. + // > If FEAT_LSE128 is implemented, then FEAT_LSE is implemented. + #[cfg_attr(not(test), allow(dead_code))] + HAS_LSE128(4, has_lse128, "lse128", any(target_feature = "lse128", portable_atomic_target_feature = "lse128")), +} + +#[cfg(target_arch = "powerpc64")] +flags! { + // lqarx and stqcx. + HAS_QUADWORD_ATOMICS(1, has_quadword_atomics, "quadword-atomics", any(target_feature = "quadword-atomics", portable_atomic_target_feature = "quadword-atomics")), +} + +#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] +flags! { + // amocas.{w,d,q} + HAS_ZACAS(1, has_zacas, "zacas", any(target_feature = "experimental-zacas", portable_atomic_target_feature = "experimental-zacas")), +} + +#[cfg(target_arch = "x86_64")] +flags! { + // cmpxchg16b + HAS_CMPXCHG16B(1, has_cmpxchg16b, "cmpxchg16b", any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b")), + // atomic vmovdqa + #[cfg(target_feature = "sse")] + HAS_VMOVDQA_ATOMIC(2, has_vmovdqa_atomic, "vmovdqa-atomic", any(/* always false */)), +} + +// core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 +#[cfg(not(target_arch = "x86_64"))] +#[cfg(not(windows))] +#[allow(dead_code, non_camel_case_types)] +mod c_types { + pub(crate) type c_void = core::ffi::c_void; + // c_{,u}int is {i,u}32 on non-16-bit architectures + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/ffi/mod.rs#L147 + // (16-bit architectures currently don't use this module) + pub(crate) type c_int = i32; + pub(crate) type c_uint = u32; + // c_{,u}long is {i,u}64 on non-Windows 64-bit targets, otherwise is {i,u}32 + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/ffi/mod.rs#L159 + // (Windows currently doesn't use this module - this module is cfg(not(windows))) + #[cfg(target_pointer_width = "64")] + pub(crate) type c_long = i64; + #[cfg(not(target_pointer_width = "64"))] + pub(crate) type c_long = i32; + #[cfg(target_pointer_width = "64")] + pub(crate) type c_ulong = u64; + #[cfg(not(target_pointer_width = "64"))] + pub(crate) type c_ulong = u32; + // c_size_t is currently always usize + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/ffi/mod.rs#L67 + pub(crate) type c_size_t = usize; + // c_char is u8 by default on most non-Apple/non-Windows Arm/PowerPC/RISC-V/s390x/Hexagon targets + // (Linux/Android/FreeBSD/NetBSD/OpenBSD/VxWorks/Fuchsia/QNX Neutrino/Horizon/AIX/z/OS) + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/ffi/mod.rs#L83 + // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/lldb/source/Utility/ArchSpec.cpp#L712 + // RISC-V https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/draft-20240829-13bfa9f54634cb60d86b9b333e109f077805b4b3/riscv-cc.adoc#cc-type-representations + // Hexagon https://lists.llvm.org/pipermail/llvm-dev/attachments/20190916/21516a52/attachment-0001.pdf + // AIX https://www.ibm.com/docs/en/xl-c-aix/13.1.3?topic=specifiers-character-types + // z/OS https://www.ibm.com/docs/en/zos/3.1.0?topic=specifiers-character-types + // (Windows currently doesn't use this module) + #[cfg(not(target_vendor = "apple"))] + pub(crate) type c_char = u8; + // c_char is i8 on all Apple targets + #[cfg(target_vendor = "apple")] + pub(crate) type c_char = i8; + + // Static assertions for C type definitions. + #[cfg(test)] + const _: fn() = || { + use test_helper::{libc, sys}; + let _: c_int = 0 as std::os::raw::c_int; + let _: c_uint = 0 as std::os::raw::c_uint; + let _: c_long = 0 as std::os::raw::c_long; + let _: c_ulong = 0 as std::os::raw::c_ulong; + let _: c_size_t = 0 as libc::size_t; // std::os::raw::c_size_t is unstable + #[cfg(not(any( + all(target_arch = "aarch64", target_os = "illumos"), // TODO: https://github.com/rust-lang/rust/issues/129945 + all(target_arch = "riscv64", target_os = "android"), // TODO: https://github.com/rust-lang/rust/issues/129945 + )))] + let _: c_char = 0 as std::os::raw::c_char; + let _: c_char = 0 as sys::c_char; + }; +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests_common { + use std::{collections::BTreeSet, vec}; + + use super::*; + + #[test] + fn test_bit_flags() { + let mut flags = vec![("init", CpuInfo::INIT)]; + flags.extend(CpuInfo::ALL_FLAGS.iter().map(|&(name, flag, _)| (name, flag))); + let flag_set = flags.iter().map(|(_, flag)| flag).collect::>(); + let name_set = flags.iter().map(|(_, flag)| flag).collect::>(); + if flag_set.len() != flags.len() { + panic!("CpuInfo flag values must be unique") + } + if name_set.len() != flags.len() { + panic!("CpuInfo flag names must be unique") + } + + let mut x = CpuInfo(0); + for &(_, f) in &flags { + assert!(!x.test(f)); + } + for i in 0..flags.len() { + x.set(flags[i].1); + for &(_, f) in &flags[..i + 1] { + assert!(x.test(f)); + } + for &(_, f) in &flags[i + 1..] { + assert!(!x.test(f)); + } + } + for &(_, f) in &flags { + assert!(x.test(f)); + } + } + + #[test] + fn print_features() { + use std::{ + fmt::Write as _, + io::{self, Write}, + string::String, + }; + + let mut features = String::new(); + features.push_str("\nfeatures:\n"); + for &(name, flag, compile_time) in CpuInfo::ALL_FLAGS { + let run_time = detect().test(flag); + if run_time == compile_time { + let _ = writeln!(features, " {}: {}", name, run_time); + } else { + let _ = writeln!( + features, + " {}: {} (compile-time), {} (run-time)", + name, compile_time, run_time + ); + } + } + let stdout = io::stderr(); + let mut stdout = stdout.lock(); + let _ = stdout.write_all(features.as_bytes()); + } + + #[cfg(any(target_arch = "aarch64", target_arch = "arm64ec"))] + #[test] + #[cfg_attr(portable_atomic_test_outline_atomics_detect_false, ignore)] + fn test_detect() { + let proc_cpuinfo = test_helper::cpuinfo::ProcCpuinfo::new(); + if detect().has_lse() { + assert!(detect().test(CpuInfo::HAS_LSE)); + if let Ok(proc_cpuinfo) = proc_cpuinfo { + assert!(proc_cpuinfo.lse); + } + } else { + assert!(!detect().test(CpuInfo::HAS_LSE)); + if let Ok(proc_cpuinfo) = proc_cpuinfo { + assert!(!proc_cpuinfo.lse); + } + } + if detect().has_lse2() { + assert!(detect().test(CpuInfo::HAS_LSE)); + assert!(detect().test(CpuInfo::HAS_LSE2)); + if let Ok(test_helper::cpuinfo::ProcCpuinfo { lse2: Some(lse2), .. }) = proc_cpuinfo { + assert!(lse2); + } + } else { + assert!(!detect().test(CpuInfo::HAS_LSE2)); + if let Ok(test_helper::cpuinfo::ProcCpuinfo { lse2: Some(lse2), .. }) = proc_cpuinfo { + assert!(!lse2); + } + } + if detect().has_lse128() { + assert!(detect().test(CpuInfo::HAS_LSE)); + assert!(detect().test(CpuInfo::HAS_LSE2)); + assert!(detect().test(CpuInfo::HAS_LSE128)); + if let Ok(test_helper::cpuinfo::ProcCpuinfo { lse128: Some(lse128), .. }) = proc_cpuinfo + { + assert!(lse128); + } + } else { + assert!(!detect().test(CpuInfo::HAS_LSE128)); + if let Ok(test_helper::cpuinfo::ProcCpuinfo { lse128: Some(lse128), .. }) = proc_cpuinfo + { + assert!(!lse128); + } + } + if detect().has_rcpc3() { + assert!(detect().test(CpuInfo::HAS_RCPC3)); + if let Ok(test_helper::cpuinfo::ProcCpuinfo { rcpc3: Some(rcpc3), .. }) = proc_cpuinfo { + assert!(rcpc3); + } + } else { + assert!(!detect().test(CpuInfo::HAS_RCPC3)); + if let Ok(test_helper::cpuinfo::ProcCpuinfo { rcpc3: Some(rcpc3), .. }) = proc_cpuinfo { + assert!(!rcpc3); + } + } + } + #[cfg(target_arch = "powerpc64")] + #[test] + #[cfg_attr(portable_atomic_test_outline_atomics_detect_false, ignore)] + fn test_detect() { + let proc_cpuinfo = test_helper::cpuinfo::ProcCpuinfo::new(); + if detect().has_quadword_atomics() { + assert!(detect().test(CpuInfo::HAS_QUADWORD_ATOMICS)); + if let Ok(proc_cpuinfo) = proc_cpuinfo { + assert!(proc_cpuinfo.power8); + } + } else { + assert!(!detect().test(CpuInfo::HAS_QUADWORD_ATOMICS)); + if let Ok(proc_cpuinfo) = proc_cpuinfo { + assert!(!proc_cpuinfo.power8); + } + } + } + #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] + #[test] + #[cfg_attr(portable_atomic_test_outline_atomics_detect_false, ignore)] + fn test_detect() { + if detect().has_zacas() { + assert!(detect().test(CpuInfo::HAS_ZACAS)); + } else { + assert!(!detect().test(CpuInfo::HAS_ZACAS)); + } + } + #[cfg(target_arch = "x86_64")] + #[test] + #[cfg_attr(portable_atomic_test_outline_atomics_detect_false, ignore)] + fn test_detect() { + if detect().has_cmpxchg16b() { + assert!(detect().test(CpuInfo::HAS_CMPXCHG16B)); + } else { + assert!(!detect().test(CpuInfo::HAS_CMPXCHG16B)); + } + if detect().has_vmovdqa_atomic() { + assert!(detect().test(CpuInfo::HAS_VMOVDQA_ATOMIC)); + } else { + assert!(!detect().test(CpuInfo::HAS_VMOVDQA_ATOMIC)); + } + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/riscv_linux.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/riscv_linux.rs new file mode 100644 index 0000000..355ccb1 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/riscv_linux.rs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on RISC-V Linux/Android by using riscv_hwprobe. + +On RISC-V, detection using auxv only supports single-letter extensions. +So, we use riscv_hwprobe that supports multi-letter extensions. + +Refs: https://github.com/torvalds/linux/blob/v6.11/Documentation/arch/riscv/hwprobe.rst +*/ + +include!("common.rs"); + +use core::ptr; + +// core::ffi::c_* (except c_void) requires Rust 1.64, libc will soon require Rust 1.47 +#[allow(non_camel_case_types, non_upper_case_globals)] +mod ffi { + pub(crate) use super::c_types::{c_long, c_size_t, c_uint, c_ulong}; + + // https://github.com/torvalds/linux/blob/v6.11/arch/riscv/include/uapi/asm/hwprobe.h + #[derive(Copy, Clone)] + #[cfg_attr(test, derive(Debug, PartialEq))] + #[repr(C)] + pub(crate) struct riscv_hwprobe { + pub(crate) key: i64, + pub(crate) value: u64, + } + + pub(crate) const __NR_riscv_hwprobe: c_long = 258; + + // https://github.com/torvalds/linux/blob/v6.11/arch/riscv/include/uapi/asm/hwprobe.h + pub(crate) const RISCV_HWPROBE_KEY_IMA_EXT_0: i64 = 4; + // Linux 6.8+ + // https://github.com/torvalds/linux/commit/154a3706122978eeb34d8223d49285ed4f3c61fa + pub(crate) const RISCV_HWPROBE_EXT_ZACAS: u64 = 1 << 34; + + #[cfg(not(all( + target_os = "linux", + any(target_arch = "riscv32", all(target_arch = "riscv64", target_pointer_width = "64")), + )))] + extern "C" { + // https://man7.org/linux/man-pages/man2/syscall.2.html + pub(crate) fn syscall(number: c_long, ...) -> c_long; + } + // Use asm-based syscall for compatibility with non-libc targets if possible. + #[cfg(all( + target_os = "linux", // https://github.com/bytecodealliance/rustix/issues/1095 + any(target_arch = "riscv32", all(target_arch = "riscv64", target_pointer_width = "64")), + ))] + #[inline] + pub(crate) unsafe fn syscall( + number: c_long, + a0: *mut riscv_hwprobe, + a1: c_size_t, + a2: c_size_t, + a3: *mut c_ulong, + a4: c_uint, + ) -> c_long { + // arguments must be extended to 64-bit if RV64 + let a4 = a4 as usize; + let r; + // SAFETY: the caller must uphold the safety contract. + // Refs: + // - https://github.com/bminor/musl/blob/v1.2.5/arch/riscv32/syscall_arch.h + // - https://github.com/bminor/musl/blob/v1.2.5/arch/riscv64/syscall_arch.h + unsafe { + core::arch::asm!( + "ecall", + in("a7") number, + inout("a0") a0 => r, + in("a1") a1, + in("a2") a2, + in("a3") a3, + in("a4") a4, + options(nostack, preserves_flags) + ); + } + r + } + + // https://github.com/torvalds/linux/blob/v6.11/Documentation/arch/riscv/hwprobe.rst + pub(crate) unsafe fn __riscv_hwprobe( + pairs: *mut riscv_hwprobe, + pair_count: c_size_t, + cpu_set_size: c_size_t, + cpus: *mut c_ulong, + flags: c_uint, + ) -> c_long { + // SAFETY: the caller must uphold the safety contract. + unsafe { syscall(__NR_riscv_hwprobe, pairs, pair_count, cpu_set_size, cpus, flags) } + } +} + +// syscall returns an unsupported error if riscv_hwprobe is not supported, +// so we can safely use this function on older versions of Linux. +fn riscv_hwprobe(out: &mut ffi::riscv_hwprobe) -> bool { + // SAFETY: We've passed the valid pointer and length, + // passing null ptr for cpus is safe because cpu_set_size is zero. + unsafe { ffi::__riscv_hwprobe(out, 1, 0, ptr::null_mut(), 0) == 0 } +} + +#[cold] +fn _detect(info: &mut CpuInfo) { + let mut out = ffi::riscv_hwprobe { key: ffi::RISCV_HWPROBE_KEY_IMA_EXT_0, value: 0 }; + if riscv_hwprobe(&mut out) && out.key != -1 { + let value = out.value; + if value & ffi::RISCV_HWPROBE_EXT_ZACAS != 0 { + info.set(CpuInfo::HAS_ZACAS); + } + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use super::*; + + // We use asm-based syscall for compatibility with non-libc targets. + // This test tests that our ones and libc::syscall returns the same result. + #[test] + fn test_linux_like() { + use test_helper::libc; + unsafe fn __libc_riscv_hwprobe( + pairs: *mut ffi::riscv_hwprobe, + pair_count: ffi::c_size_t, + cpu_set_size: ffi::c_size_t, + cpus: *mut ffi::c_ulong, + flags: ffi::c_uint, + ) -> ffi::c_long { + // SAFETY: the caller must uphold the safety contract. + unsafe { + libc::syscall(ffi::__NR_riscv_hwprobe, pairs, pair_count, cpu_set_size, cpus, flags) + } + } + fn libc_riscv_hwprobe(out: &mut ffi::riscv_hwprobe) -> bool { + unsafe { __libc_riscv_hwprobe(out, 1, 0, ptr::null_mut(), 0) == 0 } + } + let mut out = ffi::riscv_hwprobe { key: ffi::RISCV_HWPROBE_KEY_IMA_EXT_0, value: 0 }; + let mut libc_out = ffi::riscv_hwprobe { key: ffi::RISCV_HWPROBE_KEY_IMA_EXT_0, value: 0 }; + assert_eq!(riscv_hwprobe(&mut out), libc_riscv_hwprobe(&mut libc_out)); + assert_eq!(out, libc_out); + } + + // Static assertions for FFI bindings. + // This checks that FFI bindings defined in this crate, FFI bindings defined + // in libc, and FFI bindings generated for the platform's latest header file + // using bindgen have compatible signatures (or the same values if constants). + // Since this is static assertion, we can detect problems with + // `cargo check --tests --target ` run in CI (via TESTS=1 build.sh) + // without actually running tests on these platforms. + // See also tools/codegen/src/ffi.rs. + // TODO(codegen): auto-generate this test + #[allow( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::no_effect_underscore_binding + )] + const _: fn() = || { + use std::mem; + use test_helper::sys; + // TODO: syscall + // static_assert!(ffi::__NR_riscv_hwprobe == libc::__NR_riscv_hwprobe); // libc doesn't have this + static_assert!(ffi::__NR_riscv_hwprobe == sys::__NR_riscv_hwprobe as ffi::c_long); + // static_assert!(ffi::RISCV_HWPROBE_KEY_IMA_EXT_0 == libc::RISCV_HWPROBE_KEY_IMA_EXT_0); // libc doesn't have this + static_assert!(ffi::RISCV_HWPROBE_KEY_IMA_EXT_0 == sys::RISCV_HWPROBE_KEY_IMA_EXT_0 as i64); + // static_assert!(ffi::RISCV_HWPROBE_EXT_ZACAS == libc::RISCV_HWPROBE_EXT_ZACAS); // libc doesn't have this + static_assert!(ffi::RISCV_HWPROBE_EXT_ZACAS == sys::RISCV_HWPROBE_EXT_ZACAS); + // libc doesn't have this + // static_assert!( + // mem::size_of::() + // == mem::size_of::() + // ); + static_assert!( + mem::size_of::() == mem::size_of::() + ); + let ffi: ffi::riscv_hwprobe = unsafe { mem::zeroed() }; + let _ = sys::riscv_hwprobe { key: ffi.key, value: ffi.value }; + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/detect/x86_64.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/x86_64.rs new file mode 100644 index 0000000..c824baf --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/detect/x86_64.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Run-time CPU feature detection on x86_64 by using CPUID. + +Adapted from https://github.com/rust-lang/stdarch. +*/ + +#![cfg_attr(portable_atomic_sanitize_thread, allow(dead_code))] + +// Miri doesn't support inline assembly used in __cpuid: https://github.com/rust-lang/miri/issues/932 +// SGX doesn't support CPUID: https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/core_arch/src/x86/cpuid.rs#L102-L105 +#[cfg(any(target_env = "sgx", miri))] +compile_error!("internal error: this module is not supported on this environment"); + +include!("common.rs"); + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; +use core::arch::x86_64::CpuidResult; + +// Workaround for https://github.com/rust-lang/rust/issues/101346 +// It is not clear if our use cases are affected, but we implement this just in case. +// +// Refs: +// - https://www.felixcloutier.com/x86/cpuid +// - https://en.wikipedia.org/wiki/CPUID +// - https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/core_arch/src/x86/cpuid.rs +#[cfg(not(target_env = "sgx"))] +fn __cpuid(leaf: u32) -> CpuidResult { + let eax; + let mut ebx; + let ecx; + let edx; + // SAFETY: Calling `__cpuid`` is safe on all x86_64 CPUs except for SGX, + // which doesn't support `cpuid`. + // https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/core_arch/src/x86/cpuid.rs#L102-L109 + unsafe { + asm!( + "mov {ebx_tmp:r}, rbx", // save rbx which is reserved by LLVM + "cpuid", + "xchg {ebx_tmp:r}, rbx", // restore rbx + ebx_tmp = out(reg) ebx, + inout("eax") leaf => eax, + inout("ecx") 0 => ecx, + out("edx") edx, + options(nostack, preserves_flags), + ); + } + CpuidResult { eax, ebx, ecx, edx } +} + +// https://en.wikipedia.org/wiki/CPUID +const _VENDOR_ID_INTEL: [u8; 12] = *b"GenuineIntel"; // Intel +const _VENDOR_ID_INTEL2: [u8; 12] = *b"GenuineIotel"; // Intel https://github.com/InstLatx64/InstLatx64/commit/8fdd319884c67d2c6ec1ca0c595b42c1c4b8d803 +const _VENDOR_ID_AMD: [u8; 12] = *b"AuthenticAMD"; // AMD +const _VENDOR_ID_ZHAOXIN: [u8; 12] = *b" Shanghai "; // Zhaoxin +fn _vendor_id() -> [u8; 12] { + // https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/std_detect/src/detect/os/x86.rs#L40-L59 + let CpuidResult { ebx, ecx, edx, .. } = __cpuid(0); + let vendor_id: [[u8; 4]; 3] = [ebx.to_ne_bytes(), edx.to_ne_bytes(), ecx.to_ne_bytes()]; + // SAFETY: transmute is safe because `[u8; 12]` and `[[u8; 4]; 3]` has the same layout. + unsafe { core::mem::transmute(vendor_id) } +} +fn _vendor_has_vmovdqa_atomic(vendor_id: [u8; 12]) -> bool { + // VMOVDQA is atomic on Intel, AMD, and Zhaoxin CPUs with AVX. + // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104688 for details. + vendor_id == _VENDOR_ID_INTEL + || vendor_id == _VENDOR_ID_INTEL2 + || vendor_id == _VENDOR_ID_AMD + || vendor_id == _VENDOR_ID_ZHAOXIN +} + +#[cold] +fn _detect(info: &mut CpuInfo) { + let proc_info_ecx = __cpuid(0x0000_0001_u32).ecx; + + // https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/std_detect/src/detect/os/x86.rs#L111 + if test(proc_info_ecx, 13) { + info.set(CpuInfo::HAS_CMPXCHG16B); + } + + // We only use VMOVDQA when SSE is enabled. See atomic_load_vmovdqa() in atomic128/x86_64.rs for more. + #[cfg(target_feature = "sse")] + { + use core::arch::x86_64::_xgetbv; + + // https://github.com/rust-lang/stdarch/blob/a0c30f3e3c75adcd6ee7efc94014ebcead61c507/crates/std_detect/src/detect/os/x86.rs#L131-L224 + let cpu_xsave = test(proc_info_ecx, 26); + if cpu_xsave { + let cpu_osxsave = test(proc_info_ecx, 27); + if cpu_osxsave { + // SAFETY: Calling `_xgetbv`` is safe because the CPU has `xsave` support + // and OS has set `osxsave`. + let xcr0 = unsafe { _xgetbv(0) }; + let os_avx_support = xcr0 & 6 == 6; + if os_avx_support && test(proc_info_ecx, 28) { + let vendor_id = _vendor_id(); + if _vendor_has_vmovdqa_atomic(vendor_id) { + info.set(CpuInfo::HAS_VMOVDQA_ATOMIC); + } + } + } + } + } +} + +#[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] +#[cfg(test)] +mod tests { + use std::io::{self, Write}; + + use super::*; + + #[test] + #[cfg_attr(portable_atomic_test_outline_atomics_detect_false, ignore)] + fn test_cpuid() { + assert_eq!(std::is_x86_feature_detected!("cmpxchg16b"), detect().has_cmpxchg16b()); + let vendor_id = _vendor_id(); + { + let stdout = io::stderr(); + let mut stdout = stdout.lock(); + let _ = writeln!(stdout, "\n vendor_id: {}", std::str::from_utf8(&vendor_id).unwrap()); + } + if _vendor_has_vmovdqa_atomic(vendor_id) { + assert_eq!(std::is_x86_feature_detected!("avx"), detect().has_vmovdqa_atomic()); + } else { + assert!(!detect().has_vmovdqa_atomic()); + } + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/mod.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/mod.rs new file mode 100644 index 0000000..1baaf5d --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/mod.rs @@ -0,0 +1,451 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Fallback implementation using global locks. + +This implementation uses seqlock for global locks. + +This is basically based on global locks in crossbeam-utils's `AtomicCell`, +but seqlock is implemented in a way that does not depend on UB +(see comments in optimistic_read method in atomic! macro for details). + +Note that we cannot use a lock per atomic type, since the in-memory representation of the atomic +type and the value type must be the same. +*/ + +#![cfg_attr( + any( + all( + target_arch = "x86_64", + not(portable_atomic_no_outline_atomics), + not(any(target_env = "sgx", miri)), + ), + all( + target_arch = "powerpc64", + feature = "fallback", + not(portable_atomic_no_outline_atomics), + portable_atomic_outline_atomics, // TODO(powerpc64): currently disabled by default + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + all(target_os = "openbsd", portable_atomic_outline_atomics), + ), + not(any(miri, portable_atomic_sanitize_thread)), + ), + all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + ), + ), + ), + all( + target_arch = "riscv64", + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), + ), + all( + target_arch = "arm", + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any(target_os = "linux", target_os = "android"), + not(portable_atomic_no_outline_atomics), + ), + ), + allow(dead_code) +)] + +#[macro_use] +pub(crate) mod utils; + +// Use "wide" sequence lock if the pointer width <= 32 for preventing its counter against wrap +// around. +// +// In narrow architectures (pointer width <= 16), the counter is still <= 32-bit and may be +// vulnerable to wrap around. But it's mostly okay, since in such a primitive hardware, the +// counter will not be increased that fast. +// +// Some 64-bit architectures have ABI with 32-bit pointer width (e.g., x86_64 X32 ABI, +// AArch64 ILP32 ABI, mips64 N32 ABI). On those targets, AtomicU64 is available and fast, +// so use it to implement normal sequence lock. +cfg_has_fast_atomic_64! { + mod seq_lock; +} +cfg_no_fast_atomic_64! { + #[path = "seq_lock_wide.rs"] + mod seq_lock; +} + +use core::{cell::UnsafeCell, mem, sync::atomic::Ordering}; + +use seq_lock::{SeqLock, SeqLockWriteGuard}; +use utils::CachePadded; + +// Some 64-bit architectures have ABI with 32-bit pointer width (e.g., x86_64 X32 ABI, +// AArch64 ILP32 ABI, mips64 N32 ABI). On those targets, AtomicU64 is fast, +// so use it to reduce chunks of byte-wise atomic memcpy. +use seq_lock::{AtomicChunk, Chunk}; + +// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.7/crossbeam-utils/src/atomic/atomic_cell.rs#L969-L1016. +#[inline] +#[must_use] +fn lock(addr: usize) -> &'static SeqLock { + // The number of locks is a prime number because we want to make sure `addr % LEN` gets + // dispersed across all locks. + // + // crossbeam-utils 0.8.7 uses 97 here but does not use CachePadded, + // so the actual concurrency level will be smaller. + const LEN: usize = 67; + const L: CachePadded = CachePadded::new(SeqLock::new()); + static LOCKS: [CachePadded; LEN] = [ + L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, + L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, + L, L, L, L, L, L, L, + ]; + + // If the modulus is a constant number, the compiler will use crazy math to transform this into + // a sequence of cheap arithmetic operations rather than using the slow modulo instruction. + &LOCKS[addr % LEN] +} + +macro_rules! atomic { + ($atomic_type:ident, $int_type:ident, $align:literal) => { + #[repr(C, align($align))] + pub(crate) struct $atomic_type { + v: UnsafeCell<$int_type>, + } + + impl $atomic_type { + const LEN: usize = mem::size_of::<$int_type>() / mem::size_of::(); + + #[inline] + unsafe fn chunks(&self) -> &[AtomicChunk; Self::LEN] { + static_assert!($atomic_type::LEN > 1); + static_assert!(mem::size_of::<$int_type>() % mem::size_of::() == 0); + + // SAFETY: the caller must uphold the safety contract for `chunks`. + unsafe { &*(self.v.get() as *const $int_type as *const [AtomicChunk; Self::LEN]) } + } + + #[inline] + fn optimistic_read(&self) -> $int_type { + // Using `MaybeUninit<[usize; Self::LEN]>` here doesn't change codegen: https://godbolt.org/z/86f8s733M + let mut dst: [Chunk; Self::LEN] = [0; Self::LEN]; + // SAFETY: + // - There are no threads that perform non-atomic concurrent write operations. + // - There is no writer that updates the value using atomic operations of different granularity. + // + // If the atomic operation is not used here, it will cause a data race + // when `write` performs concurrent write operation. + // Such a data race is sometimes considered virtually unproblematic + // in SeqLock implementations: + // + // - https://github.com/Amanieu/seqlock/issues/2 + // - https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.7/crossbeam-utils/src/atomic/atomic_cell.rs#L1111-L1116 + // - https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/avoiding.20UB.20due.20to.20races.20by.20discarding.20result.3F + // + // However, in our use case, the implementation that loads/stores value as + // chunks of usize is enough fast and sound, so we use that implementation. + // + // See also atomic-memcpy crate, a generic implementation of this pattern: + // https://github.com/taiki-e/atomic-memcpy + let chunks = unsafe { self.chunks() }; + for i in 0..Self::LEN { + dst[i] = chunks[i].load(Ordering::Relaxed); + } + // SAFETY: integers are plain old data types so we can always transmute to them. + unsafe { mem::transmute::<[Chunk; Self::LEN], $int_type>(dst) } + } + + #[inline] + fn read(&self, _guard: &SeqLockWriteGuard<'static>) -> $int_type { + // This calls optimistic_read that can return teared value, but the resulting value + // is guaranteed not to be teared because we hold the lock to write. + self.optimistic_read() + } + + #[inline] + fn write(&self, val: $int_type, _guard: &SeqLockWriteGuard<'static>) { + // SAFETY: integers are plain old data types so we can always transmute them to arrays of integers. + let val = unsafe { mem::transmute::<$int_type, [Chunk; Self::LEN]>(val) }; + // SAFETY: + // - The guard guarantees that we hold the lock to write. + // - There are no threads that perform non-atomic concurrent read or write operations. + // + // See optimistic_read for the reason that atomic operations are used here. + let chunks = unsafe { self.chunks() }; + for i in 0..Self::LEN { + chunks[i].store(val[i], Ordering::Relaxed); + } + } + } + + // Send is implicitly implemented. + // SAFETY: any data races are prevented by the lock and atomic operation. + unsafe impl Sync for $atomic_type {} + + impl_default_no_fetch_ops!($atomic_type, $int_type); + impl_default_bit_opts!($atomic_type, $int_type); + impl $atomic_type { + #[inline] + pub(crate) const fn new(v: $int_type) -> Self { + Self { v: UnsafeCell::new(v) } + } + + #[inline] + pub(crate) fn is_lock_free() -> bool { + Self::IS_ALWAYS_LOCK_FREE + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = false; + + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $int_type { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.v.get() } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn load(&self, order: Ordering) -> $int_type { + crate::utils::assert_load_ordering(order); + let lock = lock(self.v.get() as usize); + + // Try doing an optimistic read first. + if let Some(stamp) = lock.optimistic_read() { + let val = self.optimistic_read(); + + if lock.validate_read(stamp) { + return val; + } + } + + // Grab a regular write lock so that writers don't starve this load. + let guard = lock.write(); + let val = self.read(&guard); + // The value hasn't been changed. Drop the guard without incrementing the stamp. + guard.abort(); + val + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn store(&self, val: $int_type, order: Ordering) { + crate::utils::assert_store_ordering(order); + let guard = lock(self.v.get() as usize).write(); + self.write(val, &guard) + } + + #[inline] + pub(crate) fn swap(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(val, &guard); + prev + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + if prev == current { + self.write(new, &guard); + Ok(prev) + } else { + // The value hasn't been changed. Drop the guard without incrementing the stamp. + guard.abort(); + Err(prev) + } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + self.compare_exchange(current, new, success, failure) + } + + #[inline] + pub(crate) fn fetch_add(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(prev.wrapping_add(val), &guard); + prev + } + + #[inline] + pub(crate) fn fetch_sub(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(prev.wrapping_sub(val), &guard); + prev + } + + #[inline] + pub(crate) fn fetch_and(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(prev & val, &guard); + prev + } + + #[inline] + pub(crate) fn fetch_nand(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(!(prev & val), &guard); + prev + } + + #[inline] + pub(crate) fn fetch_or(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(prev | val, &guard); + prev + } + + #[inline] + pub(crate) fn fetch_xor(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(prev ^ val, &guard); + prev + } + + #[inline] + pub(crate) fn fetch_max(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(core::cmp::max(prev, val), &guard); + prev + } + + #[inline] + pub(crate) fn fetch_min(&self, val: $int_type, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(core::cmp::min(prev, val), &guard); + prev + } + + #[inline] + pub(crate) fn fetch_not(&self, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(!prev, &guard); + prev + } + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + + #[inline] + pub(crate) fn fetch_neg(&self, _order: Ordering) -> $int_type { + let guard = lock(self.v.get() as usize).write(); + let prev = self.read(&guard); + self.write(prev.wrapping_neg(), &guard); + prev + } + #[inline] + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } + + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut $int_type { + self.v.get() + } + } + }; +} + +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(any(test, portable_atomic_no_atomic_64)))] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any( + test, + not(any( + target_has_atomic = "64", + all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ), + ), + )) + )) +)] +cfg_no_fast_atomic_64! { + atomic!(AtomicI64, i64, 8); + atomic!(AtomicU64, u64, 8); +} + +atomic!(AtomicI128, i128, 16); +atomic!(AtomicU128, u128, 16); + +#[cfg(test)] +mod tests { + use super::*; + + cfg_no_fast_atomic_64! { + test_atomic_int!(i64); + test_atomic_int!(u64); + } + test_atomic_int!(i128); + test_atomic_int!(u128); + + // load/store/swap implementation is not affected by signedness, so it is + // enough to test only unsigned types. + cfg_no_fast_atomic_64! { + stress_test!(u64); + } + stress_test!(u128); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/outline_atomics.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/outline_atomics.rs new file mode 100644 index 0000000..5a47301 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/outline_atomics.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Helper for outline-atomics. + +On architectures where DW atomics are not supported on older CPUs, we use +fallback implementation when DW atomic instructions are not supported and +outline-atomics is enabled. + +This module provides helpers to implement them. +*/ + +use core::sync::atomic::Ordering; + +#[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", target_arch = "riscv64"))] +pub(crate) type Udw = u128; +#[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", target_arch = "riscv64"))] +pub(crate) type AtomicUdw = super::super::super::fallback::AtomicU128; +#[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", target_arch = "riscv64"))] +pub(crate) type AtomicIdw = super::super::super::fallback::AtomicI128; + +#[cfg(any(target_arch = "arm", target_arch = "riscv32"))] +pub(crate) type Udw = u64; +#[cfg(any(target_arch = "arm", target_arch = "riscv32"))] +pub(crate) type AtomicUdw = super::super::super::fallback::AtomicU64; +#[cfg(any(target_arch = "arm", target_arch = "riscv32"))] +pub(crate) type AtomicIdw = super::super::super::fallback::AtomicI64; + +// Asserts that the function is called in the correct context. +macro_rules! debug_assert_outline_atomics { + () => { + #[cfg(target_arch = "x86_64")] + { + debug_assert!(!super::detect::detect().has_cmpxchg16b()); + } + #[cfg(target_arch = "powerpc64")] + { + debug_assert!(!super::detect::detect().has_quadword_atomics()); + } + #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] + { + debug_assert!(!super::detect::detect().has_zacas()); + } + #[cfg(target_arch = "arm")] + { + debug_assert!(!super::has_kuser_cmpxchg64()); + } + }; +} + +#[cold] +pub(crate) unsafe fn atomic_load(src: *mut Udw, order: Ordering) -> Udw { + debug_assert_outline_atomics!(); + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + (*(src as *const AtomicUdw)).load(order) + } +} +fn_alias! { + #[cold] + pub(crate) unsafe fn(src: *mut Udw) -> Udw; + // fallback's atomic load has at least acquire semantics. + #[cfg(not(any(target_arch = "arm", target_arch = "x86_64")))] + atomic_load_non_seqcst = atomic_load(Ordering::Acquire); + atomic_load_seqcst = atomic_load(Ordering::SeqCst); +} + +#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] +#[cold] +pub(crate) unsafe fn atomic_store(dst: *mut Udw, val: Udw, order: Ordering) { + debug_assert_outline_atomics!(); + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + (*(dst as *const AtomicUdw)).store(val, order); + } +} +#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] +fn_alias! { + #[cold] + pub(crate) unsafe fn(dst: *mut Udw, val: Udw); + // fallback's atomic store has at least release semantics. + #[cfg(not(target_arch = "arm"))] + atomic_store_non_seqcst = atomic_store(Ordering::Release); + atomic_store_seqcst = atomic_store(Ordering::SeqCst); +} + +#[cold] +pub(crate) unsafe fn atomic_compare_exchange( + dst: *mut Udw, + old: Udw, + new: Udw, + success: Ordering, + failure: Ordering, +) -> (Udw, bool) { + debug_assert_outline_atomics!(); + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + match (*(dst as *const AtomicUdw)).compare_exchange(old, new, success, failure) { + Ok(v) => (v, true), + Err(v) => (v, false), + } + } +} +fn_alias! { + #[cold] + pub(crate) unsafe fn(dst: *mut Udw, old: Udw, new: Udw) -> (Udw, bool); + // fallback's atomic CAS has at least AcqRel semantics. + #[cfg(not(any(target_arch = "arm", target_arch = "x86_64")))] + atomic_compare_exchange_non_seqcst + = atomic_compare_exchange(Ordering::AcqRel, Ordering::Acquire); + atomic_compare_exchange_seqcst + = atomic_compare_exchange(Ordering::SeqCst, Ordering::SeqCst); +} + +macro_rules! atomic_rmw_3 { + ( + $name:ident($atomic_type:ident::$method_name:ident), + $non_seqcst_alias:ident, $seqcst_alias:ident + ) => { + #[cold] + pub(crate) unsafe fn $name(dst: *mut Udw, val: Udw, order: Ordering) -> Udw { + debug_assert_outline_atomics!(); + #[allow( + clippy::as_underscore, + clippy::cast_possible_wrap, + clippy::cast_ptr_alignment, + clippy::cast_sign_loss + )] + // SAFETY: the caller must uphold the safety contract. + unsafe { + (*(dst as *const $atomic_type)).$method_name(val as _, order) as Udw + } + } + fn_alias! { + #[cold] + pub(crate) unsafe fn(dst: *mut Udw, val: Udw) -> Udw; + // fallback's atomic RMW has at least AcqRel semantics. + #[cfg(not(any(target_arch = "arm", target_arch = "x86_64")))] + $non_seqcst_alias = $name(Ordering::AcqRel); + $seqcst_alias = $name(Ordering::SeqCst); + } + }; +} +macro_rules! atomic_rmw_2 { + ( + $name:ident($atomic_type:ident::$method_name:ident), + $non_seqcst_alias:ident, $seqcst_alias:ident + ) => { + #[cold] + pub(crate) unsafe fn $name(dst: *mut Udw, order: Ordering) -> Udw { + debug_assert_outline_atomics!(); + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: the caller must uphold the safety contract. + unsafe { + (*(dst as *const $atomic_type)).$method_name(order) as Udw + } + } + fn_alias! { + #[cold] + pub(crate) unsafe fn(dst: *mut Udw) -> Udw; + // fallback's atomic RMW has at least AcqRel semantics. + #[cfg(not(any(target_arch = "arm", target_arch = "x86_64")))] + $non_seqcst_alias = $name(Ordering::AcqRel); + $seqcst_alias = $name(Ordering::SeqCst); + } + }; +} + +atomic_rmw_3!(atomic_swap(AtomicUdw::swap), atomic_swap_non_seqcst, atomic_swap_seqcst); +atomic_rmw_3!(atomic_add(AtomicUdw::fetch_add), atomic_add_non_seqcst, atomic_add_seqcst); +atomic_rmw_3!(atomic_sub(AtomicUdw::fetch_sub), atomic_sub_non_seqcst, atomic_sub_seqcst); +atomic_rmw_3!(atomic_and(AtomicUdw::fetch_and), atomic_and_non_seqcst, atomic_and_seqcst); +atomic_rmw_3!(atomic_nand(AtomicUdw::fetch_nand), atomic_nand_non_seqcst, atomic_nand_seqcst); +atomic_rmw_3!(atomic_or(AtomicUdw::fetch_or), atomic_or_non_seqcst, atomic_or_seqcst); +atomic_rmw_3!(atomic_xor(AtomicUdw::fetch_xor), atomic_xor_non_seqcst, atomic_xor_seqcst); +atomic_rmw_3!(atomic_max(AtomicIdw::fetch_max), atomic_max_non_seqcst, atomic_max_seqcst); +atomic_rmw_3!(atomic_umax(AtomicUdw::fetch_max), atomic_umax_non_seqcst, atomic_umax_seqcst); +atomic_rmw_3!(atomic_min(AtomicIdw::fetch_min), atomic_min_non_seqcst, atomic_min_seqcst); +atomic_rmw_3!(atomic_umin(AtomicUdw::fetch_min), atomic_umin_non_seqcst, atomic_umin_seqcst); + +atomic_rmw_2!(atomic_not(AtomicUdw::fetch_not), atomic_not_non_seqcst, atomic_not_seqcst); +atomic_rmw_2!(atomic_neg(AtomicUdw::fetch_neg), atomic_neg_non_seqcst, atomic_neg_seqcst); diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock.rs new file mode 100644 index 0000000..fb6803f --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock.rs @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.7/crossbeam-utils/src/atomic/seq_lock.rs. + +use core::{ + mem::ManuallyDrop, + sync::atomic::{self, Ordering}, +}; + +use super::utils::Backoff; + +// See mod.rs for details. +#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] +pub(super) use core::sync::atomic::AtomicU64 as AtomicStamp; +#[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))] +pub(super) use core::sync::atomic::AtomicUsize as AtomicStamp; +#[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))] +pub(super) type Stamp = usize; +#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] +pub(super) type Stamp = u64; + +// See mod.rs for details. +pub(super) type AtomicChunk = AtomicStamp; +pub(super) type Chunk = Stamp; + +/// A simple stamped lock. +pub(super) struct SeqLock { + /// The current state of the lock. + /// + /// All bits except the least significant one hold the current stamp. When locked, the state + /// equals 1 and doesn't contain a valid stamp. + state: AtomicStamp, +} + +impl SeqLock { + #[inline] + pub(super) const fn new() -> Self { + Self { state: AtomicStamp::new(0) } + } + + /// If not locked, returns the current stamp. + /// + /// This method should be called before optimistic reads. + #[inline] + pub(super) fn optimistic_read(&self) -> Option { + let state = self.state.load(Ordering::Acquire); + if state == 1 { + None + } else { + Some(state) + } + } + + /// Returns `true` if the current stamp is equal to `stamp`. + /// + /// This method should be called after optimistic reads to check whether they are valid. The + /// argument `stamp` should correspond to the one returned by method `optimistic_read`. + #[inline] + pub(super) fn validate_read(&self, stamp: Stamp) -> bool { + atomic::fence(Ordering::Acquire); + self.state.load(Ordering::Relaxed) == stamp + } + + /// Grabs the lock for writing. + #[inline] + pub(super) fn write(&self) -> SeqLockWriteGuard<'_> { + let mut backoff = Backoff::new(); + loop { + let previous = self.state.swap(1, Ordering::Acquire); + + if previous != 1 { + atomic::fence(Ordering::Release); + + return SeqLockWriteGuard { lock: self, state: previous }; + } + + while self.state.load(Ordering::Relaxed) == 1 { + backoff.snooze(); + } + } + } +} + +/// An RAII guard that releases the lock and increments the stamp when dropped. +#[must_use] +pub(super) struct SeqLockWriteGuard<'a> { + /// The parent lock. + lock: &'a SeqLock, + + /// The stamp before locking. + state: Stamp, +} + +impl SeqLockWriteGuard<'_> { + /// Releases the lock without incrementing the stamp. + #[inline] + pub(super) fn abort(self) { + // We specifically don't want to call drop(), since that's + // what increments the stamp. + let this = ManuallyDrop::new(self); + + // Restore the stamp. + // + // Release ordering for synchronizing with `optimistic_read`. + this.lock.state.store(this.state, Ordering::Release); + } +} + +impl Drop for SeqLockWriteGuard<'_> { + #[inline] + fn drop(&mut self) { + // Release the lock and increment the stamp. + // + // Release ordering for synchronizing with `optimistic_read`. + self.lock.state.store(self.state.wrapping_add(2), Ordering::Release); + } +} + +#[cfg(test)] +mod tests { + use super::SeqLock; + + #[test] + fn smoke() { + let lock = SeqLock::new(); + let before = lock.optimistic_read().unwrap(); + assert!(lock.validate_read(before)); + { + let _guard = lock.write(); + } + assert!(!lock.validate_read(before)); + let after = lock.optimistic_read().unwrap(); + assert_ne!(before, after); + } + + #[test] + fn test_abort() { + let lock = SeqLock::new(); + let before = lock.optimistic_read().unwrap(); + { + let guard = lock.write(); + guard.abort(); + } + let after = lock.optimistic_read().unwrap(); + assert_eq!(before, after, "aborted write does not update the stamp"); + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock_wide.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock_wide.rs new file mode 100644 index 0000000..e12996f --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/seq_lock_wide.rs @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.7/crossbeam-utils/src/atomic/seq_lock_wide.rs. + +use core::{ + mem::ManuallyDrop, + sync::atomic::{self, AtomicUsize, Ordering}, +}; + +use super::utils::Backoff; + +// See mod.rs for details. +pub(super) type AtomicChunk = AtomicUsize; +pub(super) type Chunk = usize; + +/// A simple stamped lock. +/// +/// The state is represented as two `AtomicUsize`: `state_hi` for high bits and `state_lo` for low +/// bits. +pub(super) struct SeqLock { + /// The high bits of the current state of the lock. + state_hi: AtomicUsize, + + /// The low bits of the current state of the lock. + /// + /// All bits except the least significant one hold the current stamp. When locked, the state_lo + /// equals 1 and doesn't contain a valid stamp. + state_lo: AtomicUsize, +} + +impl SeqLock { + #[inline] + pub(super) const fn new() -> Self { + Self { state_hi: AtomicUsize::new(0), state_lo: AtomicUsize::new(0) } + } + + /// If not locked, returns the current stamp. + /// + /// This method should be called before optimistic reads. + #[inline] + pub(super) fn optimistic_read(&self) -> Option<(usize, usize)> { + // The acquire loads from `state_hi` and `state_lo` synchronize with the release stores in + // `SeqLockWriteGuard::drop` and `SeqLockWriteGuard::abort`. + // + // As a consequence, we can make sure that (1) all writes within the era of `state_hi - 1` + // happens before now; and therefore, (2) if `state_lo` is even, all writes within the + // critical section of (`state_hi`, `state_lo`) happens before now. + let state_hi = self.state_hi.load(Ordering::Acquire); + let state_lo = self.state_lo.load(Ordering::Acquire); + if state_lo == 1 { + None + } else { + Some((state_hi, state_lo)) + } + } + + /// Returns `true` if the current stamp is equal to `stamp`. + /// + /// This method should be called after optimistic reads to check whether they are valid. The + /// argument `stamp` should correspond to the one returned by method `optimistic_read`. + #[inline] + pub(super) fn validate_read(&self, stamp: (usize, usize)) -> bool { + // Thanks to the fence, if we're noticing any modification to the data at the critical + // section of `(stamp.0, stamp.1)`, then the critical section's write of 1 to state_lo should be + // visible. + atomic::fence(Ordering::Acquire); + + // So if `state_lo` coincides with `stamp.1`, then either (1) we're noticing no modification + // to the data after the critical section of `(stamp.0, stamp.1)`, or (2) `state_lo` wrapped + // around. + // + // If (2) is the case, the acquire ordering ensures we see the new value of `state_hi`. + let state_lo = self.state_lo.load(Ordering::Acquire); + + // If (2) is the case and `state_hi` coincides with `stamp.0`, then `state_hi` also wrapped + // around, which we give up to correctly validate the read. + let state_hi = self.state_hi.load(Ordering::Relaxed); + + // Except for the case that both `state_hi` and `state_lo` wrapped around, the following + // condition implies that we're noticing no modification to the data after the critical + // section of `(stamp.0, stamp.1)`. + (state_hi, state_lo) == stamp + } + + /// Grabs the lock for writing. + #[inline] + pub(super) fn write(&self) -> SeqLockWriteGuard<'_> { + let mut backoff = Backoff::new(); + loop { + let previous = self.state_lo.swap(1, Ordering::Acquire); + + if previous != 1 { + // To synchronize with the acquire fence in `validate_read` via any modification to + // the data at the critical section of `(state_hi, previous)`. + atomic::fence(Ordering::Release); + + return SeqLockWriteGuard { lock: self, state_lo: previous }; + } + + while self.state_lo.load(Ordering::Relaxed) == 1 { + backoff.snooze(); + } + } + } +} + +/// An RAII guard that releases the lock and increments the stamp when dropped. +#[must_use] +pub(super) struct SeqLockWriteGuard<'a> { + /// The parent lock. + lock: &'a SeqLock, + + /// The stamp before locking. + state_lo: usize, +} + +impl SeqLockWriteGuard<'_> { + /// Releases the lock without incrementing the stamp. + #[inline] + pub(super) fn abort(self) { + // We specifically don't want to call drop(), since that's + // what increments the stamp. + let this = ManuallyDrop::new(self); + + // Restore the stamp. + // + // Release ordering for synchronizing with `optimistic_read`. + this.lock.state_lo.store(this.state_lo, Ordering::Release); + } +} + +impl Drop for SeqLockWriteGuard<'_> { + #[inline] + fn drop(&mut self) { + let state_lo = self.state_lo.wrapping_add(2); + + // Increase the high bits if the low bits wrap around. + // + // Release ordering for synchronizing with `optimistic_read`. + if state_lo == 0 { + let state_hi = self.lock.state_hi.load(Ordering::Relaxed); + self.lock.state_hi.store(state_hi.wrapping_add(1), Ordering::Release); + } + + // Release the lock and increment the stamp. + // + // Release ordering for synchronizing with `optimistic_read`. + self.lock.state_lo.store(state_lo, Ordering::Release); + } +} + +#[cfg(test)] +mod tests { + use super::SeqLock; + + #[test] + fn smoke() { + let lock = SeqLock::new(); + let before = lock.optimistic_read().unwrap(); + assert!(lock.validate_read(before)); + { + let _guard = lock.write(); + } + assert!(!lock.validate_read(before)); + let after = lock.optimistic_read().unwrap(); + assert_ne!(before, after); + } + + #[test] + fn test_abort() { + let lock = SeqLock::new(); + let before = lock.optimistic_read().unwrap(); + { + let guard = lock.write(); + guard.abort(); + } + let after = lock.optimistic_read().unwrap(); + assert_eq!(before, after, "aborted write does not update the stamp"); + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/utils.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/utils.rs new file mode 100644 index 0000000..60fcc27 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/fallback/utils.rs @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use core::ops; + +// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/9384f1eb2b356364e201ad38545e03c837d55f3a/crossbeam-utils/src/cache_padded.rs. +/// Pads and aligns a value to the length of a cache line. +// Starting from Intel's Sandy Bridge, spatial prefetcher is now pulling pairs of 64-byte cache +// lines at a time, so we have to align to 128 bytes rather than 64. +// +// Sources: +// - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf +// - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107 +// +// ARM's big.LITTLE architecture has asymmetric cores and "big" cores have 128-byte cache line size. +// +// Sources: +// - https://www.mono-project.com/news/2016/09/12/arm64-icache/ +// +// powerpc64 has 128-byte cache line size. +// +// Sources: +// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9 +// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/powerpc/include/asm/cache.h#L26 +#[cfg_attr( + any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "powerpc64", + ), + repr(align(128)) +)] +// arm, mips, mips64, sparc, and hexagon have 32-byte cache line size. +// +// Sources: +// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7 +// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7 +// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7 +// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9 +// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L17 +// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/hexagon/include/asm/cache.h#L12 +#[cfg_attr( + any( + target_arch = "arm", + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "sparc", + target_arch = "hexagon", + ), + repr(align(32)) +)] +// m68k has 16-byte cache line size. +// +// Sources: +// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/m68k/include/asm/cache.h#L9 +#[cfg_attr(target_arch = "m68k", repr(align(16)))] +// s390x has 256-byte cache line size. +// +// Sources: +// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7 +// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/s390/include/asm/cache.h#L13 +#[cfg_attr(target_arch = "s390x", repr(align(256)))] +// x86, wasm, riscv, and sparc64 have 64-byte cache line size. +// +// Sources: +// - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9 +// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7 +// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/riscv/include/asm/cache.h#L10 +// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L19 +// +// All others are assumed to have 64-byte cache line size. +#[cfg_attr( + not(any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "powerpc64", + target_arch = "arm", + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "sparc", + target_arch = "hexagon", + target_arch = "m68k", + target_arch = "s390x", + )), + repr(align(64)) +)] +pub(crate) struct CachePadded { + value: T, +} + +impl CachePadded { + #[inline] + pub(crate) const fn new(value: T) -> Self { + Self { value } + } +} + +impl ops::Deref for CachePadded { + type Target = T; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.value + } +} + +// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.7/crossbeam-utils/src/backoff.rs. +// Adjusted to reduce spinning. +/// Performs exponential backoff in spin loops. +pub(crate) struct Backoff { + step: u32, +} + +// https://github.com/oneapi-src/oneTBB/blob/v2021.5.0/include/oneapi/tbb/detail/_utils.h#L46-L48 +const SPIN_LIMIT: u32 = 4; + +impl Backoff { + #[inline] + pub(crate) const fn new() -> Self { + Self { step: 0 } + } + + #[inline] + pub(crate) fn snooze(&mut self) { + if self.step <= SPIN_LIMIT { + for _ in 0..1 << self.step { + #[allow(deprecated)] + core::sync::atomic::spin_loop_hint(); + } + self.step += 1; + } else { + #[cfg(not(feature = "std"))] + for _ in 0..1 << self.step { + #[allow(deprecated)] + core::sync::atomic::spin_loop_hint(); + } + + #[cfg(feature = "std")] + std::thread::yield_now(); + } + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/float.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/float.rs new file mode 100644 index 0000000..50c202f --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/float.rs @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +AtomicF{32,64} implementation based on AtomicU{32,64}. + +This module provides atomic float implementations using atomic integer. + +Note that most of `fetch_*` operations of atomic floats are implemented using +CAS loops, which can be slower than equivalent operations of atomic integers. + +GPU targets have atomic instructions for float, so GPU targets will use +architecture-specific implementations instead of this implementation in the +future: https://github.com/taiki-e/portable-atomic/issues/34 / https://github.com/taiki-e/portable-atomic/pull/45 +*/ + +// TODO: fetch_{minimum,maximum}* https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3008r2.html + +#![cfg_attr( + all(target_pointer_width = "16", not(feature = "fallback")), + allow(unused_imports, unused_macros) +)] + +use core::{cell::UnsafeCell, sync::atomic::Ordering}; + +macro_rules! atomic_float { + ( + $atomic_type:ident, $float_type:ident, $atomic_int_type:ident, $int_type:ident, + $align:literal + ) => { + #[repr(C, align($align))] + pub(crate) struct $atomic_type { + v: UnsafeCell<$float_type>, + } + + // Send is implicitly implemented. + // SAFETY: any data races are prevented by atomic operations. + unsafe impl Sync for $atomic_type {} + + impl $atomic_type { + #[inline] + pub(crate) const fn new(v: $float_type) -> Self { + Self { v: UnsafeCell::new(v) } + } + + #[inline] + pub(crate) fn is_lock_free() -> bool { + crate::$atomic_int_type::is_lock_free() + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = + crate::$atomic_int_type::is_always_lock_free(); + + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $float_type { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.v.get() } + } + + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn load(&self, order: Ordering) -> $float_type { + $float_type::from_bits(self.as_bits().load(order)) + } + + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn store(&self, val: $float_type, order: Ordering) { + self.as_bits().store(val.to_bits(), order) + } + + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_raw_ptr_deref))]; + #[inline(always)] + pub(crate) const fn as_bits(&self) -> &crate::$atomic_int_type { + // SAFETY: $atomic_type and $atomic_int_type have the same layout, + // and there is no concurrent access to the value that does not go through this method. + unsafe { &*(self as *const Self as *const crate::$atomic_int_type) } + } + } + + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut $float_type { + self.v.get() + } + } + + cfg_has_atomic_cas_or_amo32! { + impl $atomic_type { + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn swap(&self, val: $float_type, order: Ordering) -> $float_type { + $float_type::from_bits(self.as_bits().swap(val.to_bits(), order)) + } + + cfg_has_atomic_cas! { + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange( + &self, + current: $float_type, + new: $float_type, + success: Ordering, + failure: Ordering, + ) -> Result<$float_type, $float_type> { + match self.as_bits().compare_exchange( + current.to_bits(), + new.to_bits(), + success, + failure, + ) { + Ok(v) => Ok($float_type::from_bits(v)), + Err(v) => Err($float_type::from_bits(v)), + } + } + + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub(crate) fn compare_exchange_weak( + &self, + current: $float_type, + new: $float_type, + success: Ordering, + failure: Ordering, + ) -> Result<$float_type, $float_type> { + match self.as_bits().compare_exchange_weak( + current.to_bits(), + new.to_bits(), + success, + failure, + ) { + Ok(v) => Ok($float_type::from_bits(v)), + Err(v) => Err($float_type::from_bits(v)), + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_add(&self, val: $float_type, order: Ordering) -> $float_type { + self.fetch_update_(order, |x| x + val) + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_sub(&self, val: $float_type, order: Ordering) -> $float_type { + self.fetch_update_(order, |x| x - val) + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + fn fetch_update_(&self, order: Ordering, mut f: F) -> $float_type + where + F: FnMut($float_type) -> $float_type, + { + // This is a private function and all instances of `f` only operate on the value + // loaded, so there is no need to synchronize the first load/failed CAS. + let mut prev = self.load(Ordering::Relaxed); + loop { + let next = f(prev); + match self.compare_exchange_weak(prev, next, order, Ordering::Relaxed) { + Ok(x) => return x, + Err(next_prev) => prev = next_prev, + } + } + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_max(&self, val: $float_type, order: Ordering) -> $float_type { + self.fetch_update_(order, |x| x.max(val)) + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_min(&self, val: $float_type, order: Ordering) -> $float_type { + self.fetch_update_(order, |x| x.min(val)) + } + } // cfg_has_atomic_cas! + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_neg(&self, order: Ordering) -> $float_type { + const NEG_MASK: $int_type = !0 / 2 + 1; + $float_type::from_bits(self.as_bits().fetch_xor(NEG_MASK, order)) + } + + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn fetch_abs(&self, order: Ordering) -> $float_type { + const ABS_MASK: $int_type = !0 / 2; + $float_type::from_bits(self.as_bits().fetch_and(ABS_MASK, order)) + } + } + } // cfg_has_atomic_cas_or_amo32! + }; +} + +cfg_has_atomic_32! { + atomic_float!(AtomicF32, f32, AtomicU32, u32, 4); +} +cfg_has_atomic_64! { + atomic_float!(AtomicF64, f64, AtomicU64, u64, 8); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/README.md b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/README.md new file mode 100644 index 0000000..bf47179 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/README.md @@ -0,0 +1,35 @@ +# Implementation of disabling interrupts + +This module is used to provide atomic CAS for targets where atomic CAS is not available in the standard library. + +- On MSP430 and AVR, they are always single-core and has no unprivileged mode, so this module is always used. +- On Armv6-M (thumbv6m), pre-v6 Arm (e.g., thumbv4t, thumbv5te), RISC-V without A-extension, and Xtensa, they could be multi-core, so this module is used when the `unsafe-assume-single-core` feature (or `portable_atomic_unsafe_assume_single_core` cfg) is enabled. + +The `unsafe-assume-single-core` implementation uses privileged instructions to disable interrupts, so it usually doesn't work on unprivileged mode. +Enabling this feature in an environment where privileged instructions are not available, or if the instructions used are not sufficient to disable interrupts in the system, it is also usually considered **unsound**, although the details are system-dependent. + +Consider using the [`critical-section` feature](../../../README.md#optional-features-critical-section) for systems that cannot use the `unsafe-assume-single-core` feature (or `portable_atomic_unsafe_assume_single_core` cfg). + +For some targets, the implementation can be changed by explicitly enabling features. + +- On Armv6-M, this disables interrupts by modifying the PRIMASK register. +- On pre-v6 Arm, this disables interrupts by modifying the I (IRQ mask) bit of the CPSR. +- On pre-v6 Arm with the `disable-fiq` feature (or `portable_atomic_disable_fiq` cfg), this disables interrupts by modifying the I (IRQ mask) bit and F (FIQ mask) bit of the CPSR. +- On RISC-V (without A-extension), this disables interrupts by modifying the MIE (Machine Interrupt Enable) bit of the `mstatus` register. +- On RISC-V (without A-extension) with the `s-mode` feature (or `portable_atomic_s_mode` cfg), this disables interrupts by modifying the SIE (Supervisor Interrupt Enable) bit of the `sstatus` register. +- On RISC-V (without A-extension) with the `zaamo` target feature (or `force-amo` feature or `portable_atomic_force_amo` cfg), this uses AMO instructions for RMWs that have corresponding AMO instructions even if A-extension is disabled. For other RMWs, this disables interrupts as usual. +- On MSP430, this disables interrupts by modifying the GIE (Global Interrupt Enable) bit of the status register (SR). +- On AVR, this disables interrupts by modifying the I (Global Interrupt Enable) bit of the status register (SREG). +- On Xtensa, this disables interrupts by modifying the PS special register. + +Some operations don't require disabling interrupts: + +- On architectures except for AVR: loads and stores with pointer size or smaller +- On MSP430 additionally: {8,16}-bit `add,sub,and,or,xor,not` +- On RISC-V with the `zaamo` target feature (or `portable_atomic_target_feature="zaamo"` cfg or `force-amo` feature or `portable_atomic_force_amo` cfg) additionally: 32-bit(RV32)/{32,64}-bit(RV64) `swap,fetch_{add,sub,and,or,xor,not,max,min},add,sub,and,or,xor,not`, {8,16}-bit `fetch_{and,or,xor,not},and,or,xor,not`[^1], and all operations of `AtomicBool` + +However, when the `critical-section` feature is enabled, critical sections are taken for all atomic operations. + +Feel free to submit an issue if your target is not supported yet. + +[^1]: With the `zabha` target feature, {8,16}-bit `swap,fetch_{add,sub,max,min},add,sub` too. diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv4t.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv4t.rs new file mode 100644 index 0000000..afd1188 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv4t.rs @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Refs: https://developer.arm.com/documentation/ddi0406/cb/System-Level-Architecture/The-System-Level-Programmers--Model/ARM-processor-modes-and-ARM-core-registers/Program-Status-Registers--PSRs- + +Generated asm: +- armv5te https://godbolt.org/z/fhaW3d9Kv +*/ + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; + +// - 0x80 - I (IRQ mask) bit (1 << 7) +// - 0x40 - F (FIQ mask) bit (1 << 6) +// We disable only IRQs by default. See also https://github.com/taiki-e/portable-atomic/pull/28#issuecomment-1214146912. +#[cfg(not(portable_atomic_disable_fiq))] +macro_rules! mask { + () => { + "0x80" + }; +} +#[cfg(portable_atomic_disable_fiq)] +macro_rules! mask { + () => { + "0xC0" // 0x80 | 0x40 + }; +} + +pub(super) type State = u32; + +/// Disables interrupts and returns the previous interrupt state. +#[inline] +#[instruction_set(arm::a32)] +pub(super) fn disable() -> State { + let cpsr: State; + // SAFETY: reading CPSR and disabling interrupts are safe. + // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions) + unsafe { + asm!( + "mrs {prev}, cpsr", + concat!("orr {new}, {prev}, ", mask!()), + "msr cpsr_c, {new}", + prev = out(reg) cpsr, + new = out(reg) _, + // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled. + options(nostack, preserves_flags), + ); + } + cpsr +} + +/// Restores the previous interrupt state. +/// +/// # Safety +/// +/// The state must be the one retrieved by the previous `disable`. +#[inline] +#[instruction_set(arm::a32)] +pub(super) unsafe fn restore(cpsr: State) { + // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`, + // + // This clobbers the control field mask byte of CPSR. See msp430.rs to safety on this. + // (preserves_flags is fine because we only clobber the I, F, T, and M bits of CPSR.) + // + // Refs: https://developer.arm.com/documentation/dui0473/m/arm-and-thumb-instructions/msr--general-purpose-register-to-psr- + unsafe { + // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled. + asm!("msr cpsr_c, {0}", in(reg) cpsr, options(nostack, preserves_flags)); + } +} + +// On pre-v6 Arm, we cannot use core::sync::atomic here because they call the +// `__sync_*` builtins for non-relaxed load/store (because pre-v6 Arm doesn't +// have Data Memory Barrier). +// +// Generated asm: +// - armv5te https://godbolt.org/z/Th3z1jevK +pub(crate) mod atomic { + #[cfg(not(portable_atomic_no_asm))] + use core::arch::asm; + use core::{cell::UnsafeCell, sync::atomic::Ordering}; + + macro_rules! atomic { + ($([$($generics:tt)*])? $atomic_type:ident, $value_type:ty, $asm_suffix:tt) => { + #[repr(transparent)] + pub(crate) struct $atomic_type $(<$($generics)*>)? { + v: UnsafeCell<$value_type>, + } + + // Send is implicitly implemented for atomic integers, but not for atomic pointers. + // SAFETY: any data races are prevented by atomic operations. + unsafe impl $(<$($generics)*>)? Send for $atomic_type $(<$($generics)*>)? {} + // SAFETY: any data races are prevented by atomic operations. + unsafe impl $(<$($generics)*>)? Sync for $atomic_type $(<$($generics)*>)? {} + + impl $(<$($generics)*>)? $atomic_type $(<$($generics)*>)? { + #[inline] + pub(crate) fn load(&self, _order: Ordering) -> $value_type { + let src = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + let out; + // inline asm without nomem/readonly implies compiler fence. + // And compiler fence is fine because the user explicitly declares that + // the system is single-core by using an unsafe cfg. + asm!( + concat!("ldr", $asm_suffix, " {out}, [{src}]"), + src = in(reg) src, + out = lateout(reg) out, + options(nostack, preserves_flags), + ); + out + } + } + + #[inline] + pub(crate) fn store(&self, val: $value_type, _order: Ordering) { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + // inline asm without nomem/readonly implies compiler fence. + // And compiler fence is fine because the user explicitly declares that + // the system is single-core by using an unsafe cfg. + asm!( + concat!("str", $asm_suffix, " {val}, [{dst}]"), + dst = in(reg) dst, + val = in(reg) val, + options(nostack, preserves_flags), + ); + } + } + } + }; + } + + atomic!(AtomicI8, i8, "b"); + atomic!(AtomicU8, u8, "b"); + atomic!(AtomicI16, i16, "h"); + atomic!(AtomicU16, u16, "h"); + atomic!(AtomicI32, i32, ""); + atomic!(AtomicU32, u32, ""); + atomic!(AtomicIsize, isize, ""); + atomic!(AtomicUsize, usize, ""); + atomic!([T] AtomicPtr, *mut T, ""); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv6m.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv6m.rs new file mode 100644 index 0000000..bf53dac --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/armv6m.rs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Adapted from https://github.com/rust-embedded/cortex-m. + +Generated asm: +- armv6-m https://godbolt.org/z/1sqKnsY6n +*/ + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; + +pub(super) use core::sync::atomic; + +pub(super) type State = u32; + +/// Disables interrupts and returns the previous interrupt state. +#[inline(always)] +pub(super) fn disable() -> State { + let r: State; + // SAFETY: reading the priority mask register and disabling interrupts are safe. + // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions) + unsafe { + // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled. + asm!( + "mrs {0}, PRIMASK", + "cpsid i", + out(reg) r, + options(nostack, preserves_flags), + ); + } + r +} + +/// Restores the previous interrupt state. +/// +/// # Safety +/// +/// The state must be the one retrieved by the previous `disable`. +#[inline(always)] +pub(super) unsafe fn restore(r: State) { + if r & 0x1 == 0 { + // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`, + // and we've checked that interrupts were enabled before disabling interrupts. + unsafe { + // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled. + asm!("cpsie i", options(nostack, preserves_flags)); + } + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/avr.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/avr.rs new file mode 100644 index 0000000..7463463 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/avr.rs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Adapted from https://github.com/Rahix/avr-device. + +Refs: +- AVR Instruction Set Manual https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-InstructionSet-Manual-DS40002198.pdf +*/ + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; + +pub(super) type State = u8; + +/// Disables interrupts and returns the previous interrupt state. +#[inline(always)] +pub(super) fn disable() -> State { + let sreg: State; + // SAFETY: reading the status register (SREG) and disabling interrupts are safe. + // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions) + unsafe { + // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled. + // Do not use `preserves_flags` because CLI modifies the I bit of the status register (SREG). + // Refs: https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-InstructionSet-Manual-DS40002198.pdf#page=58 + #[cfg(not(portable_atomic_no_asm))] + asm!( + "in {0}, 0x3F", + "cli", + out(reg) sreg, + options(nostack), + ); + #[cfg(portable_atomic_no_asm)] + { + llvm_asm!("in $0, 0x3F" : "=r"(sreg) ::: "volatile"); + llvm_asm!("cli" ::: "memory" : "volatile"); + } + } + sreg +} + +/// Restores the previous interrupt state. +/// +/// # Safety +/// +/// The state must be the one retrieved by the previous `disable`. +#[inline(always)] +pub(super) unsafe fn restore(sreg: State) { + // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`, + unsafe { + // This clobbers the entire status register. See msp430.rs to safety on this. + // + // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled. + // Do not use `preserves_flags` because OUT modifies the status register (SREG). + #[cfg(not(portable_atomic_no_asm))] + asm!("out 0x3F, {0}", in(reg) sreg, options(nostack)); + #[cfg(portable_atomic_no_asm)] + llvm_asm!("out 0x3F, $0" :: "r"(sreg) : "memory" : "volatile"); + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/mod.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/mod.rs new file mode 100644 index 0000000..521a387 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/mod.rs @@ -0,0 +1,922 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Critical section based fallback implementations + +This module supports two different critical section implementations: +- Built-in "disable all interrupts". +- Call into the `critical-section` crate (which allows the user to plug any implementation). + +The `critical-section`-based fallback is enabled when the user asks for it with the `critical-section` +Cargo feature. + +The "disable interrupts" fallback is not sound on multi-core systems. +Also, this uses privileged instructions to disable interrupts, so it usually +doesn't work on unprivileged mode. Using this fallback in an environment where privileged +instructions are not available is also usually considered **unsound**, +although the details are system-dependent. + +Therefore, this implementation will only be enabled in one of the following cases: + +- When the user explicitly declares that the system is single-core and that + privileged instructions are available using an unsafe cfg. +- When we can safely assume that the system is single-core and that + privileged instructions are available on the system. + +AVR, which is single core[^avr1] and LLVM also generates code that disables +interrupts [^avr2] in atomic ops by default, is considered the latter. +MSP430 as well. + +See also README.md of this directory. + +[^avr1]: https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/AVR/AVRExpandPseudoInsts.cpp#L1074 +[^avr2]: https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/test/CodeGen/AVR/atomics/load16.ll#L5 +*/ + +// On some platforms, atomic load/store can be implemented in a more efficient +// way than disabling interrupts. On MSP430, some RMWs that do not return the +// previous value can also be optimized. +// +// Note: On single-core systems, it is okay to use critical session-based +// CAS together with atomic load/store. The load/store will not be +// called while interrupts are disabled, and since the load/store is +// atomic, it is not affected by interrupts even if interrupts are enabled. +#[cfg(not(any(target_arch = "avr", feature = "critical-section")))] +use arch::atomic; + +#[cfg(not(feature = "critical-section"))] +#[cfg_attr( + all( + target_arch = "arm", + any(target_feature = "mclass", portable_atomic_target_feature = "mclass"), + ), + path = "armv6m.rs" +)] +#[cfg_attr( + all( + target_arch = "arm", + not(any(target_feature = "mclass", portable_atomic_target_feature = "mclass")), + ), + path = "armv4t.rs" +)] +#[cfg_attr(target_arch = "avr", path = "avr.rs")] +#[cfg_attr(target_arch = "msp430", path = "msp430.rs")] +#[cfg_attr(any(target_arch = "riscv32", target_arch = "riscv64"), path = "riscv.rs")] +#[cfg_attr(target_arch = "xtensa", path = "xtensa.rs")] +mod arch; + +use core::{cell::UnsafeCell, sync::atomic::Ordering}; + +// Critical section implementations might use locks internally. +#[cfg(feature = "critical-section")] +const IS_ALWAYS_LOCK_FREE: bool = false; +// Consider atomic operations based on disabling interrupts on single-core +// systems are lock-free. (We consider the pre-v6 Arm Linux's atomic operations +// provided in a similar way by the Linux kernel to be lock-free.) +#[cfg(not(feature = "critical-section"))] +const IS_ALWAYS_LOCK_FREE: bool = true; + +#[cfg(feature = "critical-section")] +#[inline] +fn with(f: F) -> R +where + F: FnOnce() -> R, +{ + critical_section::with(|_| f()) +} +#[cfg(not(feature = "critical-section"))] +#[inline(always)] +fn with(f: F) -> R +where + F: FnOnce() -> R, +{ + // Get current interrupt state and disable interrupts + let state = arch::disable(); + + let r = f(); + + // Restore interrupt state + // SAFETY: the state was retrieved by the previous `disable`. + unsafe { arch::restore(state) } + + r +} + +#[cfg_attr(target_pointer_width = "16", repr(C, align(2)))] +#[cfg_attr(target_pointer_width = "32", repr(C, align(4)))] +#[cfg_attr(target_pointer_width = "64", repr(C, align(8)))] +#[cfg_attr(target_pointer_width = "128", repr(C, align(16)))] +pub(crate) struct AtomicPtr { + p: UnsafeCell<*mut T>, +} + +// SAFETY: any data races are prevented by disabling interrupts or +// atomic intrinsics (see module-level comments). +unsafe impl Send for AtomicPtr {} +// SAFETY: any data races are prevented by disabling interrupts or +// atomic intrinsics (see module-level comments). +unsafe impl Sync for AtomicPtr {} + +impl AtomicPtr { + #[inline] + pub(crate) const fn new(p: *mut T) -> Self { + Self { p: UnsafeCell::new(p) } + } + + #[inline] + pub(crate) fn is_lock_free() -> bool { + Self::IS_ALWAYS_LOCK_FREE + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = IS_ALWAYS_LOCK_FREE; + + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut *mut T { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.p.get() } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn load(&self, order: Ordering) -> *mut T { + crate::utils::assert_load_ordering(order); + #[cfg(not(any(target_arch = "avr", feature = "critical-section")))] + { + self.as_native().load(order) + } + #[cfg(any(target_arch = "avr", feature = "critical-section"))] + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { self.p.get().read() }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn store(&self, ptr: *mut T, order: Ordering) { + crate::utils::assert_store_ordering(order); + #[cfg(not(any(target_arch = "avr", feature = "critical-section")))] + { + self.as_native().store(ptr, order); + } + #[cfg(any(target_arch = "avr", feature = "critical-section"))] + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { self.p.get().write(ptr) }); + } + + #[inline] + pub(crate) fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T { + let _ = order; + #[cfg(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + not(feature = "critical-section"), + any( + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ), + ))] + { + self.as_native().swap(ptr, order) + } + #[cfg(not(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + not(feature = "critical-section"), + any( + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ), + )))] + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.p.get().read(); + self.p.get().write(ptr); + prev + }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + crate::utils::assert_compare_exchange_ordering(success, failure); + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.p.get().read(); + if prev == current { + self.p.get().write(new); + Ok(prev) + } else { + Err(prev) + } + }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange_weak( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + self.compare_exchange(current, new, success, failure) + } + + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut *mut T { + self.p.get() + } + + #[cfg(not(any(target_arch = "avr", feature = "critical-section")))] + #[inline(always)] + fn as_native(&self) -> &atomic::AtomicPtr { + // SAFETY: AtomicPtr and atomic::AtomicPtr have the same layout and + // guarantee atomicity in a compatible way. (see module-level comments) + unsafe { &*(self as *const Self as *const atomic::AtomicPtr) } + } +} + +macro_rules! atomic_int { + (base, $atomic_type:ident, $int_type:ident, $align:literal) => { + #[repr(C, align($align))] + pub(crate) struct $atomic_type { + v: UnsafeCell<$int_type>, + } + + // Send is implicitly implemented. + // SAFETY: any data races are prevented by disabling interrupts or + // atomic intrinsics (see module-level comments). + unsafe impl Sync for $atomic_type {} + + impl $atomic_type { + #[inline] + pub(crate) const fn new(v: $int_type) -> Self { + Self { v: UnsafeCell::new(v) } + } + + #[inline] + pub(crate) fn is_lock_free() -> bool { + Self::IS_ALWAYS_LOCK_FREE + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = IS_ALWAYS_LOCK_FREE; + + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $int_type { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.v.get() } + } + + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut $int_type { + self.v.get() + } + } + }; + (load_store_atomic $([$kind:ident])?, $atomic_type:ident, $int_type:ident, $align:literal) => { + atomic_int!(base, $atomic_type, $int_type, $align); + #[cfg(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + not(feature = "critical-section"), + any( + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ), + ))] + atomic_int!(cas $([$kind])?, $atomic_type, $int_type); + #[cfg(not(all( + any(target_arch = "riscv32", target_arch = "riscv64"), + not(feature = "critical-section"), + any( + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ), + )))] + atomic_int!(cas[emulate], $atomic_type, $int_type); + impl $atomic_type { + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn load(&self, order: Ordering) -> $int_type { + crate::utils::assert_load_ordering(order); + #[cfg(not(any(target_arch = "avr", feature = "critical-section")))] + { + self.as_native().load(order) + } + #[cfg(any(target_arch = "avr", feature = "critical-section"))] + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { self.v.get().read() }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn store(&self, val: $int_type, order: Ordering) { + crate::utils::assert_store_ordering(order); + #[cfg(not(any(target_arch = "avr", feature = "critical-section")))] + { + self.as_native().store(val, order); + } + #[cfg(any(target_arch = "avr", feature = "critical-section"))] + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { self.v.get().write(val) }); + } + + #[cfg(not(any(target_arch = "avr", feature = "critical-section")))] + #[inline(always)] + fn as_native(&self) -> &atomic::$atomic_type { + // SAFETY: $atomic_type and atomic::$atomic_type have the same layout and + // guarantee atomicity in a compatible way. (see module-level comments) + unsafe { &*(self as *const Self as *const atomic::$atomic_type) } + } + } + + #[cfg(not(all(target_arch = "msp430", not(feature = "critical-section"))))] + impl_default_no_fetch_ops!($atomic_type, $int_type); + impl_default_bit_opts!($atomic_type, $int_type); + #[cfg(not(all(target_arch = "msp430", not(feature = "critical-section"))))] + impl $atomic_type { + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + } + #[cfg(all(target_arch = "msp430", not(feature = "critical-section")))] + impl $atomic_type { + #[inline] + pub(crate) fn add(&self, val: $int_type, order: Ordering) { + self.as_native().add(val, order); + } + #[inline] + pub(crate) fn sub(&self, val: $int_type, order: Ordering) { + self.as_native().sub(val, order); + } + #[inline] + pub(crate) fn and(&self, val: $int_type, order: Ordering) { + self.as_native().and(val, order); + } + #[inline] + pub(crate) fn or(&self, val: $int_type, order: Ordering) { + self.as_native().or(val, order); + } + #[inline] + pub(crate) fn xor(&self, val: $int_type, order: Ordering) { + self.as_native().xor(val, order); + } + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.as_native().not(order); + } + } + }; + (all_critical_session, $atomic_type:ident, $int_type:ident, $align:literal) => { + atomic_int!(base, $atomic_type, $int_type, $align); + atomic_int!(cas[emulate], $atomic_type, $int_type); + impl_default_no_fetch_ops!($atomic_type, $int_type); + impl_default_bit_opts!($atomic_type, $int_type); + impl $atomic_type { + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn load(&self, order: Ordering) -> $int_type { + crate::utils::assert_load_ordering(order); + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { self.v.get().read() }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn store(&self, val: $int_type, order: Ordering) { + crate::utils::assert_store_ordering(order); + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { self.v.get().write(val) }); + } + + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + } + }; + (cas[emulate], $atomic_type:ident, $int_type:ident) => { + impl $atomic_type { + #[inline] + pub(crate) fn swap(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(val); + prev + }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + if prev == current { + self.v.get().write(new); + Ok(prev) + } else { + Err(prev) + } + }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + self.compare_exchange(current, new, success, failure) + } + + #[inline] + pub(crate) fn fetch_add(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev.wrapping_add(val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_sub(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev.wrapping_sub(val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_and(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev & val); + prev + }) + } + + #[inline] + pub(crate) fn fetch_nand(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(!(prev & val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_or(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev | val); + prev + }) + } + + #[inline] + pub(crate) fn fetch_xor(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev ^ val); + prev + }) + } + + #[inline] + pub(crate) fn fetch_max(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(core::cmp::max(prev, val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_min(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(core::cmp::min(prev, val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_not(&self, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(!prev); + prev + }) + } + + #[inline] + pub(crate) fn fetch_neg(&self, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev.wrapping_neg()); + prev + }) + } + #[inline] + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } + } + }; + // RISC-V 32-bit(RV32)/{32,64}-bit(RV64) RMW with Zaamo extension + // RISC-V 8-bit/16-bit RMW with Zabha extension + (cas, $atomic_type:ident, $int_type:ident) => { + impl $atomic_type { + #[inline] + pub(crate) fn swap(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().swap(val, order) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + if prev == current { + self.v.get().write(new); + Ok(prev) + } else { + Err(prev) + } + }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + self.compare_exchange(current, new, success, failure) + } + + #[inline] + pub(crate) fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_add(val, order) + } + #[inline] + pub(crate) fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_sub(val, order) + } + #[inline] + pub(crate) fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_and(val, order) + } + + #[inline] + pub(crate) fn fetch_nand(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(!(prev & val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_or(val, order) + } + #[inline] + pub(crate) fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_xor(val, order) + } + #[inline] + pub(crate) fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_max(val, order) + } + #[inline] + pub(crate) fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_min(val, order) + } + #[inline] + pub(crate) fn fetch_not(&self, order: Ordering) -> $int_type { + self.as_native().fetch_not(order) + } + + #[inline] + pub(crate) fn fetch_neg(&self, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev.wrapping_neg()); + prev + }) + } + #[inline] + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } + } + }; + // RISC-V 8-bit/16-bit RMW with Zaamo extension + (cas[sub_word], $atomic_type:ident, $int_type:ident) => { + #[cfg(any(target_feature = "zabha", portable_atomic_target_feature = "zabha"))] + atomic_int!(cas, $atomic_type, $int_type); + #[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] + impl $atomic_type { + #[inline] + pub(crate) fn swap(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(val); + prev + }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + crate::utils::assert_compare_exchange_ordering(success, failure); + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + if prev == current { + self.v.get().write(new); + Ok(prev) + } else { + Err(prev) + } + }) + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + self.compare_exchange(current, new, success, failure) + } + + #[inline] + pub(crate) fn fetch_add(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev.wrapping_add(val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_sub(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev.wrapping_sub(val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_and(val, order) + } + + #[inline] + pub(crate) fn fetch_nand(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(!(prev & val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_or(val, order) + } + #[inline] + pub(crate) fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { + self.as_native().fetch_xor(val, order) + } + + #[inline] + pub(crate) fn fetch_max(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(core::cmp::max(prev, val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_min(&self, val: $int_type, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(core::cmp::min(prev, val)); + prev + }) + } + + #[inline] + pub(crate) fn fetch_not(&self, order: Ordering) -> $int_type { + self.as_native().fetch_not(order) + } + + #[inline] + pub(crate) fn fetch_neg(&self, _order: Ordering) -> $int_type { + // SAFETY: any data races are prevented by disabling interrupts (see + // module-level comments) and the raw pointer is valid because we got it + // from a reference. + with(|| unsafe { + let prev = self.v.get().read(); + self.v.get().write(prev.wrapping_neg()); + prev + }) + } + #[inline] + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } + } + }; +} + +#[cfg(target_pointer_width = "16")] +atomic_int!(load_store_atomic, AtomicIsize, isize, 2); +#[cfg(target_pointer_width = "16")] +atomic_int!(load_store_atomic, AtomicUsize, usize, 2); +#[cfg(target_pointer_width = "32")] +atomic_int!(load_store_atomic, AtomicIsize, isize, 4); +#[cfg(target_pointer_width = "32")] +atomic_int!(load_store_atomic, AtomicUsize, usize, 4); +#[cfg(target_pointer_width = "64")] +atomic_int!(load_store_atomic, AtomicIsize, isize, 8); +#[cfg(target_pointer_width = "64")] +atomic_int!(load_store_atomic, AtomicUsize, usize, 8); +#[cfg(target_pointer_width = "128")] +atomic_int!(load_store_atomic, AtomicIsize, isize, 16); +#[cfg(target_pointer_width = "128")] +atomic_int!(load_store_atomic, AtomicUsize, usize, 16); + +atomic_int!(load_store_atomic[sub_word], AtomicI8, i8, 1); +atomic_int!(load_store_atomic[sub_word], AtomicU8, u8, 1); +atomic_int!(load_store_atomic[sub_word], AtomicI16, i16, 2); +atomic_int!(load_store_atomic[sub_word], AtomicU16, u16, 2); + +#[cfg(not(target_pointer_width = "16"))] +atomic_int!(load_store_atomic, AtomicI32, i32, 4); +#[cfg(not(target_pointer_width = "16"))] +atomic_int!(load_store_atomic, AtomicU32, u32, 4); +#[cfg(target_pointer_width = "16")] +#[cfg(any(test, feature = "fallback"))] +atomic_int!(all_critical_session, AtomicI32, i32, 4); +#[cfg(target_pointer_width = "16")] +#[cfg(any(test, feature = "fallback"))] +atomic_int!(all_critical_session, AtomicU32, u32, 4); + +cfg_has_fast_atomic_64! { + atomic_int!(load_store_atomic, AtomicI64, i64, 8); + atomic_int!(load_store_atomic, AtomicU64, u64, 8); +} +#[cfg(any(test, feature = "fallback"))] +cfg_no_fast_atomic_64! { + atomic_int!(all_critical_session, AtomicI64, i64, 8); + atomic_int!(all_critical_session, AtomicU64, u64, 8); +} + +#[cfg(any(test, feature = "fallback"))] +atomic_int!(all_critical_session, AtomicI128, i128, 16); +#[cfg(any(test, feature = "fallback"))] +atomic_int!(all_critical_session, AtomicU128, u128, 16); + +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_ptr_single_thread!(); + test_atomic_int_single_thread!(i8); + test_atomic_int_single_thread!(u8); + test_atomic_int_single_thread!(i16); + test_atomic_int_single_thread!(u16); + test_atomic_int_single_thread!(i32); + test_atomic_int_single_thread!(u32); + test_atomic_int_single_thread!(i64); + test_atomic_int_single_thread!(u64); + test_atomic_int_single_thread!(i128); + test_atomic_int_single_thread!(u128); + test_atomic_int_single_thread!(isize); + test_atomic_int_single_thread!(usize); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/msp430.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/msp430.rs new file mode 100644 index 0000000..e21fd86 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/msp430.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Adapted from https://github.com/rust-embedded/msp430. + +See also src/imp/msp430.rs. + +Refs: https://www.ti.com/lit/ug/slau208q/slau208q.pdf +*/ + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; + +pub(super) use super::super::msp430 as atomic; + +pub(super) type State = u16; + +/// Disables interrupts and returns the previous interrupt state. +#[inline(always)] +pub(super) fn disable() -> State { + let r: State; + // SAFETY: reading the status register and disabling interrupts are safe. + // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions) + unsafe { + // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled. + // Do not use `preserves_flags` because DINT modifies the GIE (global interrupt enable) bit of the status register. + #[cfg(not(portable_atomic_no_asm))] + asm!( + "mov R2, {0}", + "dint {{ nop", + out(reg) r, + options(nostack), + ); + #[cfg(portable_atomic_no_asm)] + { + llvm_asm!("mov R2, $0" : "=r"(r) ::: "volatile"); + llvm_asm!("dint { nop" ::: "memory" : "volatile"); + } + } + r +} + +/// Restores the previous interrupt state. +/// +/// # Safety +/// +/// The state must be the one retrieved by the previous `disable`. +#[inline(always)] +pub(super) unsafe fn restore(r: State) { + // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`, + unsafe { + // This clobbers the entire status register, but we never explicitly modify + // flags within a critical session, and the only flags that may be changed + // within a critical session are the arithmetic flags that are changed as + // a side effect of arithmetic operations, etc., which LLVM recognizes, + // so it is safe to clobber them here. + // See also the discussion at https://github.com/taiki-e/portable-atomic/pull/40. + // + // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled. + // Do not use `preserves_flags` because MOV modifies the status register. + #[cfg(not(portable_atomic_no_asm))] + asm!("nop {{ mov {0}, R2 {{ nop", in(reg) r, options(nostack)); + #[cfg(portable_atomic_no_asm)] + llvm_asm!("nop { mov $0, R2 { nop" :: "r"(r) : "memory" : "volatile"); + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/riscv.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/riscv.rs new file mode 100644 index 0000000..7e8475f --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/riscv.rs @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Refs: +- https://github.com/riscv/riscv-isa-manual/blob/riscv-isa-release-8b9dc50-2024-08-30/src/machine.adoc#machine-status-mstatus-and-mstatush-registers +- https://github.com/riscv/riscv-isa-manual/blob/riscv-isa-release-8b9dc50-2024-08-30/src/supervisor.adoc#supervisor-status-sstatus-register + +See also src/imp/riscv.rs. + +Generated asm: +- riscv64gc https://godbolt.org/z/zTrzT1Ee7 +*/ + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; + +pub(super) use super::super::riscv as atomic; + +// Status register +#[cfg(not(portable_atomic_s_mode))] +macro_rules! status { + () => { + "mstatus" + }; +} +#[cfg(portable_atomic_s_mode)] +macro_rules! status { + () => { + "sstatus" + }; +} + +// MIE (Machine Interrupt Enable) bit (1 << 3) +#[cfg(not(portable_atomic_s_mode))] +const MASK: State = 0x8; +#[cfg(not(portable_atomic_s_mode))] +macro_rules! mask { + () => { + "0x8" + }; +} +// SIE (Supervisor Interrupt Enable) bit (1 << 1) +#[cfg(portable_atomic_s_mode)] +const MASK: State = 0x2; +#[cfg(portable_atomic_s_mode)] +macro_rules! mask { + () => { + "0x2" + }; +} + +#[cfg(target_arch = "riscv32")] +pub(super) type State = u32; +#[cfg(target_arch = "riscv64")] +pub(super) type State = u64; + +/// Disables interrupts and returns the previous interrupt state. +#[inline(always)] +pub(super) fn disable() -> State { + let r: State; + // SAFETY: reading mstatus and disabling interrupts is safe. + // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions) + unsafe { + // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled. + asm!(concat!("csrrci {0}, ", status!(), ", ", mask!()), out(reg) r, options(nostack, preserves_flags)); + } + r +} + +/// Restores the previous interrupt state. +/// +/// # Safety +/// +/// The state must be the one retrieved by the previous `disable`. +#[inline(always)] +pub(super) unsafe fn restore(r: State) { + if r & MASK != 0 { + // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`, + // and we've checked that interrupts were enabled before disabling interrupts. + unsafe { + // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled. + asm!(concat!("csrsi ", status!(), ", ", mask!()), options(nostack, preserves_flags)); + } + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/xtensa.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/xtensa.rs new file mode 100644 index 0000000..8003a64 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/interrupt/xtensa.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Refs: +- Xtensa Instruction Set Architecture (ISA) Reference Manual https://0x04.net/~mwk/doc/xtensa.pdf +- Linux kernel's Xtensa atomic implementation https://github.com/torvalds/linux/blob/v6.11/arch/xtensa/include/asm/atomic.h +*/ + +use core::arch::asm; + +pub(super) use core::sync::atomic; + +pub(super) type State = u32; + +/// Disables interrupts and returns the previous interrupt state. +#[inline(always)] +pub(super) fn disable() -> State { + let r: State; + // SAFETY: reading the PS special register and disabling all interrupts is safe. + // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions) + unsafe { + // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled. + // Interrupt level 15 to disable all interrupts. + // SYNC after RSIL is not required. + asm!("rsil {0}, 15", out(reg) r, options(nostack)); + } + r +} + +/// Restores the previous interrupt state. +/// +/// # Safety +/// +/// The state must be the one retrieved by the previous `disable`. +#[inline(always)] +pub(super) unsafe fn restore(r: State) { + // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`, + // and we've checked that interrupts were enabled before disabling interrupts. + unsafe { + // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled. + // SYNC after WSR is required to guarantee that subsequent RSIL read the written value. + asm!( + "wsr.ps {0}", + "rsync", + in(reg) r, + options(nostack), + ); + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/mod.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/mod.rs new file mode 100644 index 0000000..326290d --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/mod.rs @@ -0,0 +1,477 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// ----------------------------------------------------------------------------- +// Lock-free implementations + +#[cfg(not(any( + all( + portable_atomic_no_atomic_load_store, + not(all(target_arch = "bpf", not(feature = "critical-section"))), + ), + target_arch = "avr", + target_arch = "msp430", +)))] +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(all( + any( + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + portable_atomic_unsafe_assume_single_core, + ), + portable_atomic_no_atomic_cas, + ))) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(not(all( + any( + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + portable_atomic_unsafe_assume_single_core, + ), + not(target_has_atomic = "ptr"), + ))) +)] +mod core_atomic; + +// MSP430 +#[cfg(target_arch = "msp430")] +pub(crate) mod msp430; + +// RISC-V without A-extension +#[cfg(any(test, not(feature = "critical-section")))] +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(any( + all(test, not(any(miri, portable_atomic_sanitize_thread))), + portable_atomic_no_atomic_cas, + )) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any( + all(test, not(any(miri, portable_atomic_sanitize_thread))), + not(target_has_atomic = "ptr"), + )) +)] +#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] +mod riscv; + +// x86-specific optimizations +// Miri and Sanitizer do not support inline assembly. +#[cfg(all( + any(target_arch = "x86", target_arch = "x86_64"), + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), +))] +mod x86; + +// 64-bit atomic implementations on 32-bit architectures +#[cfg(any(target_arch = "arm", target_arch = "riscv32"))] +mod atomic64; + +// 128-bit atomic implementations on 64-bit architectures +#[cfg(any( + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "x86_64", +))] +mod atomic128; + +// ----------------------------------------------------------------------------- +// Lock-based fallback implementations + +#[cfg(feature = "fallback")] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(not(portable_atomic_no_atomic_cas)))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(target_has_atomic = "ptr"))] +#[cfg(any( + test, + not(any( + all( + target_arch = "aarch64", + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + ), + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch), + all( + target_arch = "x86_64", + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"), + ), + all( + target_arch = "riscv64", + not(portable_atomic_no_asm), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ), + ), + all( + target_arch = "powerpc64", + portable_atomic_unstable_asm_experimental_arch, + any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + ), + ), + all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch), + )) +))] +mod fallback; + +// ----------------------------------------------------------------------------- +// Critical section based fallback implementations + +// On AVR, we always use critical section based fallback implementation. +// AVR can be safely assumed to be single-core, so this is sound. +// https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/AVR/AVRExpandPseudoInsts.cpp#L1074 +// MSP430 as well. +#[cfg(any( + all(test, target_os = "none"), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", +))] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(any(test, portable_atomic_no_atomic_cas)))] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any(test, not(target_has_atomic = "ptr"))) +)] +#[cfg(any( + target_arch = "arm", + target_arch = "avr", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + target_arch = "xtensa", + feature = "critical-section", +))] +mod interrupt; + +// ----------------------------------------------------------------------------- +// Atomic float implementations + +#[cfg(feature = "float")] +#[allow(clippy::float_arithmetic)] +pub(crate) mod float; + +// ----------------------------------------------------------------------------- + +#[cfg(not(any( + portable_atomic_no_atomic_load_store, + target_arch = "avr", + target_arch = "msp430", +)))] +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(all( + any( + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + portable_atomic_unsafe_assume_single_core, + ), + portable_atomic_no_atomic_cas, + ))) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(not(all( + any( + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + portable_atomic_unsafe_assume_single_core, + ), + not(target_has_atomic = "ptr"), + ))) +)] +items! { + pub(crate) use self::core_atomic::{ + AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16, AtomicU32, AtomicU8, + AtomicUsize, + }; + #[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(any( + not(portable_atomic_no_atomic_64), + not(any(target_pointer_width = "16", target_pointer_width = "32")), + )) + )] + #[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(any( + target_has_atomic = "64", + not(any(target_pointer_width = "16", target_pointer_width = "32")), + )) + )] + pub(crate) use self::core_atomic::{AtomicI64, AtomicU64}; +} +// bpf +#[cfg(all( + target_arch = "bpf", + portable_atomic_no_atomic_load_store, + not(feature = "critical-section"), +))] +pub(crate) use self::core_atomic::{AtomicI64, AtomicIsize, AtomicPtr, AtomicU64, AtomicUsize}; + +// RISC-V without A-extension & !(assume single core | critical section) +#[cfg(not(any(portable_atomic_unsafe_assume_single_core, feature = "critical-section")))] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(portable_atomic_no_atomic_cas))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(not(target_has_atomic = "ptr")))] +#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] +items! { + pub(crate) use self::riscv::{ + AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16, AtomicU32, AtomicU8, + AtomicUsize, + }; + #[cfg(target_arch = "riscv64")] + pub(crate) use self::riscv::{AtomicI64, AtomicU64}; +} + +// no core atomic CAS & (assume single core | critical section) => critical section based fallback +#[cfg(any( + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", +))] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(portable_atomic_no_atomic_cas))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(not(target_has_atomic = "ptr")))] +items! { + pub(crate) use self::interrupt::{ + AtomicI16, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16, AtomicU8, AtomicUsize, + }; + #[cfg(any(not(target_pointer_width = "16"), feature = "fallback"))] + pub(crate) use self::interrupt::{AtomicI32, AtomicU32}; + #[cfg(any( + not(any(target_pointer_width = "16", target_pointer_width = "32")), + feature = "fallback", + ))] + pub(crate) use self::interrupt::{AtomicI64, AtomicU64}; + #[cfg(feature = "fallback")] + pub(crate) use self::interrupt::{AtomicI128, AtomicU128}; +} + +// no core (64-bit | 128-bit) atomic & has CAS => use lock-base fallback +#[cfg(feature = "fallback")] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(not(portable_atomic_no_atomic_cas)))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(target_has_atomic = "ptr"))] +items! { + #[cfg(not(any( + all( + target_arch = "arm", + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any(target_os = "linux", target_os = "android"), + not(any(target_feature = "v6", portable_atomic_target_feature = "v6")), + not(portable_atomic_no_outline_atomics), + ), + all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + ), + ), + ), + )))] + #[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(portable_atomic_no_atomic_64))] + #[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(not(target_has_atomic = "64")))] + pub(crate) use self::fallback::{AtomicI64, AtomicU64}; + #[cfg(not(any( + all( + target_arch = "aarch64", + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + ), + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch), + all( + target_arch = "x86_64", + not(all( + any(miri, portable_atomic_sanitize_thread), + portable_atomic_no_cmpxchg16b_intrinsic, + )), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + not(any(target_env = "sgx", miri)), + ), + ), + ), + all( + target_arch = "riscv64", + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), + ), + all( + target_arch = "powerpc64", + portable_atomic_unstable_asm_experimental_arch, + any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + portable_atomic_outline_atomics, // TODO(powerpc64): currently disabled by default + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + all(target_os = "openbsd", portable_atomic_outline_atomics), + ), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), + ), + all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch), + )))] + pub(crate) use self::fallback::{AtomicI128, AtomicU128}; +} + +// 64-bit atomics (platform-specific) +// pre-v6 Arm Linux +#[cfg(feature = "fallback")] +#[cfg(all( + target_arch = "arm", + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any(target_os = "linux", target_os = "android"), + not(any(target_feature = "v6", portable_atomic_target_feature = "v6")), + not(portable_atomic_no_outline_atomics), +))] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(portable_atomic_no_atomic_64))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(not(target_has_atomic = "64")))] +pub(crate) use self::atomic64::arm_linux::{AtomicI64, AtomicU64}; +#[cfg(all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + ), + ), +))] +pub(crate) use self::atomic64::riscv32::{AtomicI64, AtomicU64}; + +// 128-bit atomics (platform-specific) +// AArch64 +#[cfg(any( + all(target_arch = "aarch64", any(not(portable_atomic_no_asm), portable_atomic_unstable_asm)), + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch) +))] +pub(crate) use self::atomic128::aarch64::{AtomicI128, AtomicU128}; +// x86_64 & (cmpxchg16b | outline-atomics) +#[cfg(all( + target_arch = "x86_64", + not(all(any(miri, portable_atomic_sanitize_thread), portable_atomic_no_cmpxchg16b_intrinsic)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any( + target_feature = "cmpxchg16b", + portable_atomic_target_feature = "cmpxchg16b", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + not(any(target_env = "sgx", miri)), + ), + ), +))] +pub(crate) use self::atomic128::x86_64::{AtomicI128, AtomicU128}; +// riscv64 & zacas +#[cfg(all( + target_arch = "riscv64", + not(portable_atomic_no_asm), + not(portable_atomic_pre_llvm_19), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + any(test, portable_atomic_outline_atomics), // TODO(riscv): currently disabled by default + any(target_os = "linux", target_os = "android"), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), +))] +pub(crate) use self::atomic128::riscv64::{AtomicI128, AtomicU128}; +// powerpc64 & (pwr8 | outline-atomics) +#[cfg(all( + target_arch = "powerpc64", + portable_atomic_unstable_asm_experimental_arch, + any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + portable_atomic_outline_atomics, // TODO(powerpc64): currently disabled by default + any( + all( + target_os = "linux", + any( + target_env = "gnu", + all( + any(target_env = "musl", target_env = "ohos"), + not(target_feature = "crt-static"), + ), + portable_atomic_outline_atomics, + ), + ), + target_os = "android", + target_os = "freebsd", + all(target_os = "openbsd", portable_atomic_outline_atomics), + ), + not(any(miri, portable_atomic_sanitize_thread)), + ), + ), +))] +pub(crate) use self::atomic128::powerpc64::{AtomicI128, AtomicU128}; +// s390x +#[cfg(all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch))] +pub(crate) use self::atomic128::s390x::{AtomicI128, AtomicU128}; diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/msp430.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/msp430.rs new file mode 100644 index 0000000..ce658c9 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/msp430.rs @@ -0,0 +1,291 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Atomic load/store implementation on MSP430. + +Adapted from https://github.com/pftbest/msp430-atomic. + +Operations not supported here are provided by disabling interrupts. +See also src/imp/interrupt/msp430.rs. + +Note: Ordering is always SeqCst. + +Refs: https://www.ti.com/lit/ug/slau208q/slau208q.pdf +*/ + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; +#[cfg(any(test, not(feature = "critical-section")))] +use core::cell::UnsafeCell; +use core::sync::atomic::Ordering; + +/// An atomic fence. +/// +/// # Panics +/// +/// Panics if `order` is [`Relaxed`](Ordering::Relaxed). +#[inline] +#[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] +pub fn fence(order: Ordering) { + match order { + Ordering::Relaxed => panic!("there is no such thing as a relaxed fence"), + // MSP430 is single-core and a compiler fence works as an atomic fence. + _ => compiler_fence(order), + } +} + +/// A compiler memory fence. +/// +/// # Panics +/// +/// Panics if `order` is [`Relaxed`](Ordering::Relaxed). +#[inline] +#[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] +pub fn compiler_fence(order: Ordering) { + match order { + Ordering::Relaxed => panic!("there is no such thing as a relaxed compiler fence"), + _ => {} + } + // SAFETY: using an empty asm is safe. + unsafe { + // Do not use `nomem` and `readonly` because prevent preceding and subsequent memory accesses from being reordered. + #[cfg(not(portable_atomic_no_asm))] + asm!("", options(nostack, preserves_flags)); + #[cfg(portable_atomic_no_asm)] + llvm_asm!("" ::: "memory" : "volatile"); + } +} + +macro_rules! atomic { + (load_store, $([$($generics:tt)*])? $atomic_type:ident, $value_type:ty, $asm_suffix:tt) => { + #[cfg(any(test, not(feature = "critical-section")))] + #[repr(transparent)] + pub(crate) struct $atomic_type $(<$($generics)*>)? { + v: UnsafeCell<$value_type>, + } + + #[cfg(any(test, not(feature = "critical-section")))] + // Send is implicitly implemented for atomic integers, but not for atomic pointers. + // SAFETY: any data races are prevented by atomic operations. + unsafe impl $(<$($generics)*>)? Send for $atomic_type $(<$($generics)*>)? {} + #[cfg(any(test, not(feature = "critical-section")))] + // SAFETY: any data races are prevented by atomic operations. + unsafe impl $(<$($generics)*>)? Sync for $atomic_type $(<$($generics)*>)? {} + + #[cfg(any(test, not(feature = "critical-section")))] + impl $(<$($generics)*>)? $atomic_type $(<$($generics)*>)? { + #[cfg(test)] + #[inline] + pub(crate) const fn new(v: $value_type) -> Self { + Self { v: UnsafeCell::new(v) } + } + + #[cfg(test)] + #[inline] + pub(crate) fn is_lock_free() -> bool { + Self::IS_ALWAYS_LOCK_FREE + } + #[cfg(test)] + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = true; + + #[cfg(test)] + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $value_type { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.v.get() } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn load(&self, order: Ordering) -> $value_type { + crate::utils::assert_load_ordering(order); + let src = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + let out; + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("mov", $asm_suffix, " @{src}, {out}"), + src = in(reg) src, + out = lateout(reg) out, + options(nostack, preserves_flags), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("mov", $asm_suffix, " $1, $0") + : "=r"(out) : "*m"(src) : "memory" : "volatile" + ); + out + } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn store(&self, val: $value_type, order: Ordering) { + crate::utils::assert_store_ordering(order); + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("mov", $asm_suffix, " {val}, 0({dst})"), + dst = in(reg) dst, + val = in(reg) val, + options(nostack, preserves_flags), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("mov", $asm_suffix, " $1, $0") + :: "*m"(dst), "ir"(val) : "memory" : "volatile" + ); + } + } + } + }; + ($([$($generics:tt)*])? $atomic_type:ident, $value_type:ty, $asm_suffix:tt) => { + atomic!(load_store, $([$($generics)*])? $atomic_type, $value_type, $asm_suffix); + #[cfg(any(test, not(feature = "critical-section")))] + impl $(<$($generics)*>)? $atomic_type $(<$($generics)*>)? { + #[inline] + pub(crate) fn add(&self, val: $value_type, _order: Ordering) { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("add", $asm_suffix, " {val}, 0({dst})"), + dst = in(reg) dst, + val = in(reg) val, + // Do not use `preserves_flags` because ADD modifies the V, N, Z, and C bits of the status register. + options(nostack), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("add", $asm_suffix, " $1, $0") + :: "*m"(dst), "ir"(val) : "memory" : "volatile" + ); + } + } + + #[inline] + pub(crate) fn sub(&self, val: $value_type, _order: Ordering) { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("sub", $asm_suffix, " {val}, 0({dst})"), + dst = in(reg) dst, + val = in(reg) val, + // Do not use `preserves_flags` because SUB modifies the V, N, Z, and C bits of the status register. + options(nostack), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("sub", $asm_suffix, " $1, $0") + :: "*m"(dst), "ir"(val) : "memory" : "volatile" + ); + } + } + + #[inline] + pub(crate) fn and(&self, val: $value_type, _order: Ordering) { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("and", $asm_suffix, " {val}, 0({dst})"), + dst = in(reg) dst, + val = in(reg) val, + // Do not use `preserves_flags` because AND modifies the V, N, Z, and C bits of the status register. + options(nostack), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("and", $asm_suffix, " $1, $0") + :: "*m"(dst), "ir"(val) : "memory" : "volatile" + ); + } + } + + #[inline] + pub(crate) fn or(&self, val: $value_type, _order: Ordering) { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("bis", $asm_suffix, " {val}, 0({dst})"), + dst = in(reg) dst, + val = in(reg) val, + options(nostack, preserves_flags), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("bis", $asm_suffix, " $1, $0") + :: "*m"(dst), "ir"(val) : "memory" : "volatile" + ); + } + } + + #[inline] + pub(crate) fn xor(&self, val: $value_type, _order: Ordering) { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("xor", $asm_suffix, " {val}, 0({dst})"), + dst = in(reg) dst, + val = in(reg) val, + // Do not use `preserves_flags` because XOR modifies the V, N, Z, and C bits of the status register. + options(nostack), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("xor", $asm_suffix, " $1, $0") + :: "*m"(dst), "ir"(val) : "memory" : "volatile" + ); + } + } + + #[inline] + pub(crate) fn not(&self, _order: Ordering) { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + #[cfg(not(portable_atomic_no_asm))] + asm!( + concat!("inv", $asm_suffix, " 0({dst})"), + dst = in(reg) dst, + // Do not use `preserves_flags` because INV modifies the V, N, Z, and C bits of the status register. + options(nostack), + ); + #[cfg(portable_atomic_no_asm)] + llvm_asm!( + concat!("inv", $asm_suffix, " $0") + :: "*m"(dst) : "memory" : "volatile" + ); + } + } + } + } +} + +atomic!(AtomicI8, i8, ".b"); +atomic!(AtomicU8, u8, ".b"); +atomic!(AtomicI16, i16, ".w"); +atomic!(AtomicU16, u16, ".w"); +atomic!(AtomicIsize, isize, ".w"); +atomic!(AtomicUsize, usize, ".w"); +atomic!(load_store, [T] AtomicPtr, *mut T, ".w"); diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/riscv.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/riscv.rs new file mode 100644 index 0000000..8d4913c --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/riscv.rs @@ -0,0 +1,919 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Atomic load/store implementation on RISC-V. + +This is for RISC-V targets without atomic CAS. (rustc doesn't provide atomics +at all on such targets. https://github.com/rust-lang/rust/pull/114499) + +Also, optionally provides RMW implementation when force-amo or Zaamo target feature is enabled. + +Refs: +- RISC-V Instruction Set Manual + https://github.com/riscv/riscv-isa-manual/tree/riscv-isa-release-8b9dc50-2024-08-30 + "Zaamo" Extension for Atomic Memory Operations + https://github.com/riscv/riscv-isa-manual/blob/riscv-isa-release-8b9dc50-2024-08-30/src/a-st-ext.adoc#zaamo-extension-for-atomic-memory-operations + "Zabha" Extension for Byte and Halfword Atomic Memory Operations + https://github.com/riscv/riscv-isa-manual/blob/riscv-isa-release-8b9dc50-2024-08-30/src/zabha.adoc +- RISC-V Atomics ABI Specification + https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/draft-20240829-13bfa9f54634cb60d86b9b333e109f077805b4b3/riscv-atomic.adoc +- atomic-maybe-uninit https://github.com/taiki-e/atomic-maybe-uninit + +Generated asm: +- riscv64gc https://godbolt.org/z/q4fhcPEv4 +- riscv64gc (+zabha) https://godbolt.org/z/hde3ao7hx +- riscv32imac https://godbolt.org/z/7PKMx5KK3 +- riscv32imac (+zabha) https://godbolt.org/z/E1aTff9f7 +*/ + +// TODO: Zacas extension + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; +use core::{cell::UnsafeCell, sync::atomic::Ordering}; + +#[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", +))] +#[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] +#[cfg(target_arch = "riscv32")] +macro_rules! w { + () => { + "" + }; +} +#[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", +))] +#[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] +#[cfg(target_arch = "riscv64")] +macro_rules! w { + () => { + "w" + }; +} + +#[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", +))] +macro_rules! atomic_rmw_amo_ext { + ("w") => { + "+a" + }; + ("d") => { + "+a" + }; + ("b") => { + "+a,+zabha" + }; + ("h") => { + "+a,+zabha" + }; +} +#[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", +))] +macro_rules! atomic_rmw_amo { + ($op:ident, $dst:ident, $val:ident, $order:ident, $asm_suffix:tt) => {{ + let out; + macro_rules! op { + ($asm_order:tt) => { + // SAFETY: The user guaranteed that the AMO instruction is available in this + // system by setting the portable_atomic_force_amo/target_feature and + // portable_atomic_unsafe_assume_single_core. + // The caller of this macro must guarantee the validity of the pointer. + asm!( + ".option push", + // https://github.com/riscv-non-isa/riscv-asm-manual/blob/ad0de8c004e29c9a7ac33cfd054f4d4f9392f2fb/src/asm-manual.adoc#arch + // LLVM supports `.option arch` directive on LLVM 17+, so use .insn directive on old LLVM. + // https://github.com/llvm/llvm-project/commit/9e8ed3403c191ab9c4903e8eeb8f732ff8a43cb4 + // Note that `.insn ` directive requires LLVM 19. + // https://github.com/llvm/llvm-project/commit/2a086dce691e3cc34a2fc27f4fb255bb2cbbfac9 + concat!(".option arch, ", atomic_rmw_amo_ext!($asm_suffix)), + concat!("amo", stringify!($op), ".", $asm_suffix, $asm_order, " {out}, {val}, 0({dst})"), + ".option pop", + dst = in(reg) ptr_reg!($dst), + val = in(reg) $val, + out = lateout(reg) out, + options(nostack, preserves_flags), + ) + }; + } + match $order { + Ordering::Relaxed => op!(""), + Ordering::Acquire => op!(".aq"), + Ordering::Release => op!(".rl"), + // AcqRel and SeqCst RMWs are equivalent. + Ordering::AcqRel | Ordering::SeqCst => op!(".aqrl"), + _ => unreachable!(), + } + out + }}; +} +// 32-bit val.wrapping_shl(shift) but no extra `& (u32::BITS - 1)` +#[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", +))] +#[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] +#[inline(always)] +fn sllw(val: u32, shift: u32) -> u32 { + // SAFETY: Calling sll{,w} is safe. + unsafe { + let out; + asm!( + concat!("sll", w!(), " {out}, {val}, {shift}"), + out = lateout(reg) out, + val = in(reg) val, + shift = in(reg) shift, + options(pure, nomem, nostack, preserves_flags), + ); + out + } +} +// 32-bit val.wrapping_shr(shift) but no extra `& (u32::BITS - 1)` +#[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", +))] +#[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] +macro_rules! srlw { + ($val:expr, $shift:expr) => { + // SAFETY: Calling srl{,w} is safe. + unsafe { + let val: u32 = $val; + let shift: u32 = $shift; + let out; + asm!( + concat!("srl", w!(), " {out}, {val}, {shift}"), + out = lateout(reg) out, + val = in(reg) val, + shift = in(reg) shift, + options(pure, nomem, nostack, preserves_flags), + ); + out + } + }; +} + +macro_rules! atomic_load_store { + ($([$($generics:tt)*])? $atomic_type:ident, $value_type:ty, $asm_suffix:tt) => { + #[repr(transparent)] + pub(crate) struct $atomic_type $(<$($generics)*>)? { + v: UnsafeCell<$value_type>, + } + + // Send is implicitly implemented for atomic integers, but not for atomic pointers. + // SAFETY: any data races are prevented by atomic operations. + unsafe impl $(<$($generics)*>)? Send for $atomic_type $(<$($generics)*>)? {} + // SAFETY: any data races are prevented by atomic operations. + unsafe impl $(<$($generics)*>)? Sync for $atomic_type $(<$($generics)*>)? {} + + #[cfg(any(test, not(portable_atomic_unsafe_assume_single_core)))] + impl $(<$($generics)*>)? $atomic_type $(<$($generics)*>)? { + #[inline] + pub(crate) const fn new(v: $value_type) -> Self { + Self { v: UnsafeCell::new(v) } + } + + #[inline] + pub(crate) fn is_lock_free() -> bool { + Self::IS_ALWAYS_LOCK_FREE + } + pub(crate) const IS_ALWAYS_LOCK_FREE: bool = true; + + #[inline] + pub(crate) fn get_mut(&mut self) -> &mut $value_type { + // SAFETY: the mutable reference guarantees unique ownership. + // (UnsafeCell::get_mut requires Rust 1.50) + unsafe { &mut *self.v.get() } + } + + #[inline] + pub(crate) const fn as_ptr(&self) -> *mut $value_type { + self.v.get() + } + } + impl $(<$($generics)*>)? $atomic_type $(<$($generics)*>)? { + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn load(&self, order: Ordering) -> $value_type { + crate::utils::assert_load_ordering(order); + let src = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + let out; + macro_rules! atomic_load { + ($acquire:tt, $release:tt) => { + asm!( + $release, + concat!("l", $asm_suffix, " {out}, 0({src})"), + $acquire, + src = in(reg) ptr_reg!(src), + out = lateout(reg) out, + options(nostack, preserves_flags), + ) + }; + } + match order { + Ordering::Relaxed => atomic_load!("", ""), + Ordering::Acquire => atomic_load!("fence r, rw", ""), + Ordering::SeqCst => atomic_load!("fence r, rw", "fence rw, rw"), + _ => unreachable!(), + } + out + } + } + + #[inline] + #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] + pub(crate) fn store(&self, val: $value_type, order: Ordering) { + crate::utils::assert_store_ordering(order); + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + macro_rules! atomic_store { + ($acquire:tt, $release:tt) => { + asm!( + $release, + concat!("s", $asm_suffix, " {val}, 0({dst})"), + $acquire, + dst = in(reg) ptr_reg!(dst), + val = in(reg) val, + options(nostack, preserves_flags), + ) + }; + } + match order { + Ordering::Relaxed => atomic_store!("", ""), + Ordering::Release => atomic_store!("", "fence rw, w"), + // https://github.com/llvm/llvm-project/commit/3ea8f2526541884e03d5bd4f4e46f4eb190990b6 + Ordering::SeqCst => atomic_store!("fence rw, rw", "fence rw, w"), + _ => unreachable!(), + } + } + } + } + }; +} + +macro_rules! atomic_ptr { + ($([$($generics:tt)*])? $atomic_type:ident, $value_type:ty, $asm_suffix:tt) => { + atomic_load_store!($([$($generics)*])? $atomic_type, $value_type, $asm_suffix); + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + impl $(<$($generics)*>)? $atomic_type $(<$($generics)*>)? { + #[inline] + pub(crate) fn swap(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!(swap, dst, val, order, $asm_suffix) } + } + } + }; +} + +macro_rules! atomic { + ($atomic_type:ident, $value_type:ty, $asm_suffix:tt, $max:tt, $min:tt) => { + atomic_load_store!($atomic_type, $value_type, $asm_suffix); + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + #[cfg(not(any(portable_atomic_unsafe_assume_single_core, feature = "critical-section")))] + impl_default_no_fetch_ops!($atomic_type, $value_type); + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + #[cfg(not(any(portable_atomic_unsafe_assume_single_core, feature = "critical-section")))] + impl_default_bit_opts!($atomic_type, $value_type); + // There is no amo{sub,nand,neg}. + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + impl $atomic_type { + #[inline] + pub(crate) fn swap(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!(swap, dst, val, order, $asm_suffix) } + } + + #[inline] + pub(crate) fn fetch_add(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!(add, dst, val, order, $asm_suffix) } + } + + #[inline] + pub(crate) fn fetch_sub(&self, val: $value_type, order: Ordering) -> $value_type { + self.fetch_add(val.wrapping_neg(), order) + } + + #[inline] + pub(crate) fn fetch_and(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!(and, dst, val, order, $asm_suffix) } + } + + #[inline] + pub(crate) fn fetch_or(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!(or, dst, val, order, $asm_suffix) } + } + + #[inline] + pub(crate) fn fetch_xor(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!(xor, dst, val, order, $asm_suffix) } + } + + #[inline] + pub(crate) fn fetch_not(&self, order: Ordering) -> $value_type { + self.fetch_xor(!0, order) + } + #[cfg(not(any( + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + )))] + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + + #[inline] + pub(crate) fn fetch_max(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!($max, dst, val, order, $asm_suffix) } + } + + #[inline] + pub(crate) fn fetch_min(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { atomic_rmw_amo!($min, dst, val, order, $asm_suffix) } + } + } + }; +} + +#[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", +))] +#[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] +trait ZeroExtend: Copy { + /// Zero-extends `self` to `u32` if it is smaller than 32-bit. + fn zero_extend(self) -> u32; +} +macro_rules! zero_extend { + ($int:ident, $uint:ident) => { + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + #[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] + impl ZeroExtend for $uint { + #[inline(always)] + fn zero_extend(self) -> u32 { + self as u32 + } + } + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + #[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] + impl ZeroExtend for $int { + #[allow(clippy::cast_sign_loss)] + #[inline(always)] + fn zero_extend(self) -> u32 { + self as $uint as u32 + } + } + }; +} +zero_extend!(i8, u8); +zero_extend!(i16, u16); + +macro_rules! atomic_sub_word { + ($atomic_type:ident, $value_type:ty, $asm_suffix:tt, $max:tt, $min:tt) => { + #[cfg(any(target_feature = "zabha", portable_atomic_target_feature = "zabha"))] + atomic!($atomic_type, $value_type, $asm_suffix, $max, $min); + #[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] + atomic_load_store!($atomic_type, $value_type, $asm_suffix); + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + #[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] + #[cfg(not(any(portable_atomic_unsafe_assume_single_core, feature = "critical-section")))] + impl_default_bit_opts!($atomic_type, $value_type); + #[cfg(any( + test, + portable_atomic_force_amo, + target_feature = "zaamo", + portable_atomic_target_feature = "zaamo", + ))] + #[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] + impl $atomic_type { + #[inline] + pub(crate) fn fetch_and(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + let (dst, shift, mut mask) = crate::utils::create_sub_word_mask_values(dst); + mask = !sllw(mask, shift); + let mut val = sllw(ZeroExtend::zero_extend(val), shift); + val |= mask; + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + let out: u32 = unsafe { atomic_rmw_amo!(and, dst, val, order, "w") }; + srlw!(out, shift) + } + #[cfg(not(any( + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + )))] + #[inline] + pub(crate) fn and(&self, val: $value_type, order: Ordering) { + self.fetch_and(val, order); + } + + #[inline] + pub(crate) fn fetch_or(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + let (dst, shift, _mask) = crate::utils::create_sub_word_mask_values(dst); + let val = sllw(ZeroExtend::zero_extend(val), shift); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + let out: u32 = unsafe { atomic_rmw_amo!(or, dst, val, order, "w") }; + srlw!(out, shift) + } + #[cfg(not(any( + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + )))] + #[inline] + pub(crate) fn or(&self, val: $value_type, order: Ordering) { + self.fetch_or(val, order); + } + + #[inline] + pub(crate) fn fetch_xor(&self, val: $value_type, order: Ordering) -> $value_type { + let dst = self.v.get(); + let (dst, shift, _mask) = crate::utils::create_sub_word_mask_values(dst); + let val = sllw(ZeroExtend::zero_extend(val), shift); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + let out: u32 = unsafe { atomic_rmw_amo!(xor, dst, val, order, "w") }; + srlw!(out, shift) + } + #[cfg(not(any( + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + )))] + #[inline] + pub(crate) fn xor(&self, val: $value_type, order: Ordering) { + self.fetch_xor(val, order); + } + + #[inline] + pub(crate) fn fetch_not(&self, order: Ordering) -> $value_type { + self.fetch_xor(!0, order) + } + #[cfg(not(any( + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + )))] + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + } + }; +} + +atomic_sub_word!(AtomicI8, i8, "b", max, min); +atomic_sub_word!(AtomicU8, u8, "b", maxu, minu); +atomic_sub_word!(AtomicI16, i16, "h", max, min); +atomic_sub_word!(AtomicU16, u16, "h", maxu, minu); +atomic!(AtomicI32, i32, "w", max, min); +atomic!(AtomicU32, u32, "w", maxu, minu); +#[cfg(target_arch = "riscv64")] +atomic!(AtomicI64, i64, "d", max, min); +#[cfg(target_arch = "riscv64")] +atomic!(AtomicU64, u64, "d", maxu, minu); +#[cfg(target_pointer_width = "32")] +atomic!(AtomicIsize, isize, "w", max, min); +#[cfg(target_pointer_width = "32")] +atomic!(AtomicUsize, usize, "w", maxu, minu); +#[cfg(target_pointer_width = "32")] +atomic_ptr!([T] AtomicPtr, *mut T, "w"); +#[cfg(target_pointer_width = "64")] +atomic!(AtomicIsize, isize, "d", max, min); +#[cfg(target_pointer_width = "64")] +atomic!(AtomicUsize, usize, "d", maxu, minu); +#[cfg(target_pointer_width = "64")] +atomic_ptr!([T] AtomicPtr, *mut T, "d"); + +#[cfg(test)] +mod tests { + use super::*; + + test_atomic_ptr_load_store!(); + test_atomic_int_load_store!(i8); + test_atomic_int_load_store!(u8); + test_atomic_int_load_store!(i16); + test_atomic_int_load_store!(u16); + test_atomic_int_load_store!(i32); + test_atomic_int_load_store!(u32); + #[cfg(target_arch = "riscv64")] + test_atomic_int_load_store!(i64); + #[cfg(target_arch = "riscv64")] + test_atomic_int_load_store!(u64); + test_atomic_int_load_store!(isize); + test_atomic_int_load_store!(usize); + + macro_rules! test_atomic_ptr_amo { + () => { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod test_atomic_ptr_amo { + use super::*; + test_atomic_ptr_amo!(AtomicPtr); + } + }; + ($atomic_type:ty) => { + ::quickcheck::quickcheck! { + fn quickcheck_swap(x: usize, y: usize) -> bool { + let x = sptr::invalid_mut(x); + let y = sptr::invalid_mut(y); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.swap(y, order), x); + assert_eq!(a.swap(x, order), y); + } + true + } + } + }; + } + macro_rules! test_atomic_int_amo { + ($int_type:ident) => { + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use super::*; + test_atomic_int_amo!([], $int_type); + } + } + }; + ($atomic_type:ty, $int_type:ident) => { + ::quickcheck::quickcheck! { + fn quickcheck_swap(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.swap(y, order), x); + assert_eq!(a.swap(x, order), y); + } + true + } + fn quickcheck_fetch_add(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_add(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_add(y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_add(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y.wrapping_add(x)); + } + true + } + fn quickcheck_fetch_sub(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_sub(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_sub(y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_sub(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y.wrapping_sub(x)); + } + true + } + fn quickcheck_fetch_and(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_and(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x & y); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_and(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y & x); + } + true + } + fn quickcheck_fetch_or(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_or(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x | y); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_or(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y | x); + } + true + } + fn quickcheck_fetch_xor(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_xor(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x ^ y); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_xor(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y ^ x); + } + true + } + fn quickcheck_fetch_max(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_max(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::max(x, y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_max(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::max(y, x)); + } + true + } + fn quickcheck_fetch_min(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_min(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::min(x, y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_min(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::min(y, x)); + } + true + } + fn quickcheck_fetch_not(x: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_not(order), x); + assert_eq!(a.load(Ordering::Relaxed), !x); + assert_eq!(a.fetch_not(order), !x); + assert_eq!(a.load(Ordering::Relaxed), x); + } + true + } + } + }; + } + macro_rules! test_atomic_int_amo_sub_word { + ($int_type:ident) => { + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use super::*; + #[cfg(any(target_feature = "zabha", portable_atomic_target_feature = "zabha"))] + test_atomic_int_amo!([], $int_type); + #[cfg(not(any(target_feature = "zabha", portable_atomic_target_feature = "zabha")))] + test_atomic_int_amo_sub_word!([], $int_type); + } + } + }; + ($atomic_type:ty, $int_type:ident) => { + use crate::tests::helper::*; + ::quickcheck::quickcheck! { + fn quickcheck_fetch_and(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + for base in [0, !0] { + let mut arr = Align16([ + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + ]); + let a_idx = fastrand::usize(3..=6); + arr.0[a_idx] = <$atomic_type>::new(x); + let a = &arr.0[a_idx]; + assert_eq!(a.fetch_and(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x & y); + for i in 0..a_idx { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + for i in a_idx + 1..arr.0.len() { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + arr.0[a_idx] = <$atomic_type>::new(y); + let a = &arr.0[a_idx]; + assert_eq!(a.fetch_and(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y & x); + for i in 0..a_idx { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + for i in a_idx + 1..arr.0.len() { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + } + } + true + } + fn quickcheck_fetch_or(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + for base in [0, !0] { + let mut arr = Align16([ + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + ]); + let a_idx = fastrand::usize(3..=6); + arr.0[a_idx] = <$atomic_type>::new(x); + let a = &arr.0[a_idx]; + assert_eq!(a.fetch_or(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x | y); + for i in 0..a_idx { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + for i in a_idx + 1..arr.0.len() { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + arr.0[a_idx] = <$atomic_type>::new(y); + let a = &arr.0[a_idx]; + assert_eq!(a.fetch_or(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y | x); + for i in 0..a_idx { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + for i in a_idx + 1..arr.0.len() { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + } + } + true + } + fn quickcheck_fetch_xor(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + for base in [0, !0] { + let mut arr = Align16([ + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + ]); + let a_idx = fastrand::usize(3..=6); + arr.0[a_idx] = <$atomic_type>::new(x); + let a = &arr.0[a_idx]; + assert_eq!(a.fetch_xor(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x ^ y); + for i in 0..a_idx { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + for i in a_idx + 1..arr.0.len() { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + arr.0[a_idx] = <$atomic_type>::new(y); + let a = &arr.0[a_idx]; + assert_eq!(a.fetch_xor(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y ^ x); + for i in 0..a_idx { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + for i in a_idx + 1..arr.0.len() { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + } + } + true + } + fn quickcheck_fetch_not(x: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + for base in [0, !0] { + let mut arr = Align16([ + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + <$atomic_type>::new(base), + ]); + let a_idx = fastrand::usize(3..=6); + arr.0[a_idx] = <$atomic_type>::new(x); + let a = &arr.0[a_idx]; + assert_eq!(a.fetch_not(order), x); + assert_eq!(a.load(Ordering::Relaxed), !x); + assert_eq!(a.fetch_not(order), !x); + assert_eq!(a.load(Ordering::Relaxed), x); + for i in 0..a_idx { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + for i in a_idx + 1..arr.0.len() { + assert_eq!(arr.0[i].load(Ordering::Relaxed), base, "invalid value written"); + } + } + } + true + } + } + }; + } + test_atomic_ptr_amo!(); + test_atomic_int_amo_sub_word!(i8); + test_atomic_int_amo_sub_word!(u8); + test_atomic_int_amo_sub_word!(i16); + test_atomic_int_amo_sub_word!(u16); + test_atomic_int_amo!(i32); + test_atomic_int_amo!(u32); + #[cfg(target_arch = "riscv64")] + test_atomic_int_amo!(i64); + #[cfg(target_arch = "riscv64")] + test_atomic_int_amo!(u64); + test_atomic_int_amo!(isize); + test_atomic_int_amo!(usize); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/imp/x86.rs b/bitbox02-bt/vendor/portable-atomic/src/imp/x86.rs new file mode 100644 index 0000000..49c652e --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/imp/x86.rs @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/* +Atomic operations implementation on x86/x86_64. + +This module provides atomic operations not supported by LLVM or optimizes +cases where LLVM code generation is not optimal. + +Note: On Miri and ThreadSanitizer which do not support inline assembly, we don't use +this module and use CAS loop instead. + +Refs: +- x86 and amd64 instruction reference https://www.felixcloutier.com/x86 + +Generated asm: +- x86_64 https://godbolt.org/z/Kcsj1jd9c +*/ + +#[cfg(not(portable_atomic_no_asm))] +use core::arch::asm; +use core::sync::atomic::Ordering; + +use super::core_atomic::{ + AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU64, + AtomicU8, AtomicUsize, +}; + +#[cfg(target_pointer_width = "32")] +macro_rules! ptr_modifier { + () => { + ":e" + }; +} +#[cfg(target_pointer_width = "64")] +macro_rules! ptr_modifier { + () => { + "" + }; +} + +macro_rules! atomic_int { + ($atomic_type:ident, $ptr_size:tt) => { + impl $atomic_type { + #[inline] + pub(crate) fn not(&self, _order: Ordering) { + let dst = self.as_ptr(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + // + // https://www.felixcloutier.com/x86/not + unsafe { + // atomic RMW is always SeqCst. + asm!( + concat!("lock not ", $ptr_size, " ptr [{dst", ptr_modifier!(), "}]"), + dst = in(reg) dst, + options(nostack, preserves_flags), + ); + } + } + #[inline] + pub(crate) fn neg(&self, _order: Ordering) { + let dst = self.as_ptr(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + // + // https://www.felixcloutier.com/x86/neg + unsafe { + // atomic RMW is always SeqCst. + asm!( + concat!("lock neg ", $ptr_size, " ptr [{dst", ptr_modifier!(), "}]"), + dst = in(reg) dst, + // Do not use `preserves_flags` because NEG modifies the CF, OF, SF, ZF, AF, and PF flag. + options(nostack), + ); + } + } + } + }; +} + +atomic_int!(AtomicI8, "byte"); +atomic_int!(AtomicU8, "byte"); +atomic_int!(AtomicI16, "word"); +atomic_int!(AtomicU16, "word"); +atomic_int!(AtomicI32, "dword"); +atomic_int!(AtomicU32, "dword"); +#[cfg(target_arch = "x86_64")] +atomic_int!(AtomicI64, "qword"); +#[cfg(target_arch = "x86_64")] +atomic_int!(AtomicU64, "qword"); +#[cfg(target_pointer_width = "32")] +atomic_int!(AtomicIsize, "dword"); +#[cfg(target_pointer_width = "32")] +atomic_int!(AtomicUsize, "dword"); +#[cfg(target_pointer_width = "64")] +atomic_int!(AtomicIsize, "qword"); +#[cfg(target_pointer_width = "64")] +atomic_int!(AtomicUsize, "qword"); + +#[cfg(target_arch = "x86")] +impl AtomicI64 { + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + #[inline] + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } +} +#[cfg(target_arch = "x86")] +impl AtomicU64 { + #[inline] + pub(crate) fn not(&self, order: Ordering) { + self.fetch_not(order); + } + #[inline] + pub(crate) fn neg(&self, order: Ordering) { + self.fetch_neg(order); + } +} + +macro_rules! atomic_bit_opts { + ($atomic_type:ident, $int_type:ident, $val_modifier:tt, $ptr_size:tt) => { + // LLVM 14 and older don't support generating `lock bt{s,r,c}`. + // LLVM 15 only supports generating `lock bt{s,r,c}` for immediate bit offsets. + // LLVM 16+ can generate `lock bt{s,r,c}` for both immediate and register bit offsets. + // https://godbolt.org/z/TGhr5z4ds + // So, use fetch_* based implementations on LLVM 16+, otherwise use asm based implementations. + #[cfg(not(portable_atomic_pre_llvm_16))] + impl_default_bit_opts!($atomic_type, $int_type); + #[cfg(portable_atomic_pre_llvm_16)] + impl $atomic_type { + // `::BITS` requires Rust 1.53 + const BITS: u32 = (core::mem::size_of::<$int_type>() * 8) as u32; + #[inline] + pub(crate) fn bit_set(&self, bit: u32, _order: Ordering) -> bool { + let dst = self.as_ptr(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + // the masking by the bit size of the type ensures that we do not shift + // out of bounds. + // + // https://www.felixcloutier.com/x86/bts + unsafe { + let r: u8; + // atomic RMW is always SeqCst. + asm!( + concat!("lock bts ", $ptr_size, " ptr [{dst", ptr_modifier!(), "}], {bit", $val_modifier, "}"), + "setb {r}", + dst = in(reg) dst, + bit = in(reg) (bit & (Self::BITS - 1)) as $int_type, + r = out(reg_byte) r, + // Do not use `preserves_flags` because BTS modifies the CF flag. + options(nostack), + ); + crate::utils::assert_unchecked(r == 0 || r == 1); // may help remove extra test + r != 0 + } + } + #[inline] + pub(crate) fn bit_clear(&self, bit: u32, _order: Ordering) -> bool { + let dst = self.as_ptr(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + // the masking by the bit size of the type ensures that we do not shift + // out of bounds. + // + // https://www.felixcloutier.com/x86/btr + unsafe { + let r: u8; + // atomic RMW is always SeqCst. + asm!( + concat!("lock btr ", $ptr_size, " ptr [{dst", ptr_modifier!(), "}], {bit", $val_modifier, "}"), + "setb {r}", + dst = in(reg) dst, + bit = in(reg) (bit & (Self::BITS - 1)) as $int_type, + r = out(reg_byte) r, + // Do not use `preserves_flags` because BTR modifies the CF flag. + options(nostack), + ); + crate::utils::assert_unchecked(r == 0 || r == 1); // may help remove extra test + r != 0 + } + } + #[inline] + pub(crate) fn bit_toggle(&self, bit: u32, _order: Ordering) -> bool { + let dst = self.as_ptr(); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + // the masking by the bit size of the type ensures that we do not shift + // out of bounds. + // + // https://www.felixcloutier.com/x86/btc + unsafe { + let r: u8; + // atomic RMW is always SeqCst. + asm!( + concat!("lock btc ", $ptr_size, " ptr [{dst", ptr_modifier!(), "}], {bit", $val_modifier, "}"), + "setb {r}", + dst = in(reg) dst, + bit = in(reg) (bit & (Self::BITS - 1)) as $int_type, + r = out(reg_byte) r, + // Do not use `preserves_flags` because BTC modifies the CF flag. + options(nostack), + ); + crate::utils::assert_unchecked(r == 0 || r == 1); // may help remove extra test + r != 0 + } + } + } + }; +} + +impl_default_bit_opts!(AtomicI8, i8); +impl_default_bit_opts!(AtomicU8, u8); +atomic_bit_opts!(AtomicI16, i16, ":x", "word"); +atomic_bit_opts!(AtomicU16, u16, ":x", "word"); +atomic_bit_opts!(AtomicI32, i32, ":e", "dword"); +atomic_bit_opts!(AtomicU32, u32, ":e", "dword"); +#[cfg(target_arch = "x86_64")] +atomic_bit_opts!(AtomicI64, i64, "", "qword"); +#[cfg(target_arch = "x86_64")] +atomic_bit_opts!(AtomicU64, u64, "", "qword"); +#[cfg(target_arch = "x86")] +impl_default_bit_opts!(AtomicI64, i64); +#[cfg(target_arch = "x86")] +impl_default_bit_opts!(AtomicU64, u64); +#[cfg(target_pointer_width = "32")] +atomic_bit_opts!(AtomicIsize, isize, ":e", "dword"); +#[cfg(target_pointer_width = "32")] +atomic_bit_opts!(AtomicUsize, usize, ":e", "dword"); +#[cfg(target_pointer_width = "64")] +atomic_bit_opts!(AtomicIsize, isize, "", "qword"); +#[cfg(target_pointer_width = "64")] +atomic_bit_opts!(AtomicUsize, usize, "", "qword"); diff --git a/bitbox02-bt/vendor/portable-atomic/src/lib.rs b/bitbox02-bt/vendor/portable-atomic/src/lib.rs new file mode 100644 index 0000000..3b3a173 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/lib.rs @@ -0,0 +1,4995 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/*! + +Portable atomic types including support for 128-bit atomics, atomic float, etc. + +- Provide all atomic integer types (`Atomic{I,U}{8,16,32,64}`) for all targets that can use atomic CAS. (i.e., all targets that can use `std`, and most no-std targets) +- Provide `AtomicI128` and `AtomicU128`. +- Provide `AtomicF32` and `AtomicF64`. ([optional, requires the `float` feature](#optional-features-float)) +- Provide atomic load/store for targets where atomic is not available at all in the standard library. (RISC-V without A-extension, MSP430, AVR) +- Provide atomic CAS for targets where atomic CAS is not available in the standard library. (thumbv6m, pre-v6 Arm, RISC-V without A-extension, MSP430, AVR, Xtensa, etc.) (always enabled for MSP430 and AVR, [optional](#optional-features-critical-section) otherwise) +- Provide stable equivalents of the standard library's atomic types' unstable APIs, such as [`AtomicPtr::fetch_*`](https://github.com/rust-lang/rust/issues/99108). +- Make features that require newer compilers, such as [`fetch_{max,min}`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.fetch_max), [`fetch_update`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.fetch_update), [`as_ptr`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.as_ptr), [`from_ptr`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html#method.from_ptr), [`AtomicBool::fetch_not`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.fetch_not) and [stronger CAS failure ordering](https://github.com/rust-lang/rust/pull/98383) available on Rust 1.34+. +- Provide workaround for bugs in the standard library's atomic-related APIs, such as [rust-lang/rust#100650], `fence`/`compiler_fence` on MSP430 that cause LLVM error, etc. + + + +portable-atomic version of `std::sync::Arc` is provided by the [portable-atomic-util](https://github.com/taiki-e/portable-atomic/tree/HEAD/portable-atomic-util) crate. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +portable-atomic = "1" +``` + +The default features are mainly for users who use atomics larger than the pointer width. +If you don't need them, disabling the default features may reduce code size and compile time slightly. + +```toml +[dependencies] +portable-atomic = { version = "1", default-features = false } +``` + +If your crate supports no-std environment and requires atomic CAS, enabling the `require-cas` feature will allow the `portable-atomic` to display a [helpful error message](https://github.com/taiki-e/portable-atomic/pull/100) to users on targets requiring additional action on the user side to provide atomic CAS. + +```toml +[dependencies] +portable-atomic = { version = "1.3", default-features = false, features = ["require-cas"] } +``` + +## 128-bit atomics support + +Native 128-bit atomic operations are available on x86_64 (Rust 1.59+), AArch64 (Rust 1.59+), riscv64 (Rust 1.82+), powerpc64 (nightly only), s390x (nightly only), and Arm64EC (nightly only), otherwise the fallback implementation is used. + +On x86_64, even if `cmpxchg16b` is not available at compile-time (note: `cmpxchg16b` target feature is enabled by default only on Apple and Windows (except Windows 7) targets), run-time detection checks whether `cmpxchg16b` is available. If `cmpxchg16b` is not available at either compile-time or run-time detection, the fallback implementation is used. See also [`portable_atomic_no_outline_atomics`](#optional-cfg-no-outline-atomics) cfg. + +They are usually implemented using inline assembly, and when using Miri or ThreadSanitizer that do not support inline assembly, core intrinsics are used instead of inline assembly if possible. + +See the [`atomic128` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/atomic128/README.md) for details. + +## Optional features + +- **`fallback`** *(enabled by default)*
+ Enable fallback implementations. + + Disabling this allows only atomic types for which the platform natively supports atomic operations. + +- **`float`**
+ Provide `AtomicF{32,64}`. + + Note that most of `fetch_*` operations of atomic floats are implemented using CAS loops, which can be slower than equivalent operations of atomic integers. ([GPU targets have atomic instructions for float, so we plan to use these instructions for GPU targets in the future.](https://github.com/taiki-e/portable-atomic/issues/34)) + +- **`std`**
+ Use `std`. + +- **`require-cas`**
+ Emit compile error if atomic CAS is not available. See [Usage](#usage) section and [#100](https://github.com/taiki-e/portable-atomic/pull/100) for more. + +- **`serde`**
+ Implement `serde::{Serialize,Deserialize}` for atomic types. + + Note: + - The MSRV when this feature is enabled depends on the MSRV of [serde]. + +- **`critical-section`**
+ When this feature is enabled, this crate uses [critical-section] to provide atomic CAS for targets where + it is not natively available. When enabling it, you should provide a suitable critical section implementation + for the current target, see the [critical-section] documentation for details on how to do so. + + `critical-section` support is useful to get atomic CAS when the [`unsafe-assume-single-core` feature](#optional-features-unsafe-assume-single-core) can't be used, + such as multi-core targets, unprivileged code running under some RTOS, or environments where disabling interrupts + needs extra care due to e.g. real-time requirements. + + Note that with the `critical-section` feature, critical sections are taken for all atomic operations, while with + [`unsafe-assume-single-core` feature](#optional-features-unsafe-assume-single-core) some operations don't require disabling interrupts (loads and stores, but + additionally on MSP430 `add`, `sub`, `and`, `or`, `xor`, `not`). Therefore, for better performance, if + all the `critical-section` implementation for your target does is disable interrupts, prefer using + `unsafe-assume-single-core` feature instead. + + Note: + - The MSRV when this feature is enabled depends on the MSRV of [critical-section]. + - It is usually *not* recommended to always enable this feature in dependencies of the library. + + Enabling this feature will prevent the end user from having the chance to take advantage of other (potentially) efficient implementations ([Implementations provided by `unsafe-assume-single-core` feature, default implementations on MSP430 and AVR](#optional-features-unsafe-assume-single-core), implementation proposed in [#60], etc. Other systems may also be supported in the future). + + The recommended approach for libraries is to leave it up to the end user whether or not to enable this feature. (However, it may make sense to enable this feature by default for libraries specific to a platform where other implementations are known not to work.) + + As an example, the end-user's `Cargo.toml` that uses a crate that provides a critical-section implementation and a crate that depends on portable-atomic as an option would be expected to look like this: + + ```toml + [dependencies] + portable-atomic = { version = "1", default-features = false, features = ["critical-section"] } + crate-provides-critical-section-impl = "..." + crate-uses-portable-atomic-as-feature = { version = "...", features = ["portable-atomic"] } + ``` + +- **`unsafe-assume-single-core`**
+ Assume that the target is single-core. + When this feature is enabled, this crate provides atomic CAS for targets where atomic CAS is not available in the standard library by disabling interrupts. + + This feature is `unsafe`, and note the following safety requirements: + - Enabling this feature for multi-core systems is always **unsound**. + - This uses privileged instructions to disable interrupts, so it usually doesn't work on unprivileged mode. + Enabling this feature in an environment where privileged instructions are not available, or if the instructions used are not sufficient to disable interrupts in the system, it is also usually considered **unsound**, although the details are system-dependent. + + The following are known cases: + - On pre-v6 Arm, this disables only IRQs by default. For many systems (e.g., GBA) this is enough. If the system need to disable both IRQs and FIQs, you need to enable the `disable-fiq` feature together. + - On RISC-V without A-extension, this generates code for machine-mode (M-mode) by default. If you enable the `s-mode` together, this generates code for supervisor-mode (S-mode). In particular, `qemu-system-riscv*` uses [OpenSBI](https://github.com/riscv-software-src/opensbi) as the default firmware. + + See also the [`interrupt` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/interrupt/README.md). + + Consider using the [`critical-section` feature](#optional-features-critical-section) for systems that cannot use this feature. + + It is **very strongly discouraged** to enable this feature in libraries that depend on `portable-atomic`. The recommended approach for libraries is to leave it up to the end user whether or not to enable this feature. (However, it may make sense to enable this feature by default for libraries specific to a platform where it is guaranteed to always be sound, for example in a hardware abstraction layer targeting a single-core chip.) + + Armv6-M (thumbv6m), pre-v6 Arm (e.g., thumbv4t, thumbv5te), RISC-V without A-extension, and Xtensa are currently supported. + + Since all MSP430 and AVR are single-core, we always provide atomic CAS for them without this feature. + + Enabling this feature for targets that have atomic CAS will result in a compile error. + + Feel free to submit an issue if your target is not supported yet. + +## Optional cfg + +One of the ways to enable cfg is to set [rustflags in the cargo config](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerustflags): + +```toml +# .cargo/config.toml +[target.] +rustflags = ["--cfg", "portable_atomic_no_outline_atomics"] +``` + +Or set environment variable: + +```sh +RUSTFLAGS="--cfg portable_atomic_no_outline_atomics" cargo ... +``` + +- **`--cfg portable_atomic_unsafe_assume_single_core`**
+ Since 1.4.0, this cfg is an alias of [`unsafe-assume-single-core` feature](#optional-features-unsafe-assume-single-core). + + Originally, we were providing these as cfgs instead of features, but based on a strong request from the embedded ecosystem, we have agreed to provide them as features as well. See [#94](https://github.com/taiki-e/portable-atomic/pull/94) for more. + +- **`--cfg portable_atomic_no_outline_atomics`**
+ Disable dynamic dispatching by run-time CPU feature detection. + + If dynamic dispatching by run-time CPU feature detection is enabled, it allows maintaining support for older CPUs while using features that are not supported on older CPUs, such as CMPXCHG16B (x86_64) and FEAT_LSE/FEAT_LSE2 (AArch64). + + Note: + - Dynamic detection is currently only enabled in Rust 1.59+ for x86_64 and AArch64, Rust 1.82+ for RISC-V (disabled by default), nightly only for powerpc64 (disabled by default) and Arm64EC, otherwise it works the same as when this cfg is set. + - If the required target features are enabled at compile-time, the atomic operations are inlined. + - This is compatible with no-std (as with all features except `std`). + - On some targets, run-time detection is disabled by default mainly for compatibility with older versions of operating systems or incomplete build environments, and can be enabled by `--cfg portable_atomic_outline_atomics`. (When both cfg are enabled, `*_no_*` cfg is preferred.) + - Some AArch64 targets enable LLVM's `outline-atomics` target feature by default, so if you set this cfg, you may want to disable that as well. (portable-atomic's outline-atomics does not depend on the compiler-rt symbols, so even if you need to disable LLVM's outline-atomics, you may not need to disable portable-atomic's outline-atomics.) + + See also the [`atomic128` module's readme](https://github.com/taiki-e/portable-atomic/blob/HEAD/src/imp/atomic128/README.md). + +## Related Projects + +- [atomic-maybe-uninit]: Atomic operations on potentially uninitialized integers. +- [atomic-memcpy]: Byte-wise atomic memcpy. + +[#60]: https://github.com/taiki-e/portable-atomic/issues/60 +[atomic-maybe-uninit]: https://github.com/taiki-e/atomic-maybe-uninit +[atomic-memcpy]: https://github.com/taiki-e/atomic-memcpy +[critical-section]: https://github.com/rust-embedded/critical-section +[rust-lang/rust#100650]: https://github.com/rust-lang/rust/issues/100650 +[serde]: https://github.com/serde-rs/serde + + +*/ + +#![no_std] +#![doc(test( + no_crate_inject, + attr( + deny(warnings, rust_2018_idioms, single_use_lifetimes), + allow(dead_code, unused_variables) + ) +))] +#![cfg_attr(not(portable_atomic_no_unsafe_op_in_unsafe_fn), warn(unsafe_op_in_unsafe_fn))] // unsafe_op_in_unsafe_fn requires Rust 1.52 +#![cfg_attr(portable_atomic_no_unsafe_op_in_unsafe_fn, allow(unused_unsafe))] +#![warn( + // Lints that may help when writing public library. + missing_debug_implementations, + // missing_docs, + clippy::alloc_instead_of_core, + clippy::exhaustive_enums, + clippy::exhaustive_structs, + clippy::impl_trait_in_params, + clippy::missing_inline_in_public_items, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + // Code outside of cfg(feature = "float") shouldn't use float. + clippy::float_arithmetic, +)] +#![cfg_attr(not(portable_atomic_no_asm), warn(missing_docs))] // module-level #![allow(missing_docs)] doesn't work for macros on old rustc +#![allow(clippy::inline_always, clippy::used_underscore_items)] +// asm_experimental_arch +// AVR, MSP430, and Xtensa are tier 3 platforms and require nightly anyway. +// On tier 2 platforms (arm64ec, powerpc64, and s390x), we use cfg set by build script to +// determine whether this feature is available or not. +#![cfg_attr( + all( + not(portable_atomic_no_asm), + any( + target_arch = "avr", + target_arch = "msp430", + all(target_arch = "xtensa", portable_atomic_unsafe_assume_single_core), + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch), + all(target_arch = "powerpc64", portable_atomic_unstable_asm_experimental_arch), + all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch), + ), + ), + feature(asm_experimental_arch) +)] +// Old nightly only +// These features are already stabilized or have already been removed from compilers, +// and can safely be enabled for old nightly as long as version detection works. +// - cfg(target_has_atomic) +// - asm! on Arm, AArch64, RISC-V, x86, x86_64 +// - llvm_asm! on AVR (tier 3) and MSP430 (tier 3) +// - #[instruction_set] on non-Linux/Android pre-v6 Arm (tier 3) +// This also helps us test that our assembly code works with the minimum external +// LLVM version of the first rustc version that inline assembly stabilized. +#![cfg_attr(portable_atomic_unstable_cfg_target_has_atomic, feature(cfg_target_has_atomic))] +#![cfg_attr( + all( + portable_atomic_unstable_asm, + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "riscv32", + target_arch = "riscv64", + target_arch = "x86", + target_arch = "x86_64", + ), + ), + feature(asm) +)] +#![cfg_attr( + all(any(target_arch = "avr", target_arch = "msp430"), portable_atomic_no_asm), + feature(llvm_asm) +)] +#![cfg_attr( + all( + target_arch = "arm", + portable_atomic_unstable_isa_attribute, + any(test, portable_atomic_unsafe_assume_single_core), + not(any(target_feature = "v6", portable_atomic_target_feature = "v6")), + not(target_has_atomic = "ptr"), + ), + feature(isa_attribute) +)] +// Miri and/or ThreadSanitizer only +// They do not support inline assembly, so we need to use unstable features instead. +// Since they require nightly compilers anyway, we can use the unstable features. +// This is not an ideal situation, but it is still better than always using lock-based +// fallback and causing memory ordering problems to be missed by these checkers. +#![cfg_attr( + all( + any( + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + ), + any(miri, portable_atomic_sanitize_thread), + ), + allow(internal_features) +)] +#![cfg_attr( + all( + any( + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + ), + any(miri, portable_atomic_sanitize_thread), + ), + feature(core_intrinsics) +)] +// docs.rs only (cfg is enabled by docs.rs, not build script) +#![cfg_attr(docsrs, feature(doc_cfg))] +#![cfg_attr( + all( + portable_atomic_no_atomic_load_store, + not(any( + target_arch = "avr", + target_arch = "bpf", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + )), + ), + allow(unused_imports, unused_macros) +)] + +// There are currently no 128-bit or higher builtin targets. +// (Although some of our generic code is written with the future +// addition of 128-bit targets in mind.) +// Note that Rust (and C99) pointers must be at least 16-bit (i.e., 8-bit targets are impossible): https://github.com/rust-lang/rust/pull/49305 +#[cfg(not(any( + target_pointer_width = "16", + target_pointer_width = "32", + target_pointer_width = "64", +)))] +compile_error!( + "portable-atomic currently only supports targets with {16,32,64}-bit pointer width; \ + if you need support for others, \ + please submit an issue at " +); + +#[cfg(portable_atomic_unsafe_assume_single_core)] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(not(portable_atomic_no_atomic_cas)))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(target_has_atomic = "ptr"))] +compile_error!( + "`portable_atomic_unsafe_assume_single_core` cfg (`unsafe-assume-single-core` feature) \ + does not compatible with target that supports atomic CAS;\n\ + see also for troubleshooting" +); +#[cfg(portable_atomic_unsafe_assume_single_core)] +#[cfg_attr(portable_atomic_no_cfg_target_has_atomic, cfg(portable_atomic_no_atomic_cas))] +#[cfg_attr(not(portable_atomic_no_cfg_target_has_atomic), cfg(not(target_has_atomic = "ptr")))] +#[cfg(not(any( + target_arch = "arm", + target_arch = "avr", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + target_arch = "xtensa", +)))] +compile_error!( + "`portable_atomic_unsafe_assume_single_core` cfg (`unsafe-assume-single-core` feature) \ + is not supported yet on this target;\n\ + if you need unsafe-assume-single-core support for this target,\n\ + please submit an issue at " +); + +#[cfg(portable_atomic_no_outline_atomics)] +#[cfg(not(any( + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "arm", + target_arch = "powerpc64", + target_arch = "riscv32", + target_arch = "riscv64", + target_arch = "x86_64", +)))] +compile_error!("`portable_atomic_no_outline_atomics` cfg does not compatible with this target"); +#[cfg(portable_atomic_outline_atomics)] +#[cfg(not(any( + target_arch = "aarch64", + target_arch = "powerpc64", + target_arch = "riscv32", + target_arch = "riscv64", +)))] +compile_error!("`portable_atomic_outline_atomics` cfg does not compatible with this target"); + +#[cfg(portable_atomic_disable_fiq)] +#[cfg(not(all( + target_arch = "arm", + not(any(target_feature = "mclass", portable_atomic_target_feature = "mclass")), +)))] +compile_error!( + "`portable_atomic_disable_fiq` cfg (`disable-fiq` feature) is only available on pre-v6 Arm" +); +#[cfg(portable_atomic_s_mode)] +#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] +compile_error!("`portable_atomic_s_mode` cfg (`s-mode` feature) is only available on RISC-V"); +#[cfg(portable_atomic_force_amo)] +#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))] +compile_error!("`portable_atomic_force_amo` cfg (`force-amo` feature) is only available on RISC-V"); + +#[cfg(portable_atomic_disable_fiq)] +#[cfg(not(portable_atomic_unsafe_assume_single_core))] +compile_error!( + "`portable_atomic_disable_fiq` cfg (`disable-fiq` feature) may only be used together with `portable_atomic_unsafe_assume_single_core` cfg (`unsafe-assume-single-core` feature)" +); +#[cfg(portable_atomic_s_mode)] +#[cfg(not(portable_atomic_unsafe_assume_single_core))] +compile_error!( + "`portable_atomic_s_mode` cfg (`s-mode` feature) may only be used together with `portable_atomic_unsafe_assume_single_core` cfg (`unsafe-assume-single-core` feature)" +); +#[cfg(portable_atomic_force_amo)] +#[cfg(not(portable_atomic_unsafe_assume_single_core))] +compile_error!( + "`portable_atomic_force_amo` cfg (`force-amo` feature) may only be used together with `portable_atomic_unsafe_assume_single_core` cfg (`unsafe-assume-single-core` feature)" +); + +#[cfg(all(portable_atomic_unsafe_assume_single_core, feature = "critical-section"))] +compile_error!( + "you may not enable `critical-section` feature and `portable_atomic_unsafe_assume_single_core` cfg (`unsafe-assume-single-core` feature) at the same time" +); + +#[cfg(feature = "require-cas")] +#[cfg_attr( + portable_atomic_no_cfg_target_has_atomic, + cfg(not(any( + not(portable_atomic_no_atomic_cas), + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ))) +)] +#[cfg_attr( + not(portable_atomic_no_cfg_target_has_atomic), + cfg(not(any( + target_has_atomic = "ptr", + portable_atomic_unsafe_assume_single_core, + feature = "critical-section", + target_arch = "avr", + target_arch = "msp430", + ))) +)] +compile_error!( + "dependents require atomic CAS but not available on this target by default;\n\ + consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features.\n\ + see for more." +); + +#[cfg(any(test, feature = "std"))] +extern crate std; + +#[macro_use] +mod cfgs; +#[cfg(target_pointer_width = "128")] +pub use {cfg_has_atomic_128 as cfg_has_atomic_ptr, cfg_no_atomic_128 as cfg_no_atomic_ptr}; +#[cfg(target_pointer_width = "16")] +pub use {cfg_has_atomic_16 as cfg_has_atomic_ptr, cfg_no_atomic_16 as cfg_no_atomic_ptr}; +#[cfg(target_pointer_width = "32")] +pub use {cfg_has_atomic_32 as cfg_has_atomic_ptr, cfg_no_atomic_32 as cfg_no_atomic_ptr}; +#[cfg(target_pointer_width = "64")] +pub use {cfg_has_atomic_64 as cfg_has_atomic_ptr, cfg_no_atomic_64 as cfg_no_atomic_ptr}; + +#[macro_use] +mod utils; + +#[cfg(test)] +#[macro_use] +mod tests; + +#[doc(no_inline)] +pub use core::sync::atomic::Ordering; + +#[doc(no_inline)] +// LLVM doesn't support fence/compiler_fence for MSP430. +#[cfg(not(target_arch = "msp430"))] +pub use core::sync::atomic::{compiler_fence, fence}; +#[cfg(target_arch = "msp430")] +pub use imp::msp430::{compiler_fence, fence}; + +mod imp; + +pub mod hint { + //! Re-export of the [`core::hint`] module. + //! + //! The only difference from the [`core::hint`] module is that [`spin_loop`] + //! is available in all rust versions that this crate supports. + //! + //! ``` + //! use portable_atomic::hint; + //! + //! hint::spin_loop(); + //! ``` + + #[doc(no_inline)] + pub use core::hint::*; + + /// Emits a machine instruction to signal the processor that it is running in + /// a busy-wait spin-loop ("spin lock"). + /// + /// Upon receiving the spin-loop signal the processor can optimize its behavior by, + /// for example, saving power or switching hyper-threads. + /// + /// This function is different from [`thread::yield_now`] which directly + /// yields to the system's scheduler, whereas `spin_loop` does not interact + /// with the operating system. + /// + /// A common use case for `spin_loop` is implementing bounded optimistic + /// spinning in a CAS loop in synchronization primitives. To avoid problems + /// like priority inversion, it is strongly recommended that the spin loop is + /// terminated after a finite amount of iterations and an appropriate blocking + /// syscall is made. + /// + /// **Note:** On platforms that do not support receiving spin-loop hints this + /// function does not do anything at all. + /// + /// [`thread::yield_now`]: https://doc.rust-lang.org/std/thread/fn.yield_now.html + #[inline] + pub fn spin_loop() { + #[allow(deprecated)] + core::sync::atomic::spin_loop_hint(); + } +} + +#[cfg(doc)] +use core::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release, SeqCst}; +use core::{fmt, ptr}; + +#[cfg(miri)] +use crate::utils::strict; + +cfg_has_atomic_8! { +/// A boolean type which can be safely shared between threads. +/// +/// This type has the same in-memory representation as a [`bool`]. +/// +/// If the compiler and the platform support atomic loads and stores of `u8`, +/// this type is a wrapper for the standard library's +/// [`AtomicBool`](core::sync::atomic::AtomicBool). If the platform supports it +/// but the compiler does not, atomic operations are implemented using inline +/// assembly. +#[repr(C, align(1))] +pub struct AtomicBool { + v: core::cell::UnsafeCell, +} + +impl Default for AtomicBool { + /// Creates an `AtomicBool` initialized to `false`. + #[inline] + fn default() -> Self { + Self::new(false) + } +} + +impl From for AtomicBool { + /// Converts a `bool` into an `AtomicBool`. + #[inline] + fn from(b: bool) -> Self { + Self::new(b) + } +} + +// Send is implicitly implemented. +// SAFETY: any data races are prevented by disabling interrupts or +// atomic intrinsics (see module-level comments). +unsafe impl Sync for AtomicBool {} + +// UnwindSafe is implicitly implemented. +#[cfg(not(portable_atomic_no_core_unwind_safe))] +impl core::panic::RefUnwindSafe for AtomicBool {} +#[cfg(all(portable_atomic_no_core_unwind_safe, feature = "std"))] +impl std::panic::RefUnwindSafe for AtomicBool {} + +impl_debug_and_serde!(AtomicBool); + +impl AtomicBool { + /// Creates a new `AtomicBool`. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicBool; + /// + /// let atomic_true = AtomicBool::new(true); + /// let atomic_false = AtomicBool::new(false); + /// ``` + #[inline] + #[must_use] + pub const fn new(v: bool) -> Self { + static_assert_layout!(AtomicBool, bool); + Self { v: core::cell::UnsafeCell::new(v as u8) } + } + + // TODO: update docs based on https://github.com/rust-lang/rust/pull/116762 + /// Creates a new `AtomicBool` from a pointer. + /// + /// # Safety + /// + /// * `ptr` must be aligned to `align_of::()` (note that on some platforms this can + /// be bigger than `align_of::()`). + /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. + /// * If this atomic type is [lock-free](Self::is_lock_free), non-atomic accesses to the value + /// behind `ptr` must have a happens-before relationship with atomic accesses via the returned + /// value (or vice-versa). + /// * In other words, time periods where the value is accessed atomically may not overlap + /// with periods where the value is accessed non-atomically. + /// * This requirement is trivially satisfied if `ptr` is never used non-atomically for the + /// duration of lifetime `'a`. Most use cases should be able to follow this guideline. + /// * This requirement is also trivially satisfied if all accesses (atomic or not) are done + /// from the same thread. + /// * If this atomic type is *not* lock-free: + /// * Any accesses to the value behind `ptr` must have a happens-before relationship + /// with accesses via the returned value (or vice-versa). + /// * Any concurrent accesses to the value behind `ptr` for the duration of lifetime `'a` must + /// be compatible with operations performed by this atomic type. + /// * This method must not be used to create overlapping or mixed-size atomic accesses, as + /// these are not supported by the memory model. + /// + /// [valid]: core::ptr#safety + #[inline] + #[must_use] + pub unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a Self { + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: guaranteed by the caller + unsafe { &*(ptr as *mut Self) } + } + + /// Returns `true` if operations on values of this type are lock-free. + /// + /// If the compiler or the platform doesn't support the necessary + /// atomic instructions, global locks for every potentially + /// concurrent atomic operation will be used. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicBool; + /// + /// let is_lock_free = AtomicBool::is_lock_free(); + /// ``` + #[inline] + #[must_use] + pub fn is_lock_free() -> bool { + imp::AtomicU8::is_lock_free() + } + + /// Returns `true` if operations on values of this type are lock-free. + /// + /// If the compiler or the platform doesn't support the necessary + /// atomic instructions, global locks for every potentially + /// concurrent atomic operation will be used. + /// + /// **Note:** If the atomic operation relies on dynamic CPU feature detection, + /// this type may be lock-free even if the function returns false. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicBool; + /// + /// const IS_ALWAYS_LOCK_FREE: bool = AtomicBool::is_always_lock_free(); + /// ``` + #[inline] + #[must_use] + pub const fn is_always_lock_free() -> bool { + imp::AtomicU8::IS_ALWAYS_LOCK_FREE + } + #[cfg(test)] + const IS_ALWAYS_LOCK_FREE: bool = Self::is_always_lock_free(); + + /// Returns a mutable reference to the underlying [`bool`]. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let mut some_bool = AtomicBool::new(true); + /// assert_eq!(*some_bool.get_mut(), true); + /// *some_bool.get_mut() = false; + /// assert_eq!(some_bool.load(Ordering::SeqCst), false); + /// ``` + #[inline] + pub fn get_mut(&mut self) -> &mut bool { + // SAFETY: the mutable reference guarantees unique ownership. + unsafe { &mut *(self.v.get() as *mut bool) } + } + + // TODO: Add from_mut/get_mut_slice/from_mut_slice once it is stable on std atomic types. + // https://github.com/rust-lang/rust/issues/76314 + + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_transmute))]; + /// Consumes the atomic and returns the contained value. + /// + /// This is safe because passing `self` by value guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// This is `const fn` on Rust 1.56+. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicBool; + /// + /// let some_bool = AtomicBool::new(true); + /// assert_eq!(some_bool.into_inner(), true); + /// ``` + #[inline] + pub const fn into_inner(self) -> bool { + // SAFETY: AtomicBool and u8 have the same size and in-memory representations, + // so they can be safely transmuted. + // (const UnsafeCell::into_inner is unstable) + unsafe { core::mem::transmute::(self) != 0 } + } + } + + /// Loads a value from the bool. + /// + /// `load` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// assert_eq!(some_bool.load(Ordering::Relaxed), true); + /// ``` + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn load(&self, order: Ordering) -> bool { + self.as_atomic_u8().load(order) != 0 + } + + /// Stores a value into the bool. + /// + /// `store` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// some_bool.store(false, Ordering::Relaxed); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// ``` + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn store(&self, val: bool, order: Ordering) { + self.as_atomic_u8().store(val as u8, order); + } + + cfg_has_atomic_cas_or_amo32! { + /// Stores a value into the bool, returning the previous value. + /// + /// `swap` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn swap(&self, val: bool, order: Ordering) -> bool { + #[cfg(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "loongarch64"))] + { + // See https://github.com/rust-lang/rust/pull/114034 for details. + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L233 + // https://godbolt.org/z/Enh87Ph9b + if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) } + } + #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "loongarch64")))] + { + self.as_atomic_u8().swap(val as u8, order) != 0 + } + } + + /// Stores a value into the [`bool`] if the current value is the same as the `current` value. + /// + /// The return value is a result indicating whether the new value was written and containing + /// the previous value. On success this value is guaranteed to be equal to `current`. + /// + /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `failure` is [`Release`], [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// assert_eq!( + /// some_bool.compare_exchange(true, false, Ordering::Acquire, Ordering::Relaxed), + /// Ok(true) + /// ); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// + /// assert_eq!( + /// some_bool.compare_exchange(true, true, Ordering::SeqCst, Ordering::Acquire), + /// Err(false) + /// ); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// ``` + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result { + #[cfg(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "loongarch64"))] + { + // See https://github.com/rust-lang/rust/pull/114034 for details. + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L233 + // https://godbolt.org/z/Enh87Ph9b + crate::utils::assert_compare_exchange_ordering(success, failure); + let order = crate::utils::upgrade_success_ordering(success, failure); + let old = if current == new { + // This is a no-op, but we still need to perform the operation + // for memory ordering reasons. + self.fetch_or(false, order) + } else { + // This sets the value to the new one and returns the old one. + self.swap(new, order) + }; + if old == current { Ok(old) } else { Err(old) } + } + #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "loongarch64")))] + { + match self.as_atomic_u8().compare_exchange(current as u8, new as u8, success, failure) { + Ok(x) => Ok(x != 0), + Err(x) => Err(x != 0), + } + } + } + + /// Stores a value into the [`bool`] if the current value is the same as the `current` value. + /// + /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the + /// comparison succeeds, which can result in more efficient code on some platforms. The + /// return value is a result indicating whether the new value was written and containing the + /// previous value. + /// + /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `failure` is [`Release`], [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let val = AtomicBool::new(false); + /// + /// let new = true; + /// let mut old = val.load(Ordering::Relaxed); + /// loop { + /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { + /// Ok(_) => break, + /// Err(x) => old = x, + /// } + /// } + /// ``` + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange_weak( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result { + #[cfg(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "loongarch64"))] + { + // See https://github.com/rust-lang/rust/pull/114034 for details. + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L233 + // https://godbolt.org/z/Enh87Ph9b + self.compare_exchange(current, new, success, failure) + } + #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64", target_arch = "loongarch64")))] + { + match self + .as_atomic_u8() + .compare_exchange_weak(current as u8, new as u8, success, failure) + { + Ok(x) => Ok(x != 0), + Err(x) => Err(x != 0), + } + } + } + + /// Logical "and" with a boolean value. + /// + /// Performs a logical "and" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_and(&self, val: bool, order: Ordering) -> bool { + self.as_atomic_u8().fetch_and(val as u8, order) != 0 + } + + /// Logical "and" with a boolean value. + /// + /// Performs a logical "and" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Unlike `fetch_and`, this does not return the previous value. + /// + /// `and` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// This function may generate more efficient code than `fetch_and` on some platforms. + /// + /// - x86/x86_64: `lock and` instead of `cmpxchg` loop + /// - MSP430: `and` instead of disabling interrupts + /// + /// Note: On x86/x86_64, the use of either function should not usually + /// affect the generated code, because LLVM can properly optimize the case + /// where the result is unused. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// foo.and(false, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(true); + /// foo.and(true, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(false); + /// foo.and(false, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn and(&self, val: bool, order: Ordering) { + self.as_atomic_u8().and(val as u8, order); + } + + /// Logical "nand" with a boolean value. + /// + /// Performs a logical "nand" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool { + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L956-L970 + if val { + // !(x & true) == !x + // We must invert the bool. + self.fetch_xor(true, order) + } else { + // !(x & false) == true + // We must set the bool to true. + self.swap(true, order) + } + } + + /// Logical "or" with a boolean value. + /// + /// Performs a logical "or" operation on the current value and the argument `val`, and sets the + /// new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_or(&self, val: bool, order: Ordering) -> bool { + self.as_atomic_u8().fetch_or(val as u8, order) != 0 + } + + /// Logical "or" with a boolean value. + /// + /// Performs a logical "or" operation on the current value and the argument `val`, and sets the + /// new value to the result. + /// + /// Unlike `fetch_or`, this does not return the previous value. + /// + /// `or` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// This function may generate more efficient code than `fetch_or` on some platforms. + /// + /// - x86/x86_64: `lock or` instead of `cmpxchg` loop + /// - MSP430: `bis` instead of disabling interrupts + /// + /// Note: On x86/x86_64, the use of either function should not usually + /// affect the generated code, because LLVM can properly optimize the case + /// where the result is unused. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// foo.or(false, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(true); + /// foo.or(true, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(false); + /// foo.or(false, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn or(&self, val: bool, order: Ordering) { + self.as_atomic_u8().or(val as u8, order); + } + + /// Logical "xor" with a boolean value. + /// + /// Performs a logical "xor" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool { + self.as_atomic_u8().fetch_xor(val as u8, order) != 0 + } + + /// Logical "xor" with a boolean value. + /// + /// Performs a logical "xor" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Unlike `fetch_xor`, this does not return the previous value. + /// + /// `xor` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// This function may generate more efficient code than `fetch_xor` on some platforms. + /// + /// - x86/x86_64: `lock xor` instead of `cmpxchg` loop + /// - MSP430: `xor` instead of disabling interrupts + /// + /// Note: On x86/x86_64, the use of either function should not usually + /// affect the generated code, because LLVM can properly optimize the case + /// where the result is unused. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// foo.xor(false, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(true); + /// foo.xor(true, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// foo.xor(false, Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn xor(&self, val: bool, order: Ordering) { + self.as_atomic_u8().xor(val as u8, order); + } + + /// Logical "not" with a boolean value. + /// + /// Performs a logical "not" operation on the current value, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_not(&self, order: Ordering) -> bool { + self.fetch_xor(true, order) + } + + /// Logical "not" with a boolean value. + /// + /// Performs a logical "not" operation on the current value, and sets + /// the new value to the result. + /// + /// Unlike `fetch_not`, this does not return the previous value. + /// + /// `not` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// This function may generate more efficient code than `fetch_not` on some platforms. + /// + /// - x86/x86_64: `lock xor` instead of `cmpxchg` loop + /// - MSP430: `xor` instead of disabling interrupts + /// + /// Note: On x86/x86_64, the use of either function should not usually + /// affect the generated code, because LLVM can properly optimize the case + /// where the result is unused. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// foo.not(Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// foo.not(Ordering::SeqCst); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn not(&self, order: Ordering) { + self.xor(true, order); + } + + /// Fetches the value, and applies a function to it that returns an optional + /// new value. Returns a `Result` of `Ok(previous_value)` if the function + /// returned `Some(_)`, else `Err(previous_value)`. + /// + /// Note: This may call the function multiple times if the value has been + /// changed from other threads in the meantime, as long as the function + /// returns `Some(_)`, but the function will have been applied only once to + /// the stored value. + /// + /// `fetch_update` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. The first describes the required ordering for + /// when the operation finally succeeds while the second describes the + /// required ordering for loads. These correspond to the success and failure + /// orderings of [`compare_exchange`](Self::compare_exchange) respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part of this + /// operation [`Relaxed`], and using [`Release`] makes the final successful + /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], + /// [`Acquire`] or [`Relaxed`]. + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware. + /// It is implemented in terms of [`compare_exchange_weak`](Self::compare_exchange_weak), + /// and suffers from the same drawbacks. + /// In particular, this method will not circumvent the [ABA Problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// + /// # Panics + /// + /// Panics if `fetch_order` is [`Release`], [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicBool, Ordering}; + /// + /// let x = AtomicBool::new(false); + /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false)); + /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false)); + /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true)); + /// assert_eq!(x.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: F, + ) -> Result + where + F: FnMut(bool) -> Option, + { + let mut prev = self.load(fetch_order); + while let Some(next) = f(prev) { + match self.compare_exchange_weak(prev, next, set_order, fetch_order) { + x @ Ok(_) => return x, + Err(next_prev) => prev = next_prev, + } + } + Err(prev) + } + } // cfg_has_atomic_cas_or_amo32! + + const_fn! { + // This function is actually `const fn`-compatible on Rust 1.32+, + // but makes `const fn` only on Rust 1.58+ to match other atomic types. + const_if: #[cfg(not(portable_atomic_no_const_raw_ptr_deref))]; + /// Returns a mutable pointer to the underlying [`bool`]. + /// + /// Returning an `*mut` pointer from a shared reference to this atomic is + /// safe because the atomic types work with interior mutability. Any use of + /// the returned raw pointer requires an `unsafe` block and has to uphold + /// the safety requirements. If there is concurrent access, note the following + /// additional safety requirements: + /// + /// - If this atomic type is [lock-free](Self::is_lock_free), any concurrent + /// operations on it must be atomic. + /// - Otherwise, any concurrent operations on it must be compatible with + /// operations performed by this atomic type. + /// + /// This is `const fn` on Rust 1.58+. + #[inline] + pub const fn as_ptr(&self) -> *mut bool { + self.v.get() as *mut bool + } + } + + #[inline(always)] + fn as_atomic_u8(&self) -> &imp::AtomicU8 { + // SAFETY: AtomicBool and imp::AtomicU8 have the same layout, + // and both access data in the same way. + unsafe { &*(self as *const Self as *const imp::AtomicU8) } + } +} +// See https://github.com/taiki-e/portable-atomic/issues/180 +#[cfg(not(feature = "require-cas"))] +cfg_no_atomic_cas! { +#[doc(hidden)] +#[allow(unused_variables, clippy::unused_self)] +impl<'a> AtomicBool { + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn swap(&self, val: bool, order: Ordering) -> bool + where + &'a Self: HasSwap, + { + unimplemented!() + } + #[inline] + pub fn compare_exchange( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result + where + &'a Self: HasCompareExchange, + { + unimplemented!() + } + #[inline] + pub fn compare_exchange_weak( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result + where + &'a Self: HasCompareExchangeWeak, + { + unimplemented!() + } + #[inline] + pub fn fetch_and(&self, val: bool, order: Ordering) -> bool + where + &'a Self: HasFetchAnd, + { + unimplemented!() + } + #[inline] + pub fn and(&self, val: bool, order: Ordering) + where + &'a Self: HasAnd, + { + unimplemented!() + } + #[inline] + pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool + where + &'a Self: HasFetchNand, + { + unimplemented!() + } + #[inline] + pub fn fetch_or(&self, val: bool, order: Ordering) -> bool + where + &'a Self: HasFetchOr, + { + unimplemented!() + } + #[inline] + pub fn or(&self, val: bool, order: Ordering) + where + &'a Self: HasOr, + { + unimplemented!() + } + #[inline] + pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool + where + &'a Self: HasFetchXor, + { + unimplemented!() + } + #[inline] + pub fn xor(&self, val: bool, order: Ordering) + where + &'a Self: HasXor, + { + unimplemented!() + } + #[inline] + pub fn fetch_not(&self, order: Ordering) -> bool + where + &'a Self: HasFetchNot, + { + unimplemented!() + } + #[inline] + pub fn not(&self, order: Ordering) + where + &'a Self: HasNot, + { + unimplemented!() + } + #[inline] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + f: F, + ) -> Result + where + F: FnMut(bool) -> Option, + &'a Self: HasFetchUpdate, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! +} +} // cfg_no_atomic_cas! +} // cfg_has_atomic_8! + +cfg_has_atomic_ptr! { +/// A raw pointer type which can be safely shared between threads. +/// +/// This type has the same in-memory representation as a `*mut T`. +/// +/// If the compiler and the platform support atomic loads and stores of pointers, +/// this type is a wrapper for the standard library's +/// [`AtomicPtr`](core::sync::atomic::AtomicPtr). If the platform supports it +/// but the compiler does not, atomic operations are implemented using inline +/// assembly. +// We can use #[repr(transparent)] here, but #[repr(C, align(N))] +// will show clearer docs. +#[cfg_attr(target_pointer_width = "16", repr(C, align(2)))] +#[cfg_attr(target_pointer_width = "32", repr(C, align(4)))] +#[cfg_attr(target_pointer_width = "64", repr(C, align(8)))] +#[cfg_attr(target_pointer_width = "128", repr(C, align(16)))] +pub struct AtomicPtr { + inner: imp::AtomicPtr, +} + +impl Default for AtomicPtr { + /// Creates a null `AtomicPtr`. + #[inline] + fn default() -> Self { + Self::new(ptr::null_mut()) + } +} + +impl From<*mut T> for AtomicPtr { + #[inline] + fn from(p: *mut T) -> Self { + Self::new(p) + } +} + +impl fmt::Debug for AtomicPtr { + #[inline] // fmt is not hot path, but #[inline] on fmt seems to still be useful: https://github.com/rust-lang/rust/pull/117727 + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // std atomic types use Relaxed in Debug::fmt: https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L2166 + fmt::Debug::fmt(&self.load(Ordering::Relaxed), f) + } +} + +impl fmt::Pointer for AtomicPtr { + #[inline] // fmt is not hot path, but #[inline] on fmt seems to still be useful: https://github.com/rust-lang/rust/pull/117727 + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // std atomic types use Relaxed in Debug::fmt: https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L2166 + fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f) + } +} + +// UnwindSafe is implicitly implemented. +#[cfg(not(portable_atomic_no_core_unwind_safe))] +impl core::panic::RefUnwindSafe for AtomicPtr {} +#[cfg(all(portable_atomic_no_core_unwind_safe, feature = "std"))] +impl std::panic::RefUnwindSafe for AtomicPtr {} + +impl AtomicPtr { + /// Creates a new `AtomicPtr`. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicPtr; + /// + /// let ptr = &mut 5; + /// let atomic_ptr = AtomicPtr::new(ptr); + /// ``` + #[inline] + #[must_use] + pub const fn new(p: *mut T) -> Self { + static_assert_layout!(AtomicPtr<()>, *mut ()); + Self { inner: imp::AtomicPtr::new(p) } + } + + // TODO: update docs based on https://github.com/rust-lang/rust/pull/116762 + /// Creates a new `AtomicPtr` from a pointer. + /// + /// # Safety + /// + /// * `ptr` must be aligned to `align_of::>()` (note that on some platforms this + /// can be bigger than `align_of::<*mut T>()`). + /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. + /// * If this atomic type is [lock-free](Self::is_lock_free), non-atomic accesses to the value + /// behind `ptr` must have a happens-before relationship with atomic accesses via the returned + /// value (or vice-versa). + /// * In other words, time periods where the value is accessed atomically may not overlap + /// with periods where the value is accessed non-atomically. + /// * This requirement is trivially satisfied if `ptr` is never used non-atomically for the + /// duration of lifetime `'a`. Most use cases should be able to follow this guideline. + /// * This requirement is also trivially satisfied if all accesses (atomic or not) are done + /// from the same thread. + /// * If this atomic type is *not* lock-free: + /// * Any accesses to the value behind `ptr` must have a happens-before relationship + /// with accesses via the returned value (or vice-versa). + /// * Any concurrent accesses to the value behind `ptr` for the duration of lifetime `'a` must + /// be compatible with operations performed by this atomic type. + /// * This method must not be used to create overlapping or mixed-size atomic accesses, as + /// these are not supported by the memory model. + /// + /// [valid]: core::ptr#safety + #[inline] + #[must_use] + pub unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a Self { + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: guaranteed by the caller + unsafe { &*(ptr as *mut Self) } + } + + /// Returns `true` if operations on values of this type are lock-free. + /// + /// If the compiler or the platform doesn't support the necessary + /// atomic instructions, global locks for every potentially + /// concurrent atomic operation will be used. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicPtr; + /// + /// let is_lock_free = AtomicPtr::<()>::is_lock_free(); + /// ``` + #[inline] + #[must_use] + pub fn is_lock_free() -> bool { + >::is_lock_free() + } + + /// Returns `true` if operations on values of this type are lock-free. + /// + /// If the compiler or the platform doesn't support the necessary + /// atomic instructions, global locks for every potentially + /// concurrent atomic operation will be used. + /// + /// **Note:** If the atomic operation relies on dynamic CPU feature detection, + /// this type may be lock-free even if the function returns false. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicPtr; + /// + /// const IS_ALWAYS_LOCK_FREE: bool = AtomicPtr::<()>::is_always_lock_free(); + /// ``` + #[inline] + #[must_use] + pub const fn is_always_lock_free() -> bool { + >::IS_ALWAYS_LOCK_FREE + } + #[cfg(test)] + const IS_ALWAYS_LOCK_FREE: bool = Self::is_always_lock_free(); + + /// Returns a mutable reference to the underlying pointer. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let mut data = 10; + /// let mut atomic_ptr = AtomicPtr::new(&mut data); + /// let mut other_data = 5; + /// *atomic_ptr.get_mut() = &mut other_data; + /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5); + /// ``` + #[inline] + pub fn get_mut(&mut self) -> &mut *mut T { + self.inner.get_mut() + } + + // TODO: Add from_mut/get_mut_slice/from_mut_slice once it is stable on std atomic types. + // https://github.com/rust-lang/rust/issues/76314 + + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_transmute))]; + /// Consumes the atomic and returns the contained value. + /// + /// This is safe because passing `self` by value guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// This is `const fn` on Rust 1.56+. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::AtomicPtr; + /// + /// let mut data = 5; + /// let atomic_ptr = AtomicPtr::new(&mut data); + /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5); + /// ``` + #[inline] + pub const fn into_inner(self) -> *mut T { + // SAFETY: AtomicPtr and *mut T have the same size and in-memory representations, + // so they can be safely transmuted. + // (const UnsafeCell::into_inner is unstable) + unsafe { core::mem::transmute(self) } + } + } + + /// Loads a value from the pointer. + /// + /// `load` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let value = some_ptr.load(Ordering::Relaxed); + /// ``` + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn load(&self, order: Ordering) -> *mut T { + self.inner.load(order) + } + + /// Stores a value into the pointer. + /// + /// `store` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let other_ptr = &mut 10; + /// + /// some_ptr.store(other_ptr, Ordering::Relaxed); + /// ``` + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn store(&self, ptr: *mut T, order: Ordering) { + self.inner.store(ptr, order); + } + + cfg_has_atomic_cas_or_amo32! { + /// Stores a value into the pointer, returning the previous value. + /// + /// `swap` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let other_ptr = &mut 10; + /// + /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T { + self.inner.swap(ptr, order) + } + + cfg_has_atomic_cas! { + /// Stores a value into the pointer if the current value is the same as the `current` value. + /// + /// The return value is a result indicating whether the new value was written and containing + /// the previous value. On success this value is guaranteed to be equal to `current`. + /// + /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `failure` is [`Release`], [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let other_ptr = &mut 10; + /// + /// let value = some_ptr.compare_exchange(ptr, other_ptr, Ordering::SeqCst, Ordering::Relaxed); + /// ``` + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + self.inner.compare_exchange(current, new, success, failure) + } + + /// Stores a value into the pointer if the current value is the same as the `current` value. + /// + /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the + /// comparison succeeds, which can result in more efficient code on some platforms. The + /// return value is a result indicating whether the new value was written and containing the + /// previous value. + /// + /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `failure` is [`Release`], [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let some_ptr = AtomicPtr::new(&mut 5); + /// + /// let new = &mut 10; + /// let mut old = some_ptr.load(Ordering::Relaxed); + /// loop { + /// match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { + /// Ok(_) => break, + /// Err(x) => old = x, + /// } + /// } + /// ``` + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange_weak( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + self.inner.compare_exchange_weak(current, new, success, failure) + } + + /// Fetches the value, and applies a function to it that returns an optional + /// new value. Returns a `Result` of `Ok(previous_value)` if the function + /// returned `Some(_)`, else `Err(previous_value)`. + /// + /// Note: This may call the function multiple times if the value has been + /// changed from other threads in the meantime, as long as the function + /// returns `Some(_)`, but the function will have been applied only once to + /// the stored value. + /// + /// `fetch_update` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. The first describes the required ordering for + /// when the operation finally succeeds while the second describes the + /// required ordering for loads. These correspond to the success and failure + /// orderings of [`compare_exchange`](Self::compare_exchange) respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part of this + /// operation [`Relaxed`], and using [`Release`] makes the final successful + /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], + /// [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `fetch_order` is [`Release`], [`AcqRel`]. + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware. + /// It is implemented in terms of [`compare_exchange_weak`](Self::compare_exchange_weak), + /// and suffers from the same drawbacks. + /// In particular, this method will not circumvent the [ABA Problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let ptr: *mut _ = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let new: *mut _ = &mut 10; + /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr)); + /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| { + /// if x == ptr { + /// Some(new) + /// } else { + /// None + /// } + /// }); + /// assert_eq!(result, Ok(ptr)); + /// assert_eq!(some_ptr.load(Ordering::SeqCst), new); + /// ``` + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: F, + ) -> Result<*mut T, *mut T> + where + F: FnMut(*mut T) -> Option<*mut T>, + { + let mut prev = self.load(fetch_order); + while let Some(next) = f(prev) { + match self.compare_exchange_weak(prev, next, set_order, fetch_order) { + x @ Ok(_) => return x, + Err(next_prev) => prev = next_prev, + } + } + Err(prev) + } + + #[cfg(miri)] + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + fn fetch_update_(&self, order: Ordering, mut f: F) -> *mut T + where + F: FnMut(*mut T) -> *mut T, + { + // This is a private function and all instances of `f` only operate on the value + // loaded, so there is no need to synchronize the first load/failed CAS. + let mut prev = self.load(Ordering::Relaxed); + loop { + let next = f(prev); + match self.compare_exchange_weak(prev, next, order, Ordering::Relaxed) { + Ok(x) => return x, + Err(next_prev) => prev = next_prev, + } + } + } + } // cfg_has_atomic_cas! + + /// Offsets the pointer's address by adding `val` (in units of `T`), + /// returning the previous pointer. + /// + /// This is equivalent to using [`wrapping_add`] to atomically perform the + /// equivalent of `ptr = ptr.wrapping_add(val);`. + /// + /// This method operates in units of `T`, which means that it cannot be used + /// to offset the pointer by an amount which is not a multiple of + /// `size_of::()`. This can sometimes be inconvenient, as you may want to + /// work with a deliberately misaligned pointer. In such cases, you may use + /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead. + /// + /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the + /// memory ordering of this operation. All ordering modes are possible. Note + /// that using [`Acquire`] makes the store part of this operation + /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`]. + /// + /// [`wrapping_add`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_add + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let atom = AtomicPtr::::new(core::ptr::null_mut()); + /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0); + /// // Note: units of `size_of::()`. + /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T { + self.fetch_byte_add(val.wrapping_mul(core::mem::size_of::()), order) + } + + /// Offsets the pointer's address by subtracting `val` (in units of `T`), + /// returning the previous pointer. + /// + /// This is equivalent to using [`wrapping_sub`] to atomically perform the + /// equivalent of `ptr = ptr.wrapping_sub(val);`. + /// + /// This method operates in units of `T`, which means that it cannot be used + /// to offset the pointer by an amount which is not a multiple of + /// `size_of::()`. This can sometimes be inconvenient, as you may want to + /// work with a deliberately misaligned pointer. In such cases, you may use + /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead. + /// + /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// [`wrapping_sub`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_sub + /// + /// # Examples + /// + /// ``` + /// use portable_atomic::{AtomicPtr, Ordering}; + /// + /// let array = [1i32, 2i32]; + /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _); + /// + /// assert!(core::ptr::eq(atom.fetch_ptr_sub(1, Ordering::Relaxed), &array[1])); + /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0])); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T { + self.fetch_byte_sub(val.wrapping_mul(core::mem::size_of::()), order) + } + + /// Offsets the pointer's address by adding `val` *bytes*, returning the + /// previous pointer. + /// + /// This is equivalent to using [`wrapping_add`] and [`cast`] to atomically + /// perform `ptr = ptr.cast::().wrapping_add(val).cast::()`. + /// + /// `fetch_byte_add` takes an [`Ordering`] argument which describes the + /// memory ordering of this operation. All ordering modes are possible. Note + /// that using [`Acquire`] makes the store part of this operation + /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`]. + /// + /// [`wrapping_add`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_add + /// [`cast`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let atom = AtomicPtr::::new(core::ptr::null_mut()); + /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0); + /// // Note: in units of bytes, not `size_of::()`. + /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + self.fetch_update_(order, |x| strict::map_addr(x, |x| x.wrapping_add(val))) + } + #[cfg(not(miri))] + { + self.as_atomic_usize().fetch_add(val, order) as *mut T + } + } + + /// Offsets the pointer's address by subtracting `val` *bytes*, returning the + /// previous pointer. + /// + /// This is equivalent to using [`wrapping_sub`] and [`cast`] to atomically + /// perform `ptr = ptr.cast::().wrapping_sub(val).cast::()`. + /// + /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the + /// memory ordering of this operation. All ordering modes are possible. Note + /// that using [`Acquire`] makes the store part of this operation + /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`]. + /// + /// [`wrapping_sub`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_sub + /// [`cast`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let atom = AtomicPtr::::new(sptr::invalid_mut(1)); + /// assert_eq!(atom.fetch_byte_sub(1, Ordering::Relaxed).addr(), 1); + /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 0); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + self.fetch_update_(order, |x| strict::map_addr(x, |x| x.wrapping_sub(val))) + } + #[cfg(not(miri))] + { + self.as_atomic_usize().fetch_sub(val, order) as *mut T + } + } + + /// Performs a bitwise "or" operation on the address of the current pointer, + /// and the argument `val`, and stores a pointer with provenance of the + /// current pointer and the resulting address. + /// + /// This is equivalent to using [`map_addr`] to atomically perform + /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged + /// pointer schemes to atomically set tag bits. + /// + /// **Caveat**: This operation returns the previous value. To compute the + /// stored value without losing provenance, you may use [`map_addr`]. For + /// example: `a.fetch_or(val).map_addr(|a| a | val)`. + /// + /// `fetch_or` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// This API and its claimed semantics are part of the Strict Provenance + /// experiment, see the [module documentation for `ptr`][core::ptr] for + /// details. + /// + /// [`map_addr`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.map_addr + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let pointer = &mut 3i64 as *mut i64; + /// + /// let atom = AtomicPtr::::new(pointer); + /// // Tag the bottom bit of the pointer. + /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0); + /// // Extract and untag. + /// let tagged = atom.load(Ordering::Relaxed); + /// assert_eq!(tagged.addr() & 1, 1); + /// assert_eq!(tagged.map_addr(|p| p & !1), pointer); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + self.fetch_update_(order, |x| strict::map_addr(x, |x| x | val)) + } + #[cfg(not(miri))] + { + self.as_atomic_usize().fetch_or(val, order) as *mut T + } + } + + /// Performs a bitwise "and" operation on the address of the current + /// pointer, and the argument `val`, and stores a pointer with provenance of + /// the current pointer and the resulting address. + /// + /// This is equivalent to using [`map_addr`] to atomically perform + /// `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged + /// pointer schemes to atomically unset tag bits. + /// + /// **Caveat**: This operation returns the previous value. To compute the + /// stored value without losing provenance, you may use [`map_addr`]. For + /// example: `a.fetch_and(val).map_addr(|a| a & val)`. + /// + /// `fetch_and` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// This API and its claimed semantics are part of the Strict Provenance + /// experiment, see the [module documentation for `ptr`][core::ptr] for + /// details. + /// + /// [`map_addr`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.map_addr + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let pointer = &mut 3i64 as *mut i64; + /// // A tagged pointer + /// let atom = AtomicPtr::::new(pointer.map_addr(|a| a | 1)); + /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1); + /// // Untag, and extract the previously tagged pointer. + /// let untagged = atom.fetch_and(!1, Ordering::Relaxed).map_addr(|a| a & !1); + /// assert_eq!(untagged, pointer); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + self.fetch_update_(order, |x| strict::map_addr(x, |x| x & val)) + } + #[cfg(not(miri))] + { + self.as_atomic_usize().fetch_and(val, order) as *mut T + } + } + + /// Performs a bitwise "xor" operation on the address of the current + /// pointer, and the argument `val`, and stores a pointer with provenance of + /// the current pointer and the resulting address. + /// + /// This is equivalent to using [`map_addr`] to atomically perform + /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged + /// pointer schemes to atomically toggle tag bits. + /// + /// **Caveat**: This operation returns the previous value. To compute the + /// stored value without losing provenance, you may use [`map_addr`]. For + /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`. + /// + /// `fetch_xor` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// This API and its claimed semantics are part of the Strict Provenance + /// experiment, see the [module documentation for `ptr`][core::ptr] for + /// details. + /// + /// [`map_addr`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.map_addr + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let pointer = &mut 3i64 as *mut i64; + /// let atom = AtomicPtr::::new(pointer); + /// + /// // Toggle a tag bit on the pointer. + /// atom.fetch_xor(1, Ordering::Relaxed); + /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + self.fetch_update_(order, |x| strict::map_addr(x, |x| x ^ val)) + } + #[cfg(not(miri))] + { + self.as_atomic_usize().fetch_xor(val, order) as *mut T + } + } + + /// Sets the bit at the specified bit-position to 1. + /// + /// Returns `true` if the specified bit was previously set to 1. + /// + /// `bit_set` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// This corresponds to x86's `lock bts`, and the implementation calls them on x86/x86_64. + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let pointer = &mut 3i64 as *mut i64; + /// + /// let atom = AtomicPtr::::new(pointer); + /// // Tag the bottom bit of the pointer. + /// assert!(!atom.bit_set(0, Ordering::Relaxed)); + /// // Extract and untag. + /// let tagged = atom.load(Ordering::Relaxed); + /// assert_eq!(tagged.addr() & 1, 1); + /// assert_eq!(tagged.map_addr(|p| p & !1), pointer); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn bit_set(&self, bit: u32, order: Ordering) -> bool { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + let mask = 1_usize.wrapping_shl(bit); + self.fetch_or(mask, order) as usize & mask != 0 + } + #[cfg(not(miri))] + { + self.as_atomic_usize().bit_set(bit, order) + } + } + + /// Clears the bit at the specified bit-position to 1. + /// + /// Returns `true` if the specified bit was previously set to 1. + /// + /// `bit_clear` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// This corresponds to x86's `lock btr`, and the implementation calls them on x86/x86_64. + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let pointer = &mut 3i64 as *mut i64; + /// // A tagged pointer + /// let atom = AtomicPtr::::new(pointer.map_addr(|a| a | 1)); + /// assert!(atom.bit_set(0, Ordering::Relaxed)); + /// // Untag + /// assert!(atom.bit_clear(0, Ordering::Relaxed)); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn bit_clear(&self, bit: u32, order: Ordering) -> bool { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + let mask = 1_usize.wrapping_shl(bit); + self.fetch_and(!mask, order) as usize & mask != 0 + } + #[cfg(not(miri))] + { + self.as_atomic_usize().bit_clear(bit, order) + } + } + + /// Toggles the bit at the specified bit-position. + /// + /// Returns `true` if the specified bit was previously set to 1. + /// + /// `bit_toggle` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// This corresponds to x86's `lock btc`, and the implementation calls them on x86/x86_64. + /// + /// # Examples + /// + /// ``` + /// # #![allow(unstable_name_collisions)] + /// use portable_atomic::{AtomicPtr, Ordering}; + /// use sptr::Strict; // stable polyfill for strict provenance + /// + /// let pointer = &mut 3i64 as *mut i64; + /// let atom = AtomicPtr::::new(pointer); + /// + /// // Toggle a tag bit on the pointer. + /// atom.bit_toggle(0, Ordering::Relaxed); + /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1); + /// ``` + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn bit_toggle(&self, bit: u32, order: Ordering) -> bool { + // Ideally, we would always use AtomicPtr::fetch_* since it is strict-provenance + // compatible, but it is unstable. So, for now emulate it only on cfg(miri). + // Code using AtomicUsize::fetch_* via casts is still permissive-provenance + // compatible and is sound. + // TODO: Once `#![feature(strict_provenance_atomic_ptr)]` is stabilized, + // use AtomicPtr::fetch_* in all cases from the version in which it is stabilized. + #[cfg(miri)] + { + let mask = 1_usize.wrapping_shl(bit); + self.fetch_xor(mask, order) as usize & mask != 0 + } + #[cfg(not(miri))] + { + self.as_atomic_usize().bit_toggle(bit, order) + } + } + + #[cfg(not(miri))] + #[inline(always)] + fn as_atomic_usize(&self) -> &AtomicUsize { + static_assert!( + core::mem::size_of::>() == core::mem::size_of::() + ); + static_assert!( + core::mem::align_of::>() == core::mem::align_of::() + ); + // SAFETY: AtomicPtr and AtomicUsize have the same layout, + // and both access data in the same way. + unsafe { &*(self as *const Self as *const AtomicUsize) } + } + } // cfg_has_atomic_cas_or_amo32! + + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_raw_ptr_deref))]; + /// Returns a mutable pointer to the underlying pointer. + /// + /// Returning an `*mut` pointer from a shared reference to this atomic is + /// safe because the atomic types work with interior mutability. Any use of + /// the returned raw pointer requires an `unsafe` block and has to uphold + /// the safety requirements. If there is concurrent access, note the following + /// additional safety requirements: + /// + /// - If this atomic type is [lock-free](Self::is_lock_free), any concurrent + /// operations on it must be atomic. + /// - Otherwise, any concurrent operations on it must be compatible with + /// operations performed by this atomic type. + /// + /// This is `const fn` on Rust 1.58+. + #[inline] + pub const fn as_ptr(&self) -> *mut *mut T { + self.inner.as_ptr() + } + } +} +// See https://github.com/taiki-e/portable-atomic/issues/180 +#[cfg(not(feature = "require-cas"))] +cfg_no_atomic_cas! { +#[doc(hidden)] +#[allow(unused_variables, clippy::unused_self)] +impl<'a, T: 'a> AtomicPtr { + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T + where + &'a Self: HasSwap, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! + #[inline] + pub fn compare_exchange( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> + where + &'a Self: HasCompareExchange, + { + unimplemented!() + } + #[inline] + pub fn compare_exchange_weak( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> + where + &'a Self: HasCompareExchangeWeak, + { + unimplemented!() + } + #[inline] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + f: F, + ) -> Result<*mut T, *mut T> + where + F: FnMut(*mut T) -> Option<*mut T>, + &'a Self: HasFetchUpdate, + { + unimplemented!() + } + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T + where + &'a Self: HasFetchPtrAdd, + { + unimplemented!() + } + #[inline] + pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T + where + &'a Self: HasFetchPtrSub, + { + unimplemented!() + } + #[inline] + pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T + where + &'a Self: HasFetchByteAdd, + { + unimplemented!() + } + #[inline] + pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T + where + &'a Self: HasFetchByteSub, + { + unimplemented!() + } + #[inline] + pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T + where + &'a Self: HasFetchOr, + { + unimplemented!() + } + #[inline] + pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T + where + &'a Self: HasFetchAnd, + { + unimplemented!() + } + #[inline] + pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T + where + &'a Self: HasFetchXor, + { + unimplemented!() + } + #[inline] + pub fn bit_set(&self, bit: u32, order: Ordering) -> bool + where + &'a Self: HasBitSet, + { + unimplemented!() + } + #[inline] + pub fn bit_clear(&self, bit: u32, order: Ordering) -> bool + where + &'a Self: HasBitClear, + { + unimplemented!() + } + #[inline] + pub fn bit_toggle(&self, bit: u32, order: Ordering) -> bool + where + &'a Self: HasBitToggle, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! +} +} // cfg_no_atomic_cas! +} // cfg_has_atomic_ptr! + +macro_rules! atomic_int { + // Atomic{I,U}* impls + ($atomic_type:ident, $int_type:ident, $align:literal, + $cfg_has_atomic_cas_or_amo32_or_8:ident, $cfg_no_atomic_cas_or_amo32_or_8:ident + $(, #[$cfg_float:meta] $atomic_float_type:ident, $float_type:ident)? + ) => { + doc_comment! { + concat!("An integer type which can be safely shared between threads. + +This type has the same in-memory representation as the underlying integer type, +[`", stringify!($int_type), "`]. + +If the compiler and the platform support atomic loads and stores of [`", stringify!($int_type), +"`], this type is a wrapper for the standard library's `", stringify!($atomic_type), +"`. If the platform supports it but the compiler does not, atomic operations are implemented using +inline assembly. Otherwise synchronizes using global locks. +You can call [`", stringify!($atomic_type), "::is_lock_free()`] to check whether +atomic instructions or locks will be used. +" + ), + // We can use #[repr(transparent)] here, but #[repr(C, align(N))] + // will show clearer docs. + #[repr(C, align($align))] + pub struct $atomic_type { + inner: imp::$atomic_type, + } + } + + impl Default for $atomic_type { + #[inline] + fn default() -> Self { + Self::new($int_type::default()) + } + } + + impl From<$int_type> for $atomic_type { + #[inline] + fn from(v: $int_type) -> Self { + Self::new(v) + } + } + + // UnwindSafe is implicitly implemented. + #[cfg(not(portable_atomic_no_core_unwind_safe))] + impl core::panic::RefUnwindSafe for $atomic_type {} + #[cfg(all(portable_atomic_no_core_unwind_safe, feature = "std"))] + impl std::panic::RefUnwindSafe for $atomic_type {} + + impl_debug_and_serde!($atomic_type); + + impl $atomic_type { + doc_comment! { + concat!( + "Creates a new atomic integer. + +# Examples + +``` +use portable_atomic::", stringify!($atomic_type), "; + +let atomic_forty_two = ", stringify!($atomic_type), "::new(42); +```" + ), + #[inline] + #[must_use] + pub const fn new(v: $int_type) -> Self { + static_assert_layout!($atomic_type, $int_type); + Self { inner: imp::$atomic_type::new(v) } + } + } + + // TODO: update docs based on https://github.com/rust-lang/rust/pull/116762 + doc_comment! { + concat!("Creates a new reference to an atomic integer from a pointer. + +# Safety + +* `ptr` must be aligned to `align_of::<", stringify!($atomic_type), ">()` (note that on some platforms this + can be bigger than `align_of::<", stringify!($int_type), ">()`). +* `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. +* If this atomic type is [lock-free](Self::is_lock_free), non-atomic accesses to the value + behind `ptr` must have a happens-before relationship with atomic accesses via + the returned value (or vice-versa). + * In other words, time periods where the value is accessed atomically may not + overlap with periods where the value is accessed non-atomically. + * This requirement is trivially satisfied if `ptr` is never used non-atomically + for the duration of lifetime `'a`. Most use cases should be able to follow + this guideline. + * This requirement is also trivially satisfied if all accesses (atomic or not) are + done from the same thread. +* If this atomic type is *not* lock-free: + * Any accesses to the value behind `ptr` must have a happens-before relationship + with accesses via the returned value (or vice-versa). + * Any concurrent accesses to the value behind `ptr` for the duration of lifetime `'a` must + be compatible with operations performed by this atomic type. +* This method must not be used to create overlapping or mixed-size atomic + accesses, as these are not supported by the memory model. + +[valid]: core::ptr#safety"), + #[inline] + #[must_use] + pub unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a Self { + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: guaranteed by the caller + unsafe { &*(ptr as *mut Self) } + } + } + + doc_comment! { + concat!("Returns `true` if operations on values of this type are lock-free. + +If the compiler or the platform doesn't support the necessary +atomic instructions, global locks for every potentially +concurrent atomic operation will be used. + +# Examples + +``` +use portable_atomic::", stringify!($atomic_type), "; + +let is_lock_free = ", stringify!($atomic_type), "::is_lock_free(); +```"), + #[inline] + #[must_use] + pub fn is_lock_free() -> bool { + ::is_lock_free() + } + } + + doc_comment! { + concat!("Returns `true` if operations on values of this type are lock-free. + +If the compiler or the platform doesn't support the necessary +atomic instructions, global locks for every potentially +concurrent atomic operation will be used. + +**Note:** If the atomic operation relies on dynamic CPU feature detection, +this type may be lock-free even if the function returns false. + +# Examples + +``` +use portable_atomic::", stringify!($atomic_type), "; + +const IS_ALWAYS_LOCK_FREE: bool = ", stringify!($atomic_type), "::is_always_lock_free(); +```"), + #[inline] + #[must_use] + pub const fn is_always_lock_free() -> bool { + ::IS_ALWAYS_LOCK_FREE + } + } + #[cfg(test)] + const IS_ALWAYS_LOCK_FREE: bool = Self::is_always_lock_free(); + + doc_comment! { + concat!("Returns a mutable reference to the underlying integer.\n +This is safe because the mutable reference guarantees that no other threads are +concurrently accessing the atomic data. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let mut some_var = ", stringify!($atomic_type), "::new(10); +assert_eq!(*some_var.get_mut(), 10); +*some_var.get_mut() = 5; +assert_eq!(some_var.load(Ordering::SeqCst), 5); +```"), + #[inline] + pub fn get_mut(&mut self) -> &mut $int_type { + self.inner.get_mut() + } + } + + // TODO: Add from_mut/get_mut_slice/from_mut_slice once it is stable on std atomic types. + // https://github.com/rust-lang/rust/issues/76314 + + #[cfg(not(portable_atomic_no_const_transmute))] + doc_comment! { + concat!("Consumes the atomic and returns the contained value. + +This is safe because passing `self` by value guarantees that no other threads are +concurrently accessing the atomic data. + +This is `const fn` on Rust 1.56+. + +# Examples + +``` +use portable_atomic::", stringify!($atomic_type), "; + +let some_var = ", stringify!($atomic_type), "::new(5); +assert_eq!(some_var.into_inner(), 5); +```"), + #[inline] + pub const fn into_inner(self) -> $int_type { + // SAFETY: $atomic_type and $int_type have the same size and in-memory representations, + // so they can be safely transmuted. + // (const UnsafeCell::into_inner is unstable) + unsafe { core::mem::transmute(self) } + } + } + #[cfg(portable_atomic_no_const_transmute)] + doc_comment! { + concat!("Consumes the atomic and returns the contained value. + +This is safe because passing `self` by value guarantees that no other threads are +concurrently accessing the atomic data. + +This is `const fn` on Rust 1.56+. + +# Examples + +``` +use portable_atomic::", stringify!($atomic_type), "; + +let some_var = ", stringify!($atomic_type), "::new(5); +assert_eq!(some_var.into_inner(), 5); +```"), + #[inline] + pub fn into_inner(self) -> $int_type { + // SAFETY: $atomic_type and $int_type have the same size and in-memory representations, + // so they can be safely transmuted. + // (const UnsafeCell::into_inner is unstable) + unsafe { core::mem::transmute(self) } + } + } + + doc_comment! { + concat!("Loads a value from the atomic integer. + +`load` takes an [`Ordering`] argument which describes the memory ordering of this operation. +Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + +# Panics + +Panics if `order` is [`Release`] or [`AcqRel`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let some_var = ", stringify!($atomic_type), "::new(5); + +assert_eq!(some_var.load(Ordering::Relaxed), 5); +```"), + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn load(&self, order: Ordering) -> $int_type { + self.inner.load(order) + } + } + + doc_comment! { + concat!("Stores a value into the atomic integer. + +`store` takes an [`Ordering`] argument which describes the memory ordering of this operation. +Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + +# Panics + +Panics if `order` is [`Acquire`] or [`AcqRel`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let some_var = ", stringify!($atomic_type), "::new(5); + +some_var.store(10, Ordering::Relaxed); +assert_eq!(some_var.load(Ordering::Relaxed), 10); +```"), + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn store(&self, val: $int_type, order: Ordering) { + self.inner.store(val, order) + } + } + + cfg_has_atomic_cas_or_amo32! { + $cfg_has_atomic_cas_or_amo32_or_8! { + doc_comment! { + concat!("Stores a value into the atomic integer, returning the previous value. + +`swap` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let some_var = ", stringify!($atomic_type), "::new(5); + +assert_eq!(some_var.swap(10, Ordering::Relaxed), 5); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.swap(val, order) + } + } + } // $cfg_has_atomic_cas_or_amo32_or_8! + + cfg_has_atomic_cas! { + doc_comment! { + concat!("Stores a value into the atomic integer if the current value is the same as +the `current` value. + +The return value is a result indicating whether the new value was written and +containing the previous value. On success this value is guaranteed to be equal to +`current`. + +`compare_exchange` takes two [`Ordering`] arguments to describe the memory +ordering of this operation. `success` describes the required ordering for the +read-modify-write operation that takes place if the comparison with `current` succeeds. +`failure` describes the required ordering for the load operation that takes place when +the comparison fails. Using [`Acquire`] as success ordering makes the store part +of this operation [`Relaxed`], and using [`Release`] makes the successful load +[`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + +# Panics + +Panics if `failure` is [`Release`], [`AcqRel`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let some_var = ", stringify!($atomic_type), "::new(5); + +assert_eq!( + some_var.compare_exchange(5, 10, Ordering::Acquire, Ordering::Relaxed), + Ok(5), +); +assert_eq!(some_var.load(Ordering::Relaxed), 10); + +assert_eq!( + some_var.compare_exchange(6, 12, Ordering::SeqCst, Ordering::Acquire), + Err(10), +); +assert_eq!(some_var.load(Ordering::Relaxed), 10); +```"), + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + self.inner.compare_exchange(current, new, success, failure) + } + } + + doc_comment! { + concat!("Stores a value into the atomic integer if the current value is the same as +the `current` value. +Unlike [`compare_exchange`](Self::compare_exchange) +this function is allowed to spuriously fail even +when the comparison succeeds, which can result in more efficient code on some +platforms. The return value is a result indicating whether the new value was +written and containing the previous value. + +`compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory +ordering of this operation. `success` describes the required ordering for the +read-modify-write operation that takes place if the comparison with `current` succeeds. +`failure` describes the required ordering for the load operation that takes place when +the comparison fails. Using [`Acquire`] as success ordering makes the store part +of this operation [`Relaxed`], and using [`Release`] makes the successful load +[`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + +# Panics + +Panics if `failure` is [`Release`], [`AcqRel`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let val = ", stringify!($atomic_type), "::new(4); + +let mut old = val.load(Ordering::Relaxed); +loop { + let new = old * 2; + match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { + Ok(_) => break, + Err(x) => old = x, + } +} +```"), + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> { + self.inner.compare_exchange_weak(current, new, success, failure) + } + } + } // cfg_has_atomic_cas! + + $cfg_has_atomic_cas_or_amo32_or_8! { + doc_comment! { + concat!("Adds to the current value, returning the previous value. + +This operation wraps around on overflow. + +`fetch_add` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0); +assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0); +assert_eq!(foo.load(Ordering::SeqCst), 10); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_add(val, order) + } + } + + doc_comment! { + concat!("Adds to the current value. + +This operation wraps around on overflow. + +Unlike `fetch_add`, this does not return the previous value. + +`add` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This function may generate more efficient code than `fetch_add` on some platforms. + +- MSP430: `add` instead of disabling interrupts ({8,16}-bit atomics) + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0); +foo.add(10, Ordering::SeqCst); +assert_eq!(foo.load(Ordering::SeqCst), 10); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn add(&self, val: $int_type, order: Ordering) { + self.inner.add(val, order); + } + } + + doc_comment! { + concat!("Subtracts from the current value, returning the previous value. + +This operation wraps around on overflow. + +`fetch_sub` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(20); +assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20); +assert_eq!(foo.load(Ordering::SeqCst), 10); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_sub(val, order) + } + } + + doc_comment! { + concat!("Subtracts from the current value. + +This operation wraps around on overflow. + +Unlike `fetch_sub`, this does not return the previous value. + +`sub` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This function may generate more efficient code than `fetch_sub` on some platforms. + +- MSP430: `sub` instead of disabling interrupts ({8,16}-bit atomics) + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(20); +foo.sub(10, Ordering::SeqCst); +assert_eq!(foo.load(Ordering::SeqCst), 10); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn sub(&self, val: $int_type, order: Ordering) { + self.inner.sub(val, order); + } + } + } // $cfg_has_atomic_cas_or_amo32_or_8! + + doc_comment! { + concat!("Bitwise \"and\" with the current value. + +Performs a bitwise \"and\" operation on the current value and the argument `val`, and +sets the new value to the result. + +Returns the previous value. + +`fetch_and` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b101101); +assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101); +assert_eq!(foo.load(Ordering::SeqCst), 0b100001); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_and(val, order) + } + } + + doc_comment! { + concat!("Bitwise \"and\" with the current value. + +Performs a bitwise \"and\" operation on the current value and the argument `val`, and +sets the new value to the result. + +Unlike `fetch_and`, this does not return the previous value. + +`and` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This function may generate more efficient code than `fetch_and` on some platforms. + +- x86/x86_64: `lock and` instead of `cmpxchg` loop ({8,16,32}-bit atomics on x86, but additionally 64-bit atomics on x86_64) +- MSP430: `and` instead of disabling interrupts ({8,16}-bit atomics) + +Note: On x86/x86_64, the use of either function should not usually +affect the generated code, because LLVM can properly optimize the case +where the result is unused. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b101101); +assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101); +assert_eq!(foo.load(Ordering::SeqCst), 0b100001); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn and(&self, val: $int_type, order: Ordering) { + self.inner.and(val, order); + } + } + + cfg_has_atomic_cas! { + doc_comment! { + concat!("Bitwise \"nand\" with the current value. + +Performs a bitwise \"nand\" operation on the current value and the argument `val`, and +sets the new value to the result. + +Returns the previous value. + +`fetch_nand` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0x13); +assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13); +assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31)); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_nand(val, order) + } + } + } // cfg_has_atomic_cas! + + doc_comment! { + concat!("Bitwise \"or\" with the current value. + +Performs a bitwise \"or\" operation on the current value and the argument `val`, and +sets the new value to the result. + +Returns the previous value. + +`fetch_or` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b101101); +assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101); +assert_eq!(foo.load(Ordering::SeqCst), 0b111111); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_or(val, order) + } + } + + doc_comment! { + concat!("Bitwise \"or\" with the current value. + +Performs a bitwise \"or\" operation on the current value and the argument `val`, and +sets the new value to the result. + +Unlike `fetch_or`, this does not return the previous value. + +`or` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This function may generate more efficient code than `fetch_or` on some platforms. + +- x86/x86_64: `lock or` instead of `cmpxchg` loop ({8,16,32}-bit atomics on x86, but additionally 64-bit atomics on x86_64) +- MSP430: `or` instead of disabling interrupts ({8,16}-bit atomics) + +Note: On x86/x86_64, the use of either function should not usually +affect the generated code, because LLVM can properly optimize the case +where the result is unused. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b101101); +assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101); +assert_eq!(foo.load(Ordering::SeqCst), 0b111111); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn or(&self, val: $int_type, order: Ordering) { + self.inner.or(val, order); + } + } + + doc_comment! { + concat!("Bitwise \"xor\" with the current value. + +Performs a bitwise \"xor\" operation on the current value and the argument `val`, and +sets the new value to the result. + +Returns the previous value. + +`fetch_xor` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b101101); +assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101); +assert_eq!(foo.load(Ordering::SeqCst), 0b011110); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_xor(val, order) + } + } + + doc_comment! { + concat!("Bitwise \"xor\" with the current value. + +Performs a bitwise \"xor\" operation on the current value and the argument `val`, and +sets the new value to the result. + +Unlike `fetch_xor`, this does not return the previous value. + +`xor` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This function may generate more efficient code than `fetch_xor` on some platforms. + +- x86/x86_64: `lock xor` instead of `cmpxchg` loop ({8,16,32}-bit atomics on x86, but additionally 64-bit atomics on x86_64) +- MSP430: `xor` instead of disabling interrupts ({8,16}-bit atomics) + +Note: On x86/x86_64, the use of either function should not usually +affect the generated code, because LLVM can properly optimize the case +where the result is unused. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b101101); +foo.xor(0b110011, Ordering::SeqCst); +assert_eq!(foo.load(Ordering::SeqCst), 0b011110); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn xor(&self, val: $int_type, order: Ordering) { + self.inner.xor(val, order); + } + } + + cfg_has_atomic_cas! { + doc_comment! { + concat!("Fetches the value, and applies a function to it that returns an optional +new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else +`Err(previous_value)`. + +Note: This may call the function multiple times if the value has been changed from other threads in +the meantime, as long as the function returns `Some(_)`, but the function will have been applied +only once to the stored value. + +`fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation. +The first describes the required ordering for when the operation finally succeeds while the second +describes the required ordering for loads. These correspond to the success and failure orderings of +[`compare_exchange`](Self::compare_exchange) respectively. + +Using [`Acquire`] as success ordering makes the store part +of this operation [`Relaxed`], and using [`Release`] makes the final successful load +[`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + +# Panics + +Panics if `fetch_order` is [`Release`], [`AcqRel`]. + +# Considerations + +This method is not magic; it is not provided by the hardware. +It is implemented in terms of [`compare_exchange_weak`](Self::compare_exchange_weak), +and suffers from the same drawbacks. +In particular, this method will not circumvent the [ABA Problem]. + +[ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let x = ", stringify!($atomic_type), "::new(7); +assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7)); +assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7)); +assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8)); +assert_eq!(x.load(Ordering::SeqCst), 9); +```"), + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: F, + ) -> Result<$int_type, $int_type> + where + F: FnMut($int_type) -> Option<$int_type>, + { + let mut prev = self.load(fetch_order); + while let Some(next) = f(prev) { + match self.compare_exchange_weak(prev, next, set_order, fetch_order) { + x @ Ok(_) => return x, + Err(next_prev) => prev = next_prev, + } + } + Err(prev) + } + } + } // cfg_has_atomic_cas! + + $cfg_has_atomic_cas_or_amo32_or_8! { + doc_comment! { + concat!("Maximum with the current value. + +Finds the maximum of the current value and the argument `val`, and +sets the new value to the result. + +Returns the previous value. + +`fetch_max` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(23); +assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23); +assert_eq!(foo.load(Ordering::SeqCst), 42); +``` + +If you want to obtain the maximum value in one step, you can use the following: + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(23); +let bar = 42; +let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar); +assert!(max_foo == 42); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_max(val, order) + } + } + + doc_comment! { + concat!("Minimum with the current value. + +Finds the minimum of the current value and the argument `val`, and +sets the new value to the result. + +Returns the previous value. + +`fetch_min` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(23); +assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23); +assert_eq!(foo.load(Ordering::Relaxed), 23); +assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23); +assert_eq!(foo.load(Ordering::Relaxed), 22); +``` + +If you want to obtain the minimum value in one step, you can use the following: + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(23); +let bar = 12; +let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar); +assert_eq!(min_foo, 12); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { + self.inner.fetch_min(val, order) + } + } + } // $cfg_has_atomic_cas_or_amo32_or_8! + + doc_comment! { + concat!("Sets the bit at the specified bit-position to 1. + +Returns `true` if the specified bit was previously set to 1. + +`bit_set` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This corresponds to x86's `lock bts`, and the implementation calls them on x86/x86_64. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b0000); +assert!(!foo.bit_set(0, Ordering::Relaxed)); +assert_eq!(foo.load(Ordering::Relaxed), 0b0001); +assert!(foo.bit_set(0, Ordering::Relaxed)); +assert_eq!(foo.load(Ordering::Relaxed), 0b0001); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn bit_set(&self, bit: u32, order: Ordering) -> bool { + self.inner.bit_set(bit, order) + } + } + + doc_comment! { + concat!("Clears the bit at the specified bit-position to 1. + +Returns `true` if the specified bit was previously set to 1. + +`bit_clear` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This corresponds to x86's `lock btr`, and the implementation calls them on x86/x86_64. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b0001); +assert!(foo.bit_clear(0, Ordering::Relaxed)); +assert_eq!(foo.load(Ordering::Relaxed), 0b0000); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn bit_clear(&self, bit: u32, order: Ordering) -> bool { + self.inner.bit_clear(bit, order) + } + } + + doc_comment! { + concat!("Toggles the bit at the specified bit-position. + +Returns `true` if the specified bit was previously set to 1. + +`bit_toggle` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This corresponds to x86's `lock btc`, and the implementation calls them on x86/x86_64. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0b0000); +assert!(!foo.bit_toggle(0, Ordering::Relaxed)); +assert_eq!(foo.load(Ordering::Relaxed), 0b0001); +assert!(foo.bit_toggle(0, Ordering::Relaxed)); +assert_eq!(foo.load(Ordering::Relaxed), 0b0000); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn bit_toggle(&self, bit: u32, order: Ordering) -> bool { + self.inner.bit_toggle(bit, order) + } + } + + doc_comment! { + concat!("Logical negates the current value, and sets the new value to the result. + +Returns the previous value. + +`fetch_not` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0); +assert_eq!(foo.fetch_not(Ordering::Relaxed), 0); +assert_eq!(foo.load(Ordering::Relaxed), !0); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_not(&self, order: Ordering) -> $int_type { + self.inner.fetch_not(order) + } + } + + doc_comment! { + concat!("Logical negates the current value, and sets the new value to the result. + +Unlike `fetch_not`, this does not return the previous value. + +`not` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This function may generate more efficient code than `fetch_not` on some platforms. + +- x86/x86_64: `lock not` instead of `cmpxchg` loop ({8,16,32}-bit atomics on x86, but additionally 64-bit atomics on x86_64) +- MSP430: `inv` instead of disabling interrupts ({8,16}-bit atomics) + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(0); +foo.not(Ordering::Relaxed); +assert_eq!(foo.load(Ordering::Relaxed), !0); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn not(&self, order: Ordering) { + self.inner.not(order); + } + } + + cfg_has_atomic_cas! { + doc_comment! { + concat!("Negates the current value, and sets the new value to the result. + +Returns the previous value. + +`fetch_neg` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(5); +assert_eq!(foo.fetch_neg(Ordering::Relaxed), 5); +assert_eq!(foo.load(Ordering::Relaxed), 5_", stringify!($int_type), ".wrapping_neg()); +assert_eq!(foo.fetch_neg(Ordering::Relaxed), 5_", stringify!($int_type), ".wrapping_neg()); +assert_eq!(foo.load(Ordering::Relaxed), 5); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_neg(&self, order: Ordering) -> $int_type { + self.inner.fetch_neg(order) + } + } + + doc_comment! { + concat!("Negates the current value, and sets the new value to the result. + +Unlike `fetch_neg`, this does not return the previous value. + +`neg` takes an [`Ordering`] argument which describes the memory ordering +of this operation. All ordering modes are possible. Note that using +[`Acquire`] makes the store part of this operation [`Relaxed`], and +using [`Release`] makes the load part [`Relaxed`]. + +This function may generate more efficient code than `fetch_neg` on some platforms. + +- x86/x86_64: `lock neg` instead of `cmpxchg` loop ({8,16,32}-bit atomics on x86, but additionally 64-bit atomics on x86_64) + +# Examples + +``` +use portable_atomic::{", stringify!($atomic_type), ", Ordering}; + +let foo = ", stringify!($atomic_type), "::new(5); +foo.neg(Ordering::Relaxed); +assert_eq!(foo.load(Ordering::Relaxed), 5_", stringify!($int_type), ".wrapping_neg()); +foo.neg(Ordering::Relaxed); +assert_eq!(foo.load(Ordering::Relaxed), 5); +```"), + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn neg(&self, order: Ordering) { + self.inner.neg(order); + } + } + } // cfg_has_atomic_cas! + } // cfg_has_atomic_cas_or_amo32! + + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_raw_ptr_deref))]; + /// Returns a mutable pointer to the underlying integer. + /// + /// Returning an `*mut` pointer from a shared reference to this atomic is + /// safe because the atomic types work with interior mutability. Any use of + /// the returned raw pointer requires an `unsafe` block and has to uphold + /// the safety requirements. If there is concurrent access, note the following + /// additional safety requirements: + /// + /// - If this atomic type is [lock-free](Self::is_lock_free), any concurrent + /// operations on it must be atomic. + /// - Otherwise, any concurrent operations on it must be compatible with + /// operations performed by this atomic type. + /// + /// This is `const fn` on Rust 1.58+. + #[inline] + pub const fn as_ptr(&self) -> *mut $int_type { + self.inner.as_ptr() + } + } + } + // See https://github.com/taiki-e/portable-atomic/issues/180 + #[cfg(not(feature = "require-cas"))] + cfg_no_atomic_cas! { + #[doc(hidden)] + #[allow(unused_variables, clippy::unused_self)] + impl<'a> $atomic_type { + $cfg_no_atomic_cas_or_amo32_or_8! { + #[inline] + pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasSwap, + { + unimplemented!() + } + } // $cfg_no_atomic_cas_or_amo32_or_8! + #[inline] + pub fn compare_exchange( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> + where + &'a Self: HasCompareExchange, + { + unimplemented!() + } + #[inline] + pub fn compare_exchange_weak( + &self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering, + ) -> Result<$int_type, $int_type> + where + &'a Self: HasCompareExchangeWeak, + { + unimplemented!() + } + $cfg_no_atomic_cas_or_amo32_or_8! { + #[inline] + pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchAdd, + { + unimplemented!() + } + #[inline] + pub fn add(&self, val: $int_type, order: Ordering) + where + &'a Self: HasAdd, + { + unimplemented!() + } + #[inline] + pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchSub, + { + unimplemented!() + } + #[inline] + pub fn sub(&self, val: $int_type, order: Ordering) + where + &'a Self: HasSub, + { + unimplemented!() + } + } // $cfg_no_atomic_cas_or_amo32_or_8! + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchAnd, + { + unimplemented!() + } + #[inline] + pub fn and(&self, val: $int_type, order: Ordering) + where + &'a Self: HasAnd, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! + #[inline] + pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchNand, + { + unimplemented!() + } + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchOr, + { + unimplemented!() + } + #[inline] + pub fn or(&self, val: $int_type, order: Ordering) + where + &'a Self: HasOr, + { + unimplemented!() + } + #[inline] + pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchXor, + { + unimplemented!() + } + #[inline] + pub fn xor(&self, val: $int_type, order: Ordering) + where + &'a Self: HasXor, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! + #[inline] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + f: F, + ) -> Result<$int_type, $int_type> + where + F: FnMut($int_type) -> Option<$int_type>, + &'a Self: HasFetchUpdate, + { + unimplemented!() + } + $cfg_no_atomic_cas_or_amo32_or_8! { + #[inline] + pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchMax, + { + unimplemented!() + } + #[inline] + pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type + where + &'a Self: HasFetchMin, + { + unimplemented!() + } + } // $cfg_no_atomic_cas_or_amo32_or_8! + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn bit_set(&self, bit: u32, order: Ordering) -> bool + where + &'a Self: HasBitSet, + { + unimplemented!() + } + #[inline] + pub fn bit_clear(&self, bit: u32, order: Ordering) -> bool + where + &'a Self: HasBitClear, + { + unimplemented!() + } + #[inline] + pub fn bit_toggle(&self, bit: u32, order: Ordering) -> bool + where + &'a Self: HasBitToggle, + { + unimplemented!() + } + #[inline] + pub fn fetch_not(&self, order: Ordering) -> $int_type + where + &'a Self: HasFetchNot, + { + unimplemented!() + } + #[inline] + pub fn not(&self, order: Ordering) + where + &'a Self: HasNot, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! + #[inline] + pub fn fetch_neg(&self, order: Ordering) -> $int_type + where + &'a Self: HasFetchNeg, + { + unimplemented!() + } + #[inline] + pub fn neg(&self, order: Ordering) + where + &'a Self: HasNeg, + { + unimplemented!() + } + } + } // cfg_no_atomic_cas! + $( + #[$cfg_float] + atomic_int!(float, $atomic_float_type, $float_type, $atomic_type, $int_type, $align); + )? + }; + + // AtomicF* impls + (float, + $atomic_type:ident, + $float_type:ident, + $atomic_int_type:ident, + $int_type:ident, + $align:literal + ) => { + doc_comment! { + concat!("A floating point type which can be safely shared between threads. + +This type has the same in-memory representation as the underlying floating point type, +[`", stringify!($float_type), "`]. +" + ), + #[cfg_attr(docsrs, doc(cfg(feature = "float")))] + // We can use #[repr(transparent)] here, but #[repr(C, align(N))] + // will show clearer docs. + #[repr(C, align($align))] + pub struct $atomic_type { + inner: imp::float::$atomic_type, + } + } + + impl Default for $atomic_type { + #[inline] + fn default() -> Self { + Self::new($float_type::default()) + } + } + + impl From<$float_type> for $atomic_type { + #[inline] + fn from(v: $float_type) -> Self { + Self::new(v) + } + } + + // UnwindSafe is implicitly implemented. + #[cfg(not(portable_atomic_no_core_unwind_safe))] + impl core::panic::RefUnwindSafe for $atomic_type {} + #[cfg(all(portable_atomic_no_core_unwind_safe, feature = "std"))] + impl std::panic::RefUnwindSafe for $atomic_type {} + + impl_debug_and_serde!($atomic_type); + + impl $atomic_type { + /// Creates a new atomic float. + #[inline] + #[must_use] + pub const fn new(v: $float_type) -> Self { + static_assert_layout!($atomic_type, $float_type); + Self { inner: imp::float::$atomic_type::new(v) } + } + + // TODO: update docs based on https://github.com/rust-lang/rust/pull/116762 + doc_comment! { + concat!("Creates a new reference to an atomic float from a pointer. + +# Safety + +* `ptr` must be aligned to `align_of::<", stringify!($atomic_type), ">()` (note that on some platforms this + can be bigger than `align_of::<", stringify!($float_type), ">()`). +* `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. +* If this atomic type is [lock-free](Self::is_lock_free), non-atomic accesses to the value + behind `ptr` must have a happens-before relationship with atomic accesses via + the returned value (or vice-versa). + * In other words, time periods where the value is accessed atomically may not + overlap with periods where the value is accessed non-atomically. + * This requirement is trivially satisfied if `ptr` is never used non-atomically + for the duration of lifetime `'a`. Most use cases should be able to follow + this guideline. + * This requirement is also trivially satisfied if all accesses (atomic or not) are + done from the same thread. +* If this atomic type is *not* lock-free: + * Any accesses to the value behind `ptr` must have a happens-before relationship + with accesses via the returned value (or vice-versa). + * Any concurrent accesses to the value behind `ptr` for the duration of lifetime `'a` must + be compatible with operations performed by this atomic type. +* This method must not be used to create overlapping or mixed-size atomic + accesses, as these are not supported by the memory model. + +[valid]: core::ptr#safety"), + #[inline] + #[must_use] + pub unsafe fn from_ptr<'a>(ptr: *mut $float_type) -> &'a Self { + #[allow(clippy::cast_ptr_alignment)] + // SAFETY: guaranteed by the caller + unsafe { &*(ptr as *mut Self) } + } + } + + /// Returns `true` if operations on values of this type are lock-free. + /// + /// If the compiler or the platform doesn't support the necessary + /// atomic instructions, global locks for every potentially + /// concurrent atomic operation will be used. + #[inline] + #[must_use] + pub fn is_lock_free() -> bool { + ::is_lock_free() + } + + /// Returns `true` if operations on values of this type are lock-free. + /// + /// If the compiler or the platform doesn't support the necessary + /// atomic instructions, global locks for every potentially + /// concurrent atomic operation will be used. + /// + /// **Note:** If the atomic operation relies on dynamic CPU feature detection, + /// this type may be lock-free even if the function returns false. + #[inline] + #[must_use] + pub const fn is_always_lock_free() -> bool { + ::IS_ALWAYS_LOCK_FREE + } + #[cfg(test)] + const IS_ALWAYS_LOCK_FREE: bool = Self::is_always_lock_free(); + + /// Returns a mutable reference to the underlying float. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + #[inline] + pub fn get_mut(&mut self) -> &mut $float_type { + self.inner.get_mut() + } + + // TODO: Add from_mut/get_mut_slice/from_mut_slice once it is stable on std atomic types. + // https://github.com/rust-lang/rust/issues/76314 + + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_transmute))]; + /// Consumes the atomic and returns the contained value. + /// + /// This is safe because passing `self` by value guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// This is `const fn` on Rust 1.56+. + #[inline] + pub const fn into_inner(self) -> $float_type { + // SAFETY: $atomic_type and $float_type have the same size and in-memory representations, + // so they can be safely transmuted. + // (const UnsafeCell::into_inner is unstable) + unsafe { core::mem::transmute(self) } + } + } + + /// Loads a value from the atomic float. + /// + /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation. + /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn load(&self, order: Ordering) -> $float_type { + self.inner.load(order) + } + + /// Stores a value into the atomic float. + /// + /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation. + /// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn store(&self, val: $float_type, order: Ordering) { + self.inner.store(val, order) + } + + cfg_has_atomic_cas_or_amo32! { + /// Stores a value into the atomic float, returning the previous value. + /// + /// `swap` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn swap(&self, val: $float_type, order: Ordering) -> $float_type { + self.inner.swap(val, order) + } + + cfg_has_atomic_cas! { + /// Stores a value into the atomic float if the current value is the same as + /// the `current` value. + /// + /// The return value is a result indicating whether the new value was written and + /// containing the previous value. On success this value is guaranteed to be equal to + /// `current`. + /// + /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `failure` is [`Release`], [`AcqRel`]. + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange( + &self, + current: $float_type, + new: $float_type, + success: Ordering, + failure: Ordering, + ) -> Result<$float_type, $float_type> { + self.inner.compare_exchange(current, new, success, failure) + } + + /// Stores a value into the atomic float if the current value is the same as + /// the `current` value. + /// Unlike [`compare_exchange`](Self::compare_exchange) + /// this function is allowed to spuriously fail even + /// when the comparison succeeds, which can result in more efficient code on some + /// platforms. The return value is a result indicating whether the new value was + /// written and containing the previous value. + /// + /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `failure` is [`Release`], [`AcqRel`]. + #[inline] + #[cfg_attr(docsrs, doc(alias = "compare_and_swap"))] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn compare_exchange_weak( + &self, + current: $float_type, + new: $float_type, + success: Ordering, + failure: Ordering, + ) -> Result<$float_type, $float_type> { + self.inner.compare_exchange_weak(current, new, success, failure) + } + + /// Adds to the current value, returning the previous value. + /// + /// This operation wraps around on overflow. + /// + /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_add(&self, val: $float_type, order: Ordering) -> $float_type { + self.inner.fetch_add(val, order) + } + + /// Subtracts from the current value, returning the previous value. + /// + /// This operation wraps around on overflow. + /// + /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_sub(&self, val: $float_type, order: Ordering) -> $float_type { + self.inner.fetch_sub(val, order) + } + + /// Fetches the value, and applies a function to it that returns an optional + /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else + /// `Err(previous_value)`. + /// + /// Note: This may call the function multiple times if the value has been changed from other threads in + /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied + /// only once to the stored value. + /// + /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation. + /// The first describes the required ordering for when the operation finally succeeds while the second + /// describes the required ordering for loads. These correspond to the success and failure orderings of + /// [`compare_exchange`](Self::compare_exchange) respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load + /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `fetch_order` is [`Release`], [`AcqRel`]. + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware. + /// It is implemented in terms of [`compare_exchange_weak`](Self::compare_exchange_weak), + /// and suffers from the same drawbacks. + /// In particular, this method will not circumvent the [ABA Problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + #[inline] + #[cfg_attr( + any(all(debug_assertions, not(portable_atomic_no_track_caller)), miri), + track_caller + )] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: F, + ) -> Result<$float_type, $float_type> + where + F: FnMut($float_type) -> Option<$float_type>, + { + let mut prev = self.load(fetch_order); + while let Some(next) = f(prev) { + match self.compare_exchange_weak(prev, next, set_order, fetch_order) { + x @ Ok(_) => return x, + Err(next_prev) => prev = next_prev, + } + } + Err(prev) + } + + /// Maximum with the current value. + /// + /// Finds the maximum of the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_max(&self, val: $float_type, order: Ordering) -> $float_type { + self.inner.fetch_max(val, order) + } + + /// Minimum with the current value. + /// + /// Finds the minimum of the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_min(&self, val: $float_type, order: Ordering) -> $float_type { + self.inner.fetch_min(val, order) + } + } // cfg_has_atomic_cas! + + /// Negates the current value, and sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_neg` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_neg(&self, order: Ordering) -> $float_type { + self.inner.fetch_neg(order) + } + + /// Computes the absolute value of the current value, and sets the + /// new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_abs` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub fn fetch_abs(&self, order: Ordering) -> $float_type { + self.inner.fetch_abs(order) + } + } // cfg_has_atomic_cas_or_amo32! + + #[cfg(not(portable_atomic_no_const_raw_ptr_deref))] + doc_comment! { + concat!("Raw transmutation to `&", stringify!($atomic_int_type), "`. + +See [`", stringify!($float_type) ,"::from_bits`] for some discussion of the +portability of this operation (there are almost no issues). + +This is `const fn` on Rust 1.58+."), + #[inline] + pub const fn as_bits(&self) -> &$atomic_int_type { + self.inner.as_bits() + } + } + #[cfg(portable_atomic_no_const_raw_ptr_deref)] + doc_comment! { + concat!("Raw transmutation to `&", stringify!($atomic_int_type), "`. + +See [`", stringify!($float_type) ,"::from_bits`] for some discussion of the +portability of this operation (there are almost no issues). + +This is `const fn` on Rust 1.58+."), + #[inline] + pub fn as_bits(&self) -> &$atomic_int_type { + self.inner.as_bits() + } + } + + const_fn! { + const_if: #[cfg(not(portable_atomic_no_const_raw_ptr_deref))]; + /// Returns a mutable pointer to the underlying float. + /// + /// Returning an `*mut` pointer from a shared reference to this atomic is + /// safe because the atomic types work with interior mutability. Any use of + /// the returned raw pointer requires an `unsafe` block and has to uphold + /// the safety requirements. If there is concurrent access, note the following + /// additional safety requirements: + /// + /// - If this atomic type is [lock-free](Self::is_lock_free), any concurrent + /// operations on it must be atomic. + /// - Otherwise, any concurrent operations on it must be compatible with + /// operations performed by this atomic type. + /// + /// This is `const fn` on Rust 1.58+. + #[inline] + pub const fn as_ptr(&self) -> *mut $float_type { + self.inner.as_ptr() + } + } + } + // See https://github.com/taiki-e/portable-atomic/issues/180 + #[cfg(not(feature = "require-cas"))] + cfg_no_atomic_cas! { + #[doc(hidden)] + #[allow(unused_variables, clippy::unused_self)] + impl<'a> $atomic_type { + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn swap(&self, val: $float_type, order: Ordering) -> $float_type + where + &'a Self: HasSwap, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! + #[inline] + pub fn compare_exchange( + &self, + current: $float_type, + new: $float_type, + success: Ordering, + failure: Ordering, + ) -> Result<$float_type, $float_type> + where + &'a Self: HasCompareExchange, + { + unimplemented!() + } + #[inline] + pub fn compare_exchange_weak( + &self, + current: $float_type, + new: $float_type, + success: Ordering, + failure: Ordering, + ) -> Result<$float_type, $float_type> + where + &'a Self: HasCompareExchangeWeak, + { + unimplemented!() + } + #[inline] + pub fn fetch_add(&self, val: $float_type, order: Ordering) -> $float_type + where + &'a Self: HasFetchAdd, + { + unimplemented!() + } + #[inline] + pub fn fetch_sub(&self, val: $float_type, order: Ordering) -> $float_type + where + &'a Self: HasFetchSub, + { + unimplemented!() + } + #[inline] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + f: F, + ) -> Result<$float_type, $float_type> + where + F: FnMut($float_type) -> Option<$float_type>, + &'a Self: HasFetchUpdate, + { + unimplemented!() + } + #[inline] + pub fn fetch_max(&self, val: $float_type, order: Ordering) -> $float_type + where + &'a Self: HasFetchMax, + { + unimplemented!() + } + #[inline] + pub fn fetch_min(&self, val: $float_type, order: Ordering) -> $float_type + where + &'a Self: HasFetchMin, + { + unimplemented!() + } + cfg_no_atomic_cas_or_amo32! { + #[inline] + pub fn fetch_neg(&self, order: Ordering) -> $float_type + where + &'a Self: HasFetchNeg, + { + unimplemented!() + } + #[inline] + pub fn fetch_abs(&self, order: Ordering) -> $float_type + where + &'a Self: HasFetchAbs, + { + unimplemented!() + } + } // cfg_no_atomic_cas_or_amo32! + } + } // cfg_no_atomic_cas! + }; +} + +cfg_has_atomic_ptr! { + #[cfg(target_pointer_width = "16")] + atomic_int!(AtomicIsize, isize, 2, cfg_has_atomic_cas_or_amo8, cfg_no_atomic_cas_or_amo8); + #[cfg(target_pointer_width = "16")] + atomic_int!(AtomicUsize, usize, 2, cfg_has_atomic_cas_or_amo8, cfg_no_atomic_cas_or_amo8); + #[cfg(target_pointer_width = "32")] + atomic_int!(AtomicIsize, isize, 4, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + #[cfg(target_pointer_width = "32")] + atomic_int!(AtomicUsize, usize, 4, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + #[cfg(target_pointer_width = "64")] + atomic_int!(AtomicIsize, isize, 8, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + #[cfg(target_pointer_width = "64")] + atomic_int!(AtomicUsize, usize, 8, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + #[cfg(target_pointer_width = "128")] + atomic_int!(AtomicIsize, isize, 16, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + #[cfg(target_pointer_width = "128")] + atomic_int!(AtomicUsize, usize, 16, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); +} + +cfg_has_atomic_8! { + atomic_int!(AtomicI8, i8, 1, cfg_has_atomic_cas_or_amo8, cfg_no_atomic_cas_or_amo8); + atomic_int!(AtomicU8, u8, 1, cfg_has_atomic_cas_or_amo8, cfg_no_atomic_cas_or_amo8); +} +cfg_has_atomic_16! { + atomic_int!(AtomicI16, i16, 2, cfg_has_atomic_cas_or_amo8, cfg_no_atomic_cas_or_amo8); + atomic_int!(AtomicU16, u16, 2, cfg_has_atomic_cas_or_amo8, cfg_no_atomic_cas_or_amo8); + // TODO: support once https://github.com/rust-lang/rust/issues/116909 stabilized. + // #[cfg(all(feature = "float", not(portable_atomic_no_f16)))] AtomicF16, f16); +} +cfg_has_atomic_32! { + atomic_int!(AtomicI32, i32, 4, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + atomic_int!(AtomicU32, u32, 4, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32, + #[cfg(feature = "float")] AtomicF32, f32); +} +cfg_has_atomic_64! { + atomic_int!(AtomicI64, i64, 8, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + atomic_int!(AtomicU64, u64, 8, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32, + #[cfg(feature = "float")] AtomicF64, f64); +} +cfg_has_atomic_128! { + atomic_int!(AtomicI128, i128, 16, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + atomic_int!(AtomicU128, u128, 16, cfg_has_atomic_cas_or_amo32, cfg_no_atomic_cas_or_amo32); + // TODO: support once https://github.com/rust-lang/rust/issues/116909 stabilized. + // #[cfg(all(feature = "float", not(portable_atomic_no_f128)))] AtomicF128, f128); +} + +// See https://github.com/taiki-e/portable-atomic/issues/180 +#[cfg(not(feature = "require-cas"))] +cfg_no_atomic_cas! { +cfg_no_atomic_cas_or_amo32! { +#[cfg(feature = "float")] +use diagnostic_helper::HasFetchAbs; +use diagnostic_helper::{ + HasAnd, HasBitClear, HasBitSet, HasBitToggle, HasFetchAnd, HasFetchByteAdd, HasFetchByteSub, + HasFetchNot, HasFetchOr, HasFetchPtrAdd, HasFetchPtrSub, HasFetchXor, HasNot, HasOr, HasXor, +}; +} // cfg_no_atomic_cas_or_amo32! +cfg_no_atomic_cas_or_amo8! { +use diagnostic_helper::{HasAdd, HasSub, HasSwap}; +} // cfg_no_atomic_cas_or_amo8! +#[cfg_attr(not(feature = "float"), allow(unused_imports))] +use diagnostic_helper::{ + HasCompareExchange, HasCompareExchangeWeak, HasFetchAdd, HasFetchMax, HasFetchMin, + HasFetchNand, HasFetchNeg, HasFetchSub, HasFetchUpdate, HasNeg, +}; +#[cfg_attr( + any( + all( + portable_atomic_no_atomic_load_store, + not(any( + target_arch = "avr", + target_arch = "bpf", + target_arch = "msp430", + target_arch = "riscv32", + target_arch = "riscv64", + feature = "critical-section", + )), + ), + not(feature = "float"), + ), + allow(dead_code, unreachable_pub) +)] +mod diagnostic_helper { + cfg_no_atomic_cas_or_amo8! { + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`swap` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasSwap {} + } // cfg_no_atomic_cas_or_amo8! + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`compare_exchange` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasCompareExchange {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`compare_exchange_weak` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasCompareExchangeWeak {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_add` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchAdd {} + cfg_no_atomic_cas_or_amo8! { + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`add` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasAdd {} + } // cfg_no_atomic_cas_or_amo8! + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_sub` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchSub {} + cfg_no_atomic_cas_or_amo8! { + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`sub` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasSub {} + } // cfg_no_atomic_cas_or_amo8! + cfg_no_atomic_cas_or_amo32! { + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_ptr_add` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchPtrAdd {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_ptr_sub` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchPtrSub {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_byte_add` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchByteAdd {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_byte_sub` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchByteSub {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_and` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchAnd {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`and` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasAnd {} + } // cfg_no_atomic_cas_or_amo32! + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_nand` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchNand {} + cfg_no_atomic_cas_or_amo32! { + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_or` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchOr {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`or` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasOr {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_xor` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchXor {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`xor` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasXor {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_not` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchNot {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`not` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasNot {} + } // cfg_no_atomic_cas_or_amo32! + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_neg` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchNeg {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`neg` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasNeg {} + cfg_no_atomic_cas_or_amo32! { + #[cfg(feature = "float")] + #[cfg_attr(target_pointer_width = "16", allow(dead_code, unreachable_pub))] + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_abs` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchAbs {} + } // cfg_no_atomic_cas_or_amo32! + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_min` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchMin {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_max` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchMax {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`fetch_update` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasFetchUpdate {} + cfg_no_atomic_cas_or_amo32! { + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`bit_set` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasBitSet {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`bit_clear` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasBitClear {} + #[doc(hidden)] + #[cfg_attr( + not(portable_atomic_no_diagnostic_namespace), + diagnostic::on_unimplemented( + message = "`bit_toggle` requires atomic CAS but not available on this target by default", + label = "this associated function is not available on this target by default", + note = "consider enabling one of the `unsafe-assume-single-core` or `critical-section` Cargo features", + note = "see for more." + ) + )] + pub trait HasBitToggle {} + } // cfg_no_atomic_cas_or_amo32! +} +} // cfg_no_atomic_cas! diff --git a/bitbox02-bt/vendor/portable-atomic/src/tests/helper.rs b/bitbox02-bt/vendor/portable-atomic/src/tests/helper.rs new file mode 100644 index 0000000..2f6d875 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/tests/helper.rs @@ -0,0 +1,2421 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#![allow(unused_macros, clippy::undocumented_unsafe_blocks)] + +use core::sync::atomic::Ordering; + +macro_rules! __test_atomic_common { + ($atomic_type:ty, $value_type:ty) => { + #[test] + fn assert_auto_traits() { + fn _assert() {} + _assert::<$atomic_type>(); + } + #[test] + fn alignment() { + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/tests/atomic.rs#L250 + assert_eq!(core::mem::align_of::<$atomic_type>(), core::mem::size_of::<$atomic_type>()); + assert_eq!(core::mem::size_of::<$atomic_type>(), core::mem::size_of::<$value_type>()); + } + #[test] + fn is_lock_free() { + const IS_ALWAYS_LOCK_FREE: bool = <$atomic_type>::IS_ALWAYS_LOCK_FREE; + assert_eq!(IS_ALWAYS_LOCK_FREE, <$atomic_type>::IS_ALWAYS_LOCK_FREE); + let is_lock_free = <$atomic_type>::is_lock_free(); + if IS_ALWAYS_LOCK_FREE { + // If is_always_lock_free is true, then is_lock_free must always be true. + assert!(is_lock_free); + } + } + }; +} +macro_rules! __test_atomic_pub_common { + ($atomic_type:ty, $value_type:ty) => { + #[test] + fn is_always_lock_free() { + assert_eq!(<$atomic_type>::IS_ALWAYS_LOCK_FREE, <$atomic_type>::is_always_lock_free()); + } + #[test] + fn assert_ref_unwind_safe() { + #[cfg(not(all(portable_atomic_no_core_unwind_safe, not(feature = "std"))))] + static_assertions::assert_impl_all!($atomic_type: std::panic::RefUnwindSafe); + #[cfg(all(portable_atomic_no_core_unwind_safe, not(feature = "std")))] + static_assertions::assert_not_impl_all!($atomic_type: std::panic::RefUnwindSafe); + } + }; +} + +macro_rules! __test_atomic_int_load_store { + ($atomic_type:ty, $int_type:ident, single_thread) => { + __test_atomic_common!($atomic_type, $int_type); + use crate::tests::helper::*; + #[test] + fn accessor() { + let mut a = <$atomic_type>::new(10); + assert_eq!(*a.get_mut(), 10); + *a.get_mut() = 5; + assert_eq!(a.as_ptr() as *const (), &a as *const _ as *const ()); + assert_eq!(*a.get_mut(), 5); + } + // https://bugs.llvm.org/show_bug.cgi?id=37061 + #[test] + fn static_load_only() { + static VAR: $atomic_type = <$atomic_type>::new(10); + for &order in &test_helper::LOAD_ORDERINGS { + assert_eq!(VAR.load(order), 10); + } + } + #[test] + fn load_store() { + static VAR: $atomic_type = <$atomic_type>::new(10); + test_load_ordering(|order| VAR.load(order)); + test_store_ordering(|order| VAR.store(10, order)); + for (&load_order, &store_order) in + test_helper::LOAD_ORDERINGS.iter().zip(&test_helper::STORE_ORDERINGS) + { + assert_eq!(VAR.load(load_order), 10); + VAR.store(5, store_order); + assert_eq!(VAR.load(load_order), 5); + VAR.store(10, store_order); + let a = <$atomic_type>::new(1); + assert_eq!(a.load(load_order), 1); + a.store(2, store_order); + assert_eq!(a.load(load_order), 2); + } + } + }; + ($atomic_type:ty, $int_type:ident) => { + __test_atomic_int_load_store!($atomic_type, $int_type, single_thread); + use crossbeam_utils::thread; + use std::{collections::BTreeSet, vec, vec::Vec}; + #[test] + fn stress_load_store() { + let (iterations, threads) = stress_test_config(); + let data1 = (0..iterations).map(|_| fastrand::$int_type(..)).collect::>(); + let set = data1.iter().copied().collect::>(); + let a = <$atomic_type>::new(data1[fastrand::usize(0..iterations)]); + let now = &std::time::Instant::now(); + thread::scope(|s| { + for _ in 0..threads { + s.spawn(|_| { + let now = *now; + for i in 0..iterations { + a.store(data1[i], rand_store_ordering()); + } + std::eprintln!("store end={:?}", now.elapsed()); + }); + s.spawn(|_| { + let now = *now; + let mut v = vec![0; iterations]; + for i in 0..iterations { + v[i] = a.load(rand_load_ordering()); + } + std::eprintln!("load end={:?}", now.elapsed()); + for v in v { + assert!(set.contains(&v), "v={}", v); + } + }); + } + }) + .unwrap(); + } + }; +} +macro_rules! __test_atomic_float_load_store { + ($atomic_type:ty, $float_type:ident, single_thread) => { + __test_atomic_common!($atomic_type, $float_type); + use crate::tests::helper::*; + #[test] + fn accessor() { + let mut a = <$atomic_type>::new(10.); + assert_eq!(*a.get_mut(), 10.); + *a.get_mut() = 5.; + assert_eq!(a.as_ptr() as *const (), &a as *const _ as *const ()); + assert_eq!(*a.get_mut(), 5.); + } + // https://bugs.llvm.org/show_bug.cgi?id=37061 + #[test] + fn static_load_only() { + static VAR: $atomic_type = <$atomic_type>::new(10.); + for &order in &test_helper::LOAD_ORDERINGS { + assert_eq!(VAR.load(order), 10.); + } + } + #[test] + fn load_store() { + static VAR: $atomic_type = <$atomic_type>::new(10.); + test_load_ordering(|order| VAR.load(order)); + test_store_ordering(|order| VAR.store(10., order)); + for (&load_order, &store_order) in + test_helper::LOAD_ORDERINGS.iter().zip(&test_helper::STORE_ORDERINGS) + { + assert_eq!(VAR.load(load_order), 10.); + VAR.store(5., store_order); + assert_eq!(VAR.load(load_order), 5.); + VAR.store(10., store_order); + let a = <$atomic_type>::new(1.); + assert_eq!(a.load(load_order), 1.); + a.store(2., store_order); + assert_eq!(a.load(load_order), 2.); + } + } + }; + ($atomic_type:ty, $float_type:ident) => { + __test_atomic_float_load_store!($atomic_type, $float_type, single_thread); + // TODO: multi thread + }; +} +macro_rules! __test_atomic_bool_load_store { + ($atomic_type:ty, single_thread) => { + __test_atomic_common!($atomic_type, bool); + use crate::tests::helper::*; + #[test] + fn accessor() { + let mut a = <$atomic_type>::new(false); + assert_eq!(*a.get_mut(), false); + *a.get_mut() = true; + assert_eq!(a.as_ptr() as *const (), &a as *const _ as *const ()); + assert_eq!(*a.get_mut(), true); + } + // https://bugs.llvm.org/show_bug.cgi?id=37061 + #[test] + fn static_load_only() { + static VAR: $atomic_type = <$atomic_type>::new(false); + for &order in &test_helper::LOAD_ORDERINGS { + assert_eq!(VAR.load(order), false); + } + } + #[test] + fn load_store() { + static VAR: $atomic_type = <$atomic_type>::new(false); + test_load_ordering(|order| VAR.load(order)); + test_store_ordering(|order| VAR.store(false, order)); + for (&load_order, &store_order) in + test_helper::LOAD_ORDERINGS.iter().zip(&test_helper::STORE_ORDERINGS) + { + assert_eq!(VAR.load(load_order), false); + VAR.store(true, store_order); + assert_eq!(VAR.load(load_order), true); + VAR.store(false, store_order); + let a = <$atomic_type>::new(true); + assert_eq!(a.load(load_order), true); + a.store(false, store_order); + assert_eq!(a.load(load_order), false); + } + } + }; + ($atomic_type:ty) => { + __test_atomic_bool_load_store!($atomic_type, single_thread); + // TODO: multi thread + }; +} +macro_rules! __test_atomic_ptr_load_store { + ($atomic_type:ty, single_thread) => { + __test_atomic_common!($atomic_type, *mut u8); + use crate::tests::helper::*; + use std::ptr; + #[test] + fn accessor() { + let mut v = 1; + let mut a = <$atomic_type>::new(ptr::null_mut()); + assert!(a.get_mut().is_null()); + *a.get_mut() = &mut v; + assert_eq!(a.as_ptr() as *const (), &a as *const _ as *const ()); + assert!(!a.get_mut().is_null()); + } + // https://bugs.llvm.org/show_bug.cgi?id=37061 + #[test] + fn static_load_only() { + static VAR: $atomic_type = <$atomic_type>::new(ptr::null_mut()); + for &order in &test_helper::LOAD_ORDERINGS { + assert_eq!(VAR.load(order), ptr::null_mut()); + } + } + #[test] + fn load_store() { + static VAR: $atomic_type = <$atomic_type>::new(ptr::null_mut()); + test_load_ordering(|order| VAR.load(order)); + test_store_ordering(|order| VAR.store(ptr::null_mut(), order)); + let mut v = 1_u8; + let p = &mut v as *mut u8; + for (&load_order, &store_order) in + test_helper::LOAD_ORDERINGS.iter().zip(&test_helper::STORE_ORDERINGS) + { + assert_eq!(VAR.load(load_order), ptr::null_mut()); + VAR.store(p, store_order); + assert_eq!(VAR.load(load_order), p); + VAR.store(ptr::null_mut(), store_order); + let a = <$atomic_type>::new(p); + assert_eq!(a.load(load_order), p); + a.store(ptr::null_mut(), store_order); + assert_eq!(a.load(load_order), ptr::null_mut()); + } + } + }; + ($atomic_type:ty) => { + __test_atomic_ptr_load_store!($atomic_type, single_thread); + // TODO: multi thread + }; +} + +macro_rules! __test_atomic_int { + ($atomic_type:ty, $int_type:ident, single_thread) => { + #[test] + fn swap() { + let a = <$atomic_type>::new(5); + test_swap_ordering(|order| a.swap(5, order)); + for &order in &test_helper::SWAP_ORDERINGS { + assert_eq!(a.swap(10, order), 5); + assert_eq!(a.swap(5, order), 10); + } + } + #[test] + fn compare_exchange() { + let a = <$atomic_type>::new(5); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange(5, 5, success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(5); + assert_eq!(a.compare_exchange(5, 10, success, failure), Ok(5)); + assert_eq!(a.load(Ordering::Relaxed), 10); + assert_eq!(a.compare_exchange(6, 12, success, failure), Err(10)); + assert_eq!(a.load(Ordering::Relaxed), 10); + } + } + #[test] + fn compare_exchange_weak() { + let a = <$atomic_type>::new(4); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange_weak(4, 4, success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(4); + assert_eq!(a.compare_exchange_weak(6, 8, success, failure), Err(4)); + let mut old = a.load(Ordering::Relaxed); + loop { + let new = old * 2; + match a.compare_exchange_weak(old, new, success, failure) { + Ok(_) => break, + Err(x) => old = x, + } + } + assert_eq!(a.load(Ordering::Relaxed), 8); + } + } + #[test] + fn fetch_add() { + let a = <$atomic_type>::new(0); + test_swap_ordering(|order| a.fetch_add(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0); + assert_eq!(a.fetch_add(10, order), 0); + assert_eq!(a.load(Ordering::Relaxed), 10); + let a = <$atomic_type>::new($int_type::MAX); + assert_eq!(a.fetch_add(1, order), $int_type::MAX); + assert_eq!(a.load(Ordering::Relaxed), $int_type::MAX.wrapping_add(1)); + } + } + #[test] + fn add() { + let a = <$atomic_type>::new(0); + test_swap_ordering(|order| a.add(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0); + a.add(10, order); + assert_eq!(a.load(Ordering::Relaxed), 10); + let a = <$atomic_type>::new($int_type::MAX); + a.add(1, order); + assert_eq!(a.load(Ordering::Relaxed), $int_type::MAX.wrapping_add(1)); + } + } + #[test] + fn fetch_sub() { + let a = <$atomic_type>::new(20); + test_swap_ordering(|order| a.fetch_sub(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(20); + assert_eq!(a.fetch_sub(10, order), 20); + assert_eq!(a.load(Ordering::Relaxed), 10); + let a = <$atomic_type>::new($int_type::MIN); + assert_eq!(a.fetch_sub(1, order), $int_type::MIN); + assert_eq!(a.load(Ordering::Relaxed), $int_type::MIN.wrapping_sub(1)); + } + } + #[test] + fn sub() { + let a = <$atomic_type>::new(20); + test_swap_ordering(|order| a.sub(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(20); + a.sub(10, order); + assert_eq!(a.load(Ordering::Relaxed), 10); + let a = <$atomic_type>::new($int_type::MIN); + a.sub(1, order); + assert_eq!(a.load(Ordering::Relaxed), $int_type::MIN.wrapping_sub(1)); + } + } + #[test] + fn fetch_and() { + let a = <$atomic_type>::new(0b101101); + test_swap_ordering(|order| a.fetch_and(0b101101, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b101101); + assert_eq!(a.fetch_and(0b110011, order), 0b101101); + assert_eq!(a.load(Ordering::Relaxed), 0b100001); + } + } + #[test] + fn and() { + let a = <$atomic_type>::new(0b101101); + test_swap_ordering(|order| a.and(0b101101, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b101101); + a.and(0b110011, order); + assert_eq!(a.load(Ordering::Relaxed), 0b100001); + } + } + #[test] + fn fetch_nand() { + let a = <$atomic_type>::new(0x13); + test_swap_ordering(|order| a.fetch_nand(0x31, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0x13); + assert_eq!(a.fetch_nand(0x31, order), 0x13); + assert_eq!(a.load(Ordering::Relaxed), !(0x13 & 0x31)); + } + } + #[test] + fn fetch_or() { + let a = <$atomic_type>::new(0b101101); + test_swap_ordering(|order| a.fetch_or(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b101101); + assert_eq!(a.fetch_or(0b110011, order), 0b101101); + assert_eq!(a.load(Ordering::Relaxed), 0b111111); + } + } + #[test] + fn or() { + let a = <$atomic_type>::new(0b101101); + test_swap_ordering(|order| a.or(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b101101); + a.or(0b110011, order); + assert_eq!(a.load(Ordering::Relaxed), 0b111111); + } + } + #[test] + fn fetch_xor() { + let a = <$atomic_type>::new(0b101101); + test_swap_ordering(|order| a.fetch_xor(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b101101); + assert_eq!(a.fetch_xor(0b110011, order), 0b101101); + assert_eq!(a.load(Ordering::Relaxed), 0b011110); + } + } + #[test] + fn xor() { + let a = <$atomic_type>::new(0b101101); + test_swap_ordering(|order| a.xor(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b101101); + a.xor(0b110011, order); + assert_eq!(a.load(Ordering::Relaxed), 0b011110); + } + } + #[test] + fn fetch_max() { + let a = <$atomic_type>::new(23); + test_swap_ordering(|order| a.fetch_max(23, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(23); + assert_eq!(a.fetch_max(22, order), 23); + assert_eq!(a.load(Ordering::Relaxed), 23); + assert_eq!(a.fetch_max(24, order), 23); + assert_eq!(a.load(Ordering::Relaxed), 24); + let a = <$atomic_type>::new(0); + assert_eq!(a.fetch_max(1, order), 0); + assert_eq!(a.load(Ordering::Relaxed), 1); + assert_eq!(a.fetch_max(0, order), 1); + assert_eq!(a.load(Ordering::Relaxed), 1); + let a = <$atomic_type>::new(!0); + assert_eq!(a.fetch_max(0, order), !0); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::max(!0, 0)); + } + } + #[test] + fn fetch_min() { + let a = <$atomic_type>::new(23); + test_swap_ordering(|order| a.fetch_min(23, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(23); + assert_eq!(a.fetch_min(24, order), 23); + assert_eq!(a.load(Ordering::Relaxed), 23); + assert_eq!(a.fetch_min(22, order), 23); + assert_eq!(a.load(Ordering::Relaxed), 22); + let a = <$atomic_type>::new(1); + assert_eq!(a.fetch_min(0, order), 1); + assert_eq!(a.load(Ordering::Relaxed), 0); + assert_eq!(a.fetch_min(1, order), 0); + assert_eq!(a.load(Ordering::Relaxed), 0); + let a = <$atomic_type>::new(!0); + assert_eq!(a.fetch_min(0, order), !0); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::min(!0, 0)); + } + } + #[test] + fn fetch_not() { + let a = <$atomic_type>::new(1); + test_swap_ordering(|order| a.fetch_not(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(1); + assert_eq!(a.fetch_not(order), 1); + assert_eq!(a.load(Ordering::Relaxed), !1); + } + } + #[test] + fn not() { + let a = <$atomic_type>::new(1); + test_swap_ordering(|order| a.not(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(1); + a.not(order); + assert_eq!(a.load(Ordering::Relaxed), !1); + } + } + #[test] + fn fetch_neg() { + let a = <$atomic_type>::new(5); + test_swap_ordering(|order| a.fetch_neg(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(5); + assert_eq!(a.fetch_neg(order), 5); + assert_eq!(a.load(Ordering::Relaxed), <$int_type>::wrapping_neg(5)); + assert_eq!(a.fetch_neg(order), <$int_type>::wrapping_neg(5)); + assert_eq!(a.load(Ordering::Relaxed), 5); + let a = <$atomic_type>::new(<$int_type>::MIN); + assert_eq!(a.fetch_neg(order), <$int_type>::MIN); + assert_eq!(a.load(Ordering::Relaxed), <$int_type>::MIN.wrapping_neg()); + assert_eq!(a.fetch_neg(order), <$int_type>::MIN.wrapping_neg()); + assert_eq!(a.load(Ordering::Relaxed), <$int_type>::MIN); + } + } + #[test] + fn neg() { + let a = <$atomic_type>::new(5); + test_swap_ordering(|order| a.neg(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(5); + a.neg(order); + assert_eq!(a.load(Ordering::Relaxed), <$int_type>::wrapping_neg(5)); + a.neg(order); + assert_eq!(a.load(Ordering::Relaxed), 5); + let a = <$atomic_type>::new(<$int_type>::MIN); + a.neg(order); + assert_eq!(a.load(Ordering::Relaxed), <$int_type>::MIN.wrapping_neg()); + a.neg(order); + assert_eq!(a.load(Ordering::Relaxed), <$int_type>::MIN); + } + } + #[test] + fn bit_set() { + let a = <$atomic_type>::new(0b0001); + test_swap_ordering(|order| assert!(a.bit_set(0, order))); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b0000); + assert!(!a.bit_set(0, order)); + assert_eq!(a.load(Ordering::Relaxed), 0b0001); + assert!(a.bit_set(0, order)); + assert_eq!(a.load(Ordering::Relaxed), 0b0001); + } + } + #[test] + fn bit_clear() { + let a = <$atomic_type>::new(0b0000); + test_swap_ordering(|order| assert!(!a.bit_clear(0, order))); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b0001); + assert!(a.bit_clear(0, order)); + assert_eq!(a.load(Ordering::Relaxed), 0b0000); + assert!(!a.bit_clear(0, order)); + assert_eq!(a.load(Ordering::Relaxed), 0b0000); + } + } + #[test] + fn bit_toggle() { + let a = <$atomic_type>::new(0b0000); + test_swap_ordering(|order| a.bit_toggle(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0b0000); + assert!(!a.bit_toggle(0, order)); + assert_eq!(a.load(Ordering::Relaxed), 0b0001); + assert!(a.bit_toggle(0, order)); + assert_eq!(a.load(Ordering::Relaxed), 0b0000); + } + } + ::quickcheck::quickcheck! { + fn quickcheck_swap(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.swap(y, order), x); + assert_eq!(a.swap(x, order), y); + } + true + } + fn quickcheck_compare_exchange(x: $int_type, y: $int_type) -> bool { + #[cfg(all( + target_arch = "arm", + not(any(target_feature = "v6", portable_atomic_target_feature = "v6")), + ))] + { + // TODO: LLVM bug: + // https://github.com/llvm/llvm-project/issues/61880 + // https://github.com/taiki-e/portable-atomic/issues/2 + if core::mem::size_of::<$int_type>() <= 2 { + return true; + } + } + let z = loop { + let z = fastrand::$int_type(..); + if z != y { + break z; + } + }; + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.compare_exchange(x, y, success, failure).unwrap(), x); + assert_eq!(a.load(Ordering::Relaxed), y); + assert_eq!(a.compare_exchange(z, x, success, failure).unwrap_err(), y); + assert_eq!(a.load(Ordering::Relaxed), y); + } + true + } + fn quickcheck_fetch_add(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_add(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_add(y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_add(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y.wrapping_add(x)); + } + true + } + fn quickcheck_add(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + a.add(y, order); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_add(y)); + let a = <$atomic_type>::new(y); + a.add(x, order); + assert_eq!(a.load(Ordering::Relaxed), y.wrapping_add(x)); + } + true + } + fn quickcheck_fetch_sub(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_sub(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_sub(y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_sub(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y.wrapping_sub(x)); + } + true + } + fn quickcheck_sub(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + a.sub(y, order); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_sub(y)); + let a = <$atomic_type>::new(y); + a.sub(x, order); + assert_eq!(a.load(Ordering::Relaxed), y.wrapping_sub(x)); + } + true + } + fn quickcheck_fetch_and(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_and(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x & y); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_and(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y & x); + } + true + } + fn quickcheck_and(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + a.and(y, order); + assert_eq!(a.load(Ordering::Relaxed), x & y); + let a = <$atomic_type>::new(y); + a.and(x, order); + assert_eq!(a.load(Ordering::Relaxed), y & x); + } + true + } + fn quickcheck_fetch_nand(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_nand(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), !(x & y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_nand(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), !(y & x)); + } + true + } + fn quickcheck_fetch_or(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_or(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x | y); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_or(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y | x); + } + true + } + fn quickcheck_or(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + a.or(y, order); + assert_eq!(a.load(Ordering::Relaxed), x | y); + let a = <$atomic_type>::new(y); + a.or(x, order); + assert_eq!(a.load(Ordering::Relaxed), y | x); + } + true + } + fn quickcheck_fetch_xor(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_xor(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), x ^ y); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_xor(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), y ^ x); + } + true + } + fn quickcheck_xor(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + a.xor(y, order); + assert_eq!(a.load(Ordering::Relaxed), x ^ y); + let a = <$atomic_type>::new(y); + a.xor(x, order); + assert_eq!(a.load(Ordering::Relaxed), y ^ x); + } + true + } + fn quickcheck_fetch_max(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_max(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::max(x, y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_max(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::max(y, x)); + } + true + } + fn quickcheck_fetch_min(x: $int_type, y: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_min(y, order), x); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::min(x, y)); + let a = <$atomic_type>::new(y); + assert_eq!(a.fetch_min(x, order), y); + assert_eq!(a.load(Ordering::Relaxed), core::cmp::min(y, x)); + } + true + } + fn quickcheck_fetch_not(x: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_not(order), x); + assert_eq!(a.load(Ordering::Relaxed), !x); + assert_eq!(a.fetch_not(order), !x); + assert_eq!(a.load(Ordering::Relaxed), x); + } + true + } + fn quickcheck_not(x: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + a.not(order); + assert_eq!(a.load(Ordering::Relaxed), !x); + a.not(order); + assert_eq!(a.load(Ordering::Relaxed), x); + } + true + } + fn quickcheck_fetch_neg(x: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.fetch_neg(order), x); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_neg()); + assert_eq!(a.fetch_neg(order), x.wrapping_neg()); + assert_eq!(a.load(Ordering::Relaxed), x); + } + true + } + fn quickcheck_neg(x: $int_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + a.neg(order); + assert_eq!(a.load(Ordering::Relaxed), x.wrapping_neg()); + a.neg(order); + assert_eq!(a.load(Ordering::Relaxed), x); + } + true + } + fn quickcheck_bit_set(x: $int_type, bit: u32) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + let b = a.bit_set(bit, order); + let mask = <$int_type>::wrapping_shl(1, bit); + assert_eq!(a.load(Ordering::Relaxed), x | mask); + assert_eq!(b, x & mask != 0); + } + true + } + fn quickcheck_bit_clear(x: $int_type, bit: u32) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + let b = a.bit_clear(bit, order); + let mask = <$int_type>::wrapping_shl(1, bit); + assert_eq!(a.load(Ordering::Relaxed), x & !mask); + assert_eq!(b, x & mask != 0); + } + true + } + fn quickcheck_bit_toggle(x: $int_type, bit: u32) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + let b = a.bit_toggle(bit, order); + let mask = <$int_type>::wrapping_shl(1, bit); + assert_eq!(a.load(Ordering::Relaxed), x ^ mask); + assert_eq!(b, x & mask != 0); + } + true + } + } + }; + ($atomic_type:ty, $int_type:ident) => { + __test_atomic_int!($atomic_type, $int_type, single_thread); + + #[test] + fn stress_swap() { + let (iterations, threads) = stress_test_config(); + let data1 = &(0..threads) + .map(|_| (0..iterations).map(|_| fastrand::$int_type(..)).collect::>()) + .collect::>(); + let data2 = &(0..threads) + .map(|_| (0..iterations).map(|_| fastrand::$int_type(..)).collect::>()) + .collect::>(); + let set = &data1 + .iter() + .flat_map(|v| v.iter().copied()) + .chain(data2.iter().flat_map(|v| v.iter().copied())) + .collect::>(); + let a = &<$atomic_type>::new(data2[0][fastrand::usize(0..iterations)]); + let now = &std::time::Instant::now(); + thread::scope(|s| { + for thread in 0..threads { + if thread % 2 == 0 { + s.spawn(move |_| { + let now = *now; + for i in 0..iterations { + a.store(data1[thread][i], rand_store_ordering()); + } + std::eprintln!("store end={:?}", now.elapsed()); + }); + } else { + s.spawn(|_| { + let now = *now; + let mut v = vec![0; iterations]; + for i in 0..iterations { + v[i] = a.load(rand_load_ordering()); + } + std::eprintln!("load end={:?}", now.elapsed()); + for v in v { + assert!(set.contains(&v), "v={}", v); + } + }); + } + s.spawn(move |_| { + let now = *now; + let mut v = vec![0; iterations]; + for i in 0..iterations { + v[i] = a.swap(data2[thread][i], rand_swap_ordering()); + } + std::eprintln!("swap end={:?}", now.elapsed()); + for v in v { + assert!(set.contains(&v), "v={}", v); + } + }); + } + }) + .unwrap(); + } + #[test] + fn stress_compare_exchange() { + let (iterations, threads) = stress_test_config(); + let data1 = &(0..threads) + .map(|_| (0..iterations).map(|_| fastrand::$int_type(..)).collect::>()) + .collect::>(); + let data2 = &(0..threads) + .map(|_| (0..iterations).map(|_| fastrand::$int_type(..)).collect::>()) + .collect::>(); + let set = &data1 + .iter() + .flat_map(|v| v.iter().copied()) + .chain(data2.iter().flat_map(|v| v.iter().copied())) + .collect::>(); + let a = &<$atomic_type>::new(data2[0][fastrand::usize(0..iterations)]); + let now = &std::time::Instant::now(); + thread::scope(|s| { + for thread in 0..threads { + s.spawn(move |_| { + let now = *now; + for i in 0..iterations { + a.store(data1[thread][i], rand_store_ordering()); + } + std::eprintln!("store end={:?}", now.elapsed()); + }); + s.spawn(|_| { + let now = *now; + let mut v = vec![data2[0][0]; iterations]; + for i in 0..iterations { + v[i] = a.load(rand_load_ordering()); + } + std::eprintln!("load end={:?}", now.elapsed()); + for v in v { + assert!(set.contains(&v), "v={}", v); + } + }); + s.spawn(move |_| { + let now = *now; + let mut v = vec![data2[0][0]; iterations]; + for i in 0..iterations { + let old = if i % 2 == 0 { + fastrand::$int_type(..) + } else { + a.load(Ordering::Relaxed) + }; + let new = data2[thread][i]; + let o = rand_compare_exchange_ordering(); + match a.compare_exchange(old, new, o.0, o.1) { + Ok(r) => assert_eq!(old, r), + Err(r) => v[i] = r, + } + } + std::eprintln!("compare_exchange end={:?}", now.elapsed()); + for v in v { + assert!(set.contains(&v), "v={}", v); + } + }); + } + }) + .unwrap(); + } + }; +} +macro_rules! __test_atomic_float { + ($atomic_type:ty, $float_type:ident, single_thread) => { + #[test] + fn swap() { + let a = <$atomic_type>::new(5.); + test_swap_ordering(|order| a.swap(5., order)); + for &order in &test_helper::SWAP_ORDERINGS { + assert_eq!(a.swap(10., order), 5.); + assert_eq!(a.swap(5., order), 10.); + } + } + #[test] + fn compare_exchange() { + let a = <$atomic_type>::new(5.); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange(5., 5., success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(5.); + assert_eq!(a.compare_exchange(5., 10., success, failure), Ok(5.)); + assert_eq!(a.load(Ordering::Relaxed), 10.); + assert_eq!(a.compare_exchange(6., 12., success, failure), Err(10.)); + assert_eq!(a.load(Ordering::Relaxed), 10.); + } + } + #[test] + fn compare_exchange_weak() { + let a = <$atomic_type>::new(4.); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange_weak(4., 4., success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(4.); + assert_eq!(a.compare_exchange_weak(6., 8., success, failure), Err(4.)); + let mut old = a.load(Ordering::Relaxed); + loop { + let new = old * 2.; + match a.compare_exchange_weak(old, new, success, failure) { + Ok(_) => break, + Err(x) => old = x, + } + } + assert_eq!(a.load(Ordering::Relaxed), 8.); + } + } + #[test] + fn fetch_add() { + let a = <$atomic_type>::new(0.); + test_swap_ordering(|order| a.fetch_add(0., order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(0.); + assert_eq!(a.fetch_add(10., order), 0.); + assert_eq!(a.load(Ordering::Relaxed), 10.); + let a = <$atomic_type>::new($float_type::MAX); + assert_eq!(a.fetch_add(1., order), $float_type::MAX); + assert_eq!(a.load(Ordering::Relaxed), $float_type::MAX + 1.); + } + } + #[test] + fn fetch_sub() { + let a = <$atomic_type>::new(20.); + test_swap_ordering(|order| a.fetch_sub(0., order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(20.); + assert_eq!(a.fetch_sub(10., order), 20.); + assert_eq!(a.load(Ordering::Relaxed), 10.); + let a = <$atomic_type>::new($float_type::MIN); + assert_eq!(a.fetch_sub(1., order), $float_type::MIN); + assert_eq!(a.load(Ordering::Relaxed), $float_type::MIN - 1.); + } + } + #[test] + fn fetch_max() { + let a = <$atomic_type>::new(23.); + test_swap_ordering(|order| a.fetch_max(23., order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(23.); + assert_eq!(a.fetch_max(22., order), 23.); + assert_eq!(a.load(Ordering::Relaxed), 23.); + assert_eq!(a.fetch_max(24., order), 23.); + assert_eq!(a.load(Ordering::Relaxed), 24.); + } + } + #[test] + fn fetch_min() { + let a = <$atomic_type>::new(23.); + test_swap_ordering(|order| a.fetch_min(23., order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(23.); + assert_eq!(a.fetch_min(24., order), 23.); + assert_eq!(a.load(Ordering::Relaxed), 23.); + assert_eq!(a.fetch_min(22., order), 23.); + assert_eq!(a.load(Ordering::Relaxed), 22.); + } + } + #[test] + fn fetch_neg() { + let a = <$atomic_type>::new(5.); + test_swap_ordering(|order| a.fetch_neg(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(5.); + assert_eq!(a.fetch_neg(order), 5.); + assert_eq!(a.load(Ordering::Relaxed), -5.); + assert_eq!(a.fetch_neg(order), -5.); + assert_eq!(a.load(Ordering::Relaxed), 5.); + } + } + #[test] + fn fetch_abs() { + let a = <$atomic_type>::new(23.); + test_swap_ordering(|order| a.fetch_abs(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(-23.); + assert_eq!(a.fetch_abs(order), -23.); + assert_eq!(a.load(Ordering::Relaxed), 23.); + assert_eq!(a.fetch_abs(order), 23.); + assert_eq!(a.load(Ordering::Relaxed), 23.); + } + } + ::quickcheck::quickcheck! { + fn quickcheck_swap(x: $float_type, y: $float_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.swap(y, order), x); + assert_float_op_eq!(a.swap(x, order), y); + } + true + } + fn quickcheck_compare_exchange(x: $float_type, y: $float_type) -> bool { + let z = loop { + let z = fastrand::$float_type(); + if z != y { + break z; + } + }; + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.compare_exchange(x, y, success, failure).unwrap(), x); + assert_float_op_eq!(a.load(Ordering::Relaxed), y); + assert_float_op_eq!( + a.compare_exchange(z, x, success, failure).unwrap_err(), + y, + ); + assert_float_op_eq!(a.load(Ordering::Relaxed), y); + } + true + } + fn quickcheck_fetch_add(x: $float_type, y: $float_type) -> bool { + if cfg!(all(not(debug_assertions), target_arch = "x86", not(target_feature = "sse2"))) { + // TODO: rustc bug: + // https://github.com/rust-lang/rust/issues/72327 + // https://github.com/rust-lang/rust/issues/73288 + return true; + } + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.fetch_add(y, order), x); + assert_float_op_eq!(a.load(Ordering::Relaxed), x + y); + let a = <$atomic_type>::new(y); + assert_float_op_eq!(a.fetch_add(x, order), y); + assert_float_op_eq!(a.load(Ordering::Relaxed), y + x); + } + true + } + fn quickcheck_fetch_sub(x: $float_type, y: $float_type) -> bool { + if cfg!(all(not(debug_assertions), target_arch = "x86", not(target_feature = "sse2"))) { + // TODO: rustc bug: + // https://github.com/rust-lang/rust/issues/72327 + // https://github.com/rust-lang/rust/issues/73288 + return true; + } + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.fetch_sub(y, order), x); + assert_float_op_eq!(a.load(Ordering::Relaxed), x - y); + let a = <$atomic_type>::new(y); + assert_float_op_eq!(a.fetch_sub(x, order), y); + assert_float_op_eq!(a.load(Ordering::Relaxed), y - x); + } + true + } + fn quickcheck_fetch_max(x: $float_type, y: $float_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.fetch_max(y, order), x); + assert_float_op_eq!(a.load(Ordering::Relaxed), x.max(y)); + let a = <$atomic_type>::new(y); + assert_float_op_eq!(a.fetch_max(x, order), y); + assert_float_op_eq!(a.load(Ordering::Relaxed), y.max(x)); + } + true + } + fn quickcheck_fetch_min(x: $float_type, y: $float_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.fetch_min(y, order), x); + assert_float_op_eq!(a.load(Ordering::Relaxed), x.min(y)); + let a = <$atomic_type>::new(y); + assert_float_op_eq!(a.fetch_min(x, order), y); + assert_float_op_eq!(a.load(Ordering::Relaxed), y.min(x)); + } + true + } + fn quickcheck_fetch_neg(x: $float_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.fetch_neg(order), x); + assert_float_op_eq!(a.load(Ordering::Relaxed), -x); + assert_float_op_eq!(a.fetch_neg(order), -x); + assert_float_op_eq!(a.load(Ordering::Relaxed), x); + } + true + } + fn quickcheck_fetch_abs(x: $float_type) -> bool { + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_float_op_eq!(a.fetch_abs(order), x); + assert_float_op_eq!(a.fetch_abs(order), x.abs()); + assert_float_op_eq!(a.load(Ordering::Relaxed), x.abs()); + } + true + } + } + }; + ($atomic_type:ty, $float_type:ident) => { + __test_atomic_float!($atomic_type, $float_type, single_thread); + // TODO: multi thread + }; +} +macro_rules! __test_atomic_bool { + ($atomic_type:ty, single_thread) => { + #[test] + fn swap() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| a.swap(true, order)); + for &order in &test_helper::SWAP_ORDERINGS { + assert_eq!(a.swap(true, order), true); + assert_eq!(a.swap(false, order), true); + assert_eq!(a.swap(false, order), false); + assert_eq!(a.swap(true, order), false); + } + } + #[test] + fn compare_exchange() { + let a = <$atomic_type>::new(true); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange(true, true, success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(true); + assert_eq!(a.compare_exchange(true, false, success, failure), Ok(true)); + assert_eq!(a.load(Ordering::Relaxed), false); + assert_eq!(a.compare_exchange(true, true, success, failure), Err(false)); + assert_eq!(a.load(Ordering::Relaxed), false); + } + } + #[test] + fn compare_exchange_weak() { + let a = <$atomic_type>::new(false); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange_weak(false, false, success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(false); + assert_eq!(a.compare_exchange_weak(true, true, success, failure), Err(false)); + let mut old = a.load(Ordering::Relaxed); + let new = true; + loop { + match a.compare_exchange_weak(old, new, success, failure) { + Ok(_) => break, + Err(x) => old = x, + } + } + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + #[test] + fn fetch_and() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| assert_eq!(a.fetch_and(true, order), true)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_and(false, order), true); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_and(true, order), true); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_and(false, order), false); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_and(true, order), false); + assert_eq!(a.load(Ordering::Relaxed), false); + } + } + #[test] + fn and() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| a.and(true, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + a.and(false, order); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(true); + a.and(true, order); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(false); + a.and(false, order); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + a.and(true, order); + assert_eq!(a.load(Ordering::Relaxed), false); + } + } + #[test] + fn fetch_or() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| assert_eq!(a.fetch_or(false, order), true)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_or(false, order), true); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_or(true, order), true); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_or(false, order), false); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_or(true, order), false); + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + #[test] + fn or() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| a.or(false, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + a.or(false, order); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(true); + a.or(true, order); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(false); + a.or(false, order); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + a.or(true, order); + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + #[test] + fn fetch_xor() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| assert_eq!(a.fetch_xor(false, order), true)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_xor(false, order), true); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_xor(true, order), true); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_xor(false, order), false); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_xor(true, order), false); + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + #[test] + fn xor() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| a.xor(false, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + a.xor(false, order); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(true); + a.xor(true, order); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + a.xor(false, order); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + a.xor(true, order); + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + ::quickcheck::quickcheck! { + fn quickcheck_compare_exchange(x: bool, y: bool) -> bool { + let z = !y; + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.compare_exchange(x, y, success, failure).unwrap(), x); + assert_eq!(a.load(Ordering::Relaxed), y); + assert_eq!(a.compare_exchange(z, x, success, failure).unwrap_err(), y); + assert_eq!(a.load(Ordering::Relaxed), y); + } + true + } + } + }; + ($atomic_type:ty) => { + __test_atomic_bool!($atomic_type, single_thread); + // TODO: multi thread + }; +} +macro_rules! __test_atomic_ptr { + ($atomic_type:ty, single_thread) => { + #[test] + fn swap() { + let a = <$atomic_type>::new(ptr::null_mut()); + test_swap_ordering(|order| a.swap(ptr::null_mut(), order)); + let x = &mut 1; + for &order in &test_helper::SWAP_ORDERINGS { + assert_eq!(a.swap(x, order), ptr::null_mut()); + assert_eq!(a.swap(ptr::null_mut(), order), x as *mut _); + } + } + #[test] + fn compare_exchange() { + let a = <$atomic_type>::new(ptr::null_mut()); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange(ptr::null_mut(), ptr::null_mut(), success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(ptr::null_mut()); + let x = &mut 1; + assert_eq!( + a.compare_exchange(ptr::null_mut(), x, success, failure), + Ok(ptr::null_mut()), + ); + assert_eq!(a.load(Ordering::Relaxed), x as *mut _); + assert_eq!( + a.compare_exchange(ptr::null_mut(), ptr::null_mut(), success, failure), + Err(x as *mut _), + ); + assert_eq!(a.load(Ordering::Relaxed), x as *mut _); + } + } + #[test] + fn compare_exchange_weak() { + let a = <$atomic_type>::new(ptr::null_mut()); + test_compare_exchange_ordering(|success, failure| { + a.compare_exchange_weak(ptr::null_mut(), ptr::null_mut(), success, failure) + }); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(ptr::null_mut()); + let x = &mut 1; + assert_eq!(a.compare_exchange_weak(x, x, success, failure), Err(ptr::null_mut())); + let mut old = a.load(Ordering::Relaxed); + loop { + match a.compare_exchange_weak(old, x, success, failure) { + Ok(_) => break, + Err(x) => old = x, + } + } + assert_eq!(a.load(Ordering::Relaxed), x as *mut _); + } + } + ::quickcheck::quickcheck! { + fn quickcheck_swap(x: usize, y: usize) -> bool { + let x = sptr::invalid_mut(x); + let y = sptr::invalid_mut(y); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.swap(y, order), x); + assert_eq!(a.swap(x, order), y); + } + true + } + fn quickcheck_compare_exchange(x: usize, y: usize) -> bool { + let z = loop { + let z = fastrand::usize(..); + if z != y { + break z; + } + }; + let x = sptr::invalid_mut(x); + let y = sptr::invalid_mut(y); + let z = sptr::invalid_mut(z); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!(a.compare_exchange(x, y, success, failure).unwrap(), x); + assert_eq!(a.load(Ordering::Relaxed), y); + assert_eq!(a.compare_exchange(z, x, success, failure).unwrap_err(), y); + assert_eq!(a.load(Ordering::Relaxed), y); + } + true + } + } + }; + ($atomic_type:ty) => { + __test_atomic_ptr!($atomic_type, single_thread); + // TODO: multi thread + }; +} + +macro_rules! __test_atomic_int_pub { + ($atomic_type:ty, $int_type:ident) => { + __test_atomic_pub_common!($atomic_type, $int_type); + use std::{boxed::Box, mem}; + #[test] + fn fetch_update() { + let a = <$atomic_type>::new(7); + test_compare_exchange_ordering(|set, fetch| a.fetch_update(set, fetch, |x| Some(x))); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(7); + assert_eq!(a.fetch_update(success, failure, |_| None), Err(7)); + assert_eq!(a.fetch_update(success, failure, |x| Some(x + 1)), Ok(7)); + assert_eq!(a.fetch_update(success, failure, |x| Some(x + 1)), Ok(8)); + assert_eq!(a.load(Ordering::SeqCst), 9); + } + } + #[test] + fn impls() { + #[cfg(not(portable_atomic_no_const_transmute))] + const _: $int_type = { + let a = <$atomic_type>::new(10); + a.into_inner() + }; + let a = <$atomic_type>::default(); + let b = <$atomic_type>::from(0); + assert_eq!(a.load(Ordering::SeqCst), b.load(Ordering::SeqCst)); + assert_eq!(std::format!("{:?}", a), std::format!("{:?}", a.load(Ordering::SeqCst))); + assert_eq!(a.into_inner(), 0); + assert_eq!(b.into_inner(), 0); + + unsafe { + let ptr: *mut Align16<$int_type> = Box::into_raw(Box::new(Align16(0))); + assert!(ptr as usize % mem::align_of::<$atomic_type>() == 0); + { + let a = <$atomic_type>::from_ptr(ptr.cast::<$int_type>()); + *a.as_ptr() = 1; + } + assert_eq!((*ptr).0, 1); + drop(Box::from_raw(ptr)); + } + } + ::quickcheck::quickcheck! { + fn quickcheck_fetch_update(x: $int_type, y: $int_type) -> bool { + let z = loop { + let z = fastrand::$int_type(..); + if z != y { + break z; + } + }; + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(x); + assert_eq!( + a.fetch_update(success, failure, |_| Some(y)) + .unwrap(), + x + ); + assert_eq!( + a.fetch_update(success, failure, |_| Some(z)) + .unwrap(), + y + ); + assert_eq!(a.load(Ordering::Relaxed), z); + assert_eq!( + a.fetch_update(success, failure, |z| if z == y { Some(z) } else { None }) + .unwrap_err(), + z + ); + assert_eq!(a.load(Ordering::Relaxed), z); + } + true + } + } + }; +} +macro_rules! __test_atomic_float_pub { + ($atomic_type:ty, $float_type:ident) => { + __test_atomic_pub_common!($atomic_type, $float_type); + use std::{boxed::Box, mem}; + #[test] + fn fetch_update() { + let a = <$atomic_type>::new(7.); + test_compare_exchange_ordering(|set, fetch| a.fetch_update(set, fetch, |x| Some(x))); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(7.); + assert_eq!(a.fetch_update(success, failure, |_| None), Err(7.)); + assert_eq!(a.fetch_update(success, failure, |x| Some(x + 1.)), Ok(7.)); + assert_eq!(a.fetch_update(success, failure, |x| Some(x + 1.)), Ok(8.)); + assert_eq!(a.load(Ordering::SeqCst), 9.); + } + } + #[test] + fn impls() { + #[cfg(not(portable_atomic_no_const_transmute))] + const _: $float_type = { + let a = <$atomic_type>::new(10.); + a.into_inner() + }; + let a = <$atomic_type>::default(); + let b = <$atomic_type>::from(0.); + assert_eq!(a.load(Ordering::SeqCst), b.load(Ordering::SeqCst)); + assert_eq!(std::format!("{:?}", a), std::format!("{:?}", a.load(Ordering::SeqCst))); + assert_eq!(a.into_inner(), 0.); + assert_eq!(b.into_inner(), 0.); + + unsafe { + let ptr: *mut Align16<$float_type> = Box::into_raw(Box::new(Align16(0.))); + assert!(ptr as usize % mem::align_of::<$atomic_type>() == 0); + { + let a = <$atomic_type>::from_ptr(ptr.cast::<$float_type>()); + *a.as_ptr() = 1.; + } + assert_eq!((*ptr).0, 1.); + drop(Box::from_raw(ptr)); + } + } + }; +} +macro_rules! __test_atomic_bool_pub { + ($atomic_type:ty) => { + __test_atomic_pub_common!($atomic_type, bool); + use std::{boxed::Box, mem}; + #[test] + fn fetch_nand() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| assert_eq!(a.fetch_nand(false, order), true)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_nand(false, order), true); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_nand(true, order), true); + assert_eq!(a.load(Ordering::Relaxed) as usize, 0); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_nand(false, order), false); + assert_eq!(a.load(Ordering::Relaxed), true); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_nand(true, order), false); + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + #[test] + fn fetch_not() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| a.fetch_not(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + assert_eq!(a.fetch_not(order), true); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_not(order), false); + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + #[test] + fn not() { + let a = <$atomic_type>::new(true); + test_swap_ordering(|order| a.fetch_not(order)); + for &order in &test_helper::SWAP_ORDERINGS { + let a = <$atomic_type>::new(true); + a.not(order); + assert_eq!(a.load(Ordering::Relaxed), false); + let a = <$atomic_type>::new(false); + a.not(order); + assert_eq!(a.load(Ordering::Relaxed), true); + } + } + #[test] + fn fetch_update() { + let a = <$atomic_type>::new(false); + test_compare_exchange_ordering(|set, fetch| a.fetch_update(set, fetch, |x| Some(x))); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(false); + assert_eq!(a.fetch_update(success, failure, |_| None), Err(false)); + assert_eq!(a.fetch_update(success, failure, |x| Some(!x)), Ok(false)); + assert_eq!(a.fetch_update(success, failure, |x| Some(!x)), Ok(true)); + assert_eq!(a.load(Ordering::SeqCst), false); + } + } + #[test] + fn impls() { + #[cfg(not(portable_atomic_no_const_transmute))] + const _: bool = { + let a = <$atomic_type>::new(true); + a.into_inner() + }; + let a = <$atomic_type>::default(); + let b = <$atomic_type>::from(false); + assert_eq!(a.load(Ordering::SeqCst), b.load(Ordering::SeqCst)); + assert_eq!(std::format!("{:?}", a), std::format!("{:?}", a.load(Ordering::SeqCst))); + assert_eq!(a.into_inner(), false); + assert_eq!(b.into_inner(), false); + + unsafe { + let ptr: *mut bool = Box::into_raw(Box::new(false)); + assert!(ptr as usize % mem::align_of::<$atomic_type>() == 0); + { + let a = <$atomic_type>::from_ptr(ptr); + *a.as_ptr() = true; + } + assert_eq!((*ptr), true); + drop(Box::from_raw(ptr)); + } + } + }; +} +macro_rules! __test_atomic_ptr_pub { + ($atomic_type:ty) => { + __test_atomic_pub_common!($atomic_type, *mut u8); + use sptr::Strict; + use std::{boxed::Box, mem}; + #[test] + fn fetch_update() { + let a = <$atomic_type>::new(ptr::null_mut()); + test_compare_exchange_ordering(|set, fetch| a.fetch_update(set, fetch, |x| Some(x))); + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + let a = <$atomic_type>::new(ptr::null_mut()); + assert_eq!(a.fetch_update(success, failure, |_| None), Err(ptr::null_mut())); + assert_eq!( + a.fetch_update(success, failure, |_| Some(&a as *const _ as *mut _)), + Ok(ptr::null_mut()) + ); + assert_eq!(a.load(Ordering::SeqCst), &a as *const _ as *mut _); + } + } + #[test] + fn impls() { + #[cfg(not(portable_atomic_no_const_transmute))] + const _: *mut u8 = { + let a = <$atomic_type>::new(ptr::null_mut()); + a.into_inner() + }; + let a = <$atomic_type>::default(); + let b = <$atomic_type>::from(ptr::null_mut()); + assert_eq!(a.load(Ordering::SeqCst), b.load(Ordering::SeqCst)); + assert_eq!(std::format!("{:?}", a), std::format!("{:?}", a.load(Ordering::SeqCst))); + assert_eq!(std::format!("{:p}", a), std::format!("{:p}", a.load(Ordering::SeqCst))); + assert_eq!(a.into_inner(), ptr::null_mut()); + assert_eq!(b.into_inner(), ptr::null_mut()); + + unsafe { + let ptr: *mut Align16<*mut u8> = Box::into_raw(Box::new(Align16(ptr::null_mut()))); + assert!(ptr as usize % mem::align_of::<$atomic_type>() == 0); + { + let a = <$atomic_type>::from_ptr(ptr.cast::<*mut u8>()); + *a.as_ptr() = ptr::null_mut::().wrapping_add(1); + } + assert_eq!((*ptr).0, ptr::null_mut::().wrapping_add(1)); + drop(Box::from_raw(ptr)); + } + } + // https://github.com/rust-lang/rust/blob/1.80.0/library/core/tests/atomic.rs#L130-L213 + #[test] + fn ptr_add_null() { + let atom = AtomicPtr::::new(core::ptr::null_mut()); + assert_eq!(atom.fetch_ptr_add(1, Ordering::SeqCst).addr(), 0); + assert_eq!(atom.load(Ordering::SeqCst).addr(), 8); + + assert_eq!(atom.fetch_byte_add(1, Ordering::SeqCst).addr(), 8); + assert_eq!(atom.load(Ordering::SeqCst).addr(), 9); + + assert_eq!(atom.fetch_ptr_sub(1, Ordering::SeqCst).addr(), 9); + assert_eq!(atom.load(Ordering::SeqCst).addr(), 1); + + assert_eq!(atom.fetch_byte_sub(1, Ordering::SeqCst).addr(), 1); + assert_eq!(atom.load(Ordering::SeqCst).addr(), 0); + } + #[test] + fn ptr_add_data() { + let num = 0i64; + let n = &num as *const i64 as *mut _; + let atom = AtomicPtr::::new(n); + assert_eq!(atom.fetch_ptr_add(1, Ordering::SeqCst), n); + assert_eq!(atom.load(Ordering::SeqCst), n.wrapping_add(1)); + + assert_eq!(atom.fetch_ptr_sub(1, Ordering::SeqCst), n.wrapping_add(1)); + assert_eq!(atom.load(Ordering::SeqCst), n); + #[allow(clippy::cast_ptr_alignment)] + let bytes_from_n = |b| n.cast::().wrapping_add(b).cast::(); + + assert_eq!(atom.fetch_byte_add(1, Ordering::SeqCst), n); + assert_eq!(atom.load(Ordering::SeqCst), bytes_from_n(1)); + + assert_eq!(atom.fetch_byte_add(5, Ordering::SeqCst), bytes_from_n(1)); + assert_eq!(atom.load(Ordering::SeqCst), bytes_from_n(6)); + + assert_eq!(atom.fetch_byte_sub(1, Ordering::SeqCst), bytes_from_n(6)); + assert_eq!(atom.load(Ordering::SeqCst), bytes_from_n(5)); + + assert_eq!(atom.fetch_byte_sub(5, Ordering::SeqCst), bytes_from_n(5)); + assert_eq!(atom.load(Ordering::SeqCst), n); + } + #[test] + fn ptr_bitops() { + let atom = AtomicPtr::::new(core::ptr::null_mut()); + assert_eq!(atom.fetch_or(0b0111, Ordering::SeqCst).addr(), 0); + assert_eq!(atom.load(Ordering::SeqCst).addr(), 0b0111); + + assert_eq!(atom.fetch_and(0b1101, Ordering::SeqCst).addr(), 0b0111); + assert_eq!(atom.load(Ordering::SeqCst).addr(), 0b0101); + + assert_eq!(atom.fetch_xor(0b1111, Ordering::SeqCst).addr(), 0b0101); + assert_eq!(atom.load(Ordering::SeqCst).addr(), 0b1010); + } + #[test] + fn ptr_bitops_tagging() { + const MASK_TAG: usize = 0b1111; + const MASK_PTR: usize = !MASK_TAG; + + #[repr(align(16))] + struct Tagme(#[allow(dead_code)] u128); + + let tagme = Tagme(1000); + let ptr = &tagme as *const Tagme as *mut Tagme; + let atom: AtomicPtr = AtomicPtr::new(ptr); + + assert_eq!(ptr.addr() & MASK_TAG, 0); + + assert_eq!(atom.fetch_or(0b0111, Ordering::SeqCst), ptr); + assert_eq!(atom.load(Ordering::SeqCst), ptr.map_addr(|a| a | 0b111)); + + assert_eq!( + atom.fetch_and(MASK_PTR | 0b0010, Ordering::SeqCst), + ptr.map_addr(|a| a | 0b111) + ); + assert_eq!(atom.load(Ordering::SeqCst), ptr.map_addr(|a| a | 0b0010)); + + assert_eq!(atom.fetch_xor(0b1011, Ordering::SeqCst), ptr.map_addr(|a| a | 0b0010)); + assert_eq!(atom.load(Ordering::SeqCst), ptr.map_addr(|a| a | 0b1001)); + + assert_eq!(atom.fetch_and(MASK_PTR, Ordering::SeqCst), ptr.map_addr(|a| a | 0b1001)); + assert_eq!(atom.load(Ordering::SeqCst), ptr); + } + #[test] + fn bit_set() { + let a = <$atomic_type>::new(ptr::null_mut::().cast::().map_addr(|a| a | 1)); + test_swap_ordering(|order| assert!(a.bit_set(0, order))); + for &order in &test_helper::SWAP_ORDERINGS { + let pointer = &mut 1u64 as *mut u64 as *mut u8; + let atom = <$atomic_type>::new(pointer); + // Tag the bottom bit of the pointer. + assert!(!atom.bit_set(0, order)); + // Extract and untag. + let tagged = atom.load(Ordering::Relaxed); + assert_eq!(tagged.addr() & 1, 1); + assert_eq!(tagged.map_addr(|p| p & !1), pointer); + } + } + #[test] + fn bit_clear() { + let a = <$atomic_type>::new(ptr::null_mut::().cast::()); + test_swap_ordering(|order| assert!(!a.bit_clear(0, order))); + for &order in &test_helper::SWAP_ORDERINGS { + let pointer = &mut 1u64 as *mut u64 as *mut u8; + // A tagged pointer + let atom = <$atomic_type>::new(pointer.map_addr(|a| a | 1)); + assert!(atom.bit_set(0, order)); + // Untag + assert!(atom.bit_clear(0, order)); + } + } + #[test] + fn bit_toggle() { + let a = <$atomic_type>::new(ptr::null_mut::().cast::()); + test_swap_ordering(|order| a.bit_toggle(0, order)); + for &order in &test_helper::SWAP_ORDERINGS { + let pointer = &mut 1u64 as *mut u64 as *mut u8; + let atom = <$atomic_type>::new(pointer); + // Toggle a tag bit on the pointer. + atom.bit_toggle(0, order); + assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1); + } + } + }; +} + +macro_rules! test_atomic_int_load_store { + ($int_type:ident) => { + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use super::*; + __test_atomic_int_load_store!([], $int_type); + } + } + }; +} +macro_rules! test_atomic_ptr_load_store { + () => { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod test_atomic_ptr { + use super::*; + __test_atomic_ptr_load_store!(AtomicPtr); + } + }; +} + +macro_rules! test_atomic_int_single_thread { + ($int_type:ident) => { + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use super::*; + __test_atomic_int_load_store!([], $int_type, single_thread); + __test_atomic_int!([], $int_type, single_thread); + } + } + }; +} +macro_rules! test_atomic_ptr_single_thread { + () => { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod test_atomic_ptr { + use super::*; + __test_atomic_ptr_load_store!(AtomicPtr, single_thread); + __test_atomic_ptr!(AtomicPtr, single_thread); + } + }; +} + +macro_rules! test_atomic_int { + ($int_type:ident) => { + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use super::*; + __test_atomic_int_load_store!([], $int_type); + __test_atomic_int!([], $int_type); + } + } + }; +} +macro_rules! test_atomic_ptr { + () => { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + #[allow(unstable_name_collisions)] // for sptr crate + mod test_atomic_ptr { + use super::*; + __test_atomic_ptr_load_store!(AtomicPtr); + __test_atomic_ptr!(AtomicPtr); + } + }; +} + +macro_rules! test_atomic_int_pub { + ($int_type:ident) => { + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use super::*; + __test_atomic_int_load_store!([], $int_type); + __test_atomic_int!([], $int_type); + __test_atomic_int_pub!([], $int_type); + } + } + }; +} +#[cfg(feature = "float")] +macro_rules! test_atomic_float_pub { + ($float_type:ident) => { + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::float_arithmetic, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use super::*; + __test_atomic_float_load_store!([], $float_type); + __test_atomic_float!([], $float_type); + __test_atomic_float_pub!([], $float_type); + } + } + }; +} +macro_rules! test_atomic_bool_pub { + () => { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod test_atomic_bool { + use super::*; + __test_atomic_bool_load_store!(AtomicBool); + __test_atomic_bool!(AtomicBool); + __test_atomic_bool_pub!(AtomicBool); + } + }; +} +macro_rules! test_atomic_ptr_pub { + () => { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + #[allow(unstable_name_collisions)] // for sptr crate + mod test_atomic_ptr { + use super::*; + __test_atomic_ptr_load_store!(AtomicPtr); + __test_atomic_ptr!(AtomicPtr); + __test_atomic_ptr_pub!(AtomicPtr); + } + }; +} + +// Asserts that `$a` and `$b` have performed equivalent operations. +#[cfg(feature = "float")] +macro_rules! assert_float_op_eq { + ($a:expr, $b:expr $(,)?) => {{ + // See also: + // - https://github.com/rust-lang/unsafe-code-guidelines/issues/237. + // - https://github.com/rust-lang/portable-simd/issues/39. + let a = $a; + let b = $b; + if a.is_nan() && b.is_nan() // don't check sign of NaN: https://github.com/rust-lang/rust/issues/55131 + || a.is_infinite() + && b.is_infinite() + && a.is_sign_positive() == b.is_sign_positive() + && a.is_sign_negative() == b.is_sign_negative() + { + // ok + } else { + assert_eq!(a, b); + } + }}; +} + +#[allow(unused_unsafe)] // for old rustc +#[cfg_attr(not(portable_atomic_no_track_caller), track_caller)] +pub(crate) fn assert_panic(f: impl FnOnce() -> T) -> std::string::String { + let backtrace = std::env::var_os("RUST_BACKTRACE"); + let hook = std::panic::take_hook(); + // set_var/remove_var is fine as we run tests with RUST_TEST_THREADS=1 + // std::panic::set_backtrace_style is better way here, but is unstable. + unsafe { std::env::set_var("RUST_BACKTRACE", "0") } // Suppress backtrace + std::panic::set_hook(std::boxed::Box::new(|_| {})); // Suppress panic msg + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + std::panic::set_hook(hook); + match backtrace { + Some(v) => unsafe { std::env::set_var("RUST_BACKTRACE", v) }, + None => unsafe { std::env::remove_var("RUST_BACKTRACE") }, + } + let msg = res.unwrap_err(); + msg.downcast_ref::() + .cloned() + .unwrap_or_else(|| msg.downcast_ref::<&'static str>().copied().unwrap().into()) +} +pub(crate) fn rand_load_ordering() -> Ordering { + test_helper::LOAD_ORDERINGS[fastrand::usize(0..test_helper::LOAD_ORDERINGS.len())] +} +pub(crate) fn test_load_ordering(f: impl Fn(Ordering) -> T) { + for &order in &test_helper::LOAD_ORDERINGS { + f(order); + } + + if !skip_should_panic_test() { + assert_eq!( + assert_panic(|| f(Ordering::Release)), + "there is no such thing as a release load" + ); + assert_eq!( + assert_panic(|| f(Ordering::AcqRel)), + "there is no such thing as an acquire-release load" + ); + } +} +pub(crate) fn rand_store_ordering() -> Ordering { + test_helper::STORE_ORDERINGS[fastrand::usize(0..test_helper::STORE_ORDERINGS.len())] +} +pub(crate) fn test_store_ordering(f: impl Fn(Ordering) -> T) { + for &order in &test_helper::STORE_ORDERINGS { + f(order); + } + + if !skip_should_panic_test() { + assert_eq!( + assert_panic(|| f(Ordering::Acquire)), + "there is no such thing as an acquire store" + ); + assert_eq!( + assert_panic(|| f(Ordering::AcqRel)), + "there is no such thing as an acquire-release store" + ); + } +} +pub(crate) fn rand_compare_exchange_ordering() -> (Ordering, Ordering) { + test_helper::COMPARE_EXCHANGE_ORDERINGS + [fastrand::usize(0..test_helper::COMPARE_EXCHANGE_ORDERINGS.len())] +} +pub(crate) fn test_compare_exchange_ordering( + f: impl Fn(Ordering, Ordering) -> T, +) { + for &(success, failure) in &test_helper::COMPARE_EXCHANGE_ORDERINGS { + f(success, failure); + } + + if !skip_should_panic_test() { + for &order in &test_helper::SWAP_ORDERINGS { + let msg = assert_panic(|| f(order, Ordering::AcqRel)); + assert!( + msg == "there is no such thing as an acquire-release failure ordering" + || msg == "there is no such thing as an acquire-release load", + "{}", + msg + ); + let msg = assert_panic(|| f(order, Ordering::Release)); + assert!( + msg == "there is no such thing as a release failure ordering" + || msg == "there is no such thing as a release load", + "{}", + msg + ); + } + } +} +pub(crate) fn rand_swap_ordering() -> Ordering { + test_helper::SWAP_ORDERINGS[fastrand::usize(0..test_helper::SWAP_ORDERINGS.len())] +} +pub(crate) fn test_swap_ordering(f: impl Fn(Ordering) -> T) { + for &order in &test_helper::SWAP_ORDERINGS { + f(order); + } +} +// for stress test generated by __test_atomic_* macros +pub(crate) fn stress_test_config() -> (usize, usize) { + let iterations = if cfg!(miri) { + 50 + } else if cfg!(debug_assertions) { + 5_000 + } else { + 25_000 + }; + let threads = if cfg!(debug_assertions) { 2 } else { fastrand::usize(2..=8) }; + std::eprintln!("threads={}", threads); + (iterations, threads) +} +fn skip_should_panic_test() -> bool { + // Miri's panic handling is slow + // MSAN false positive: https://gist.github.com/taiki-e/dd6269a8ffec46284fdc764a4849f884 + is_panic_abort() + || cfg!(miri) + || option_env!("CARGO_PROFILE_RELEASE_LTO").map_or(false, |v| v == "fat") + && build_context::SANITIZE.contains("memory") +} + +// For -C panic=abort -Z panic_abort_tests: https://github.com/rust-lang/rust/issues/67650 +fn is_panic_abort() -> bool { + build_context::PANIC.contains("abort") +} + +#[repr(C, align(16))] +pub(crate) struct Align16(pub(crate) T); + +// Test the cases that should not fail if the memory ordering is implemented correctly. +// This is still not exhaustive and only tests a few cases. +// This currently only supports 32-bit or more integers. +macro_rules! __stress_test_acquire_release { + (should_pass, $int_type:ident, $write:ident, $load_order:ident, $store_order:ident) => { + paste::paste! { + #[test] + #[allow(clippy::cast_possible_truncation)] + fn []() { + __stress_test_acquire_release!([], + $int_type, $write, $load_order, $store_order); + } + } + }; + (can_panic, $int_type:ident, $write:ident, $load_order:ident, $store_order:ident) => { + paste::paste! { + // Currently, to make this test work well enough outside of Miri, tens of thousands + // of iterations are needed, but this test is slow in some environments. + // So, ignore on non-Miri environments by default. See also catch_unwind_on_weak_memory_arch. + #[test] + #[cfg_attr(not(miri), ignore)] + #[allow(clippy::cast_possible_truncation)] + fn []() { + can_panic("a=", || __stress_test_acquire_release!([], + $int_type, $write, $load_order, $store_order)); + } + } + }; + ($atomic_type:ident, $int_type:ident, $write:ident, $load_order:ident, $store_order:ident) => {{ + use super::*; + use crossbeam_utils::thread; + use std::{ + convert::TryFrom, + sync::atomic::{AtomicUsize, Ordering}, + }; + let mut n: usize = if cfg!(miri) { 10 } else { 50_000 }; + // This test is relatively fast because it spawns only one thread, but + // the iterations are limited to a maximum value of integers. + if $int_type::try_from(n).is_err() { + n = $int_type::MAX as usize; + } + let a = &$atomic_type::new(0); + let b = &AtomicUsize::new(0); + thread::scope(|s| { + s.spawn(|_| { + for i in 0..n { + b.store(i, Ordering::Relaxed); + a.$write(i as $int_type, Ordering::$store_order); + } + }); + loop { + let a = a.load(Ordering::$load_order); + let b = b.load(Ordering::Relaxed); + assert!(a as usize <= b, "a={},b={}", a, b); + if a as usize == n - 1 { + break; + } + } + }) + .unwrap(); + }}; +} +macro_rules! __stress_test_seqcst { + (should_pass, $int_type:ident, $write:ident, $load_order:ident, $store_order:ident) => { + paste::paste! { + // Currently, to make this test work well enough outside of Miri, tens of thousands + // of iterations are needed, but this test is very slow in some environments because + // it creates two threads for each iteration. + // So, ignore on QEMU by default. + #[test] + #[cfg_attr(qemu, ignore)] + fn []() { + __stress_test_seqcst!([], + $write, $load_order, $store_order); + } + } + }; + (can_panic, $int_type:ident, $write:ident, $load_order:ident, $store_order:ident) => { + paste::paste! { + // Currently, to make this test work well enough outside of Miri, tens of thousands + // of iterations are needed, but this test is very slow in some environments because + // it creates two threads for each iteration. + // So, ignore on non-Miri environments by default. See also catch_unwind_on_non_seqcst_arch. + #[test] + #[cfg_attr(not(miri), ignore)] + fn []() { + can_panic("c=2", || __stress_test_seqcst!([], + $write, $load_order, $store_order)); + } + } + }; + ($atomic_type:ident, $write:ident, $load_order:ident, $store_order:ident) => {{ + use super::*; + use crossbeam_utils::thread; + use std::sync::atomic::{AtomicUsize, Ordering}; + let n: usize = if cfg!(miri) { + 8 + } else if cfg!(valgrind) + || build_context::SANITIZE.contains("address") + || build_context::SANITIZE.contains("memory") + { + 50 + } else if option_env!("GITHUB_ACTIONS").is_some() && cfg!(not(target_os = "linux")) { + // GitHub Actions' macOS and Windows runners are slow. + 5_000 + } else { + 50_000 + }; + let a = &$atomic_type::new(0); + let b = &$atomic_type::new(0); + let c = &AtomicUsize::new(0); + let ready = &AtomicUsize::new(0); + thread::scope(|s| { + for n in 0..n { + a.store(0, Ordering::Relaxed); + b.store(0, Ordering::Relaxed); + c.store(0, Ordering::Relaxed); + let h_a = s.spawn(|_| { + while ready.load(Ordering::Relaxed) == 0 {} + a.$write(1, Ordering::$store_order); + if b.load(Ordering::$load_order) == 0 { + c.fetch_add(1, Ordering::Relaxed); + } + }); + let h_b = s.spawn(|_| { + while ready.load(Ordering::Relaxed) == 0 {} + b.$write(1, Ordering::$store_order); + if a.load(Ordering::$load_order) == 0 { + c.fetch_add(1, Ordering::Relaxed); + } + }); + ready.store(1, Ordering::Relaxed); + h_a.join().unwrap(); + h_b.join().unwrap(); + let c = c.load(Ordering::Relaxed); + assert!(c == 0 || c == 1, "c={},n={}", c, n); + } + }) + .unwrap(); + }}; +} +// Catches unwinding panic on architectures with weak memory models. +#[allow(dead_code)] +pub(crate) fn catch_unwind_on_weak_memory_arch(pat: &str, f: impl Fn()) { + // With x86 TSO, RISC-V TSO (optional, not default), SPARC TSO (optional, default), + // and IBM-370 memory models should never be a panic here. + // Miri emulates weak memory models regardless of target architectures. + if cfg!(all( + any( + target_arch = "x86", + target_arch = "x86_64", + target_arch = "s390x", + target_arch = "sparc", + target_arch = "sparc64", + ), + not(any(miri)), + )) { + f(); + } else if !is_panic_abort() { + // This could be is_err on architectures with weak memory models. + // However, this does not necessarily mean that it will always be panic, + // and implementing it with stronger orderings is also okay. + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) { + Ok(()) => { + // panic!(); + } + Err(msg) => { + let msg = msg + .downcast_ref::() + .cloned() + .unwrap_or_else(|| msg.downcast_ref::<&'static str>().copied().unwrap().into()); + assert!(msg.contains(pat), "{}", msg); + } + } + } +} +// Catches unwinding panic on architectures with non-sequentially consistent memory models. +#[allow(dead_code)] +pub(crate) fn catch_unwind_on_non_seqcst_arch(pat: &str, f: impl Fn()) { + if !is_panic_abort() { + // This could be Err on architectures with non-sequentially consistent memory models. + // However, this does not necessarily mean that it will always be panic, + // and implementing it with stronger orderings is also okay. + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) { + Ok(()) => { + // panic!(); + } + Err(msg) => { + let msg = msg + .downcast_ref::() + .cloned() + .unwrap_or_else(|| msg.downcast_ref::<&'static str>().copied().unwrap().into()); + assert!(msg.contains(pat), "{}", msg); + } + } + } +} +macro_rules! stress_test_load_store { + ($int_type:ident) => { + // debug mode is slow. + #[cfg(any(not(debug_assertions), miri))] + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use crate::tests::helper::catch_unwind_on_weak_memory_arch as can_panic; + __stress_test_acquire_release!(can_panic, $int_type, store, Relaxed, Relaxed); + __stress_test_acquire_release!(can_panic, $int_type, store, Relaxed, Release); + __stress_test_acquire_release!(can_panic, $int_type, store, Relaxed, SeqCst); + __stress_test_acquire_release!(can_panic, $int_type, store, Acquire, Relaxed); + __stress_test_acquire_release!(should_pass, $int_type, store, Acquire, Release); + __stress_test_acquire_release!(should_pass, $int_type, store, Acquire, SeqCst); + __stress_test_acquire_release!(can_panic, $int_type, store, SeqCst, Relaxed); + __stress_test_acquire_release!(should_pass, $int_type, store, SeqCst, Release); + __stress_test_acquire_release!(should_pass, $int_type, store, SeqCst, SeqCst); + } + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use crate::tests::helper::catch_unwind_on_non_seqcst_arch as can_panic; + __stress_test_seqcst!(can_panic, $int_type, store, Relaxed, Relaxed); + __stress_test_seqcst!(can_panic, $int_type, store, Relaxed, Release); + __stress_test_seqcst!(can_panic, $int_type, store, Relaxed, SeqCst); + __stress_test_seqcst!(can_panic, $int_type, store, Acquire, Relaxed); + __stress_test_seqcst!(can_panic, $int_type, store, Acquire, Release); + __stress_test_seqcst!(can_panic, $int_type, store, Acquire, SeqCst); + __stress_test_seqcst!(can_panic, $int_type, store, SeqCst, Relaxed); + __stress_test_seqcst!(can_panic, $int_type, store, SeqCst, Release); + __stress_test_seqcst!(should_pass, $int_type, store, SeqCst, SeqCst); + } + } + }; +} +macro_rules! stress_test { + ($int_type:ident) => { + stress_test_load_store!($int_type); + // debug mode is slow. + #[cfg(any(not(debug_assertions), miri))] + paste::paste! { + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use crate::tests::helper::catch_unwind_on_weak_memory_arch as can_panic; + __stress_test_acquire_release!(can_panic, $int_type, swap, Relaxed, Relaxed); + __stress_test_acquire_release!(can_panic, $int_type, swap, Relaxed, Acquire); + __stress_test_acquire_release!(can_panic, $int_type, swap, Relaxed, Release); + __stress_test_acquire_release!(can_panic, $int_type, swap, Relaxed, AcqRel); + __stress_test_acquire_release!(can_panic, $int_type, swap, Relaxed, SeqCst); + __stress_test_acquire_release!(can_panic, $int_type, swap, Acquire, Relaxed); + __stress_test_acquire_release!(can_panic, $int_type, swap, Acquire, Acquire); + __stress_test_acquire_release!(should_pass, $int_type, swap, Acquire, Release); + __stress_test_acquire_release!(should_pass, $int_type, swap, Acquire, AcqRel); + __stress_test_acquire_release!(should_pass, $int_type, swap, Acquire, SeqCst); + __stress_test_acquire_release!(can_panic, $int_type, swap, SeqCst, Relaxed); + __stress_test_acquire_release!(can_panic, $int_type, swap, SeqCst, Acquire); + __stress_test_acquire_release!(should_pass, $int_type, swap, SeqCst, Release); + __stress_test_acquire_release!(should_pass, $int_type, swap, SeqCst, AcqRel); + __stress_test_acquire_release!(should_pass, $int_type, swap, SeqCst, SeqCst); + } + #[allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks + )] + mod [] { + use crate::tests::helper::catch_unwind_on_non_seqcst_arch as can_panic; + __stress_test_seqcst!(can_panic, $int_type, swap, Relaxed, Relaxed); + __stress_test_seqcst!(can_panic, $int_type, swap, Relaxed, Acquire); + __stress_test_seqcst!(can_panic, $int_type, swap, Relaxed, Release); + __stress_test_seqcst!(can_panic, $int_type, swap, Relaxed, AcqRel); + __stress_test_seqcst!(can_panic, $int_type, swap, Relaxed, SeqCst); + __stress_test_seqcst!(can_panic, $int_type, swap, Acquire, Relaxed); + __stress_test_seqcst!(can_panic, $int_type, swap, Acquire, Acquire); + __stress_test_seqcst!(can_panic, $int_type, swap, Acquire, Release); + __stress_test_seqcst!(can_panic, $int_type, swap, Acquire, AcqRel); + __stress_test_seqcst!(can_panic, $int_type, swap, Acquire, SeqCst); + __stress_test_seqcst!(can_panic, $int_type, swap, SeqCst, Relaxed); + __stress_test_seqcst!(can_panic, $int_type, swap, SeqCst, Acquire); + __stress_test_seqcst!(can_panic, $int_type, swap, SeqCst, Release); + __stress_test_seqcst!(can_panic, $int_type, swap, SeqCst, AcqRel); + __stress_test_seqcst!(should_pass, $int_type, swap, SeqCst, SeqCst); + } + } + }; +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/tests/mod.rs b/bitbox02-bt/vendor/portable-atomic/src/tests/mod.rs new file mode 100644 index 0000000..c1ab425 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/tests/mod.rs @@ -0,0 +1,433 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#![allow( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + clippy::undocumented_unsafe_blocks, + clippy::wildcard_imports +)] + +#[macro_use] +pub(crate) mod helper; + +#[allow(dead_code)] +#[path = "../../version.rs"] +mod version; + +use super::*; + +test_atomic_bool_pub!(); +test_atomic_ptr_pub!(); + +test_atomic_int_pub!(isize); +test_atomic_int_pub!(usize); +test_atomic_int_pub!(i8); +test_atomic_int_pub!(u8); +test_atomic_int_pub!(i16); +test_atomic_int_pub!(u16); +test_atomic_int_pub!(i32); +test_atomic_int_pub!(u32); +test_atomic_int_pub!(i64); +test_atomic_int_pub!(u64); +test_atomic_int_pub!(i128); +test_atomic_int_pub!(u128); + +#[cfg(feature = "float")] +test_atomic_float_pub!(f32); +#[cfg(feature = "float")] +test_atomic_float_pub!(f64); + +#[deny(improper_ctypes)] +extern "C" { + fn _atomic_bool_ffi_safety(_: AtomicBool); + fn _atomic_ptr_ffi_safety(_: AtomicPtr); + fn _atomic_isize_ffi_safety(_: AtomicIsize); + fn _atomic_usize_ffi_safety(_: AtomicUsize); + fn _atomic_i8_ffi_safety(_: AtomicI8); + fn _atomic_u8_ffi_safety(_: AtomicU8); + fn _atomic_i16_ffi_safety(_: AtomicI16); + fn _atomic_u16_ffi_safety(_: AtomicU16); + fn _atomic_i32_ffi_safety(_: AtomicI32); + fn _atomic_u32_ffi_safety(_: AtomicU32); + fn _atomic_i64_ffi_safety(_: AtomicI64); + fn _atomic_u64_ffi_safety(_: AtomicU64); + // TODO: 128-bit integers are not FFI safe + // https://github.com/rust-lang/unsafe-code-guidelines/issues/119 + // https://github.com/rust-lang/rust/issues/54341 + // fn _atomic_i128_ffi_safety(_: AtomicI128); + // fn _atomic_u128_ffi_safety(_: AtomicU128); + #[cfg(feature = "float")] + fn _atomic_f32_ffi_safety(_: AtomicF32); + #[cfg(feature = "float")] + fn _atomic_f64_ffi_safety(_: AtomicF64); +} + +#[test] +fn test_is_lock_free() { + assert!(AtomicI8::is_always_lock_free()); + assert!(AtomicI8::is_lock_free()); + assert!(AtomicU8::is_always_lock_free()); + assert!(AtomicU8::is_lock_free()); + assert!(AtomicI16::is_always_lock_free()); + assert!(AtomicI16::is_lock_free()); + assert!(AtomicU16::is_always_lock_free()); + assert!(AtomicU16::is_lock_free()); + assert!(AtomicI32::is_always_lock_free()); + assert!(AtomicI32::is_lock_free()); + assert!(AtomicU32::is_always_lock_free()); + assert!(AtomicU32::is_lock_free()); + #[cfg(not(portable_atomic_no_cfg_target_has_atomic))] + { + if cfg!(any( + target_has_atomic = "64", + all( + target_arch = "riscv32", + not(any(miri, portable_atomic_sanitize_thread)), + not(portable_atomic_no_asm), + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ), + ), + )) { + assert!(AtomicI64::is_always_lock_free()); + assert!(AtomicI64::is_lock_free()); + assert!(AtomicU64::is_always_lock_free()); + assert!(AtomicU64::is_lock_free()); + } else if cfg!(all( + feature = "fallback", + target_arch = "arm", + not(any(miri, portable_atomic_sanitize_thread)), + any(not(portable_atomic_no_asm), portable_atomic_unstable_asm), + any(target_os = "linux", target_os = "android"), + not(any(target_feature = "v6", portable_atomic_target_feature = "v6")), + not(portable_atomic_no_outline_atomics), + not(target_has_atomic = "64"), + not(portable_atomic_test_outline_atomics_detect_false), + )) { + assert!(!AtomicI64::is_always_lock_free()); + assert!(!AtomicU64::is_always_lock_free()); + assert!(AtomicI64::is_lock_free()); + assert!(AtomicU64::is_lock_free()); + } else { + assert!(!AtomicI64::is_always_lock_free()); + assert!(!AtomicU64::is_always_lock_free()); + #[cfg(not(target_arch = "riscv32"))] + { + assert!(!AtomicI64::is_lock_free()); + assert!(!AtomicU64::is_lock_free()); + } + #[cfg(target_arch = "riscv32")] + { + // TODO(riscv): check detect.has_zacas + } + } + } + if cfg!(portable_atomic_no_asm) && cfg!(not(portable_atomic_unstable_asm)) { + assert!(!AtomicI128::is_always_lock_free()); + assert!(!AtomicI128::is_lock_free()); + assert!(!AtomicU128::is_always_lock_free()); + assert!(!AtomicU128::is_lock_free()); + } else if cfg!(any( + target_arch = "aarch64", + all(target_arch = "arm64ec", portable_atomic_unstable_asm_experimental_arch), + all( + target_arch = "x86_64", + any(target_feature = "cmpxchg16b", portable_atomic_target_feature = "cmpxchg16b"), + ), + all( + target_arch = "riscv64", + any( + target_feature = "experimental-zacas", + portable_atomic_target_feature = "experimental-zacas", + ), + ), + all( + target_arch = "powerpc64", + portable_atomic_unstable_asm_experimental_arch, + any( + target_feature = "quadword-atomics", + portable_atomic_target_feature = "quadword-atomics", + ), + ), + all(target_arch = "s390x", portable_atomic_unstable_asm_experimental_arch), + )) { + assert!(AtomicI128::is_always_lock_free()); + assert!(AtomicI128::is_lock_free()); + assert!(AtomicU128::is_always_lock_free()); + assert!(AtomicU128::is_lock_free()); + } else { + assert!(!AtomicI128::is_always_lock_free()); + assert!(!AtomicU128::is_always_lock_free()); + #[cfg(not(any( + target_arch = "x86_64", + target_arch = "powerpc64", + target_arch = "riscv64", + )))] + { + assert!(!AtomicI128::is_lock_free()); + assert!(!AtomicU128::is_lock_free()); + } + #[cfg(target_arch = "x86_64")] + { + let has_cmpxchg16b = cfg!(all( + feature = "fallback", + not(portable_atomic_no_outline_atomics), + not(any(target_env = "sgx", miri)), + not(portable_atomic_test_outline_atomics_detect_false), + )) && std::is_x86_feature_detected!("cmpxchg16b"); + assert_eq!(AtomicI128::is_lock_free(), has_cmpxchg16b); + assert_eq!(AtomicU128::is_lock_free(), has_cmpxchg16b); + } + #[cfg(target_arch = "powerpc64")] + { + // TODO(powerpc64): is_powerpc_feature_detected is unstable + } + #[cfg(target_arch = "riscv64")] + { + // TODO(riscv): check detect.has_zacas + } + } +} + +// test version parsing code used in the build script. +#[test] +fn test_rustc_version() { + use version::Version; + + // rustc 1.34 (rustup) + let v = Version::parse( + "rustc 1.34.2 (6c2484dc3 2019-05-13) +binary: rustc +commit-hash: 6c2484dc3c532c052f159264e970278d8b77cdc9 +commit-date: 2019-05-13 +host: x86_64-apple-darwin +release: 1.34.2 +LLVM version: 8.0", + ) + .unwrap(); + assert_eq!(v, Version::stable(34, 8)); + + // rustc 1.50 (rustup) + let v = Version::parse( + "rustc 1.50.0 (cb75ad5db 2021-02-10) +binary: rustc +commit-hash: cb75ad5db02783e8b0222fee363c5f63f7e2cf5b +commit-date: 2021-02-10 +host: aarch64-unknown-linux-gnu +release: 1.50.0", + ) + .unwrap(); + assert_eq!(v, Version::stable(50, 0)); + + // rustc 1.67 (rustup) + let v = Version::parse( + "rustc 1.67.0 (fc594f156 2023-01-24) +binary: rustc +commit-hash: fc594f15669680fa70d255faec3ca3fb507c3405 +commit-date: 2023-01-24 +host: aarch64-apple-darwin +release: 1.67.0 +LLVM version: 15.0.6", + ) + .unwrap(); + assert_eq!(v, Version::stable(67, 15)); + + // rustc 1.68-beta (rustup) + let v = Version::parse( + "rustc 1.68.0-beta.2 (10b73bf73 2023-02-01) +binary: rustc +commit-hash: 10b73bf73a6b770cd92ad8ff538173bc3298411c +commit-date: 2023-02-01 +host: aarch64-apple-darwin +release: 1.68.0-beta.2 +LLVM version: 15.0.6", + ) + .unwrap(); + // We do not distinguish between stable and beta because we are only + // interested in whether unstable features are potentially available. + assert_eq!(v, Version::stable(68, 15)); + + // rustc nightly-2019-01-27 (rustup) + let v = Version::parse( + "rustc 1.33.0-nightly (20c2cba61 2019-01-26) +binary: rustc +commit-hash: 20c2cba61dc83e612d25ed496025171caa3db30f +commit-date: 2019-01-26 +host: x86_64-apple-darwin +release: 1.33.0-nightly +LLVM version: 8.0", + ) + .unwrap(); + assert_eq!(v.minor, 33); + assert!(v.nightly); + assert_eq!(v.llvm, 8); + assert_eq!(v.commit_date().year, 2019); + assert_eq!(v.commit_date().month, 1); + assert_eq!(v.commit_date().day, 26); + + // rustc 1.69-nightly (rustup) + let v = Version::parse( + "rustc 1.69.0-nightly (bd39bbb4b 2023-02-07) +binary: rustc +commit-hash: bd39bbb4bb92df439bf6d85470e296cc6a47ffbd +commit-date: 2023-02-07 +host: aarch64-apple-darwin +release: 1.69.0-nightly +LLVM version: 15.0.7", + ) + .unwrap(); + assert_eq!(v.minor, 69); + assert!(v.nightly); + assert_eq!(v.llvm, 15); + assert_eq!(v.commit_date().year, 2023); + assert_eq!(v.commit_date().month, 2); + assert_eq!(v.commit_date().day, 7); + + // clippy-driver 1.69-nightly (rustup) + let v = Version::parse( + "rustc 1.69.0-nightly (bd39bbb4b 2023-02-07) +binary: rustc +commit-hash: bd39bbb4bb92df439bf6d85470e296cc6a47ffbd +commit-date: 2023-02-07 +host: aarch64-apple-darwin +release: 1.69.0-nightly +LLVM version: 15.0.7", + ) + .unwrap(); + assert_eq!(v.minor, 69); + assert!(v.nightly); + assert_eq!(v.llvm, 15); + assert_eq!(v.commit_date().year, 2023); + assert_eq!(v.commit_date().month, 2); + assert_eq!(v.commit_date().day, 7); + + // rustc 1.69-dev (from source: ./x.py build) + let v = Version::parse( + "rustc 1.69.0-dev +binary: rustc +commit-hash: unknown +commit-date: unknown +host: aarch64-unknown-linux-gnu +release: 1.69.0-dev +LLVM version: 16.0.0", + ) + .unwrap(); + assert_eq!(v.minor, 69); + assert!(v.nightly); + assert_eq!(v.llvm, 16); + assert_eq!(v.commit_date().year, 0); + assert_eq!(v.commit_date().month, 0); + assert_eq!(v.commit_date().day, 0); + + // rustc 1.48 (debian 11: apt-get install cargo) + let v = Version::parse( + "rustc 1.48.0 +binary: rustc +commit-hash: unknown +commit-date: unknown +host: aarch64-unknown-linux-gnu +release: 1.48.0 +LLVM version: 11.0", + ) + .unwrap(); + assert_eq!(v, Version::stable(48, 11)); + + // rustc 1.67 (fedora: dnf install cargo) + let v = Version::parse( + "rustc 1.67.0 (fc594f156 2023-01-24) (Fedora 1.67.0-2.fc37) +binary: rustc +commit-hash: fc594f15669680fa70d255faec3ca3fb507c3405 +commit-date: 2023-01-24 +host: aarch64-unknown-linux-gnu +release: 1.67.0 +LLVM version: 15.0.7", + ) + .unwrap(); + assert_eq!(v, Version::stable(67, 15)); + + // rustc 1.64 (alpine: apk add cargo) + let v = Version::parse( + "rustc 1.64.0 +binary: rustc +commit-hash: unknown +commit-date: unknown +host: aarch64-alpine-linux-musl +release: 1.64.0 +LLVM version: 15.0.3", + ) + .unwrap(); + assert_eq!(v, Version::stable(64, 15)); +} + +#[cfg(feature = "serde")] +#[allow(clippy::as_underscore)] +#[test] +fn test_serde() { + use std::fmt; + + use serde::{ + de::{Deserialize, Deserializer}, + ser::{Serialize, Serializer}, + }; + use serde_test::{assert_tokens, Token}; + + #[derive(Debug)] + struct DebugPartialEq(T); + impl PartialEq for DebugPartialEq { + fn eq(&self, other: &Self) -> bool { + std::format!("{:?}", self) == std::format!("{:?}", other) + } + } + impl Serialize for DebugPartialEq { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } + } + impl<'de, T: Deserialize<'de>> Deserialize<'de> for DebugPartialEq { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize(deserializer).map(Self) + } + } + + macro_rules! t { + ($atomic_type:ty, $value_type:ident, $token_type:ident) => { + std::eprint!("test_serde {} ... ", stringify!($value_type)); + assert_tokens(&DebugPartialEq(<$atomic_type>::new($value_type::MAX)), &[ + Token::$token_type($value_type::MAX as _), + ]); + assert_tokens(&DebugPartialEq(<$atomic_type>::new($value_type::MIN)), &[ + Token::$token_type($value_type::MIN as _), + ]); + std::eprintln!("ok"); + }; + } + + assert_tokens(&DebugPartialEq(AtomicBool::new(true)), &[Token::Bool(true)]); + assert_tokens(&DebugPartialEq(AtomicBool::new(false)), &[Token::Bool(false)]); + t!(AtomicIsize, isize, I64); + t!(AtomicUsize, usize, U64); + t!(AtomicI8, i8, I8); + t!(AtomicU8, u8, U8); + t!(AtomicI16, i16, I16); + t!(AtomicU16, u16, U16); + t!(AtomicI32, i32, I32); + t!(AtomicU32, u32, U32); + t!(AtomicI64, i64, I64); + t!(AtomicU64, u64, U64); + t!(AtomicI128, i128, I128); + t!(AtomicU128, u128, U128); + #[cfg(feature = "float")] + t!(AtomicF32, f32, F32); + #[cfg(feature = "float")] + // TODO: fixed in LLVM 18? + #[cfg(not(target_arch = "mips"))] // LLVM 17 (nightly-2023-08-09) bug: assertion failed at core/src/num/diy_float.rs:78:9 + t!(AtomicF64, f64, F64); +} diff --git a/bitbox02-bt/vendor/portable-atomic/src/utils.rs b/bitbox02-bt/vendor/portable-atomic/src/utils.rs new file mode 100644 index 0000000..50fa092 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/src/utils.rs @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#![cfg_attr(not(all(test, feature = "float")), allow(dead_code, unused_macros))] + +#[macro_use] +#[path = "gen/utils.rs"] +mod gen; + +use core::sync::atomic::Ordering; + +macro_rules! static_assert { + ($cond:expr $(,)?) => {{ + let [] = [(); true as usize - $crate::utils::_assert_is_bool($cond) as usize]; + }}; +} +pub(crate) const fn _assert_is_bool(v: bool) -> bool { + v +} + +macro_rules! static_assert_layout { + ($atomic_type:ty, $value_type:ty) => { + static_assert!( + core::mem::align_of::<$atomic_type>() == core::mem::size_of::<$atomic_type>() + ); + static_assert!(core::mem::size_of::<$atomic_type>() == core::mem::size_of::<$value_type>()); + }; +} + +// #[doc = concat!(...)] requires Rust 1.54 +macro_rules! doc_comment { + ($doc:expr, $($tt:tt)*) => { + #[doc = $doc] + $($tt)* + }; +} + +// Adapted from https://github.com/BurntSushi/memchr/blob/2.4.1/src/memchr/x86/mod.rs#L9-L71. +/// # Safety +/// +/// - the caller must uphold the safety contract for the function returned by $detect_body. +/// - the memory pointed by the function pointer returned by $detect_body must be visible from any threads. +/// +/// The second requirement is always met if the function pointer is to the function definition. +/// (Currently, all uses of this macro in our code are in this case.) +#[allow(unused_macros)] +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "arm64ec", + target_arch = "powerpc64", + target_arch = "riscv32", + target_arch = "riscv64", + all(target_arch = "x86_64", not(any(target_env = "sgx", miri))), +))] +macro_rules! ifunc { + (unsafe fn($($arg_pat:ident: $arg_ty:ty),*) $(-> $ret_ty:ty)? { $($detect_body:tt)* }) => {{ + type FnTy = unsafe fn($($arg_ty),*) $(-> $ret_ty)?; + static FUNC: core::sync::atomic::AtomicPtr<()> + = core::sync::atomic::AtomicPtr::new(detect as *mut ()); + #[cold] + unsafe fn detect($($arg_pat: $arg_ty),*) $(-> $ret_ty)? { + let func: FnTy = { $($detect_body)* }; + FUNC.store(func as *mut (), core::sync::atomic::Ordering::Relaxed); + // SAFETY: the caller must uphold the safety contract for the function returned by $detect_body. + unsafe { func($($arg_pat),*) } + } + // SAFETY: `FnTy` is a function pointer, which is always safe to transmute with a `*mut ()`. + // (To force the caller to use unsafe block for this macro, do not use + // unsafe block here.) + let func = { + core::mem::transmute::<*mut (), FnTy>(FUNC.load(core::sync::atomic::Ordering::Relaxed)) + }; + // SAFETY: the caller must uphold the safety contract for the function returned by $detect_body. + // (To force the caller to use unsafe block for this macro, do not use + // unsafe block here.) + func($($arg_pat),*) + }}; +} + +#[allow(unused_macros)] +#[cfg(not(portable_atomic_no_outline_atomics))] +#[cfg(any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "arm64ec", + target_arch = "powerpc64", + target_arch = "riscv32", + target_arch = "riscv64", + all(target_arch = "x86_64", not(any(target_env = "sgx", miri))), +))] +macro_rules! fn_alias { + ( + $(#[$($fn_attr:tt)*])* + $vis:vis unsafe fn($($arg_pat:ident: $arg_ty:ty),*) $(-> $ret_ty:ty)?; + $(#[$($alias_attr:tt)*])* + $new:ident = $from:ident($($last_args:tt)*); + $($rest:tt)* + ) => { + $(#[$($fn_attr)*])* + $(#[$($alias_attr)*])* + $vis unsafe fn $new($($arg_pat: $arg_ty),*) $(-> $ret_ty)? { + // SAFETY: the caller must uphold the safety contract. + unsafe { $from($($arg_pat,)* $($last_args)*) } + } + fn_alias! { + $(#[$($fn_attr)*])* + $vis unsafe fn($($arg_pat: $arg_ty),*) $(-> $ret_ty)?; + $($rest)* + } + }; + ( + $(#[$($attr:tt)*])* + $vis:vis unsafe fn($($arg_pat:ident: $arg_ty:ty),*) $(-> $ret_ty:ty)?; + ) => {} +} + +/// Make the given function const if the given condition is true. +macro_rules! const_fn { + ( + const_if: #[cfg($($cfg:tt)+)]; + $(#[$($attr:tt)*])* + $vis:vis const fn $($rest:tt)* + ) => { + #[cfg($($cfg)+)] + $(#[$($attr)*])* + $vis const fn $($rest)* + #[cfg(not($($cfg)+))] + $(#[$($attr)*])* + $vis fn $($rest)* + }; +} + +/// Implements `core::fmt::Debug` and `serde::{Serialize, Deserialize}` (when serde +/// feature is enabled) for atomic bool, integer, or float. +macro_rules! impl_debug_and_serde { + ($atomic_type:ident) => { + impl fmt::Debug for $atomic_type { + #[inline] // fmt is not hot path, but #[inline] on fmt seems to still be useful: https://github.com/rust-lang/rust/pull/117727 + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // std atomic types use Relaxed in Debug::fmt: https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L2166 + fmt::Debug::fmt(&self.load(Ordering::Relaxed), f) + } + } + #[cfg(feature = "serde")] + #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] + impl serde::ser::Serialize for $atomic_type { + #[allow(clippy::missing_inline_in_public_items)] // serde doesn't use inline on std atomic's Serialize/Deserialize impl + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + // https://github.com/serde-rs/serde/blob/v1.0.152/serde/src/ser/impls.rs#L958-L959 + self.load(Ordering::Relaxed).serialize(serializer) + } + } + #[cfg(feature = "serde")] + #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] + impl<'de> serde::de::Deserialize<'de> for $atomic_type { + #[allow(clippy::missing_inline_in_public_items)] // serde doesn't use inline on std atomic's Serialize/Deserialize impl + fn deserialize(deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { + serde::de::Deserialize::deserialize(deserializer).map(Self::new) + } + } + }; +} + +// We do not provide `nand` because it cannot be optimized on neither x86 nor MSP430. +// https://godbolt.org/z/ahWejchbT +macro_rules! impl_default_no_fetch_ops { + ($atomic_type:ident, bool) => { + impl $atomic_type { + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn and(&self, val: bool, order: Ordering) { + self.fetch_and(val, order); + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn or(&self, val: bool, order: Ordering) { + self.fetch_or(val, order); + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn xor(&self, val: bool, order: Ordering) { + self.fetch_xor(val, order); + } + } + }; + ($atomic_type:ident, $int_type:ty) => { + impl $atomic_type { + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn add(&self, val: $int_type, order: Ordering) { + self.fetch_add(val, order); + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn sub(&self, val: $int_type, order: Ordering) { + self.fetch_sub(val, order); + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn and(&self, val: $int_type, order: Ordering) { + self.fetch_and(val, order); + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn or(&self, val: $int_type, order: Ordering) { + self.fetch_or(val, order); + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn xor(&self, val: $int_type, order: Ordering) { + self.fetch_xor(val, order); + } + } + }; +} +macro_rules! impl_default_bit_opts { + ($atomic_type:ident, $int_type:ty) => { + impl $atomic_type { + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn bit_set(&self, bit: u32, order: Ordering) -> bool { + let mask = <$int_type>::wrapping_shl(1, bit); + self.fetch_or(mask, order) & mask != 0 + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn bit_clear(&self, bit: u32, order: Ordering) -> bool { + let mask = <$int_type>::wrapping_shl(1, bit); + self.fetch_and(!mask, order) & mask != 0 + } + #[inline] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub(crate) fn bit_toggle(&self, bit: u32, order: Ordering) -> bool { + let mask = <$int_type>::wrapping_shl(1, bit); + self.fetch_xor(mask, order) & mask != 0 + } + } + }; +} + +// This just outputs the input as is, but can be used like an item-level block by using it with cfg. +macro_rules! items { + ($($tt:tt)*) => { + $($tt)* + }; +} + +#[allow(dead_code)] +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +// Stable version of https://doc.rust-lang.org/nightly/std/hint/fn.assert_unchecked.html. +// TODO: use real core::hint::assert_unchecked on 1.81+ https://github.com/rust-lang/rust/pull/123588 +#[inline(always)] +#[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] +pub(crate) unsafe fn assert_unchecked(cond: bool) { + if !cond { + if cfg!(debug_assertions) { + unreachable!() + } else { + // SAFETY: the caller promised `cond` is true. + unsafe { core::hint::unreachable_unchecked() } + } + } +} + +// https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L3294 +#[inline] +#[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] +pub(crate) fn assert_load_ordering(order: Ordering) { + match order { + Ordering::Acquire | Ordering::Relaxed | Ordering::SeqCst => {} + Ordering::Release => panic!("there is no such thing as a release load"), + Ordering::AcqRel => panic!("there is no such thing as an acquire-release load"), + _ => unreachable!(), + } +} + +// https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L3279 +#[inline] +#[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] +pub(crate) fn assert_store_ordering(order: Ordering) { + match order { + Ordering::Release | Ordering::Relaxed | Ordering::SeqCst => {} + Ordering::Acquire => panic!("there is no such thing as an acquire store"), + Ordering::AcqRel => panic!("there is no such thing as an acquire-release store"), + _ => unreachable!(), + } +} + +// https://github.com/rust-lang/rust/blob/1.80.0/library/core/src/sync/atomic.rs#L3360 +#[inline] +#[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)] +pub(crate) fn assert_compare_exchange_ordering(success: Ordering, failure: Ordering) { + match success { + Ordering::AcqRel + | Ordering::Acquire + | Ordering::Relaxed + | Ordering::Release + | Ordering::SeqCst => {} + _ => unreachable!(), + } + match failure { + Ordering::Acquire | Ordering::Relaxed | Ordering::SeqCst => {} + Ordering::Release => panic!("there is no such thing as a release failure ordering"), + Ordering::AcqRel => panic!("there is no such thing as an acquire-release failure ordering"), + _ => unreachable!(), + } +} + +// https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0418r2.html +// https://github.com/rust-lang/rust/pull/98383 +#[allow(dead_code)] +#[inline] +pub(crate) fn upgrade_success_ordering(success: Ordering, failure: Ordering) -> Ordering { + match (success, failure) { + (Ordering::Relaxed, Ordering::Acquire) => Ordering::Acquire, + (Ordering::Release, Ordering::Acquire) => Ordering::AcqRel, + (_, Ordering::SeqCst) => Ordering::SeqCst, + _ => success, + } +} + +/// Zero-extends the given 32-bit pointer to `MaybeUninit`. +/// This is used for 64-bit architecture's 32-bit ABI (e.g., AArch64 ILP32 ABI). +/// See ptr_reg! macro in src/gen/utils.rs for details. +#[cfg(not(portable_atomic_no_asm_maybe_uninit))] +#[cfg(target_pointer_width = "32")] +#[allow(dead_code)] +#[inline] +pub(crate) fn zero_extend64_ptr(v: *mut ()) -> core::mem::MaybeUninit { + #[repr(C)] + struct ZeroExtended { + #[cfg(target_endian = "big")] + pad: *mut (), + v: *mut (), + #[cfg(target_endian = "little")] + pad: *mut (), + } + // SAFETY: we can safely transmute any 64-bit value to MaybeUninit. + unsafe { core::mem::transmute(ZeroExtended { v, pad: core::ptr::null_mut() }) } +} + +#[allow(dead_code)] +#[cfg(any( + target_arch = "aarch64", + target_arch = "arm64ec", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "x86_64", +))] +/// A 128-bit value represented as a pair of 64-bit values. +/// +/// This type is `#[repr(C)]`, both fields have the same in-memory representation +/// and are plain old data types, so access to the fields is always safe. +#[derive(Clone, Copy)] +#[repr(C)] +pub(crate) union U128 { + pub(crate) whole: u128, + pub(crate) pair: Pair, +} +#[allow(dead_code)] +#[cfg(any(target_arch = "arm", target_arch = "riscv32"))] +/// A 64-bit value represented as a pair of 32-bit values. +/// +/// This type is `#[repr(C)]`, both fields have the same in-memory representation +/// and are plain old data types, so access to the fields is always safe. +#[derive(Clone, Copy)] +#[repr(C)] +pub(crate) union U64 { + pub(crate) whole: u64, + pub(crate) pair: Pair, +} +#[allow(dead_code)] +#[derive(Clone, Copy)] +#[repr(C)] +pub(crate) struct Pair { + // little endian order + #[cfg(any( + target_endian = "little", + target_arch = "aarch64", + target_arch = "arm", + target_arch = "arm64ec", + ))] + pub(crate) lo: T, + pub(crate) hi: T, + // big endian order + #[cfg(not(any( + target_endian = "little", + target_arch = "aarch64", + target_arch = "arm", + target_arch = "arm64ec", + )))] + pub(crate) lo: T, +} + +#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] +type MinWord = u32; +#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] +type RetInt = u32; +// Adapted from https://github.com/taiki-e/atomic-maybe-uninit/blob/v0.3.0/src/utils.rs#L210. +// Helper for implementing sub-word atomic operations using word-sized LL/SC loop or CAS loop. +// +// Refs: https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/CodeGen/AtomicExpandPass.cpp#L737 +// (aligned_ptr, shift, mask) +#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] +#[allow(dead_code)] +#[inline] +pub(crate) fn create_sub_word_mask_values(ptr: *mut T) -> (*mut MinWord, RetInt, RetInt) { + use core::mem; + const SHIFT_MASK: bool = !cfg!(any( + target_arch = "riscv32", + target_arch = "riscv64", + target_arch = "loongarch64", + target_arch = "s390x", + )); + let ptr_mask = mem::size_of::() - 1; + let aligned_ptr = strict::with_addr(ptr, ptr as usize & !ptr_mask) as *mut MinWord; + let ptr_lsb = if SHIFT_MASK { + ptr as usize & ptr_mask + } else { + // We use 32-bit wrapping shift instructions in asm on these platforms. + ptr as usize + }; + let shift = if cfg!(any(target_endian = "little", target_arch = "s390x")) { + ptr_lsb.wrapping_mul(8) + } else { + (ptr_lsb ^ (mem::size_of::() - mem::size_of::())).wrapping_mul(8) + }; + let mut mask: RetInt = (1 << (mem::size_of::() * 8)) - 1; // !(0 as T) as RetInt + if SHIFT_MASK { + mask <<= shift; + } + (aligned_ptr, shift as RetInt, mask) +} + +/// Emulate strict provenance. +/// +/// Once strict_provenance is stable, migrate to the standard library's APIs. +#[cfg(any(miri, target_arch = "riscv32", target_arch = "riscv64"))] +#[allow(dead_code)] +pub(crate) mod strict { + /// Replace the address portion of this pointer with a new address. + #[inline] + #[must_use] + pub(crate) fn with_addr(ptr: *mut T, addr: usize) -> *mut T { + // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic. + // + // In the mean-time, this operation is defined to be "as if" it was + // a wrapping_add, so we can emulate it as such. This should properly + // restore pointer provenance even under today's compiler. + let offset = addr.wrapping_sub(ptr as usize); + + // This is the canonical desugaring of this operation. + (ptr as *mut u8).wrapping_add(offset) as *mut T + } + + /// Run an operation of some kind on a pointer. + #[inline] + #[must_use] + pub(crate) fn map_addr(ptr: *mut T, f: impl FnOnce(usize) -> usize) -> *mut T { + with_addr(ptr, f(ptr as usize)) + } +} diff --git a/bitbox02-bt/vendor/portable-atomic/version.rs b/bitbox02-bt/vendor/portable-atomic/version.rs new file mode 100644 index 0000000..a410358 --- /dev/null +++ b/bitbox02-bt/vendor/portable-atomic/version.rs @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use std::{env, iter, process::Command, str}; + +pub(crate) fn rustc_version() -> Option { + let rustc = env::var_os("RUSTC")?; + let rustc_wrapper = if env::var_os("CARGO_ENCODED_RUSTFLAGS").is_some() { + env::var_os("RUSTC_WRAPPER").filter(|v| !v.is_empty()) + } else { + // Cargo sets environment variables for wrappers correctly only since https://github.com/rust-lang/cargo/pull/9601. + None + }; + // Do not apply RUSTC_WORKSPACE_WRAPPER: https://github.com/cuviper/autocfg/issues/58#issuecomment-2067625980 + let mut rustc = rustc_wrapper.into_iter().chain(iter::once(rustc)); + let mut cmd = Command::new(rustc.next().unwrap()); + cmd.args(rustc); + // Use verbose version output because the packagers add extra strings to the normal version output. + // Do not use long flags (--version --verbose) because clippy-deriver doesn't handle them properly. + // -vV is also matched with that cargo internally uses: https://github.com/rust-lang/cargo/blob/0.80.0/src/cargo/util/rustc.rs#L65 + let output = cmd.arg("-vV").output().ok()?; + let verbose_version = str::from_utf8(&output.stdout).ok()?; + Version::parse(verbose_version) +} + +#[cfg_attr(test, derive(Debug, PartialEq))] +pub(crate) struct Version { + pub(crate) minor: u32, + pub(crate) nightly: bool, + commit_date: Date, + pub(crate) llvm: u32, +} + +impl Version { + // The known latest stable version. If we unable to determine + // the rustc version, we assume this is the current version. + // It is no problem if this is older than the actual latest stable. + // LLVM version is assumed to be the minimum external LLVM version: + // https://github.com/rust-lang/rust/blob/1.81.0/src/bootstrap/src/core/build_steps/llvm.rs#L588 + pub(crate) const LATEST: Self = Self::stable(81, 17); + + pub(crate) const fn stable(rustc_minor: u32, llvm_major: u32) -> Self { + Self { minor: rustc_minor, nightly: false, commit_date: Date::UNKNOWN, llvm: llvm_major } + } + + pub(crate) fn probe(&self, minor: u32, year: u16, month: u8, day: u8) -> bool { + if self.nightly { + self.minor > minor + || self.minor == minor && self.commit_date >= Date::new(year, month, day) + } else { + self.minor >= minor + } + } + + #[cfg(test)] + pub(crate) fn commit_date(&self) -> &Date { + &self.commit_date + } + + pub(crate) fn parse(verbose_version: &str) -> Option { + let mut release = verbose_version + .lines() + .find(|line| line.starts_with("release: ")) + .map(|line| &line["release: ".len()..])? + .splitn(2, '-'); + let version = release.next().unwrap(); + let channel = release.next().unwrap_or_default(); + let mut digits = version.splitn(3, '.'); + let major = digits.next()?; + if major != "1" { + return None; + } + let minor = digits.next()?.parse::().ok()?; + let _patch = digits.next().unwrap_or("0").parse::().ok()?; + let nightly = channel == "nightly" || channel == "dev"; + + // Note that rustc 1.49-1.50 (and 1.13 or older) don't print LLVM version. + let llvm_major = (|| { + let version = verbose_version + .lines() + .find(|line| line.starts_with("LLVM version: ")) + .map(|line| &line["LLVM version: ".len()..])?; + let mut digits = version.splitn(3, '.'); + let major = digits.next()?.parse::().ok()?; + let _minor = digits.next()?.parse::().ok()?; + let _patch = digits.next().unwrap_or("0").parse::().ok()?; + Some(major) + })() + .unwrap_or(0); + + // we don't refer commit date on stable/beta. + if nightly { + let commit_date = (|| { + let mut commit_date = verbose_version + .lines() + .find(|line| line.starts_with("commit-date: ")) + .map(|line| &line["commit-date: ".len()..])? + .splitn(3, '-'); + let year = commit_date.next()?.parse::().ok()?; + let month = commit_date.next()?.parse::().ok()?; + let day = commit_date.next()?.parse::().ok()?; + if month > 12 || day > 31 { + return None; + } + Some(Date::new(year, month, day)) + })(); + Some(Self { + minor, + nightly, + commit_date: commit_date.unwrap_or(Date::UNKNOWN), + llvm: llvm_major, + }) + } else { + Some(Self::stable(minor, llvm_major)) + } + } +} + +#[derive(PartialEq, PartialOrd)] +#[cfg_attr(test, derive(Debug))] +pub(crate) struct Date { + pub(crate) year: u16, + pub(crate) month: u8, + pub(crate) day: u8, +} + +impl Date { + const UNKNOWN: Self = Self::new(0, 0, 0); + + const fn new(year: u16, month: u8, day: u8) -> Self { + Self { year, month, day } + } +} diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/.cargo-checksum.json b/bitbox02-bt/vendor/proc-macro-error-attr/.cargo-checksum.json new file mode 100644 index 0000000..c30b541 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"fbd3ce928441a0b43859bbbe36549f05e7a1ebfee62e5982710671a8f41de527","LICENSE-APACHE":"6fd0f3522047150ca7c1939f02bc4a15662a4741a89bc03ae784eefa18caa299","LICENSE-MIT":"544b3aed1fd723d0cadea567affdcfe0431e43e18d997a718f9d67256b814fde","build.rs":"37b0aca3c4a14dfc050c2df38ae633311d7a1532cdbb8eb57182802c4a1983eb","src/lib.rs":"9e3d13c266376b688642572bb4091e094ff5277fce4bee72bcc3c5f982dd831c","src/parse.rs":"2d8f220f91235be8ed0ddcab55ec3699b9d3b28d538ed24197797cc20194c473","src/settings.rs":"be9382479d7a857b55e5a0b1014f72150c9ee7f2bbb5a5bdeabc0f8de2d95c26"},"package":"a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/Cargo.toml b/bitbox02-bt/vendor/proc-macro-error-attr/Cargo.toml new file mode 100644 index 0000000..a2c766d --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/Cargo.toml @@ -0,0 +1,33 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "proc-macro-error-attr" +version = "1.0.4" +authors = ["CreepySkeleton "] +build = "build.rs" +description = "Attribute macro for proc-macro-error crate" +license = "MIT OR Apache-2.0" +repository = "https://gitlab.com/CreepySkeleton/proc-macro-error" +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +proc-macro = true +[dependencies.proc-macro2] +version = "1" + +[dependencies.quote] +version = "1" +[build-dependencies.version_check] +version = "0.9" diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-APACHE b/bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-APACHE new file mode 100644 index 0000000..658240a --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2019-2020 CreepySkeleton + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-MIT b/bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-MIT new file mode 100644 index 0000000..fc73e59 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-2020 CreepySkeleton + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/build.rs b/bitbox02-bt/vendor/proc-macro-error-attr/build.rs new file mode 100644 index 0000000..f2ac6a7 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/build.rs @@ -0,0 +1,5 @@ +fn main() { + if version_check::is_max_version("1.36.0").unwrap_or(false) { + println!("cargo:rustc-cfg=always_assert_unwind"); + } +} diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/src/lib.rs b/bitbox02-bt/vendor/proc-macro-error-attr/src/lib.rs new file mode 100644 index 0000000..ac0ac21 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/src/lib.rs @@ -0,0 +1,121 @@ +//! This is `#[proc_macro_error]` attribute to be used with +//! [`proc-macro-error`](https://docs.rs/proc-macro-error/). There you go. + +extern crate proc_macro; + +use crate::parse::parse_input; +use crate::parse::Attribute; +use proc_macro::TokenStream; +use proc_macro2::{Literal, Span, TokenStream as TokenStream2, TokenTree}; +use quote::{quote, quote_spanned}; + +use crate::settings::{Setting::*, *}; + +mod parse; +mod settings; + +type Result = std::result::Result; + +struct Error { + span: Span, + message: String, +} + +impl Error { + fn new(span: Span, message: String) -> Self { + Error { span, message } + } + + fn into_compile_error(self) -> TokenStream2 { + let mut message = Literal::string(&self.message); + message.set_span(self.span); + quote_spanned!(self.span=> compile_error!{#message}) + } +} + +#[proc_macro_attribute] +pub fn proc_macro_error(attr: TokenStream, input: TokenStream) -> TokenStream { + match impl_proc_macro_error(attr.into(), input.clone().into()) { + Ok(ts) => ts, + Err(e) => { + let error = e.into_compile_error(); + let input = TokenStream2::from(input); + + quote!(#input #error).into() + } + } +} + +fn impl_proc_macro_error(attr: TokenStream2, input: TokenStream2) -> Result { + let (attrs, signature, body) = parse_input(input)?; + let mut settings = parse_settings(attr)?; + + let is_proc_macro = is_proc_macro(&attrs); + if is_proc_macro { + settings.set(AssertUnwindSafe); + } + + if detect_proc_macro_hack(&attrs) { + settings.set(ProcMacroHack); + } + + if settings.is_set(ProcMacroHack) { + settings.set(AllowNotMacro); + } + + if !(settings.is_set(AllowNotMacro) || is_proc_macro) { + return Err(Error::new( + Span::call_site(), + "#[proc_macro_error] attribute can be used only with procedural macros\n\n \ + = hint: if you are really sure that #[proc_macro_error] should be applied \ + to this exact function, use #[proc_macro_error(allow_not_macro)]\n" + .into(), + )); + } + + let body = gen_body(body, settings); + + let res = quote! { + #(#attrs)* + #(#signature)* + { #body } + }; + Ok(res.into()) +} + +#[cfg(not(always_assert_unwind))] +fn gen_body(block: TokenTree, settings: Settings) -> proc_macro2::TokenStream { + let is_proc_macro_hack = settings.is_set(ProcMacroHack); + let closure = if settings.is_set(AssertUnwindSafe) { + quote!(::std::panic::AssertUnwindSafe(|| #block )) + } else { + quote!(|| #block) + }; + + quote!( ::proc_macro_error::entry_point(#closure, #is_proc_macro_hack) ) +} + +// FIXME: +// proc_macro::TokenStream does not implement UnwindSafe until 1.37.0. +// Considering this is the closure's return type the unwind safety check would fail +// for virtually every closure possible, the check is meaningless. +#[cfg(always_assert_unwind)] +fn gen_body(block: TokenTree, settings: Settings) -> proc_macro2::TokenStream { + let is_proc_macro_hack = settings.is_set(ProcMacroHack); + let closure = quote!(::std::panic::AssertUnwindSafe(|| #block )); + quote!( ::proc_macro_error::entry_point(#closure, #is_proc_macro_hack) ) +} + +fn detect_proc_macro_hack(attrs: &[Attribute]) -> bool { + attrs + .iter() + .any(|attr| attr.path_is_ident("proc_macro_hack")) +} + +fn is_proc_macro(attrs: &[Attribute]) -> bool { + attrs.iter().any(|attr| { + attr.path_is_ident("proc_macro") + || attr.path_is_ident("proc_macro_derive") + || attr.path_is_ident("proc_macro_attribute") + }) +} diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/src/parse.rs b/bitbox02-bt/vendor/proc-macro-error-attr/src/parse.rs new file mode 100644 index 0000000..6f4663f --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/src/parse.rs @@ -0,0 +1,89 @@ +use crate::{Error, Result}; +use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; +use quote::ToTokens; +use std::iter::Peekable; + +pub(crate) fn parse_input( + input: TokenStream, +) -> Result<(Vec, Vec, TokenTree)> { + let mut input = input.into_iter().peekable(); + let mut attrs = Vec::new(); + + while let Some(attr) = parse_next_attr(&mut input)? { + attrs.push(attr); + } + + let sig = parse_signature(&mut input); + let body = input.next().ok_or_else(|| { + Error::new( + Span::call_site(), + "`#[proc_macro_error]` can be applied only to functions".to_string(), + ) + })?; + + Ok((attrs, sig, body)) +} + +fn parse_next_attr( + input: &mut Peekable>, +) -> Result> { + let shebang = match input.peek() { + Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(), + _ => return Ok(None), + }; + + let group = match input.peek() { + Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Bracket => { + let res = group.clone(); + input.next(); + res + } + other => { + let span = other.map_or(Span::call_site(), |tt| tt.span()); + return Err(Error::new(span, "expected `[`".to_string())); + } + }; + + let path = match group.stream().into_iter().next() { + Some(TokenTree::Ident(ident)) => Some(ident), + _ => None, + }; + + Ok(Some(Attribute { + shebang, + group: TokenTree::Group(group), + path, + })) +} + +fn parse_signature(input: &mut Peekable>) -> Vec { + let mut sig = Vec::new(); + loop { + match input.peek() { + Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => { + return sig; + } + None => return sig, + _ => sig.push(input.next().unwrap()), + } + } +} + +pub(crate) struct Attribute { + pub(crate) shebang: TokenTree, + pub(crate) group: TokenTree, + pub(crate) path: Option, +} + +impl Attribute { + pub(crate) fn path_is_ident(&self, ident: &str) -> bool { + self.path.as_ref().map_or(false, |p| *p == ident) + } +} + +impl ToTokens for Attribute { + fn to_tokens(&self, ts: &mut TokenStream) { + self.shebang.to_tokens(ts); + self.group.to_tokens(ts); + } +} diff --git a/bitbox02-bt/vendor/proc-macro-error-attr/src/settings.rs b/bitbox02-bt/vendor/proc-macro-error-attr/src/settings.rs new file mode 100644 index 0000000..0b7ec76 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error-attr/src/settings.rs @@ -0,0 +1,72 @@ +use crate::{Error, Result}; +use proc_macro2::{Ident, Span, TokenStream, TokenTree}; + +macro_rules! decl_settings { + ($($val:expr => $variant:ident),+ $(,)*) => { + #[derive(PartialEq)] + pub(crate) enum Setting { + $($variant),* + } + + fn ident_to_setting(ident: Ident) -> Result { + match &*ident.to_string() { + $($val => Ok(Setting::$variant),)* + _ => { + let possible_vals = [$($val),*] + .iter() + .map(|v| format!("`{}`", v)) + .collect::>() + .join(", "); + + Err(Error::new( + ident.span(), + format!("unknown setting `{}`, expected one of {}", ident, possible_vals))) + } + } + } + }; +} + +decl_settings! { + "assert_unwind_safe" => AssertUnwindSafe, + "allow_not_macro" => AllowNotMacro, + "proc_macro_hack" => ProcMacroHack, +} + +pub(crate) fn parse_settings(input: TokenStream) -> Result { + let mut input = input.into_iter(); + let mut res = Settings(Vec::new()); + loop { + match input.next() { + Some(TokenTree::Ident(ident)) => { + res.0.push(ident_to_setting(ident)?); + } + None => return Ok(res), + other => { + let span = other.map_or(Span::call_site(), |tt| tt.span()); + return Err(Error::new(span, "expected identifier".to_string())); + } + } + + match input.next() { + Some(TokenTree::Punct(ref punct)) if punct.as_char() == ',' => {} + None => return Ok(res), + other => { + let span = other.map_or(Span::call_site(), |tt| tt.span()); + return Err(Error::new(span, "expected `,`".to_string())); + } + } + } +} + +pub(crate) struct Settings(Vec); + +impl Settings { + pub(crate) fn is_set(&self, setting: Setting) -> bool { + self.0.iter().any(|s| *s == setting) + } + + pub(crate) fn set(&mut self, setting: Setting) { + self.0.push(setting) + } +} diff --git a/bitbox02-bt/vendor/proc-macro-error/.cargo-checksum.json b/bitbox02-bt/vendor/proc-macro-error/.cargo-checksum.json new file mode 100644 index 0000000..79bcfa6 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"b84c4baa5fb093c6aaca44b98f9f28ef54d399ef6dd43c91f1dca618ab366b45","Cargo.toml":"50db093e1a4617606939dfb1f098cb59babbea0d7b390e973a3ed6bb1406170d","LICENSE-APACHE":"4665f973ccb9393807a7fb1264add6b3513d19abc6b357e4cb52c6fe59cc6a3b","LICENSE-MIT":"544b3aed1fd723d0cadea567affdcfe0431e43e18d997a718f9d67256b814fde","README.md":"72d59787d0a1f7bf161e292d0bc1bc25fdfb08cd6ad379a34cc3ed1b388d11fa","build.rs":"6238a0ad4f1146fbf55112419609e6449986154cf7ded1b5fdc978b06f4413b3","src/diagnostic.rs":"cb8724bb0bf9d2eee2f7119d0960fd5349edaa80e147abdef060ebf4572eca01","src/dummy.rs":"b44728091ddcdf9786523c01178efcedd83462bfe8bac6b97b1c2ffb19c96d09","src/imp/delegate.rs":"81da3a602a883240161dd98deb52b3b4ae29e626bfd2e1e07ef5e38d1be00679","src/imp/fallback.rs":"c3d333aba1122ac7e26f038f69750aa02e6a1222433a7cffd1c2f961befedd93","src/lib.rs":"e563d5dceaeb81551a5cb2610c1a3ad1a46200a6cbf8c3c3b394d8ac307b8cfa","src/macros.rs":"3be6feccd343cd9dc4bf03780f3107909bf70e02c6c7c72912e4b160dc6a68fc","src/sealed.rs":"dcf569c4c7ce1d372ff51b0fa73fa67f995bdca8e520cb225cde789c71276439","tests/macro-errors.rs":"7f793921dfbec692bfb2bbb067faf0480c0e7eeec83982b5e9fcddd817817616","tests/ok.rs":"a8c1925ac8647d185c7490ed1e33e3ce3203f5945bd3db4dcaf50ea55078df29","tests/runtime-errors.rs":"e53aa7d8e6c0e5128a90e856105eb05e4e7e72ea6db1bd580f3fe439bff62f24","tests/ui/abort.rs":"e209c8dd9dde6bde7440f8795624ad84b0f8486f563c8fe838238818f459bb67","tests/ui/abort.stderr":"dd0605e79be0309f92b251d055f087b0375c48ec60da978df354b48e8563fa10","tests/ui/append_dummy.rs":"ecaf939c8aabd94eef2dd1c10e9515489ba78e4db5b25195e19833b020d2483c","tests/ui/append_dummy.stderr":"ef03b01fc823aba8cfb9eb6d116640ca953fec569e61ed6ed6b7b7fa3bbad686","tests/ui/children_messages.rs":"32299679804133cb5295ed7a9341bf1ab86a4f1277679ee9738a83115c6b1d2b","tests/ui/children_messages.stderr":"dadeb86e1c7094d5fb38664b1766212b3d083fbe04962c137f8281fb3f5d162e","tests/ui/dummy.rs":"ba51c9158cef88ff2ddf0185be26fcd35a641d73c7124fab9ace0bbd546de847","tests/ui/dummy.stderr":"0635fd563d26691d07a2a875111f0b5e155caa45c37ad9cbaefe5fe617eac703","tests/ui/emit.rs":"82aaf06bcee56b7e139bbcba3a92c29448af14974d6806a28c9961aa764026e5","tests/ui/emit.stderr":"d3daa6d304453d436317495b7fc1d9d36bbebb7705bef75a5260d6d8fcfad5b1","tests/ui/explicit_span_range.rs":"3c37d5fc75b2bd460a091acd97a19acc80a40ba8d1d4ac7f36cd2f0e171bf5e7","tests/ui/explicit_span_range.stderr":"d7562847c326badbce2df8546e6f625eef0725b1dd2c786a037cc46357e4d2e8","tests/ui/misuse.rs":"0d66c61ab5c9723cf2f85cd12216751ab09722e9386cc27928034ee17f1c34e3","tests/ui/misuse.stderr":"52568a2208423e8e4050774559f269e79181a350f0805a34880bfa208e08c6bb","tests/ui/multiple_tokens.rs":"74997da1fdd3bce88a04ab42866c651723861fba4f59e826ee602d905398dcca","tests/ui/multiple_tokens.stderr":"e347ef1c18949711ce41957848e255095132f855c94db1e7e28d32e7d2c79a74","tests/ui/not_proc_macro.rs":"ca448d832ccf0cfdcda6f04281d8134a76c61b3ad96437e972b2cb5c6e0844c4","tests/ui/not_proc_macro.stderr":"a22c53a7dd5a03ddfaee5a7fb7fe5d61cb588b2d81a30c1e935b789baf0d2676","tests/ui/option_ext.rs":"1db81c17172f155c0ca8bcf92d55b5852b92107a3ba1d4b2ae6d14020df67f96","tests/ui/option_ext.stderr":"3b363759db60ee4f249dfde4d4571963032d5f0043249de40bd3b38eecc65404","tests/ui/proc_macro_hack.rs":"1d08c3e2c4c331e230c7cdaa2635ca1e43077252f90d3a430dcd091c646a842c","tests/ui/proc_macro_hack.stderr":"65e887dc208b92bfcd44405e76d5d05e315c3c5c5f637070954b7d593c723731","tests/ui/result_ext.rs":"ef398e76aab82a574ca5a988a91353e1a87fcfcb459d30314eceed3cbcf6fcd8","tests/ui/result_ext.stderr":"9e1e387b1378d9ec40ccb29be9f8cdaa5b42060c3f4f9b3c09fb307d5dcf7d85","tests/ui/to_tokens_span.rs":"d017a3c4cd583defe9806cdc51220bde89ced871ddd4d65b7cd089882feb1f61","tests/ui/to_tokens_span.stderr":"0b88e659ab214d6c7dfcd99274d327fe72da4b9bd009477e0e65165ddde65e02","tests/ui/unknown_setting.rs":"16fe9631b51023909497e857a6c674cd216ba9802fbdba360bb8273d6e00fa31","tests/ui/unknown_setting.stderr":"d605f151ce8eba5b2f867667394bd2d2adf0a233145516a9d6b801817521e587","tests/ui/unrelated_panic.rs":"438db25f8f14f1263152545a1c5135e20b3f5063dc4ab223fd8145b891039b24","tests/ui/unrelated_panic.stderr":"04cd814f2bd57d5271f93f90f0dd078b09ee3fd73137245a914d698e4a33ed57"},"package":"da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/proc-macro-error/CHANGELOG.md b/bitbox02-bt/vendor/proc-macro-error/CHANGELOG.md new file mode 100644 index 0000000..3c422f1 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/CHANGELOG.md @@ -0,0 +1,162 @@ +# v1.0.4 (2020-7-31) + +* `SpanRange` facility is now public. +* Docs have been improved. +* Introduced the `syn-error` feature so you can opt-out from the `syn` dependency. + +# v1.0.3 (2020-6-26) + +* Corrected a few typos. +* Fixed the `emit_call_site_warning` macro. + +# v1.0.2 (2020-4-9) + +* An obsolete note was removed from documentation. + +# v1.0.1 (2020-4-9) + +* `proc-macro-hack` is now well tested and supported. Not sure about `proc-macro-nested`, + please fill a request if you need it. +* Fixed `emit_call_site_error`. +* Documentation improvements. + +# v1.0.0 (2020-3-25) + +I believe the API can be considered stable because it's been a few months without +breaking changes, and I also don't think this crate will receive much further evolution. +It's perfect, admit it. + +Hence, meet the new, stable release! + +### Improvements + +* Supported nested `#[proc_macro_error]` attributes. Well, you aren't supposed to do that, + but I caught myself doing it by accident on one occasion and the behavior was... surprising. + Better to handle this smooth. + +# v0.4.12 (2020-3-23) + +* Error message on macros' misuse is now a bit more understandable. + +# v0.4.11 (2020-3-02) + +* `build.rs` no longer fails when `rustc` date could not be determined, + (thanks to [`Fabian Möller`](https://gitlab.com/CreepySkeleton/proc-macro-error/issues/8) + for noticing and to [`Igor Gnatenko`](https://gitlab.com/CreepySkeleton/proc-macro-error/-/merge_requests/25) + for fixing). + +# v0.4.10 (2020-2-29) + +* `proc-macro-error` doesn't depend on syn\[full\] anymore, the compilation + is \~30secs faster. + +# v0.4.9 (2020-2-13) + +* New function: `append_dummy`. + +# v0.4.8 (2020-2-01) + +* Support for children messages + +# v0.4.7 (2020-1-31) + +* Now any type that implements `quote::ToTokens` can be used instead of spans. + This allows for high quality error messages. + +# v0.4.6 (2020-1-31) + +* `From` implementation doesn't lose span info anymore, see + [#6](https://gitlab.com/CreepySkeleton/proc-macro-error/issues/6). + +# v0.4.5 (2020-1-20) +Just a small intermediate release. + +* Fix some bugs. +* Populate license files into subfolders. + +# v0.4.4 (2019-11-13) +* Fix `abort_if_dirty` + warnings bug +* Allow trailing commas in macros + +# v0.4.2 (2019-11-7) +* FINALLY fixed `__pme__suggestions not found` bug + +# v0.4.1 (2019-11-7) YANKED +* Fixed `__pme__suggestions not found` bug +* Documentation improvements, links checked + +# v0.4.0 (2019-11-6) YANKED + +## New features +* "help" messages that can have their own span on nightly, they + inherit parent span on stable. + ```rust + let cond_help = if condition { Some("some help message") else { None } }; + abort!( + span, // parent span + "something's wrong, {} wrongs in total", 10; // main message + help = "here's a help for you, {}", "take it"; // unconditional help message + help =? cond_help; // conditional help message, must be Option + note = note_span => "don't forget the note, {}", "would you?" // notes can have their own span but it's effective only on nightly + ) + ``` +* Warnings via `emit_warning` and `emit_warning_call_site`. Nightly only, they're ignored on stable. +* Now `proc-macro-error` delegates to `proc_macro::Diagnostic` on nightly. + +## Breaking changes +* `MacroError` is now replaced by `Diagnostic`. Its API resembles `proc_macro::Diagnostic`. +* `Diagnostic` does not implement `From<&str/String>` so `Result::abort_or_exit()` + won't work anymore (nobody used it anyway). +* `macro_error!` macro is replaced with `diagnostic!`. + +## Improvements +* Now `proc-macro-error` renders notes exactly just like rustc does. +* We don't parse a body of a function annotated with `#[proc_macro_error]` anymore, + only looking at the signature. This should somewhat decrease expansion time for large functions. + +# v0.3.3 (2019-10-16) +* Now you can use any word instead of "help", undocumented. + +# v0.3.2 (2019-10-16) +* Introduced support for "help" messages, undocumented. + +# v0.3.0 (2019-10-8) + +## The crate has been completely rewritten from scratch! + +## Changes (most are breaking): +* Renamed macros: + * `span_error` => `abort` + * `call_site_error` => `abort_call_site` +* `filter_macro_errors` was replaced by `#[proc_macro_error]` attribute. +* `set_dummy` now takes `TokenStream` instead of `Option` +* Support for multiple errors via `emit_error` and `emit_call_site_error` +* New `macro_error` macro for building errors in format=like style. +* `MacroError` API had been reconsidered. It also now implements `quote::ToTokens`. + +# v0.2.6 (2019-09-02) +* Introduce support for dummy implementations via `dummy::set_dummy` +* `multi::*` is now deprecated, will be completely rewritten in v0.3 + +# v0.2.0 (2019-08-15) + +## Breaking changes +* `trigger_error` replaced with `MacroError::trigger` and `filter_macro_error_panics` + is hidden from docs. + This is not quite a breaking change since users weren't supposed to use these functions directly anyway. +* All dependencies are updated to `v1.*`. + +## New features +* Ability to stack multiple errors via `multi::MultiMacroErrors` and emit them at once. + +## Improvements +* Now `MacroError` implements `std::fmt::Display` instead of `std::string::ToString`. +* `MacroError::span` inherent method. +* `From for proc_macro/proc_macro2::TokenStream` implementations. +* `AsRef/AsMut for MacroError` implementations. + +# v0.1.x (2019-07-XX) + +## New features +* An easy way to report errors inside within a proc-macro via `span_error`, + `call_site_error` and `filter_macro_errors`. diff --git a/bitbox02-bt/vendor/proc-macro-error/Cargo.toml b/bitbox02-bt/vendor/proc-macro-error/Cargo.toml new file mode 100644 index 0000000..869585f --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/Cargo.toml @@ -0,0 +1,56 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "proc-macro-error" +version = "1.0.4" +authors = ["CreepySkeleton "] +build = "build.rs" +description = "Almost drop-in replacement to panics in proc-macros" +readme = "README.md" +keywords = ["proc-macro", "error", "errors"] +categories = ["development-tools::procedural-macro-helpers"] +license = "MIT OR Apache-2.0" +repository = "https://gitlab.com/CreepySkeleton/proc-macro-error" +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] +[dependencies.proc-macro-error-attr] +version = "=1.0.4" + +[dependencies.proc-macro2] +version = "1" + +[dependencies.quote] +version = "1" + +[dependencies.syn] +version = "1" +optional = true +default-features = false +[dev-dependencies.serde_derive] +version = "=1.0.107" + +[dev-dependencies.toml] +version = "=0.5.2" + +[dev-dependencies.trybuild] +version = "1.0.19" +features = ["diff"] +[build-dependencies.version_check] +version = "0.9" + +[features] +default = ["syn-error"] +syn-error = ["syn"] +[badges.maintenance] +status = "passively-maintained" diff --git a/bitbox02-bt/vendor/proc-macro-error/LICENSE-APACHE b/bitbox02-bt/vendor/proc-macro-error/LICENSE-APACHE new file mode 100644 index 0000000..cc17374 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2019-2020 CreepySkeleton + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/proc-macro-error/LICENSE-MIT b/bitbox02-bt/vendor/proc-macro-error/LICENSE-MIT new file mode 100644 index 0000000..fc73e59 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-2020 CreepySkeleton + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bitbox02-bt/vendor/proc-macro-error/README.md b/bitbox02-bt/vendor/proc-macro-error/README.md new file mode 100644 index 0000000..7fbe07c --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/README.md @@ -0,0 +1,258 @@ +# Makes error reporting in procedural macros nice and easy + +[![travis ci](https://travis-ci.org/CreepySkeleton/proc-macro-error.svg?branch=master)](https://travis-ci.org/CreepySkeleton/proc-macro-error) +[![docs.rs](https://docs.rs/proc-macro-error/badge.svg)](https://docs.rs/proc-macro-error) +[![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/) + +This crate aims to make error reporting in proc-macros simple and easy to use. +Migrate from `panic!`-based errors for as little effort as possible! + +Also, you can explicitly [append a dummy token stream][crate::dummy] to your errors. + +To achieve his, this crate serves as a tiny shim around `proc_macro::Diagnostic` and +`compile_error!`. It detects the most preferable way to emit errors based on compiler's version. +When the underlying diagnostic type is finally stabilized, this crate will be simply +delegating to it, requiring no changes in your code! + +So you can just use this crate and have *both* some of `proc_macro::Diagnostic` functionality +available on stable ahead of time and your error-reporting code future-proof. + +```toml +[dependencies] +proc-macro-error = "1.0" +``` + +*Supports rustc 1.31 and up* + +[Documentation and guide][guide] + +## Quick example + +Code: + +```rust +#[proc_macro] +#[proc_macro_error] +pub fn make_fn(input: TokenStream) -> TokenStream { + let mut input = TokenStream2::from(input).into_iter(); + let name = input.next().unwrap(); + if let Some(second) = input.next() { + abort! { second, + "I don't like this part!"; + note = "I see what you did there..."; + help = "I need only one part, you know?"; + } + } + + quote!( fn #name() {} ).into() +} +``` + +This is how the error is rendered in a terminal: + +

+ +

+ +And this is what your users will see in their IDE: + +

+ +

+ +## Examples + +### Panic-like usage + +```rust +use proc_macro_error::{ + proc_macro_error, + abort, + abort_call_site, + ResultExt, + OptionExt, +}; +use proc_macro::TokenStream; +use syn::{DeriveInput, parse_macro_input}; +use quote::quote; + +// This is your main entry point +#[proc_macro] +// This attribute *MUST* be placed on top of the #[proc_macro] function +#[proc_macro_error] +pub fn make_answer(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + + if let Err(err) = some_logic(&input) { + // we've got a span to blame, let's use it + // This immediately aborts the proc-macro and shows the error + // + // You can use `proc_macro::Span`, `proc_macro2::Span`, and + // anything that implements `quote::ToTokens` (almost every type from + // `syn` and `proc_macro2`) + abort!(err, "You made an error, go fix it: {}", err.msg); + } + + // `Result` has some handy shortcuts if your error type implements + // `Into`. `Option` has one unconditionally. + more_logic(&input).expect_or_abort("What a careless user, behave!"); + + if !more_logic_for_logic_god(&input) { + // We don't have an exact location this time, + // so just highlight the proc-macro invocation itself + abort_call_site!( + "Bad, bad user! Now go stand in the corner and think about what you did!"); + } + + // Now all the processing is done, return `proc_macro::TokenStream` + quote!(/* stuff */).into() +} +``` + +### `proc_macro::Diagnostic`-like usage + +```rust +use proc_macro_error::*; +use proc_macro::TokenStream; +use syn::{spanned::Spanned, DeriveInput, ItemStruct, Fields, Attribute , parse_macro_input}; +use quote::quote; + +fn process_attrs(attrs: &[Attribute]) -> Vec { + attrs + .iter() + .filter_map(|attr| match process_attr(attr) { + Ok(res) => Some(res), + Err(msg) => { + emit_error!(attr, "Invalid attribute: {}", msg); + None + } + }) + .collect() +} + +fn process_fields(_attrs: &Fields) -> Vec { + // processing fields in pretty much the same way as attributes + unimplemented!() +} + +#[proc_macro] +#[proc_macro_error] +pub fn make_answer(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as ItemStruct); + let attrs = process_attrs(&input.attrs); + + // abort right now if some errors were encountered + // at the attributes processing stage + abort_if_dirty(); + + let fields = process_fields(&input.fields); + + // no need to think about emitted errors + // #[proc_macro_error] will handle them for you + // + // just return a TokenStream as you normally would + quote!(/* stuff */).into() +} +``` + +## Real world examples + +* [`structopt-derive`](https://github.com/TeXitoi/structopt/tree/master/structopt-derive) + (abort-like usage) +* [`auto-impl`](https://github.com/auto-impl-rs/auto_impl/) (emit-like usage) + +## Limitations + +- Warnings are emitted only on nightly, they are ignored on stable. +- "help" suggestions can't have their own span info on stable, + (essentially inheriting the parent span). +- If your macro happens to trigger a panic, no errors will be displayed. This is not a + technical limitation but rather intentional design. `panic` is not for error reporting. + +## MSRV policy + +`proc_macro_error` will always be compatible with proc-macro Holy Trinity: +`proc_macro2`, `syn`, `quote` crates. In other words, if the Trinity is available +to you - `proc_macro_error` is available too. + +> **Important!** +> +> If you want to use `#[proc_macro_error]` with `synstructure`, you're going +> to have to put the attribute inside the `decl_derive!` invocation. Unfortunately, +> due to some bug in pre-1.34 rustc, putting proc-macro attributes inside macro +> invocations doesn't work, so your MSRV is effectively 1.34. + +## Motivation + +Error handling in proc-macros sucks. There's not much of a choice today: +you either "bubble up" the error up to the top-level of the macro and convert it to +a [`compile_error!`][compl_err] invocation or just use a good old panic. Both these ways suck: + +- Former sucks because it's quite redundant to unroll a proper error handling + just for critical errors that will crash the macro anyway; so people mostly + choose not to bother with it at all and use panic. Simple `.expect` is too tempting. + + Also, if you do decide to implement this `Result`-based architecture in your macro + you're going to have to rewrite it entirely once [`proc_macro::Diagnostic`][] is finally + stable. Not cool. + +- Later sucks because there's no way to carry out the span info via `panic!`. + `rustc` will highlight the invocation itself but not some specific token inside it. + + Furthermore, panics aren't for error-reporting at all; panics are for bug-detecting + (like unwrapping on `None` or out-of-range indexing) or for early development stages + when you need a prototype ASAP so error handling can wait. Mixing these usages only + messes things up. + +- There is [`proc_macro::Diagnostic`][] which is awesome but it has been experimental + for more than a year and is unlikely to be stabilized any time soon. + + This crate's API is intentionally designed to be compatible with `proc_macro::Diagnostic` + and delegates to it whenever possible. Once `Diagnostics` is stable this crate + will **always** delegate to it, no code changes will be required on user side. + +That said, we need a solution, but this solution must meet these conditions: + +- It must be better than `panic!`. The main point: it must offer a way to carry the span information + over to user. +- It must take as little effort as possible to migrate from `panic!`. Ideally, a new + macro with similar semantics plus ability to carry out span info. +- It must maintain compatibility with [`proc_macro::Diagnostic`][] . +- **It must be usable on stable**. + +This crate aims to provide such a mechanism. All you have to do is annotate your top-level +`#[proc_macro]` function with `#[proc_macro_error]` attribute and change panics to +[`abort!`]/[`abort_call_site!`] where appropriate, see [the Guide][guide]. + +## Disclaimer +Please note that **this crate is not intended to be used in any way other +than error reporting in procedural macros**, use `Result` and `?` (possibly along with one of the +many helpers out there) for anything else. + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + + + +[compl_err]: https://doc.rust-lang.org/std/macro.compile_error.html +[`proc_macro::Diagnostic`]: https://doc.rust-lang.org/proc_macro/struct.Diagnostic.html + +[crate::dummy]: https://docs.rs/proc-macro-error/1/proc_macro_error/dummy/index.html +[crate::multi]: https://docs.rs/proc-macro-error/1/proc_macro_error/multi/index.html + +[`abort_call_site!`]: https://docs.rs/proc-macro-error/1/proc_macro_error/macro.abort_call_site.html +[`abort!`]: https://docs.rs/proc-macro-error/1/proc_macro_error/macro.abort.html +[guide]: https://docs.rs/proc-macro-error diff --git a/bitbox02-bt/vendor/proc-macro-error/build.rs b/bitbox02-bt/vendor/proc-macro-error/build.rs new file mode 100644 index 0000000..3c1196f --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/build.rs @@ -0,0 +1,11 @@ +fn main() { + if !version_check::is_feature_flaggable().unwrap_or(false) { + println!("cargo:rustc-cfg=use_fallback"); + } + + if version_check::is_max_version("1.38.0").unwrap_or(false) + || !version_check::Channel::read().unwrap().is_stable() + { + println!("cargo:rustc-cfg=skip_ui_tests"); + } +} diff --git a/bitbox02-bt/vendor/proc-macro-error/src/diagnostic.rs b/bitbox02-bt/vendor/proc-macro-error/src/diagnostic.rs new file mode 100644 index 0000000..983e617 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/src/diagnostic.rs @@ -0,0 +1,349 @@ +use crate::{abort_now, check_correctness, sealed::Sealed, SpanRange}; +use proc_macro2::Span; +use proc_macro2::TokenStream; + +use quote::{quote_spanned, ToTokens}; + +/// Represents a diagnostic level +/// +/// # Warnings +/// +/// Warnings are ignored on stable/beta +#[derive(Debug, PartialEq)] +pub enum Level { + Error, + Warning, + #[doc(hidden)] + NonExhaustive, +} + +/// Represents a single diagnostic message +#[derive(Debug)] +pub struct Diagnostic { + pub(crate) level: Level, + pub(crate) span_range: SpanRange, + pub(crate) msg: String, + pub(crate) suggestions: Vec<(SuggestionKind, String, Option)>, + pub(crate) children: Vec<(SpanRange, String)>, +} + +/// A collection of methods that do not exist in `proc_macro::Diagnostic` +/// but still useful to have around. +/// +/// This trait is sealed and cannot be implemented outside of `proc_macro_error`. +pub trait DiagnosticExt: Sealed { + /// Create a new diagnostic message that points to the `span_range`. + /// + /// This function is the same as `Diagnostic::spanned` but produces considerably + /// better error messages for multi-token spans on stable. + fn spanned_range(span_range: SpanRange, level: Level, message: String) -> Self; + + /// Add another error message to self such that it will be emitted right after + /// the main message. + /// + /// This function is the same as `Diagnostic::span_error` but produces considerably + /// better error messages for multi-token spans on stable. + fn span_range_error(self, span_range: SpanRange, msg: String) -> Self; + + /// Attach a "help" note to your main message, the note will have it's own span on nightly. + /// + /// This function is the same as `Diagnostic::span_help` but produces considerably + /// better error messages for multi-token spans on stable. + /// + /// # Span + /// + /// The span is ignored on stable, the note effectively inherits its parent's (main message) span + fn span_range_help(self, span_range: SpanRange, msg: String) -> Self; + + /// Attach a note to your main message, the note will have it's own span on nightly. + /// + /// This function is the same as `Diagnostic::span_note` but produces considerably + /// better error messages for multi-token spans on stable. + /// + /// # Span + /// + /// The span is ignored on stable, the note effectively inherits its parent's (main message) span + fn span_range_note(self, span_range: SpanRange, msg: String) -> Self; +} + +impl DiagnosticExt for Diagnostic { + fn spanned_range(span_range: SpanRange, level: Level, message: String) -> Self { + Diagnostic { + level, + span_range, + msg: message, + suggestions: vec![], + children: vec![], + } + } + + fn span_range_error(mut self, span_range: SpanRange, msg: String) -> Self { + self.children.push((span_range, msg)); + self + } + + fn span_range_help(mut self, span_range: SpanRange, msg: String) -> Self { + self.suggestions + .push((SuggestionKind::Help, msg, Some(span_range))); + self + } + + fn span_range_note(mut self, span_range: SpanRange, msg: String) -> Self { + self.suggestions + .push((SuggestionKind::Note, msg, Some(span_range))); + self + } +} + +impl Diagnostic { + /// Create a new diagnostic message that points to `Span::call_site()` + pub fn new(level: Level, message: String) -> Self { + Diagnostic::spanned(Span::call_site(), level, message) + } + + /// Create a new diagnostic message that points to the `span` + pub fn spanned(span: Span, level: Level, message: String) -> Self { + Diagnostic::spanned_range( + SpanRange { + first: span, + last: span, + }, + level, + message, + ) + } + + /// Add another error message to self such that it will be emitted right after + /// the main message. + pub fn span_error(self, span: Span, msg: String) -> Self { + self.span_range_error( + SpanRange { + first: span, + last: span, + }, + msg, + ) + } + + /// Attach a "help" note to your main message, the note will have it's own span on nightly. + /// + /// # Span + /// + /// The span is ignored on stable, the note effectively inherits its parent's (main message) span + pub fn span_help(self, span: Span, msg: String) -> Self { + self.span_range_help( + SpanRange { + first: span, + last: span, + }, + msg, + ) + } + + /// Attach a "help" note to your main message. + pub fn help(mut self, msg: String) -> Self { + self.suggestions.push((SuggestionKind::Help, msg, None)); + self + } + + /// Attach a note to your main message, the note will have it's own span on nightly. + /// + /// # Span + /// + /// The span is ignored on stable, the note effectively inherits its parent's (main message) span + pub fn span_note(self, span: Span, msg: String) -> Self { + self.span_range_note( + SpanRange { + first: span, + last: span, + }, + msg, + ) + } + + /// Attach a note to your main message + pub fn note(mut self, msg: String) -> Self { + self.suggestions.push((SuggestionKind::Note, msg, None)); + self + } + + /// The message of main warning/error (no notes attached) + pub fn message(&self) -> &str { + &self.msg + } + + /// Abort the proc-macro's execution and display the diagnostic. + /// + /// # Warnings + /// + /// Warnings are not emitted on stable and beta, but this function will abort anyway. + pub fn abort(self) -> ! { + self.emit(); + abort_now() + } + + /// Display the diagnostic while not aborting macro execution. + /// + /// # Warnings + /// + /// Warnings are ignored on stable/beta + pub fn emit(self) { + check_correctness(); + crate::imp::emit_diagnostic(self); + } +} + +/// **NOT PUBLIC API! NOTHING TO SEE HERE!!!** +#[doc(hidden)] +impl Diagnostic { + pub fn span_suggestion(self, span: Span, suggestion: &str, msg: String) -> Self { + match suggestion { + "help" | "hint" => self.span_help(span, msg), + _ => self.span_note(span, msg), + } + } + + pub fn suggestion(self, suggestion: &str, msg: String) -> Self { + match suggestion { + "help" | "hint" => self.help(msg), + _ => self.note(msg), + } + } +} + +impl ToTokens for Diagnostic { + fn to_tokens(&self, ts: &mut TokenStream) { + use std::borrow::Cow; + + fn ensure_lf(buf: &mut String, s: &str) { + if s.ends_with('\n') { + buf.push_str(s); + } else { + buf.push_str(s); + buf.push('\n'); + } + } + + fn diag_to_tokens( + span_range: SpanRange, + level: &Level, + msg: &str, + suggestions: &[(SuggestionKind, String, Option)], + ) -> TokenStream { + if *level == Level::Warning { + return TokenStream::new(); + } + + let message = if suggestions.is_empty() { + Cow::Borrowed(msg) + } else { + let mut message = String::new(); + ensure_lf(&mut message, msg); + message.push('\n'); + + for (kind, note, _span) in suggestions { + message.push_str(" = "); + message.push_str(kind.name()); + message.push_str(": "); + ensure_lf(&mut message, note); + } + message.push('\n'); + + Cow::Owned(message) + }; + + let mut msg = proc_macro2::Literal::string(&message); + msg.set_span(span_range.last); + let group = quote_spanned!(span_range.last=> { #msg } ); + quote_spanned!(span_range.first=> compile_error!#group) + } + + ts.extend(diag_to_tokens( + self.span_range, + &self.level, + &self.msg, + &self.suggestions, + )); + ts.extend( + self.children + .iter() + .map(|(span_range, msg)| diag_to_tokens(*span_range, &Level::Error, &msg, &[])), + ); + } +} + +#[derive(Debug)] +pub(crate) enum SuggestionKind { + Help, + Note, +} + +impl SuggestionKind { + fn name(&self) -> &'static str { + match self { + SuggestionKind::Note => "note", + SuggestionKind::Help => "help", + } + } +} + +#[cfg(feature = "syn-error")] +impl From for Diagnostic { + fn from(err: syn::Error) -> Self { + use proc_macro2::{Delimiter, TokenTree}; + + fn gut_error(ts: &mut impl Iterator) -> Option<(SpanRange, String)> { + let first = match ts.next() { + // compile_error + None => return None, + Some(tt) => tt.span(), + }; + ts.next().unwrap(); // ! + + let lit = match ts.next().unwrap() { + TokenTree::Group(group) => { + // Currently `syn` builds `compile_error!` invocations + // exclusively in `ident{"..."}` (braced) form which is not + // followed by `;` (semicolon). + // + // But if it changes to `ident("...");` (parenthesized) + // or `ident["..."];` (bracketed) form, + // we will need to skip the `;` as well. + // Highly unlikely, but better safe than sorry. + + if group.delimiter() == Delimiter::Parenthesis + || group.delimiter() == Delimiter::Bracket + { + ts.next().unwrap(); // ; + } + + match group.stream().into_iter().next().unwrap() { + TokenTree::Literal(lit) => lit, + _ => unreachable!(), + } + } + _ => unreachable!(), + }; + + let last = lit.span(); + let mut msg = lit.to_string(); + + // "abc" => abc + msg.pop(); + msg.remove(0); + + Some((SpanRange { first, last }, msg)) + } + + let mut ts = err.to_compile_error().into_iter(); + + let (span_range, msg) = gut_error(&mut ts).unwrap(); + let mut res = Diagnostic::spanned_range(span_range, Level::Error, msg); + + while let Some((span_range, msg)) = gut_error(&mut ts) { + res = res.span_range_error(span_range, msg); + } + + res + } +} diff --git a/bitbox02-bt/vendor/proc-macro-error/src/dummy.rs b/bitbox02-bt/vendor/proc-macro-error/src/dummy.rs new file mode 100644 index 0000000..571a595 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/src/dummy.rs @@ -0,0 +1,150 @@ +//! Facility to emit dummy implementations (or whatever) in case +//! an error happen. +//! +//! `compile_error!` does not abort a compilation right away. This means +//! `rustc` doesn't just show you the error and abort, it carries on the +//! compilation process looking for other errors to report. +//! +//! Let's consider an example: +//! +//! ```rust,ignore +//! use proc_macro::TokenStream; +//! use proc_macro_error::*; +//! +//! trait MyTrait { +//! fn do_thing(); +//! } +//! +//! // this proc macro is supposed to generate MyTrait impl +//! #[proc_macro_derive(MyTrait)] +//! #[proc_macro_error] +//! fn example(input: TokenStream) -> TokenStream { +//! // somewhere deep inside +//! abort!(span, "something's wrong"); +//! +//! // this implementation will be generated if no error happened +//! quote! { +//! impl MyTrait for #name { +//! fn do_thing() {/* whatever */} +//! } +//! } +//! } +//! +//! // ================ +//! // in main.rs +//! +//! // this derive triggers an error +//! #[derive(MyTrait)] // first BOOM! +//! struct Foo; +//! +//! fn main() { +//! Foo::do_thing(); // second BOOM! +//! } +//! ``` +//! +//! The problem is: the generated token stream contains only `compile_error!` +//! invocation, the impl was not generated. That means user will see two compilation +//! errors: +//! +//! ```text +//! error: something's wrong +//! --> $DIR/probe.rs:9:10 +//! | +//! 9 |#[proc_macro_derive(MyTrait)] +//! | ^^^^^^^ +//! +//! error[E0599]: no function or associated item named `do_thing` found for type `Foo` in the current scope +//! --> src\main.rs:3:10 +//! | +//! 1 | struct Foo; +//! | ----------- function or associated item `do_thing` not found for this +//! 2 | fn main() { +//! 3 | Foo::do_thing(); // second BOOM! +//! | ^^^^^^^^ function or associated item not found in `Foo` +//! ``` +//! +//! But the second error is meaningless! We definitely need to fix this. +//! +//! Most used approach in cases like this is "dummy implementation" - +//! omit `impl MyTrait for #name` and fill functions bodies with `unimplemented!()`. +//! +//! This is how you do it: +//! +//! ```rust,ignore +//! use proc_macro::TokenStream; +//! use proc_macro_error::*; +//! +//! trait MyTrait { +//! fn do_thing(); +//! } +//! +//! // this proc macro is supposed to generate MyTrait impl +//! #[proc_macro_derive(MyTrait)] +//! #[proc_macro_error] +//! fn example(input: TokenStream) -> TokenStream { +//! // first of all - we set a dummy impl which will be appended to +//! // `compile_error!` invocations in case a trigger does happen +//! set_dummy(quote! { +//! impl MyTrait for #name { +//! fn do_thing() { unimplemented!() } +//! } +//! }); +//! +//! // somewhere deep inside +//! abort!(span, "something's wrong"); +//! +//! // this implementation will be generated if no error happened +//! quote! { +//! impl MyTrait for #name { +//! fn do_thing() {/* whatever */} +//! } +//! } +//! } +//! +//! // ================ +//! // in main.rs +//! +//! // this derive triggers an error +//! #[derive(MyTrait)] // first BOOM! +//! struct Foo; +//! +//! fn main() { +//! Foo::do_thing(); // no more errors! +//! } +//! ``` + +use proc_macro2::TokenStream; +use std::cell::RefCell; + +use crate::check_correctness; + +thread_local! { + static DUMMY_IMPL: RefCell> = RefCell::new(None); +} + +/// Sets dummy token stream which will be appended to `compile_error!(msg);...` +/// invocations in case you'll emit any errors. +/// +/// See [guide](../index.html#guide). +pub fn set_dummy(dummy: TokenStream) -> Option { + check_correctness(); + DUMMY_IMPL.with(|old_dummy| old_dummy.replace(Some(dummy))) +} + +/// Same as [`set_dummy`] but, instead of resetting, appends tokens to the +/// existing dummy (if any). Behaves as `set_dummy` if no dummy is present. +pub fn append_dummy(dummy: TokenStream) { + check_correctness(); + DUMMY_IMPL.with(|old_dummy| { + let mut cell = old_dummy.borrow_mut(); + if let Some(ts) = cell.as_mut() { + ts.extend(dummy); + } else { + *cell = Some(dummy); + } + }); +} + +pub(crate) fn cleanup() -> Option { + DUMMY_IMPL.with(|old_dummy| old_dummy.replace(None)) +} diff --git a/bitbox02-bt/vendor/proc-macro-error/src/imp/delegate.rs b/bitbox02-bt/vendor/proc-macro-error/src/imp/delegate.rs new file mode 100644 index 0000000..07def2b --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/src/imp/delegate.rs @@ -0,0 +1,69 @@ +//! This implementation uses [`proc_macro::Diagnostic`], nightly only. + +use std::cell::Cell; + +use proc_macro::{Diagnostic as PDiag, Level as PLevel}; + +use crate::{ + abort_now, check_correctness, + diagnostic::{Diagnostic, Level, SuggestionKind}, +}; + +pub fn abort_if_dirty() { + check_correctness(); + if IS_DIRTY.with(|c| c.get()) { + abort_now() + } +} + +pub(crate) fn cleanup() -> Vec { + IS_DIRTY.with(|c| c.set(false)); + vec![] +} + +pub(crate) fn emit_diagnostic(diag: Diagnostic) { + let Diagnostic { + level, + span_range, + msg, + suggestions, + children, + } = diag; + + let span = span_range.collapse().unwrap(); + + let level = match level { + Level::Warning => PLevel::Warning, + Level::Error => { + IS_DIRTY.with(|c| c.set(true)); + PLevel::Error + } + _ => unreachable!(), + }; + + let mut res = PDiag::spanned(span, level, msg); + + for (kind, msg, span) in suggestions { + res = match (kind, span) { + (SuggestionKind::Note, Some(span_range)) => { + res.span_note(span_range.collapse().unwrap(), msg) + } + (SuggestionKind::Help, Some(span_range)) => { + res.span_help(span_range.collapse().unwrap(), msg) + } + (SuggestionKind::Note, None) => res.note(msg), + (SuggestionKind::Help, None) => res.help(msg), + } + } + + for (span_range, msg) in children { + let span = span_range.collapse().unwrap(); + res = res.span_error(span, msg); + } + + res.emit() +} + +thread_local! { + static IS_DIRTY: Cell = Cell::new(false); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/src/imp/fallback.rs b/bitbox02-bt/vendor/proc-macro-error/src/imp/fallback.rs new file mode 100644 index 0000000..ad1f730 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/src/imp/fallback.rs @@ -0,0 +1,30 @@ +//! This implementation uses self-written stable facilities. + +use crate::{ + abort_now, check_correctness, + diagnostic::{Diagnostic, Level}, +}; +use std::cell::RefCell; + +pub fn abort_if_dirty() { + check_correctness(); + ERR_STORAGE.with(|storage| { + if !storage.borrow().is_empty() { + abort_now() + } + }); +} + +pub(crate) fn cleanup() -> Vec { + ERR_STORAGE.with(|storage| storage.replace(Vec::new())) +} + +pub(crate) fn emit_diagnostic(diag: Diagnostic) { + if diag.level == Level::Error { + ERR_STORAGE.with(|storage| storage.borrow_mut().push(diag)); + } +} + +thread_local! { + static ERR_STORAGE: RefCell> = RefCell::new(Vec::new()); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/src/lib.rs b/bitbox02-bt/vendor/proc-macro-error/src/lib.rs new file mode 100644 index 0000000..fb867fd --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/src/lib.rs @@ -0,0 +1,560 @@ +//! # proc-macro-error +//! +//! This crate aims to make error reporting in proc-macros simple and easy to use. +//! Migrate from `panic!`-based errors for as little effort as possible! +//! +//! (Also, you can explicitly [append a dummy token stream](dummy/index.html) to your errors). +//! +//! To achieve his, this crate serves as a tiny shim around `proc_macro::Diagnostic` and +//! `compile_error!`. It detects the best way of emitting available based on compiler's version. +//! When the underlying diagnostic type is finally stabilized, this crate will simply be +//! delegating to it requiring no changes in your code! +//! +//! So you can just use this crate and have *both* some of `proc_macro::Diagnostic` functionality +//! available on stable ahead of time *and* your error-reporting code future-proof. +//! +//! ## Cargo features +//! +//! This crate provides *enabled by default* `syn-error` feature that gates +//! `impl From for Diagnostic` conversion. If you don't use `syn` and want +//! to cut off some of compilation time, you can disable it via +//! +//! ```toml +//! [dependencies] +//! proc-macro-error = { version = "1", default-features = false } +//! ``` +//! +//! ***Please note that disabling this feature makes sense only if you don't depend on `syn` +//! directly or indirectly, and you very likely do.** +//! +//! ## Real world examples +//! +//! * [`structopt-derive`](https://github.com/TeXitoi/structopt/tree/master/structopt-derive) +//! (abort-like usage) +//! * [`auto-impl`](https://github.com/auto-impl-rs/auto_impl/) (emit-like usage) +//! +//! ## Limitations +//! +//! - Warnings are emitted only on nightly, they are ignored on stable. +//! - "help" suggestions can't have their own span info on stable, +//! (essentially inheriting the parent span). +//! - If a panic occurs somewhere in your macro no errors will be displayed. This is not a +//! technical limitation but rather intentional design. `panic` is not for error reporting. +//! +//! ### `#[proc_macro_error]` attribute +//! +//! **This attribute MUST be present on the top level of your macro** (the function +//! annotated with any of `#[proc_macro]`, `#[proc_macro_derive]`, `#[proc_macro_attribute]`). +//! +//! This attribute performs the setup and cleanup necessary to make things work. +//! +//! In most cases you'll need the simple `#[proc_macro_error]` form without any +//! additional settings. Feel free to [skip the "Syntax" section](#macros). +//! +//! #### Syntax +//! +//! `#[proc_macro_error]` or `#[proc_macro_error(settings...)]`, where `settings...` +//! is a comma-separated list of: +//! +//! - `proc_macro_hack`: +//! +//! In order to correctly cooperate with `#[proc_macro_hack]`, `#[proc_macro_error]` +//! attribute must be placed *before* (above) it, like this: +//! +//! ```no_run +//! # use proc_macro2::TokenStream; +//! # const IGNORE: &str = " +//! #[proc_macro_error] +//! #[proc_macro_hack] +//! #[proc_macro] +//! # "; +//! fn my_macro(input: TokenStream) -> TokenStream { +//! unimplemented!() +//! } +//! ``` +//! +//! If, for some reason, you can't place it like that you can use +//! `#[proc_macro_error(proc_macro_hack)]` instead. +//! +//! # Note +//! +//! If `proc-macro-hack` was detected (by any means) `allow_not_macro` +//! and `assert_unwind_safe` will be applied automatically. +//! +//! - `allow_not_macro`: +//! +//! By default, the attribute checks that it's applied to a proc-macro. +//! If none of `#[proc_macro]`, `#[proc_macro_derive]` nor `#[proc_macro_attribute]` are +//! present it will panic. It's the intention - this crate is supposed to be used only with +//! proc-macros. +//! +//! This setting is made to bypass the check, useful in certain circumstances. +//! +//! Pay attention: the function this attribute is applied to must return +//! `proc_macro::TokenStream`. +//! +//! This setting is implied if `proc-macro-hack` was detected. +//! +//! - `assert_unwind_safe`: +//! +//! By default, your code must be [unwind safe]. If your code is not unwind safe, +//! but you believe it's correct, you can use this setting to bypass the check. +//! You would need this for code that uses `lazy_static` or `thread_local` with +//! `Cell/RefCell` inside (and the like). +//! +//! This setting is implied if `#[proc_macro_error]` is applied to a function +//! marked as `#[proc_macro]`, `#[proc_macro_derive]` or `#[proc_macro_attribute]`. +//! +//! This setting is also implied if `proc-macro-hack` was detected. +//! +//! ## Macros +//! +//! Most of the time you want to use the macros. Syntax is described in the next section below. +//! +//! You'll need to decide how you want to emit errors: +//! +//! * Emit the error and abort. Very much panic-like usage. Served by [`abort!`] and +//! [`abort_call_site!`]. +//! * Emit the error but do not abort right away, looking for other errors to report. +//! Served by [`emit_error!`] and [`emit_call_site_error!`]. +//! +//! You **can** mix these usages. +//! +//! `abort` and `emit_error` take a "source span" as the first argument. This source +//! will be used to highlight the place the error originates from. It must be one of: +//! +//! * *Something* that implements [`ToTokens`] (most types in `syn` and `proc-macro2` do). +//! This source is the preferable one since it doesn't lose span information on multi-token +//! spans, see [this issue](https://gitlab.com/CreepySkeleton/proc-macro-error/-/issues/6) +//! for details. +//! * [`proc_macro::Span`] +//! * [`proc-macro2::Span`] +//! +//! The rest is your message in format-like style. +//! +//! See [the next section](#syntax-1) for detailed syntax. +//! +//! - [`abort!`]: +//! +//! Very much panic-like usage - abort right away and show the error. +//! Expands to [`!`] (never type). +//! +//! - [`abort_call_site!`]: +//! +//! Shortcut for `abort!(Span::call_site(), ...)`. Expands to [`!`] (never type). +//! +//! - [`emit_error!`]: +//! +//! [`proc_macro::Diagnostic`]-like usage - emit the error but keep going, +//! looking for other errors to report. +//! The compilation will fail nonetheless. Expands to [`()`] (unit type). +//! +//! - [`emit_call_site_error!`]: +//! +//! Shortcut for `emit_error!(Span::call_site(), ...)`. Expands to [`()`] (unit type). +//! +//! - [`emit_warning!`]: +//! +//! Like `emit_error!` but emit a warning instead of error. The compilation won't fail +//! because of warnings. +//! Expands to [`()`] (unit type). +//! +//! **Beware**: warnings are nightly only, they are completely ignored on stable. +//! +//! - [`emit_call_site_warning!`]: +//! +//! Shortcut for `emit_warning!(Span::call_site(), ...)`. Expands to [`()`] (unit type). +//! +//! - [`diagnostic`]: +//! +//! Build an instance of `Diagnostic` in format-like style. +//! +//! #### Syntax +//! +//! All the macros have pretty much the same syntax: +//! +//! 1. ```ignore +//! abort!(single_expr) +//! ``` +//! Shortcut for `Diagnostic::from(expr).abort()`. +//! +//! 2. ```ignore +//! abort!(span, message) +//! ``` +//! The first argument is an expression the span info should be taken from. +//! +//! The second argument is the error message, it must implement [`ToString`]. +//! +//! 3. ```ignore +//! abort!(span, format_literal, format_args...) +//! ``` +//! +//! This form is pretty much the same as 2, except `format!(format_literal, format_args...)` +//! will be used to for the message instead of [`ToString`]. +//! +//! That's it. `abort!`, `emit_warning`, `emit_error` share this exact syntax. +//! +//! `abort_call_site!`, `emit_call_site_warning`, `emit_call_site_error` lack 1 form +//! and do not take span in 2'th and 3'th forms. Those are essentially shortcuts for +//! `macro!(Span::call_site(), args...)`. +//! +//! `diagnostic!` requires a [`Level`] instance between `span` and second argument +//! (1'th form is the same). +//! +//! > **Important!** +//! > +//! > If you have some type from `proc_macro` or `syn` to point to, do not call `.span()` +//! > on it but rather use it directly: +//! > ```no_run +//! > # use proc_macro_error::abort; +//! > # let input = proc_macro2::TokenStream::new(); +//! > let ty: syn::Type = syn::parse2(input).unwrap(); +//! > abort!(ty, "BOOM"); +//! > // ^^ <-- avoid .span() +//! > ``` +//! > +//! > `.span()` calls work too, but you may experience regressions in message quality. +//! +//! #### Note attachments +//! +//! 3. Every macro can have "note" attachments (only 2 and 3 form). +//! ```ignore +//! let opt_help = if have_some_info { Some("did you mean `this`?") } else { None }; +//! +//! abort!( +//! span, message; // <--- attachments start with `;` (semicolon) +//! +//! help = "format {} {}", "arg1", "arg2"; // <--- every attachment ends with `;`, +//! // maybe except the last one +//! +//! note = "to_string"; // <--- one arg uses `.to_string()` instead of `format!()` +//! +//! yay = "I see what {} did here", "you"; // <--- "help =" and "hint =" are mapped +//! // to Diagnostic::help, +//! // anything else is Diagnostic::note +//! +//! wow = note_span => "custom span"; // <--- attachments can have their own span +//! // it takes effect only on nightly though +//! +//! hint =? opt_help; // <-- "optional" attachment, get displayed only if `Some` +//! // must be single `Option` expression +//! +//! note =? note_span => opt_help // <-- optional attachments can have custom spans too +//! ); +//! ``` +//! + +//! ### Diagnostic type +//! +//! [`Diagnostic`] type is intentionally designed to be API compatible with [`proc_macro::Diagnostic`]. +//! Not all API is implemented, only the part that can be reasonably implemented on stable. +//! +//! +//! [`abort!`]: macro.abort.html +//! [`abort_call_site!`]: macro.abort_call_site.html +//! [`emit_warning!`]: macro.emit_warning.html +//! [`emit_error!`]: macro.emit_error.html +//! [`emit_call_site_warning!`]: macro.emit_call_site_error.html +//! [`emit_call_site_error!`]: macro.emit_call_site_warning.html +//! [`diagnostic!`]: macro.diagnostic.html +//! [`Diagnostic`]: struct.Diagnostic.html +//! +//! [`proc_macro::Span`]: https://doc.rust-lang.org/proc_macro/struct.Span.html +//! [`proc_macro::Diagnostic`]: https://doc.rust-lang.org/proc_macro/struct.Diagnostic.html +//! +//! [unwind safe]: https://doc.rust-lang.org/std/panic/trait.UnwindSafe.html#what-is-unwind-safety +//! [`!`]: https://doc.rust-lang.org/std/primitive.never.html +//! [`()`]: https://doc.rust-lang.org/std/primitive.unit.html +//! [`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html +//! +//! [`proc-macro2::Span`]: https://docs.rs/proc-macro2/1.0.10/proc_macro2/struct.Span.html +//! [`ToTokens`]: https://docs.rs/quote/1.0.3/quote/trait.ToTokens.html +//! + +#![cfg_attr(not(use_fallback), feature(proc_macro_diagnostic))] +#![forbid(unsafe_code)] +#![allow(clippy::needless_doctest_main)] + +extern crate proc_macro; + +pub use crate::{ + diagnostic::{Diagnostic, DiagnosticExt, Level}, + dummy::{append_dummy, set_dummy}, +}; +pub use proc_macro_error_attr::proc_macro_error; + +use proc_macro2::Span; +use quote::{quote, ToTokens}; + +use std::cell::Cell; +use std::panic::{catch_unwind, resume_unwind, UnwindSafe}; + +pub mod dummy; + +mod diagnostic; +mod macros; +mod sealed; + +#[cfg(use_fallback)] +#[path = "imp/fallback.rs"] +mod imp; + +#[cfg(not(use_fallback))] +#[path = "imp/delegate.rs"] +mod imp; + +#[derive(Debug, Clone, Copy)] +pub struct SpanRange { + pub first: Span, + pub last: Span, +} + +impl SpanRange { + /// Create a range with the `first` and `last` spans being the same. + pub fn single_span(span: Span) -> Self { + SpanRange { + first: span, + last: span, + } + } + + /// Create a `SpanRange` resolving at call site. + pub fn call_site() -> Self { + SpanRange::single_span(Span::call_site()) + } + + /// Construct span range from a `TokenStream`. This method always preserves all the + /// range. + /// + /// ### Note + /// + /// If the stream is empty, the result is `SpanRange::call_site()`. If the stream + /// consists of only one `TokenTree`, the result is `SpanRange::single_span(tt.span())` + /// that doesn't lose anything. + pub fn from_tokens(ts: &dyn ToTokens) -> Self { + let mut spans = ts.to_token_stream().into_iter().map(|tt| tt.span()); + let first = spans.next().unwrap_or_else(|| Span::call_site()); + let last = spans.last().unwrap_or(first); + + SpanRange { first, last } + } + + /// Join two span ranges. The resulting range will start at `self.first` and end at + /// `other.last`. + pub fn join_range(self, other: SpanRange) -> Self { + SpanRange { + first: self.first, + last: other.last, + } + } + + /// Collapse the range into single span, preserving as much information as possible. + pub fn collapse(self) -> Span { + self.first.join(self.last).unwrap_or(self.first) + } +} + +/// This traits expands `Result>` with some handy shortcuts. +pub trait ResultExt { + type Ok; + + /// Behaves like `Result::unwrap`: if self is `Ok` yield the contained value, + /// otherwise abort macro execution via `abort!`. + fn unwrap_or_abort(self) -> Self::Ok; + + /// Behaves like `Result::expect`: if self is `Ok` yield the contained value, + /// otherwise abort macro execution via `abort!`. + /// If it aborts then resulting error message will be preceded with `message`. + fn expect_or_abort(self, msg: &str) -> Self::Ok; +} + +/// This traits expands `Option` with some handy shortcuts. +pub trait OptionExt { + type Some; + + /// Behaves like `Option::expect`: if self is `Some` yield the contained value, + /// otherwise abort macro execution via `abort_call_site!`. + /// If it aborts the `message` will be used for [`compile_error!`][compl_err] invocation. + /// + /// [compl_err]: https://doc.rust-lang.org/std/macro.compile_error.html + fn expect_or_abort(self, msg: &str) -> Self::Some; +} + +/// Abort macro execution and display all the emitted errors, if any. +/// +/// Does nothing if no errors were emitted (warnings do not count). +pub fn abort_if_dirty() { + imp::abort_if_dirty(); +} + +impl> ResultExt for Result { + type Ok = T; + + fn unwrap_or_abort(self) -> T { + match self { + Ok(res) => res, + Err(e) => e.into().abort(), + } + } + + fn expect_or_abort(self, message: &str) -> T { + match self { + Ok(res) => res, + Err(e) => { + let mut e = e.into(); + e.msg = format!("{}: {}", message, e.msg); + e.abort() + } + } + } +} + +impl OptionExt for Option { + type Some = T; + + fn expect_or_abort(self, message: &str) -> T { + match self { + Some(res) => res, + None => abort_call_site!(message), + } + } +} + +/// This is the entry point for a proc-macro. +/// +/// **NOT PUBLIC API, SUBJECT TO CHANGE WITHOUT ANY NOTICE** +#[doc(hidden)] +pub fn entry_point(f: F, proc_macro_hack: bool) -> proc_macro::TokenStream +where + F: FnOnce() -> proc_macro::TokenStream + UnwindSafe, +{ + ENTERED_ENTRY_POINT.with(|flag| flag.set(flag.get() + 1)); + let caught = catch_unwind(f); + let dummy = dummy::cleanup(); + let err_storage = imp::cleanup(); + ENTERED_ENTRY_POINT.with(|flag| flag.set(flag.get() - 1)); + + let gen_error = || { + if proc_macro_hack { + quote! {{ + macro_rules! proc_macro_call { + () => ( unimplemented!() ) + } + + #(#err_storage)* + #dummy + + unimplemented!() + }} + } else { + quote!( #(#err_storage)* #dummy ) + } + }; + + match caught { + Ok(ts) => { + if err_storage.is_empty() { + ts + } else { + gen_error().into() + } + } + + Err(boxed) => match boxed.downcast::() { + Ok(_) => gen_error().into(), + Err(boxed) => resume_unwind(boxed), + }, + } +} + +fn abort_now() -> ! { + check_correctness(); + panic!(AbortNow) +} + +thread_local! { + static ENTERED_ENTRY_POINT: Cell = Cell::new(0); +} + +struct AbortNow; + +fn check_correctness() { + if ENTERED_ENTRY_POINT.with(|flag| flag.get()) == 0 { + panic!( + "proc-macro-error API cannot be used outside of `entry_point` invocation, \ + perhaps you forgot to annotate your #[proc_macro] function with `#[proc_macro_error]" + ); + } +} + +/// **ALL THE STUFF INSIDE IS NOT PUBLIC API!!!** +#[doc(hidden)] +pub mod __export { + // reexports for use in macros + pub extern crate proc_macro; + pub extern crate proc_macro2; + + use proc_macro2::Span; + use quote::ToTokens; + + use crate::SpanRange; + + // inspired by + // https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md#simple-application + + pub trait SpanAsSpanRange { + #[allow(non_snake_case)] + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange; + } + + pub trait Span2AsSpanRange { + #[allow(non_snake_case)] + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange; + } + + pub trait ToTokensAsSpanRange { + #[allow(non_snake_case)] + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange; + } + + pub trait SpanRangeAsSpanRange { + #[allow(non_snake_case)] + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange; + } + + impl ToTokensAsSpanRange for &T { + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange { + let mut ts = self.to_token_stream().into_iter(); + let first = ts + .next() + .map(|tt| tt.span()) + .unwrap_or_else(Span::call_site); + let last = ts.last().map(|tt| tt.span()).unwrap_or(first); + SpanRange { first, last } + } + } + + impl Span2AsSpanRange for Span { + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange { + SpanRange { + first: *self, + last: *self, + } + } + } + + impl SpanAsSpanRange for proc_macro::Span { + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange { + SpanRange { + first: self.clone().into(), + last: self.clone().into(), + } + } + } + + impl SpanRangeAsSpanRange for SpanRange { + fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange { + *self + } + } +} diff --git a/bitbox02-bt/vendor/proc-macro-error/src/macros.rs b/bitbox02-bt/vendor/proc-macro-error/src/macros.rs new file mode 100644 index 0000000..747b684 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/src/macros.rs @@ -0,0 +1,288 @@ +// FIXME: this can be greatly simplified via $()? +// as soon as MRSV hits 1.32 + +/// Build [`Diagnostic`](struct.Diagnostic.html) instance from provided arguments. +/// +/// # Syntax +/// +/// See [the guide](index.html#guide). +/// +#[macro_export] +macro_rules! diagnostic { + // from alias + ($err:expr) => { $crate::Diagnostic::from($err) }; + + // span, message, help + ($span:expr, $level:expr, $fmt:expr, $($args:expr),+ ; $($rest:tt)+) => {{ + #[allow(unused_imports)] + use $crate::__export::{ + ToTokensAsSpanRange, + Span2AsSpanRange, + SpanAsSpanRange, + SpanRangeAsSpanRange + }; + use $crate::DiagnosticExt; + let span_range = (&$span).FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(); + + let diag = $crate::Diagnostic::spanned_range( + span_range, + $level, + format!($fmt, $($args),*) + ); + $crate::__pme__suggestions!(diag $($rest)*); + diag + }}; + + ($span:expr, $level:expr, $msg:expr ; $($rest:tt)+) => {{ + #[allow(unused_imports)] + use $crate::__export::{ + ToTokensAsSpanRange, + Span2AsSpanRange, + SpanAsSpanRange, + SpanRangeAsSpanRange + }; + use $crate::DiagnosticExt; + let span_range = (&$span).FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(); + + let diag = $crate::Diagnostic::spanned_range(span_range, $level, $msg.to_string()); + $crate::__pme__suggestions!(diag $($rest)*); + diag + }}; + + // span, message, no help + ($span:expr, $level:expr, $fmt:expr, $($args:expr),+) => {{ + #[allow(unused_imports)] + use $crate::__export::{ + ToTokensAsSpanRange, + Span2AsSpanRange, + SpanAsSpanRange, + SpanRangeAsSpanRange + }; + use $crate::DiagnosticExt; + let span_range = (&$span).FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(); + + $crate::Diagnostic::spanned_range( + span_range, + $level, + format!($fmt, $($args),*) + ) + }}; + + ($span:expr, $level:expr, $msg:expr) => {{ + #[allow(unused_imports)] + use $crate::__export::{ + ToTokensAsSpanRange, + Span2AsSpanRange, + SpanAsSpanRange, + SpanRangeAsSpanRange + }; + use $crate::DiagnosticExt; + let span_range = (&$span).FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(); + + $crate::Diagnostic::spanned_range(span_range, $level, $msg.to_string()) + }}; + + + // trailing commas + + ($span:expr, $level:expr, $fmt:expr, $($args:expr),+, ; $($rest:tt)+) => { + $crate::diagnostic!($span, $level, $fmt, $($args),* ; $($rest)*) + }; + ($span:expr, $level:expr, $msg:expr, ; $($rest:tt)+) => { + $crate::diagnostic!($span, $level, $msg ; $($rest)*) + }; + ($span:expr, $level:expr, $fmt:expr, $($args:expr),+,) => { + $crate::diagnostic!($span, $level, $fmt, $($args),*) + }; + ($span:expr, $level:expr, $msg:expr,) => { + $crate::diagnostic!($span, $level, $msg) + }; + // ($err:expr,) => { $crate::diagnostic!($err) }; +} + +/// Abort proc-macro execution right now and display the error. +/// +/// # Syntax +/// +/// See [the guide](index.html#guide). +#[macro_export] +macro_rules! abort { + ($err:expr) => { + $crate::diagnostic!($err).abort() + }; + + ($span:expr, $($tts:tt)*) => { + $crate::diagnostic!($span, $crate::Level::Error, $($tts)*).abort() + }; +} + +/// Shortcut for `abort!(Span::call_site(), msg...)`. This macro +/// is still preferable over plain panic, panics are not for error reporting. +/// +/// # Syntax +/// +/// See [the guide](index.html#guide). +/// +#[macro_export] +macro_rules! abort_call_site { + ($($tts:tt)*) => { + $crate::abort!($crate::__export::proc_macro2::Span::call_site(), $($tts)*) + }; +} + +/// Emit an error while not aborting the proc-macro right away. +/// +/// # Syntax +/// +/// See [the guide](index.html#guide). +/// +#[macro_export] +macro_rules! emit_error { + ($err:expr) => { + $crate::diagnostic!($err).emit() + }; + + ($span:expr, $($tts:tt)*) => {{ + let level = $crate::Level::Error; + $crate::diagnostic!($span, level, $($tts)*).emit() + }}; +} + +/// Shortcut for `emit_error!(Span::call_site(), ...)`. This macro +/// is still preferable over plain panic, panics are not for error reporting.. +/// +/// # Syntax +/// +/// See [the guide](index.html#guide). +/// +#[macro_export] +macro_rules! emit_call_site_error { + ($($tts:tt)*) => { + $crate::emit_error!($crate::__export::proc_macro2::Span::call_site(), $($tts)*) + }; +} + +/// Emit a warning. Warnings are not errors and compilation won't fail because of them. +/// +/// **Does nothing on stable** +/// +/// # Syntax +/// +/// See [the guide](index.html#guide). +/// +#[macro_export] +macro_rules! emit_warning { + ($span:expr, $($tts:tt)*) => { + $crate::diagnostic!($span, $crate::Level::Warning, $($tts)*).emit() + }; +} + +/// Shortcut for `emit_warning!(Span::call_site(), ...)`. +/// +/// **Does nothing on stable** +/// +/// # Syntax +/// +/// See [the guide](index.html#guide). +/// +#[macro_export] +macro_rules! emit_call_site_warning { + ($($tts:tt)*) => {{ + $crate::emit_warning!($crate::__export::proc_macro2::Span::call_site(), $($tts)*) + }}; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __pme__suggestions { + ($var:ident) => (); + + ($var:ident $help:ident =? $msg:expr) => { + let $var = if let Some(msg) = $msg { + $var.suggestion(stringify!($help), msg.to_string()) + } else { + $var + }; + }; + ($var:ident $help:ident =? $span:expr => $msg:expr) => { + let $var = if let Some(msg) = $msg { + $var.span_suggestion($span.into(), stringify!($help), msg.to_string()) + } else { + $var + }; + }; + + ($var:ident $help:ident =? $msg:expr ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help =? $msg); + $crate::__pme__suggestions!($var $($rest)*); + }; + ($var:ident $help:ident =? $span:expr => $msg:expr ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help =? $span => $msg); + $crate::__pme__suggestions!($var $($rest)*); + }; + + + ($var:ident $help:ident = $msg:expr) => { + let $var = $var.suggestion(stringify!($help), $msg.to_string()); + }; + ($var:ident $help:ident = $fmt:expr, $($args:expr),+) => { + let $var = $var.suggestion( + stringify!($help), + format!($fmt, $($args),*) + ); + }; + ($var:ident $help:ident = $span:expr => $msg:expr) => { + let $var = $var.span_suggestion($span.into(), stringify!($help), $msg.to_string()); + }; + ($var:ident $help:ident = $span:expr => $fmt:expr, $($args:expr),+) => { + let $var = $var.span_suggestion( + $span.into(), + stringify!($help), + format!($fmt, $($args),*) + ); + }; + + ($var:ident $help:ident = $msg:expr ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $msg); + $crate::__pme__suggestions!($var $($rest)*); + }; + ($var:ident $help:ident = $fmt:expr, $($args:expr),+ ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $fmt, $($args),*); + $crate::__pme__suggestions!($var $($rest)*); + }; + ($var:ident $help:ident = $span:expr => $msg:expr ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $span => $msg); + $crate::__pme__suggestions!($var $($rest)*); + }; + ($var:ident $help:ident = $span:expr => $fmt:expr, $($args:expr),+ ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $span => $fmt, $($args),*); + $crate::__pme__suggestions!($var $($rest)*); + }; + + // trailing commas + + ($var:ident $help:ident = $msg:expr,) => { + $crate::__pme__suggestions!($var $help = $msg) + }; + ($var:ident $help:ident = $fmt:expr, $($args:expr),+,) => { + $crate::__pme__suggestions!($var $help = $fmt, $($args)*) + }; + ($var:ident $help:ident = $span:expr => $msg:expr,) => { + $crate::__pme__suggestions!($var $help = $span => $msg) + }; + ($var:ident $help:ident = $span:expr => $fmt:expr, $($args:expr),*,) => { + $crate::__pme__suggestions!($var $help = $span => $fmt, $($args)*) + }; + ($var:ident $help:ident = $msg:expr, ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $msg; $($rest)*) + }; + ($var:ident $help:ident = $fmt:expr, $($args:expr),+, ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $fmt, $($args),*; $($rest)*) + }; + ($var:ident $help:ident = $span:expr => $msg:expr, ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $span => $msg; $($rest)*) + }; + ($var:ident $help:ident = $span:expr => $fmt:expr, $($args:expr),+, ; $($rest:tt)*) => { + $crate::__pme__suggestions!($var $help = $span => $fmt, $($args),*; $($rest)*) + }; +} diff --git a/bitbox02-bt/vendor/proc-macro-error/src/sealed.rs b/bitbox02-bt/vendor/proc-macro-error/src/sealed.rs new file mode 100644 index 0000000..a2d5081 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/src/sealed.rs @@ -0,0 +1,3 @@ +pub trait Sealed {} + +impl Sealed for crate::Diagnostic {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/macro-errors.rs b/bitbox02-bt/vendor/proc-macro-error/tests/macro-errors.rs new file mode 100644 index 0000000..dd60f88 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/macro-errors.rs @@ -0,0 +1,8 @@ +extern crate trybuild; + +#[cfg_attr(skip_ui_tests, ignore)] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/ui/*.rs"); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ok.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ok.rs new file mode 100644 index 0000000..cf64c02 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ok.rs @@ -0,0 +1,10 @@ +extern crate test_crate; + +use test_crate::*; + +ok!(it_works); + +#[test] +fn check_it_works() { + it_works(); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/runtime-errors.rs b/bitbox02-bt/vendor/proc-macro-error/tests/runtime-errors.rs new file mode 100644 index 0000000..13108a2 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/runtime-errors.rs @@ -0,0 +1,13 @@ +use proc_macro_error::*; + +#[test] +#[should_panic = "proc-macro-error API cannot be used outside of"] +fn missing_attr_emit() { + emit_call_site_error!("You won't see me"); +} + +#[test] +#[should_panic = "proc-macro-error API cannot be used outside of"] +fn missing_attr_abort() { + abort_call_site!("You won't see me"); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.rs new file mode 100644 index 0000000..f631182 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.rs @@ -0,0 +1,11 @@ +extern crate test_crate; +use test_crate::*; + +abort_from!(one, two); +abort_to_string!(one, two); +abort_format!(one, two); +direct_abort!(one, two); +abort_notes!(one, two); +abort_call_site_test!(one, two); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.stderr new file mode 100644 index 0000000..c5399d9 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/abort.stderr @@ -0,0 +1,48 @@ +error: abort!(span, from) test + --> $DIR/abort.rs:4:13 + | +4 | abort_from!(one, two); + | ^^^ + +error: abort!(span, single_expr) test + --> $DIR/abort.rs:5:18 + | +5 | abort_to_string!(one, two); + | ^^^ + +error: abort!(span, expr1, expr2) test + --> $DIR/abort.rs:6:15 + | +6 | abort_format!(one, two); + | ^^^ + +error: Diagnostic::abort() test + --> $DIR/abort.rs:7:15 + | +7 | direct_abort!(one, two); + | ^^^ + +error: This is an error + + = note: simple note + = help: simple help + = help: simple hint + = note: simple yay + = note: format note + = note: Some note + = note: spanned simple note + = note: spanned format note + = note: Some note + + --> $DIR/abort.rs:8:14 + | +8 | abort_notes!(one, two); + | ^^^ + +error: abort_call_site! test + --> $DIR/abort.rs:9:1 + | +9 | abort_call_site_test!(one, two); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.rs new file mode 100644 index 0000000..53d6fea --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.rs @@ -0,0 +1,13 @@ +extern crate test_crate; +use test_crate::*; + +enum NeedDefault { + A, + B +} + +append_dummy!(need_default); + +fn main() { + let _ = NeedDefault::default(); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.stderr new file mode 100644 index 0000000..8a47dda --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/append_dummy.stderr @@ -0,0 +1,5 @@ +error: append_dummy test + --> $DIR/append_dummy.rs:9:15 + | +9 | append_dummy!(need_default); + | ^^^^^^^^^^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.rs new file mode 100644 index 0000000..fb9e6dc --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.rs @@ -0,0 +1,6 @@ +extern crate test_crate; +use test_crate::*; + +children_messages!(one, two, three, four); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.stderr new file mode 100644 index 0000000..3b49d83 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/children_messages.stderr @@ -0,0 +1,23 @@ +error: main macro message + --> $DIR/children_messages.rs:4:20 + | +4 | children_messages!(one, two, three, four); + | ^^^ + +error: child message + --> $DIR/children_messages.rs:4:25 + | +4 | children_messages!(one, two, three, four); + | ^^^ + +error: main syn::Error + --> $DIR/children_messages.rs:4:30 + | +4 | children_messages!(one, two, three, four); + | ^^^^^ + +error: child syn::Error + --> $DIR/children_messages.rs:4:37 + | +4 | children_messages!(one, two, three, four); + | ^^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.rs new file mode 100644 index 0000000..caa4827 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.rs @@ -0,0 +1,13 @@ +extern crate test_crate; +use test_crate::*; + +enum NeedDefault { + A, + B +} + +dummy!(need_default); + +fn main() { + let _ = NeedDefault::default(); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.stderr new file mode 100644 index 0000000..bae078a --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/dummy.stderr @@ -0,0 +1,5 @@ +error: set_dummy test + --> $DIR/dummy.rs:9:8 + | +9 | dummy!(need_default); + | ^^^^^^^^^^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.rs new file mode 100644 index 0000000..c5c7db0 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.rs @@ -0,0 +1,7 @@ +extern crate test_crate; +use test_crate::*; + +emit!(one, two, three, four, five); +emit_notes!(one, two); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.stderr new file mode 100644 index 0000000..9484bd6 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/emit.stderr @@ -0,0 +1,48 @@ +error: emit!(span, from) test + --> $DIR/emit.rs:4:7 + | +4 | emit!(one, two, three, four, five); + | ^^^ + +error: emit!(span, expr1, expr2) test + --> $DIR/emit.rs:4:12 + | +4 | emit!(one, two, three, four, five); + | ^^^ + +error: emit!(span, single_expr) test + --> $DIR/emit.rs:4:17 + | +4 | emit!(one, two, three, four, five); + | ^^^^^ + +error: Diagnostic::emit() test + --> $DIR/emit.rs:4:24 + | +4 | emit!(one, two, three, four, five); + | ^^^^ + +error: emit_call_site_error!(expr) test + --> $DIR/emit.rs:4:1 + | +4 | emit!(one, two, three, four, five); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) + +error: This is an error + + = note: simple note + = help: simple help + = help: simple hint + = note: simple yay + = note: format note + = note: Some note + = note: spanned simple note + = note: spanned format note + = note: Some note + + --> $DIR/emit.rs:5:13 + | +5 | emit_notes!(one, two); + | ^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.rs new file mode 100644 index 0000000..82bbebc --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.rs @@ -0,0 +1,6 @@ +extern crate test_crate; +use test_crate::*; + +explicit_span_range!(one, two, three, four); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.stderr new file mode 100644 index 0000000..781a71e --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/explicit_span_range.stderr @@ -0,0 +1,5 @@ +error: explicit SpanRange + --> $DIR/explicit_span_range.rs:4:22 + | +4 | explicit_span_range!(one, two, three, four); + | ^^^^^^^^^^^^^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.rs new file mode 100644 index 0000000..e6d2d24 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.rs @@ -0,0 +1,11 @@ +extern crate proc_macro_error; +use proc_macro_error::abort; + +struct Foo; + +#[allow(unused)] +fn foo() { + abort!(Foo, "BOOM"); +} + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.stderr new file mode 100644 index 0000000..8eaf645 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/misuse.stderr @@ -0,0 +1,13 @@ +error[E0599]: no method named `FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange` found for reference `&Foo` in the current scope + --> $DIR/misuse.rs:8:5 + | +4 | struct Foo; + | ----------- doesn't satisfy `Foo: quote::to_tokens::ToTokens` +... +8 | abort!(Foo, "BOOM"); + | ^^^^^^^^^^^^^^^^^^^^ method not found in `&Foo` + | + = note: the method `FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange` exists but the following trait bounds were not satisfied: + `Foo: quote::to_tokens::ToTokens` + which is required by `&Foo: proc_macro_error::__export::ToTokensAsSpanRange` + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.rs new file mode 100644 index 0000000..215928f --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.rs @@ -0,0 +1,6 @@ +extern crate test_crate; + +#[test_crate::multiple_tokens] +type T = (); + +fn main() {} \ No newline at end of file diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.stderr new file mode 100644 index 0000000..c6172c6 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/multiple_tokens.stderr @@ -0,0 +1,5 @@ +error: ... + --> $DIR/multiple_tokens.rs:4:1 + | +4 | type T = (); + | ^^^^^^^^^^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.rs new file mode 100644 index 0000000..e241c5c --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.rs @@ -0,0 +1,4 @@ +use proc_macro_error::proc_macro_error; + +#[proc_macro_error] +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.stderr new file mode 100644 index 0000000..f19f01b --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/not_proc_macro.stderr @@ -0,0 +1,10 @@ +error: #[proc_macro_error] attribute can be used only with procedural macros + + = hint: if you are really sure that #[proc_macro_error] should be applied to this exact function, use #[proc_macro_error(allow_not_macro)] + + --> $DIR/not_proc_macro.rs:3:1 + | +3 | #[proc_macro_error] + | ^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.rs new file mode 100644 index 0000000..dfbfc03 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.rs @@ -0,0 +1,6 @@ +extern crate test_crate; +use test_crate::*; + +option_ext!(one, two); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.stderr new file mode 100644 index 0000000..91b151e --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/option_ext.stderr @@ -0,0 +1,7 @@ +error: Option::expect_or_abort() test + --> $DIR/option_ext.rs:4:1 + | +4 | option_ext!(one, two); + | ^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.rs new file mode 100644 index 0000000..2504bdd --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.rs @@ -0,0 +1,10 @@ +// Adapted from https://github.com/dtolnay/proc-macro-hack/blob/master/example/src/main.rs +// Licensed under either of Apache License, Version 2.0 or MIT license at your option. + +use proc_macro_hack_test::add_one; + +fn main() { + let two = 2; + let nine = add_one!(two) + add_one!(2 + 3); + println!("nine = {}", nine); +} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.stderr new file mode 100644 index 0000000..0e984f9 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/proc_macro_hack.stderr @@ -0,0 +1,26 @@ +error: BOOM + --> $DIR/proc_macro_hack.rs:8:25 + | +8 | let nine = add_one!(two) + add_one!(2 + 3); + | ^^^ + | + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) + +error: BOOM + --> $DIR/proc_macro_hack.rs:8:41 + | +8 | let nine = add_one!(two) + add_one!(2 + 3); + | ^^^^^ + | + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) + +warning: unreachable expression + --> $DIR/proc_macro_hack.rs:8:32 + | +8 | let nine = add_one!(two) + add_one!(2 + 3); + | ------------- ^^^^^^^^^^^^^^^ unreachable expression + | | + | any code following this expression is unreachable + | + = note: `#[warn(unreachable_code)]` on by default + = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.rs new file mode 100644 index 0000000..bdd560d --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.rs @@ -0,0 +1,7 @@ +extern crate test_crate; +use test_crate::*; + +result_unwrap_or_abort!(one, two); +result_expect_or_abort!(one, two); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.stderr new file mode 100644 index 0000000..f2dc0e4 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/result_ext.stderr @@ -0,0 +1,11 @@ +error: Result::unwrap_or_abort() test + --> $DIR/result_ext.rs:4:25 + | +4 | result_unwrap_or_abort!(one, two); + | ^^^ + +error: BOOM: Result::expect_or_abort() test + --> $DIR/result_ext.rs:5:25 + | +5 | result_expect_or_abort!(one, two); + | ^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.rs new file mode 100644 index 0000000..a7c3fc9 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.rs @@ -0,0 +1,6 @@ +extern crate test_crate; +use test_crate::*; + +to_tokens_span!(std::option::Option); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.stderr new file mode 100644 index 0000000..b8c4968 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/to_tokens_span.stderr @@ -0,0 +1,11 @@ +error: whole type + --> $DIR/to_tokens_span.rs:4:17 + | +4 | to_tokens_span!(std::option::Option); + | ^^^^^^^^^^^^^^^^^^^ + +error: explicit .span() + --> $DIR/to_tokens_span.rs:4:17 + | +4 | to_tokens_span!(std::option::Option); + | ^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.rs new file mode 100644 index 0000000..d8e58ea --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.rs @@ -0,0 +1,4 @@ +use proc_macro_error::proc_macro_error; + +#[proc_macro_error(allow_not_macro, assert_unwind_safe, trololo)] +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.stderr new file mode 100644 index 0000000..a55de0b --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unknown_setting.stderr @@ -0,0 +1,5 @@ +error: unknown setting `trololo`, expected one of `assert_unwind_safe`, `allow_not_macro`, `proc_macro_hack` + --> $DIR/unknown_setting.rs:3:57 + | +3 | #[proc_macro_error(allow_not_macro, assert_unwind_safe, trololo)] + | ^^^^^^^ diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.rs b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.rs new file mode 100644 index 0000000..c74e3e0 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.rs @@ -0,0 +1,6 @@ +extern crate test_crate; +use test_crate::*; + +unrelated_panic!(); + +fn main() {} diff --git a/bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.stderr b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.stderr new file mode 100644 index 0000000..d46d689 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro-error/tests/ui/unrelated_panic.stderr @@ -0,0 +1,7 @@ +error: proc macro panicked + --> $DIR/unrelated_panic.rs:4:1 + | +4 | unrelated_panic!(); + | ^^^^^^^^^^^^^^^^^^^ + | + = help: message: unrelated panic test diff --git a/bitbox02-bt/vendor/proc-macro2/.cargo-checksum.json b/bitbox02-bt/vendor/proc-macro2/.cargo-checksum.json new file mode 100644 index 0000000..f71eeae --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"07d612ee6a9cc09c660ab6a807b6ef6c17adaaf6ff0cfc507cfdf9ccb8ae5d2b","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"c609b6865476d6c35879784e9155367a97a0da496aa5c3c61488440a20f59883","build.rs":"cf78c0005f11d54ca42dbaee77cb76a440e6fa2e0b64798d3f74c04770a0ad2b","build/probe.rs":"971fd2178dc506ccdc5c2065c37b77696a4aee8e00330ca52625db4a857f68d3","rust-toolchain.toml":"6bbb61302978c736b2da03e4fb40e3beab908f85d533ab46fd541e637b5f3e0f","src/detection.rs":"ed9a5f9a979ab01247d7a68eeb1afa3c13209334c5bfff0f9289cb07e5bb4e8b","src/extra.rs":"29f094473279a29b71c3cc9f5fa27c2e2c30c670390cf7e4b7cf451486cc857e","src/fallback.rs":"be1ce5e32c88c29d41d2ab663375951817d52decce3dc9e335ec22378be8fa65","src/lib.rs":"f730f10dc8774a90217e339d812ee177072838faed47a25ff2f6db7afd732d78","src/location.rs":"9225c5a55f03b56cce42bc55ceb509e8216a5e0b24c94aa1cd071b04e3d6c15f","src/marker.rs":"c11c5a1be8bdf18be3fcd224393f350a9aae7ce282e19ce583c84910c6903a8f","src/parse.rs":"4b77cddbc2752bc4d38a65acd8b96b6786c5220d19b1e1b37810257b5d24132d","src/rcvec.rs":"1c3c48c4f819927cc445ae15ca3bb06775feff2fd1cb21901ae4c40c7e6b4e82","src/wrapper.rs":"e41df9abc846b40f0cf01150d22b91944d07cde93bc72aa34798101652675844","tests/comments.rs":"31115b3a56c83d93eef2fb4c9566bf4543e302560732986161b98aef504785ed","tests/features.rs":"a86deb8644992a4eb64d9fd493eff16f9cf9c5cb6ade3a634ce0c990cf87d559","tests/marker.rs":"473e962ee1aa0633dd5cf9a973b3bbd0ef43b740d4b7f6d008ff455a6b89d386","tests/test.rs":"2e7106f582367d168638be7364d4e9aadbe0affca8b51dd80f0b3977cc2fcf83","tests/test_fmt.rs":"b7743b612af65f2c88cbe109d50a093db7aa7e87f9e37bf45b7bbaeb240aa020","tests/test_size.rs":"62d8373ea46b669b87bc90a9c49b6d02f90ff4c21f9a25acebf60c9926e01fb7"},"package":"b3e4daa0dcf6feba26f985457cdf104d4b4256fc5a09547140f3631bb076b19a"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/proc-macro2/Cargo.toml b/bitbox02-bt/vendor/proc-macro2/Cargo.toml new file mode 100644 index 0000000..ea6aa93 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/Cargo.toml @@ -0,0 +1,105 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.56" +name = "proc-macro2" +version = "1.0.87" +authors = [ + "David Tolnay ", + "Alex Crichton ", +] +build = "build.rs" +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case." +documentation = "https://docs.rs/proc-macro2" +readme = "README.md" +keywords = [ + "macros", + "syn", +] +categories = ["development-tools::procedural-macro-helpers"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/proc-macro2" + +[package.metadata.docs.rs] +rustc-args = [ + "--cfg", + "procmacro2_semver_exempt", +] +rustdoc-args = [ + "--cfg", + "procmacro2_semver_exempt", + "--generate-link-to-definition", +] +targets = ["x86_64-unknown-linux-gnu"] + +[package.metadata.playground] +features = ["span-locations"] + +[lib] +name = "proc_macro2" +path = "src/lib.rs" +doc-scrape-examples = false + +[[test]] +name = "comments" +path = "tests/comments.rs" + +[[test]] +name = "features" +path = "tests/features.rs" + +[[test]] +name = "marker" +path = "tests/marker.rs" + +[[test]] +name = "test" +path = "tests/test.rs" + +[[test]] +name = "test_fmt" +path = "tests/test_fmt.rs" + +[[test]] +name = "test_size" +path = "tests/test_size.rs" + +[dependencies.unicode-ident] +version = "1.0" + +[dev-dependencies.flate2] +version = "1.0" + +[dev-dependencies.quote] +version = "1.0" +default-features = false + +[dev-dependencies.rayon] +version = "1.0" + +[dev-dependencies.rustversion] +version = "1" + +[dev-dependencies.tar] +version = "0.4" + +[features] +default = ["proc-macro"] +nightly = [] +proc-macro = [] +span-locations = [] diff --git a/bitbox02-bt/vendor/proc-macro2/LICENSE-APACHE b/bitbox02-bt/vendor/proc-macro2/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/proc-macro2/LICENSE-MIT b/bitbox02-bt/vendor/proc-macro2/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/proc-macro2/README.md b/bitbox02-bt/vendor/proc-macro2/README.md new file mode 100644 index 0000000..3a29ce8 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/README.md @@ -0,0 +1,94 @@ +# proc-macro2 + +[github](https://github.com/dtolnay/proc-macro2) +[crates.io](https://crates.io/crates/proc-macro2) +[docs.rs](https://docs.rs/proc-macro2) +[build status](https://github.com/dtolnay/proc-macro2/actions?query=branch%3Amaster) + +A wrapper around the procedural macro API of the compiler's `proc_macro` crate. +This library serves two purposes: + +- **Bring proc-macro-like functionality to other contexts like build.rs and + main.rs.** Types from `proc_macro` are entirely specific to procedural macros + and cannot ever exist in code outside of a procedural macro. Meanwhile + `proc_macro2` types may exist anywhere including non-macro code. By developing + foundational libraries like [syn] and [quote] against `proc_macro2` rather + than `proc_macro`, the procedural macro ecosystem becomes easily applicable to + many other use cases and we avoid reimplementing non-macro equivalents of + those libraries. + +- **Make procedural macros unit testable.** As a consequence of being specific + to procedural macros, nothing that uses `proc_macro` can be executed from a + unit test. In order for helper libraries or components of a macro to be + testable in isolation, they must be implemented using `proc_macro2`. + +[syn]: https://github.com/dtolnay/syn +[quote]: https://github.com/dtolnay/quote + +## Usage + +```toml +[dependencies] +proc-macro2 = "1.0" +``` + +The skeleton of a typical procedural macro typically looks like this: + +```rust +extern crate proc_macro; + +#[proc_macro_derive(MyDerive)] +pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = proc_macro2::TokenStream::from(input); + + let output: proc_macro2::TokenStream = { + /* transform input */ + }; + + proc_macro::TokenStream::from(output) +} +``` + +If parsing with [Syn], you'll use [`parse_macro_input!`] instead to propagate +parse errors correctly back to the compiler when parsing fails. + +[`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html + +## Unstable features + +The default feature set of proc-macro2 tracks the most recent stable compiler +API. Functionality in `proc_macro` that is not yet stable is not exposed by +proc-macro2 by default. + +To opt into the additional APIs available in the most recent nightly compiler, +the `procmacro2_semver_exempt` config flag must be passed to rustc. We will +polyfill those nightly-only APIs back to Rust 1.56.0. As these are unstable APIs +that track the nightly compiler, minor versions of proc-macro2 may make breaking +changes to them at any time. + +``` +RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build +``` + +Note that this must not only be done for your crate, but for any crate that +depends on your crate. This infectious nature is intentional, as it serves as a +reminder that you are outside of the normal semver guarantees. + +Semver exempt methods are marked as such in the proc-macro2 documentation. + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/proc-macro2/build.rs b/bitbox02-bt/vendor/proc-macro2/build.rs new file mode 100644 index 0000000..1d3ae17 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/build.rs @@ -0,0 +1,213 @@ +#![allow(unknown_lints)] +#![allow(unexpected_cfgs)] + +use std::env; +use std::ffi::OsString; +use std::iter; +use std::path::Path; +use std::process::{self, Command, Stdio}; +use std::str; + +fn main() { + let rustc = rustc_minor_version().unwrap_or(u32::MAX); + + if rustc >= 80 { + println!("cargo:rustc-check-cfg=cfg(fuzzing)"); + println!("cargo:rustc-check-cfg=cfg(no_is_available)"); + println!("cargo:rustc-check-cfg=cfg(no_literal_byte_character)"); + println!("cargo:rustc-check-cfg=cfg(no_literal_c_string)"); + println!("cargo:rustc-check-cfg=cfg(no_source_text)"); + println!("cargo:rustc-check-cfg=cfg(proc_macro_span)"); + println!("cargo:rustc-check-cfg=cfg(procmacro2_backtrace)"); + println!("cargo:rustc-check-cfg=cfg(procmacro2_nightly_testing)"); + println!("cargo:rustc-check-cfg=cfg(procmacro2_semver_exempt)"); + println!("cargo:rustc-check-cfg=cfg(randomize_layout)"); + println!("cargo:rustc-check-cfg=cfg(span_locations)"); + println!("cargo:rustc-check-cfg=cfg(super_unstable)"); + println!("cargo:rustc-check-cfg=cfg(wrap_proc_macro)"); + } + + let docs_rs = env::var_os("DOCS_RS").is_some(); + let semver_exempt = cfg!(procmacro2_semver_exempt) || docs_rs; + if semver_exempt { + // https://github.com/dtolnay/proc-macro2/issues/147 + println!("cargo:rustc-cfg=procmacro2_semver_exempt"); + } + + if semver_exempt || cfg!(feature = "span-locations") { + // Provide methods Span::start and Span::end which give the line/column + // location of a token. This is behind a cfg because tracking location + // inside spans is a performance hit. + println!("cargo:rustc-cfg=span_locations"); + } + + if rustc < 57 { + // Do not use proc_macro::is_available() to detect whether the proc + // macro API is available vs needs to be polyfilled. Instead, use the + // proc macro API unconditionally and catch the panic that occurs if it + // isn't available. + println!("cargo:rustc-cfg=no_is_available"); + } + + if rustc < 66 { + // Do not call libproc_macro's Span::source_text. Always return None. + println!("cargo:rustc-cfg=no_source_text"); + } + + if rustc < 79 { + // Do not call Literal::byte_character nor Literal::c_string. They can + // be emulated by way of Literal::from_str. + println!("cargo:rustc-cfg=no_literal_byte_character"); + println!("cargo:rustc-cfg=no_literal_c_string"); + } + + if !cfg!(feature = "proc-macro") { + println!("cargo:rerun-if-changed=build.rs"); + return; + } + + println!("cargo:rerun-if-changed=build/probe.rs"); + + let proc_macro_span; + let consider_rustc_bootstrap; + if compile_probe(false) { + // This is a nightly or dev compiler, so it supports unstable features + // regardless of RUSTC_BOOTSTRAP. No need to rerun build script if + // RUSTC_BOOTSTRAP is changed. + proc_macro_span = true; + consider_rustc_bootstrap = false; + } else if let Some(rustc_bootstrap) = env::var_os("RUSTC_BOOTSTRAP") { + if compile_probe(true) { + // This is a stable or beta compiler for which the user has set + // RUSTC_BOOTSTRAP to turn on unstable features. Rerun build script + // if they change it. + proc_macro_span = true; + consider_rustc_bootstrap = true; + } else if rustc_bootstrap == "1" { + // This compiler does not support the proc macro Span API in the + // form that proc-macro2 expects. No need to pay attention to + // RUSTC_BOOTSTRAP. + proc_macro_span = false; + consider_rustc_bootstrap = false; + } else { + // This is a stable or beta compiler for which RUSTC_BOOTSTRAP is + // set to restrict the use of unstable features by this crate. + proc_macro_span = false; + consider_rustc_bootstrap = true; + } + } else { + // Without RUSTC_BOOTSTRAP, this compiler does not support the proc + // macro Span API in the form that proc-macro2 expects, but try again if + // the user turns on unstable features. + proc_macro_span = false; + consider_rustc_bootstrap = true; + } + + if proc_macro_span || !semver_exempt { + // Wrap types from libproc_macro rather than polyfilling the whole API. + // Enabled as long as procmacro2_semver_exempt is not set, because we + // can't emulate the unstable API without emulating everything else. + // Also enabled unconditionally on nightly, in which case the + // procmacro2_semver_exempt surface area is implemented by using the + // nightly-only proc_macro API. + println!("cargo:rustc-cfg=wrap_proc_macro"); + } + + if proc_macro_span { + // Enable non-dummy behavior of Span::start and Span::end methods which + // requires an unstable compiler feature. Enabled when building with + // nightly, unless `-Z allow-feature` in RUSTFLAGS disallows unstable + // features. + println!("cargo:rustc-cfg=proc_macro_span"); + } + + if semver_exempt && proc_macro_span { + // Implement the semver exempt API in terms of the nightly-only + // proc_macro API. + println!("cargo:rustc-cfg=super_unstable"); + } + + if consider_rustc_bootstrap { + println!("cargo:rerun-if-env-changed=RUSTC_BOOTSTRAP"); + } +} + +fn compile_probe(rustc_bootstrap: bool) -> bool { + if env::var_os("RUSTC_STAGE").is_some() { + // We are running inside rustc bootstrap. This is a highly non-standard + // environment with issues such as: + // + // https://github.com/rust-lang/cargo/issues/11138 + // https://github.com/rust-lang/rust/issues/114839 + // + // Let's just not use nightly features here. + return false; + } + + let rustc = cargo_env_var("RUSTC"); + let out_dir = cargo_env_var("OUT_DIR"); + let probefile = Path::new("build").join("probe.rs"); + + let rustc_wrapper = env::var_os("RUSTC_WRAPPER").filter(|wrapper| !wrapper.is_empty()); + let rustc_workspace_wrapper = + env::var_os("RUSTC_WORKSPACE_WRAPPER").filter(|wrapper| !wrapper.is_empty()); + let mut rustc = rustc_wrapper + .into_iter() + .chain(rustc_workspace_wrapper) + .chain(iter::once(rustc)); + let mut cmd = Command::new(rustc.next().unwrap()); + cmd.args(rustc); + + if !rustc_bootstrap { + cmd.env_remove("RUSTC_BOOTSTRAP"); + } + + cmd.stderr(Stdio::null()) + .arg("--edition=2021") + .arg("--crate-name=proc_macro2") + .arg("--crate-type=lib") + .arg("--cap-lints=allow") + .arg("--emit=dep-info,metadata") + .arg("--out-dir") + .arg(out_dir) + .arg(probefile); + + if let Some(target) = env::var_os("TARGET") { + cmd.arg("--target").arg(target); + } + + // If Cargo wants to set RUSTFLAGS, use that. + if let Ok(rustflags) = env::var("CARGO_ENCODED_RUSTFLAGS") { + if !rustflags.is_empty() { + for arg in rustflags.split('\x1f') { + cmd.arg(arg); + } + } + } + + match cmd.status() { + Ok(status) => status.success(), + Err(_) => false, + } +} + +fn rustc_minor_version() -> Option { + let rustc = cargo_env_var("RUSTC"); + let output = Command::new(rustc).arg("--version").output().ok()?; + let version = str::from_utf8(&output.stdout).ok()?; + let mut pieces = version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + pieces.next()?.parse().ok() +} + +fn cargo_env_var(key: &str) -> OsString { + env::var_os(key).unwrap_or_else(|| { + eprintln!( + "Environment variable ${} is not set during execution of build script", + key, + ); + process::exit(1); + }) +} diff --git a/bitbox02-bt/vendor/proc-macro2/build/probe.rs b/bitbox02-bt/vendor/proc-macro2/build/probe.rs new file mode 100644 index 0000000..2c4947a --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/build/probe.rs @@ -0,0 +1,25 @@ +// This code exercises the surface area that we expect of Span's unstable API. +// If the current toolchain is able to compile it, then proc-macro2 is able to +// offer these APIs too. + +#![feature(proc_macro_span)] + +extern crate proc_macro; + +use core::ops::{Range, RangeBounds}; +use proc_macro::{Literal, Span}; + +pub fn byte_range(this: &Span) -> Range { + this.byte_range() +} + +pub fn join(this: &Span, other: Span) -> Option { + this.join(other) +} + +pub fn subspan>(this: &Literal, range: R) -> Option { + this.subspan(range) +} + +// Include in sccache cache key. +const _: Option<&str> = option_env!("RUSTC_BOOTSTRAP"); diff --git a/bitbox02-bt/vendor/proc-macro2/rust-toolchain.toml b/bitbox02-bt/vendor/proc-macro2/rust-toolchain.toml new file mode 100644 index 0000000..20fe888 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +components = ["rust-src"] diff --git a/bitbox02-bt/vendor/proc-macro2/src/detection.rs b/bitbox02-bt/vendor/proc-macro2/src/detection.rs new file mode 100644 index 0000000..beba7b2 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/detection.rs @@ -0,0 +1,75 @@ +use core::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Once; + +static WORKS: AtomicUsize = AtomicUsize::new(0); +static INIT: Once = Once::new(); + +pub(crate) fn inside_proc_macro() -> bool { + match WORKS.load(Ordering::Relaxed) { + 1 => return false, + 2 => return true, + _ => {} + } + + INIT.call_once(initialize); + inside_proc_macro() +} + +pub(crate) fn force_fallback() { + WORKS.store(1, Ordering::Relaxed); +} + +pub(crate) fn unforce_fallback() { + initialize(); +} + +#[cfg(not(no_is_available))] +fn initialize() { + let available = proc_macro::is_available(); + WORKS.store(available as usize + 1, Ordering::Relaxed); +} + +// Swap in a null panic hook to avoid printing "thread panicked" to stderr, +// then use catch_unwind to determine whether the compiler's proc_macro is +// working. When proc-macro2 is used from outside of a procedural macro all +// of the proc_macro crate's APIs currently panic. +// +// The Once is to prevent the possibility of this ordering: +// +// thread 1 calls take_hook, gets the user's original hook +// thread 1 calls set_hook with the null hook +// thread 2 calls take_hook, thinks null hook is the original hook +// thread 2 calls set_hook with the null hook +// thread 1 calls set_hook with the actual original hook +// thread 2 calls set_hook with what it thinks is the original hook +// +// in which the user's hook has been lost. +// +// There is still a race condition where a panic in a different thread can +// happen during the interval that the user's original panic hook is +// unregistered such that their hook is incorrectly not called. This is +// sufficiently unlikely and less bad than printing panic messages to stderr +// on correct use of this crate. Maybe there is a libstd feature request +// here. For now, if a user needs to guarantee that this failure mode does +// not occur, they need to call e.g. `proc_macro2::Span::call_site()` from +// the main thread before launching any other threads. +#[cfg(no_is_available)] +fn initialize() { + use std::panic::{self, PanicInfo}; + + type PanicHook = dyn Fn(&PanicInfo) + Sync + Send + 'static; + + let null_hook: Box = Box::new(|_panic_info| { /* ignore */ }); + let sanity_check = &*null_hook as *const PanicHook; + let original_hook = panic::take_hook(); + panic::set_hook(null_hook); + + let works = panic::catch_unwind(proc_macro::Span::call_site).is_ok(); + WORKS.store(works as usize + 1, Ordering::Relaxed); + + let hopefully_null_hook = panic::take_hook(); + panic::set_hook(original_hook); + if sanity_check != &*hopefully_null_hook { + panic!("observed race condition in proc_macro2::inside_proc_macro"); + } +} diff --git a/bitbox02-bt/vendor/proc-macro2/src/extra.rs b/bitbox02-bt/vendor/proc-macro2/src/extra.rs new file mode 100644 index 0000000..522a90e --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/extra.rs @@ -0,0 +1,151 @@ +//! Items which do not have a correspondence to any API in the proc_macro crate, +//! but are necessary to include in proc-macro2. + +use crate::fallback; +use crate::imp; +use crate::marker::{ProcMacroAutoTraits, MARKER}; +use crate::Span; +use core::fmt::{self, Debug}; + +/// Invalidate any `proc_macro2::Span` that exist on the current thread. +/// +/// The implementation of `Span` uses thread-local data structures and this +/// function clears them. Calling any method on a `Span` on the current thread +/// created prior to the invalidation will return incorrect values or crash. +/// +/// This function is useful for programs that process more than 232 +/// bytes of Rust source code on the same thread. Just like rustc, proc-macro2 +/// uses 32-bit source locations, and these wrap around when the total source +/// code processed by the same thread exceeds 232 bytes (4 +/// gigabytes). After a wraparound, `Span` methods such as `source_text()` can +/// return wrong data. +/// +/// # Example +/// +/// As of late 2023, there is 200 GB of Rust code published on crates.io. +/// Looking at just the newest version of every crate, it is 16 GB of code. So a +/// workload that involves parsing it all would overflow a 32-bit source +/// location unless spans are being invalidated. +/// +/// ``` +/// use flate2::read::GzDecoder; +/// use std::ffi::OsStr; +/// use std::io::{BufReader, Read}; +/// use std::str::FromStr; +/// use tar::Archive; +/// +/// rayon::scope(|s| { +/// for krate in every_version_of_every_crate() { +/// s.spawn(move |_| { +/// proc_macro2::extra::invalidate_current_thread_spans(); +/// +/// let reader = BufReader::new(krate); +/// let tar = GzDecoder::new(reader); +/// let mut archive = Archive::new(tar); +/// for entry in archive.entries().unwrap() { +/// let mut entry = entry.unwrap(); +/// let path = entry.path().unwrap(); +/// if path.extension() != Some(OsStr::new("rs")) { +/// continue; +/// } +/// let mut content = String::new(); +/// entry.read_to_string(&mut content).unwrap(); +/// match proc_macro2::TokenStream::from_str(&content) { +/// Ok(tokens) => {/* ... */}, +/// Err(_) => continue, +/// } +/// } +/// }); +/// } +/// }); +/// # +/// # fn every_version_of_every_crate() -> Vec { +/// # Vec::new() +/// # } +/// ``` +/// +/// # Panics +/// +/// This function is not applicable to and will panic if called from a +/// procedural macro. +#[cfg(span_locations)] +#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] +pub fn invalidate_current_thread_spans() { + crate::imp::invalidate_current_thread_spans(); +} + +/// An object that holds a [`Group`]'s `span_open()` and `span_close()` together +/// in a more compact representation than holding those 2 spans individually. +/// +/// [`Group`]: crate::Group +#[derive(Copy, Clone)] +pub struct DelimSpan { + inner: DelimSpanEnum, + _marker: ProcMacroAutoTraits, +} + +#[derive(Copy, Clone)] +enum DelimSpanEnum { + #[cfg(wrap_proc_macro)] + Compiler { + join: proc_macro::Span, + open: proc_macro::Span, + close: proc_macro::Span, + }, + Fallback(fallback::Span), +} + +impl DelimSpan { + pub(crate) fn new(group: &imp::Group) -> Self { + #[cfg(wrap_proc_macro)] + let inner = match group { + imp::Group::Compiler(group) => DelimSpanEnum::Compiler { + join: group.span(), + open: group.span_open(), + close: group.span_close(), + }, + imp::Group::Fallback(group) => DelimSpanEnum::Fallback(group.span()), + }; + + #[cfg(not(wrap_proc_macro))] + let inner = DelimSpanEnum::Fallback(group.span()); + + DelimSpan { + inner, + _marker: MARKER, + } + } + + /// Returns a span covering the entire delimited group. + pub fn join(&self) -> Span { + match &self.inner { + #[cfg(wrap_proc_macro)] + DelimSpanEnum::Compiler { join, .. } => Span::_new(imp::Span::Compiler(*join)), + DelimSpanEnum::Fallback(span) => Span::_new_fallback(*span), + } + } + + /// Returns a span for the opening punctuation of the group only. + pub fn open(&self) -> Span { + match &self.inner { + #[cfg(wrap_proc_macro)] + DelimSpanEnum::Compiler { open, .. } => Span::_new(imp::Span::Compiler(*open)), + DelimSpanEnum::Fallback(span) => Span::_new_fallback(span.first_byte()), + } + } + + /// Returns a span for the closing punctuation of the group only. + pub fn close(&self) -> Span { + match &self.inner { + #[cfg(wrap_proc_macro)] + DelimSpanEnum::Compiler { close, .. } => Span::_new(imp::Span::Compiler(*close)), + DelimSpanEnum::Fallback(span) => Span::_new_fallback(span.last_byte()), + } + } +} + +impl Debug for DelimSpan { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.join(), f) + } +} diff --git a/bitbox02-bt/vendor/proc-macro2/src/fallback.rs b/bitbox02-bt/vendor/proc-macro2/src/fallback.rs new file mode 100644 index 0000000..2d1c991 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/fallback.rs @@ -0,0 +1,1226 @@ +#[cfg(span_locations)] +use crate::location::LineColumn; +use crate::parse::{self, Cursor}; +use crate::rcvec::{RcVec, RcVecBuilder, RcVecIntoIter, RcVecMut}; +use crate::{Delimiter, Spacing, TokenTree}; +#[cfg(all(span_locations, not(fuzzing)))] +use alloc::collections::BTreeMap; +#[cfg(all(span_locations, not(fuzzing)))] +use core::cell::RefCell; +#[cfg(span_locations)] +use core::cmp; +use core::fmt::{self, Debug, Display, Write}; +use core::mem::ManuallyDrop; +#[cfg(span_locations)] +use core::ops::Range; +use core::ops::RangeBounds; +use core::ptr; +use core::str::{self, FromStr}; +use std::ffi::CStr; +#[cfg(procmacro2_semver_exempt)] +use std::path::PathBuf; + +/// Force use of proc-macro2's fallback implementation of the API for now, even +/// if the compiler's implementation is available. +pub fn force() { + #[cfg(wrap_proc_macro)] + crate::detection::force_fallback(); +} + +/// Resume using the compiler's implementation of the proc macro API if it is +/// available. +pub fn unforce() { + #[cfg(wrap_proc_macro)] + crate::detection::unforce_fallback(); +} + +#[derive(Clone)] +pub(crate) struct TokenStream { + inner: RcVec, +} + +#[derive(Debug)] +pub(crate) struct LexError { + pub(crate) span: Span, +} + +impl LexError { + pub(crate) fn span(&self) -> Span { + self.span + } + + pub(crate) fn call_site() -> Self { + LexError { + span: Span::call_site(), + } + } +} + +impl TokenStream { + pub fn new() -> Self { + TokenStream { + inner: RcVecBuilder::new().build(), + } + } + + pub fn is_empty(&self) -> bool { + self.inner.len() == 0 + } + + fn take_inner(self) -> RcVecBuilder { + let nodrop = ManuallyDrop::new(self); + unsafe { ptr::read(&nodrop.inner) }.make_owned() + } +} + +fn push_token_from_proc_macro(mut vec: RcVecMut, token: TokenTree) { + // https://github.com/dtolnay/proc-macro2/issues/235 + match token { + TokenTree::Literal(crate::Literal { + #[cfg(wrap_proc_macro)] + inner: crate::imp::Literal::Fallback(literal), + #[cfg(not(wrap_proc_macro))] + inner: literal, + .. + }) if literal.repr.starts_with('-') => { + push_negative_literal(vec, literal); + } + _ => vec.push(token), + } + + #[cold] + fn push_negative_literal(mut vec: RcVecMut, mut literal: Literal) { + literal.repr.remove(0); + let mut punct = crate::Punct::new('-', Spacing::Alone); + punct.set_span(crate::Span::_new_fallback(literal.span)); + vec.push(TokenTree::Punct(punct)); + vec.push(TokenTree::Literal(crate::Literal::_new_fallback(literal))); + } +} + +// Nonrecursive to prevent stack overflow. +impl Drop for TokenStream { + fn drop(&mut self) { + let mut inner = match self.inner.get_mut() { + Some(inner) => inner, + None => return, + }; + while let Some(token) = inner.pop() { + let group = match token { + TokenTree::Group(group) => group.inner, + _ => continue, + }; + #[cfg(wrap_proc_macro)] + let group = match group { + crate::imp::Group::Fallback(group) => group, + crate::imp::Group::Compiler(_) => continue, + }; + inner.extend(group.stream.take_inner()); + } + } +} + +pub(crate) struct TokenStreamBuilder { + inner: RcVecBuilder, +} + +impl TokenStreamBuilder { + pub fn new() -> Self { + TokenStreamBuilder { + inner: RcVecBuilder::new(), + } + } + + pub fn with_capacity(cap: usize) -> Self { + TokenStreamBuilder { + inner: RcVecBuilder::with_capacity(cap), + } + } + + pub fn push_token_from_parser(&mut self, tt: TokenTree) { + self.inner.push(tt); + } + + pub fn build(self) -> TokenStream { + TokenStream { + inner: self.inner.build(), + } + } +} + +#[cfg(span_locations)] +fn get_cursor(src: &str) -> Cursor { + #[cfg(fuzzing)] + return Cursor { rest: src, off: 1 }; + + // Create a dummy file & add it to the source map + #[cfg(not(fuzzing))] + SOURCE_MAP.with(|sm| { + let mut sm = sm.borrow_mut(); + let span = sm.add_file(src); + Cursor { + rest: src, + off: span.lo, + } + }) +} + +#[cfg(not(span_locations))] +fn get_cursor(src: &str) -> Cursor { + Cursor { rest: src } +} + +impl FromStr for TokenStream { + type Err = LexError; + + fn from_str(src: &str) -> Result { + // Create a dummy file & add it to the source map + let mut cursor = get_cursor(src); + + // Strip a byte order mark if present + const BYTE_ORDER_MARK: &str = "\u{feff}"; + if cursor.starts_with(BYTE_ORDER_MARK) { + cursor = cursor.advance(BYTE_ORDER_MARK.len()); + } + + parse::token_stream(cursor) + } +} + +impl Display for LexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("cannot parse string into token stream") + } +} + +impl Display for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut joint = false; + for (i, tt) in self.inner.iter().enumerate() { + if i != 0 && !joint { + write!(f, " ")?; + } + joint = false; + match tt { + TokenTree::Group(tt) => Display::fmt(tt, f), + TokenTree::Ident(tt) => Display::fmt(tt, f), + TokenTree::Punct(tt) => { + joint = tt.spacing() == Spacing::Joint; + Display::fmt(tt, f) + } + TokenTree::Literal(tt) => Display::fmt(tt, f), + }?; + } + + Ok(()) + } +} + +impl Debug for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("TokenStream ")?; + f.debug_list().entries(self.clone()).finish() + } +} + +#[cfg(feature = "proc-macro")] +impl From for TokenStream { + fn from(inner: proc_macro::TokenStream) -> Self { + inner + .to_string() + .parse() + .expect("compiler token stream parse failed") + } +} + +#[cfg(feature = "proc-macro")] +impl From for proc_macro::TokenStream { + fn from(inner: TokenStream) -> Self { + inner + .to_string() + .parse() + .expect("failed to parse to compiler tokens") + } +} + +impl From for TokenStream { + fn from(tree: TokenTree) -> Self { + let mut stream = RcVecBuilder::new(); + push_token_from_proc_macro(stream.as_mut(), tree); + TokenStream { + inner: stream.build(), + } + } +} + +impl FromIterator for TokenStream { + fn from_iter>(tokens: I) -> Self { + let mut stream = TokenStream::new(); + stream.extend(tokens); + stream + } +} + +impl FromIterator for TokenStream { + fn from_iter>(streams: I) -> Self { + let mut v = RcVecBuilder::new(); + + for stream in streams { + v.extend(stream.take_inner()); + } + + TokenStream { inner: v.build() } + } +} + +impl Extend for TokenStream { + fn extend>(&mut self, tokens: I) { + let mut vec = self.inner.make_mut(); + tokens + .into_iter() + .for_each(|token| push_token_from_proc_macro(vec.as_mut(), token)); + } +} + +impl Extend for TokenStream { + fn extend>(&mut self, streams: I) { + self.inner.make_mut().extend(streams.into_iter().flatten()); + } +} + +pub(crate) type TokenTreeIter = RcVecIntoIter; + +impl IntoIterator for TokenStream { + type Item = TokenTree; + type IntoIter = TokenTreeIter; + + fn into_iter(self) -> TokenTreeIter { + self.take_inner().into_iter() + } +} + +#[cfg(procmacro2_semver_exempt)] +#[derive(Clone, PartialEq, Eq)] +pub(crate) struct SourceFile { + path: PathBuf, +} + +#[cfg(procmacro2_semver_exempt)] +impl SourceFile { + /// Get the path to this source file as a string. + pub fn path(&self) -> PathBuf { + self.path.clone() + } + + pub fn is_real(&self) -> bool { + false + } +} + +#[cfg(procmacro2_semver_exempt)] +impl Debug for SourceFile { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("SourceFile") + .field("path", &self.path()) + .field("is_real", &self.is_real()) + .finish() + } +} + +#[cfg(all(span_locations, not(fuzzing)))] +thread_local! { + static SOURCE_MAP: RefCell = RefCell::new(SourceMap { + // Start with a single dummy file which all call_site() and def_site() + // spans reference. + files: vec![FileInfo { + source_text: String::new(), + span: Span { lo: 0, hi: 0 }, + lines: vec![0], + char_index_to_byte_offset: BTreeMap::new(), + }], + }); +} + +#[cfg(span_locations)] +pub(crate) fn invalidate_current_thread_spans() { + #[cfg(not(fuzzing))] + SOURCE_MAP.with(|sm| sm.borrow_mut().files.truncate(1)); +} + +#[cfg(all(span_locations, not(fuzzing)))] +struct FileInfo { + source_text: String, + span: Span, + lines: Vec, + char_index_to_byte_offset: BTreeMap, +} + +#[cfg(all(span_locations, not(fuzzing)))] +impl FileInfo { + fn offset_line_column(&self, offset: usize) -> LineColumn { + assert!(self.span_within(Span { + lo: offset as u32, + hi: offset as u32, + })); + let offset = offset - self.span.lo as usize; + match self.lines.binary_search(&offset) { + Ok(found) => LineColumn { + line: found + 1, + column: 0, + }, + Err(idx) => LineColumn { + line: idx, + column: offset - self.lines[idx - 1], + }, + } + } + + fn span_within(&self, span: Span) -> bool { + span.lo >= self.span.lo && span.hi <= self.span.hi + } + + fn byte_range(&mut self, span: Span) -> Range { + let lo_char = (span.lo - self.span.lo) as usize; + + // Look up offset of the largest already-computed char index that is + // less than or equal to the current requested one. We resume counting + // chars from that point. + let (&last_char_index, &last_byte_offset) = self + .char_index_to_byte_offset + .range(..=lo_char) + .next_back() + .unwrap_or((&0, &0)); + + let lo_byte = if last_char_index == lo_char { + last_byte_offset + } else { + let total_byte_offset = match self.source_text[last_byte_offset..] + .char_indices() + .nth(lo_char - last_char_index) + { + Some((additional_offset, _ch)) => last_byte_offset + additional_offset, + None => self.source_text.len(), + }; + self.char_index_to_byte_offset + .insert(lo_char, total_byte_offset); + total_byte_offset + }; + + let trunc_lo = &self.source_text[lo_byte..]; + let char_len = (span.hi - span.lo) as usize; + lo_byte..match trunc_lo.char_indices().nth(char_len) { + Some((offset, _ch)) => lo_byte + offset, + None => self.source_text.len(), + } + } + + fn source_text(&mut self, span: Span) -> String { + let byte_range = self.byte_range(span); + self.source_text[byte_range].to_owned() + } +} + +/// Computes the offsets of each line in the given source string +/// and the total number of characters +#[cfg(all(span_locations, not(fuzzing)))] +fn lines_offsets(s: &str) -> (usize, Vec) { + let mut lines = vec![0]; + let mut total = 0; + + for ch in s.chars() { + total += 1; + if ch == '\n' { + lines.push(total); + } + } + + (total, lines) +} + +#[cfg(all(span_locations, not(fuzzing)))] +struct SourceMap { + files: Vec, +} + +#[cfg(all(span_locations, not(fuzzing)))] +impl SourceMap { + fn next_start_pos(&self) -> u32 { + // Add 1 so there's always space between files. + // + // We'll always have at least 1 file, as we initialize our files list + // with a dummy file. + self.files.last().unwrap().span.hi + 1 + } + + fn add_file(&mut self, src: &str) -> Span { + let (len, lines) = lines_offsets(src); + let lo = self.next_start_pos(); + let span = Span { + lo, + hi: lo + (len as u32), + }; + + self.files.push(FileInfo { + source_text: src.to_owned(), + span, + lines, + // Populated lazily by source_text(). + char_index_to_byte_offset: BTreeMap::new(), + }); + + span + } + + #[cfg(procmacro2_semver_exempt)] + fn filepath(&self, span: Span) -> PathBuf { + for (i, file) in self.files.iter().enumerate() { + if file.span_within(span) { + return PathBuf::from(if i == 0 { + "".to_owned() + } else { + format!("", i) + }); + } + } + unreachable!("Invalid span with no related FileInfo!"); + } + + fn fileinfo(&self, span: Span) -> &FileInfo { + for file in &self.files { + if file.span_within(span) { + return file; + } + } + unreachable!("Invalid span with no related FileInfo!"); + } + + fn fileinfo_mut(&mut self, span: Span) -> &mut FileInfo { + for file in &mut self.files { + if file.span_within(span) { + return file; + } + } + unreachable!("Invalid span with no related FileInfo!"); + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct Span { + #[cfg(span_locations)] + pub(crate) lo: u32, + #[cfg(span_locations)] + pub(crate) hi: u32, +} + +impl Span { + #[cfg(not(span_locations))] + pub fn call_site() -> Self { + Span {} + } + + #[cfg(span_locations)] + pub fn call_site() -> Self { + Span { lo: 0, hi: 0 } + } + + pub fn mixed_site() -> Self { + Span::call_site() + } + + #[cfg(procmacro2_semver_exempt)] + pub fn def_site() -> Self { + Span::call_site() + } + + pub fn resolved_at(&self, _other: Span) -> Span { + // Stable spans consist only of line/column information, so + // `resolved_at` and `located_at` only select which span the + // caller wants line/column information from. + *self + } + + pub fn located_at(&self, other: Span) -> Span { + other + } + + #[cfg(procmacro2_semver_exempt)] + pub fn source_file(&self) -> SourceFile { + #[cfg(fuzzing)] + return SourceFile { + path: PathBuf::from(""), + }; + + #[cfg(not(fuzzing))] + SOURCE_MAP.with(|sm| { + let sm = sm.borrow(); + let path = sm.filepath(*self); + SourceFile { path } + }) + } + + #[cfg(span_locations)] + pub fn byte_range(&self) -> Range { + #[cfg(fuzzing)] + return 0..0; + + #[cfg(not(fuzzing))] + { + if self.is_call_site() { + 0..0 + } else { + SOURCE_MAP.with(|sm| sm.borrow_mut().fileinfo_mut(*self).byte_range(*self)) + } + } + } + + #[cfg(span_locations)] + pub fn start(&self) -> LineColumn { + #[cfg(fuzzing)] + return LineColumn { line: 0, column: 0 }; + + #[cfg(not(fuzzing))] + SOURCE_MAP.with(|sm| { + let sm = sm.borrow(); + let fi = sm.fileinfo(*self); + fi.offset_line_column(self.lo as usize) + }) + } + + #[cfg(span_locations)] + pub fn end(&self) -> LineColumn { + #[cfg(fuzzing)] + return LineColumn { line: 0, column: 0 }; + + #[cfg(not(fuzzing))] + SOURCE_MAP.with(|sm| { + let sm = sm.borrow(); + let fi = sm.fileinfo(*self); + fi.offset_line_column(self.hi as usize) + }) + } + + #[cfg(not(span_locations))] + pub fn join(&self, _other: Span) -> Option { + Some(Span {}) + } + + #[cfg(span_locations)] + pub fn join(&self, other: Span) -> Option { + #[cfg(fuzzing)] + return { + let _ = other; + None + }; + + #[cfg(not(fuzzing))] + SOURCE_MAP.with(|sm| { + let sm = sm.borrow(); + // If `other` is not within the same FileInfo as us, return None. + if !sm.fileinfo(*self).span_within(other) { + return None; + } + Some(Span { + lo: cmp::min(self.lo, other.lo), + hi: cmp::max(self.hi, other.hi), + }) + }) + } + + #[cfg(not(span_locations))] + pub fn source_text(&self) -> Option { + None + } + + #[cfg(span_locations)] + pub fn source_text(&self) -> Option { + #[cfg(fuzzing)] + return None; + + #[cfg(not(fuzzing))] + { + if self.is_call_site() { + None + } else { + Some(SOURCE_MAP.with(|sm| sm.borrow_mut().fileinfo_mut(*self).source_text(*self))) + } + } + } + + #[cfg(not(span_locations))] + pub(crate) fn first_byte(self) -> Self { + self + } + + #[cfg(span_locations)] + pub(crate) fn first_byte(self) -> Self { + Span { + lo: self.lo, + hi: cmp::min(self.lo.saturating_add(1), self.hi), + } + } + + #[cfg(not(span_locations))] + pub(crate) fn last_byte(self) -> Self { + self + } + + #[cfg(span_locations)] + pub(crate) fn last_byte(self) -> Self { + Span { + lo: cmp::max(self.hi.saturating_sub(1), self.lo), + hi: self.hi, + } + } + + #[cfg(span_locations)] + fn is_call_site(&self) -> bool { + self.lo == 0 && self.hi == 0 + } +} + +impl Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + #[cfg(span_locations)] + return write!(f, "bytes({}..{})", self.lo, self.hi); + + #[cfg(not(span_locations))] + write!(f, "Span") + } +} + +pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) { + #[cfg(span_locations)] + { + if span.is_call_site() { + return; + } + } + + if cfg!(span_locations) { + debug.field("span", &span); + } +} + +#[derive(Clone)] +pub(crate) struct Group { + delimiter: Delimiter, + stream: TokenStream, + span: Span, +} + +impl Group { + pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { + Group { + delimiter, + stream, + span: Span::call_site(), + } + } + + pub fn delimiter(&self) -> Delimiter { + self.delimiter + } + + pub fn stream(&self) -> TokenStream { + self.stream.clone() + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn span_open(&self) -> Span { + self.span.first_byte() + } + + pub fn span_close(&self) -> Span { + self.span.last_byte() + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + +impl Display for Group { + // We attempt to match libproc_macro's formatting. + // Empty parens: () + // Nonempty parens: (...) + // Empty brackets: [] + // Nonempty brackets: [...] + // Empty braces: { } + // Nonempty braces: { ... } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let (open, close) = match self.delimiter { + Delimiter::Parenthesis => ("(", ")"), + Delimiter::Brace => ("{ ", "}"), + Delimiter::Bracket => ("[", "]"), + Delimiter::None => ("", ""), + }; + + f.write_str(open)?; + Display::fmt(&self.stream, f)?; + if self.delimiter == Delimiter::Brace && !self.stream.inner.is_empty() { + f.write_str(" ")?; + } + f.write_str(close)?; + + Ok(()) + } +} + +impl Debug for Group { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut debug = fmt.debug_struct("Group"); + debug.field("delimiter", &self.delimiter); + debug.field("stream", &self.stream); + debug_span_field_if_nontrivial(&mut debug, self.span); + debug.finish() + } +} + +#[derive(Clone)] +pub(crate) struct Ident { + sym: Box, + span: Span, + raw: bool, +} + +impl Ident { + #[track_caller] + pub fn new_checked(string: &str, span: Span) -> Self { + validate_ident(string); + Ident::new_unchecked(string, span) + } + + pub fn new_unchecked(string: &str, span: Span) -> Self { + Ident { + sym: Box::from(string), + span, + raw: false, + } + } + + #[track_caller] + pub fn new_raw_checked(string: &str, span: Span) -> Self { + validate_ident_raw(string); + Ident::new_raw_unchecked(string, span) + } + + pub fn new_raw_unchecked(string: &str, span: Span) -> Self { + Ident { + sym: Box::from(string), + span, + raw: true, + } + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + +pub(crate) fn is_ident_start(c: char) -> bool { + c == '_' || unicode_ident::is_xid_start(c) +} + +pub(crate) fn is_ident_continue(c: char) -> bool { + unicode_ident::is_xid_continue(c) +} + +#[track_caller] +fn validate_ident(string: &str) { + if string.is_empty() { + panic!("Ident is not allowed to be empty; use Option"); + } + + if string.bytes().all(|digit| b'0' <= digit && digit <= b'9') { + panic!("Ident cannot be a number; use Literal instead"); + } + + fn ident_ok(string: &str) -> bool { + let mut chars = string.chars(); + let first = chars.next().unwrap(); + if !is_ident_start(first) { + return false; + } + for ch in chars { + if !is_ident_continue(ch) { + return false; + } + } + true + } + + if !ident_ok(string) { + panic!("{:?} is not a valid Ident", string); + } +} + +#[track_caller] +fn validate_ident_raw(string: &str) { + validate_ident(string); + + match string { + "_" | "super" | "self" | "Self" | "crate" => { + panic!("`r#{}` cannot be a raw identifier", string); + } + _ => {} + } +} + +impl PartialEq for Ident { + fn eq(&self, other: &Ident) -> bool { + self.sym == other.sym && self.raw == other.raw + } +} + +impl PartialEq for Ident +where + T: ?Sized + AsRef, +{ + fn eq(&self, other: &T) -> bool { + let other = other.as_ref(); + if self.raw { + other.starts_with("r#") && *self.sym == other[2..] + } else { + *self.sym == *other + } + } +} + +impl Display for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.raw { + f.write_str("r#")?; + } + Display::fmt(&self.sym, f) + } +} + +#[allow(clippy::missing_fields_in_debug)] +impl Debug for Ident { + // Ident(proc_macro), Ident(r#union) + #[cfg(not(span_locations))] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut debug = f.debug_tuple("Ident"); + debug.field(&format_args!("{}", self)); + debug.finish() + } + + // Ident { + // sym: proc_macro, + // span: bytes(128..138) + // } + #[cfg(span_locations)] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut debug = f.debug_struct("Ident"); + debug.field("sym", &format_args!("{}", self)); + debug_span_field_if_nontrivial(&mut debug, self.span); + debug.finish() + } +} + +#[derive(Clone)] +pub(crate) struct Literal { + pub(crate) repr: String, + span: Span, +} + +macro_rules! suffixed_numbers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + Literal::_new(format!(concat!("{}", stringify!($kind)), n)) + } + )*) +} + +macro_rules! unsuffixed_numbers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + Literal::_new(n.to_string()) + } + )*) +} + +impl Literal { + pub(crate) fn _new(repr: String) -> Self { + Literal { + repr, + span: Span::call_site(), + } + } + + pub(crate) unsafe fn from_str_unchecked(repr: &str) -> Self { + Literal::_new(repr.to_owned()) + } + + suffixed_numbers! { + u8_suffixed => u8, + u16_suffixed => u16, + u32_suffixed => u32, + u64_suffixed => u64, + u128_suffixed => u128, + usize_suffixed => usize, + i8_suffixed => i8, + i16_suffixed => i16, + i32_suffixed => i32, + i64_suffixed => i64, + i128_suffixed => i128, + isize_suffixed => isize, + + f32_suffixed => f32, + f64_suffixed => f64, + } + + unsuffixed_numbers! { + u8_unsuffixed => u8, + u16_unsuffixed => u16, + u32_unsuffixed => u32, + u64_unsuffixed => u64, + u128_unsuffixed => u128, + usize_unsuffixed => usize, + i8_unsuffixed => i8, + i16_unsuffixed => i16, + i32_unsuffixed => i32, + i64_unsuffixed => i64, + i128_unsuffixed => i128, + isize_unsuffixed => isize, + } + + pub fn f32_unsuffixed(f: f32) -> Literal { + let mut s = f.to_string(); + if !s.contains('.') { + s.push_str(".0"); + } + Literal::_new(s) + } + + pub fn f64_unsuffixed(f: f64) -> Literal { + let mut s = f.to_string(); + if !s.contains('.') { + s.push_str(".0"); + } + Literal::_new(s) + } + + pub fn string(string: &str) -> Literal { + let mut repr = String::with_capacity(string.len() + 2); + repr.push('"'); + escape_utf8(string, &mut repr); + repr.push('"'); + Literal::_new(repr) + } + + pub fn character(ch: char) -> Literal { + let mut repr = String::new(); + repr.push('\''); + if ch == '"' { + // escape_debug turns this into '\"' which is unnecessary. + repr.push(ch); + } else { + repr.extend(ch.escape_debug()); + } + repr.push('\''); + Literal::_new(repr) + } + + pub fn byte_character(byte: u8) -> Literal { + let mut repr = "b'".to_string(); + #[allow(clippy::match_overlapping_arm)] + match byte { + b'\0' => repr.push_str(r"\0"), + b'\t' => repr.push_str(r"\t"), + b'\n' => repr.push_str(r"\n"), + b'\r' => repr.push_str(r"\r"), + b'\'' => repr.push_str(r"\'"), + b'\\' => repr.push_str(r"\\"), + b'\x20'..=b'\x7E' => repr.push(byte as char), + _ => { + let _ = write!(repr, r"\x{:02X}", byte); + } + } + repr.push('\''); + Literal::_new(repr) + } + + pub fn byte_string(bytes: &[u8]) -> Literal { + let mut repr = "b\"".to_string(); + let mut bytes = bytes.iter(); + while let Some(&b) = bytes.next() { + #[allow(clippy::match_overlapping_arm)] + match b { + b'\0' => repr.push_str(match bytes.as_slice().first() { + // circumvent clippy::octal_escapes lint + Some(b'0'..=b'7') => r"\x00", + _ => r"\0", + }), + b'\t' => repr.push_str(r"\t"), + b'\n' => repr.push_str(r"\n"), + b'\r' => repr.push_str(r"\r"), + b'"' => repr.push_str("\\\""), + b'\\' => repr.push_str(r"\\"), + b'\x20'..=b'\x7E' => repr.push(b as char), + _ => { + let _ = write!(repr, r"\x{:02X}", b); + } + } + } + repr.push('"'); + Literal::_new(repr) + } + + pub fn c_string(string: &CStr) -> Literal { + let mut repr = "c\"".to_string(); + let mut bytes = string.to_bytes(); + while !bytes.is_empty() { + let (valid, invalid) = match str::from_utf8(bytes) { + Ok(all_valid) => { + bytes = b""; + (all_valid, bytes) + } + Err(utf8_error) => { + let (valid, rest) = bytes.split_at(utf8_error.valid_up_to()); + let valid = str::from_utf8(valid).unwrap(); + let invalid = utf8_error + .error_len() + .map_or(rest, |error_len| &rest[..error_len]); + bytes = &bytes[valid.len() + invalid.len()..]; + (valid, invalid) + } + }; + escape_utf8(valid, &mut repr); + for &byte in invalid { + let _ = write!(repr, r"\x{:02X}", byte); + } + } + repr.push('"'); + Literal::_new(repr) + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } + + pub fn subspan>(&self, range: R) -> Option { + #[cfg(not(span_locations))] + { + let _ = range; + None + } + + #[cfg(span_locations)] + { + use core::ops::Bound; + + let lo = match range.start_bound() { + Bound::Included(start) => { + let start = u32::try_from(*start).ok()?; + self.span.lo.checked_add(start)? + } + Bound::Excluded(start) => { + let start = u32::try_from(*start).ok()?; + self.span.lo.checked_add(start)?.checked_add(1)? + } + Bound::Unbounded => self.span.lo, + }; + let hi = match range.end_bound() { + Bound::Included(end) => { + let end = u32::try_from(*end).ok()?; + self.span.lo.checked_add(end)?.checked_add(1)? + } + Bound::Excluded(end) => { + let end = u32::try_from(*end).ok()?; + self.span.lo.checked_add(end)? + } + Bound::Unbounded => self.span.hi, + }; + if lo <= hi && hi <= self.span.hi { + Some(Span { lo, hi }) + } else { + None + } + } + } +} + +impl FromStr for Literal { + type Err = LexError; + + fn from_str(repr: &str) -> Result { + let mut cursor = get_cursor(repr); + #[cfg(span_locations)] + let lo = cursor.off; + + let negative = cursor.starts_with_char('-'); + if negative { + cursor = cursor.advance(1); + if !cursor.starts_with_fn(|ch| ch.is_ascii_digit()) { + return Err(LexError::call_site()); + } + } + + if let Ok((rest, mut literal)) = parse::literal(cursor) { + if rest.is_empty() { + if negative { + literal.repr.insert(0, '-'); + } + literal.span = Span { + #[cfg(span_locations)] + lo, + #[cfg(span_locations)] + hi: rest.off, + }; + return Ok(literal); + } + } + Err(LexError::call_site()) + } +} + +impl Display for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.repr, f) + } +} + +impl Debug for Literal { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut debug = fmt.debug_struct("Literal"); + debug.field("lit", &format_args!("{}", self.repr)); + debug_span_field_if_nontrivial(&mut debug, self.span); + debug.finish() + } +} + +fn escape_utf8(string: &str, repr: &mut String) { + let mut chars = string.chars(); + while let Some(ch) = chars.next() { + if ch == '\0' { + repr.push_str( + if chars + .as_str() + .starts_with(|next| '0' <= next && next <= '7') + { + // circumvent clippy::octal_escapes lint + r"\x00" + } else { + r"\0" + }, + ); + } else if ch == '\'' { + // escape_debug turns this into "\'" which is unnecessary. + repr.push(ch); + } else { + repr.extend(ch.escape_debug()); + } + } +} diff --git a/bitbox02-bt/vendor/proc-macro2/src/lib.rs b/bitbox02-bt/vendor/proc-macro2/src/lib.rs new file mode 100644 index 0000000..46b6e84 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/lib.rs @@ -0,0 +1,1377 @@ +//! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs +//! +//!
+//! +//! A wrapper around the procedural macro API of the compiler's [`proc_macro`] +//! crate. This library serves two purposes: +//! +//! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/ +//! +//! - **Bring proc-macro-like functionality to other contexts like build.rs and +//! main.rs.** Types from `proc_macro` are entirely specific to procedural +//! macros and cannot ever exist in code outside of a procedural macro. +//! Meanwhile `proc_macro2` types may exist anywhere including non-macro code. +//! By developing foundational libraries like [syn] and [quote] against +//! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem +//! becomes easily applicable to many other use cases and we avoid +//! reimplementing non-macro equivalents of those libraries. +//! +//! - **Make procedural macros unit testable.** As a consequence of being +//! specific to procedural macros, nothing that uses `proc_macro` can be +//! executed from a unit test. In order for helper libraries or components of +//! a macro to be testable in isolation, they must be implemented using +//! `proc_macro2`. +//! +//! [syn]: https://github.com/dtolnay/syn +//! [quote]: https://github.com/dtolnay/quote +//! +//! # Usage +//! +//! The skeleton of a typical procedural macro typically looks like this: +//! +//! ``` +//! extern crate proc_macro; +//! +//! # const IGNORE: &str = stringify! { +//! #[proc_macro_derive(MyDerive)] +//! # }; +//! # #[cfg(wrap_proc_macro)] +//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { +//! let input = proc_macro2::TokenStream::from(input); +//! +//! let output: proc_macro2::TokenStream = { +//! /* transform input */ +//! # input +//! }; +//! +//! proc_macro::TokenStream::from(output) +//! } +//! ``` +//! +//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to +//! propagate parse errors correctly back to the compiler when parsing fails. +//! +//! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html +//! +//! # Unstable features +//! +//! The default feature set of proc-macro2 tracks the most recent stable +//! compiler API. Functionality in `proc_macro` that is not yet stable is not +//! exposed by proc-macro2 by default. +//! +//! To opt into the additional APIs available in the most recent nightly +//! compiler, the `procmacro2_semver_exempt` config flag must be passed to +//! rustc. We will polyfill those nightly-only APIs back to Rust 1.56.0. As +//! these are unstable APIs that track the nightly compiler, minor versions of +//! proc-macro2 may make breaking changes to them at any time. +//! +//! ```sh +//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build +//! ``` +//! +//! Note that this must not only be done for your crate, but for any crate that +//! depends on your crate. This infectious nature is intentional, as it serves +//! as a reminder that you are outside of the normal semver guarantees. +//! +//! Semver exempt methods are marked as such in the proc-macro2 documentation. +//! +//! # Thread-Safety +//! +//! Most types in this crate are `!Sync` because the underlying compiler +//! types make use of thread-local memory, meaning they cannot be accessed from +//! a different thread. + +// Proc-macro2 types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.87")] +#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))] +#![cfg_attr(super_unstable, feature(proc_macro_def_site))] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![deny(unsafe_op_in_unsafe_fn)] +#![allow( + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::checked_conversions, + clippy::doc_markdown, + clippy::incompatible_msrv, + clippy::items_after_statements, + clippy::iter_without_into_iter, + clippy::let_underscore_untyped, + clippy::manual_assert, + clippy::manual_range_contains, + clippy::missing_panics_doc, + clippy::missing_safety_doc, + clippy::must_use_candidate, + clippy::needless_doctest_main, + clippy::needless_lifetimes, + clippy::new_without_default, + clippy::return_self_not_must_use, + clippy::shadow_unrelated, + clippy::trivially_copy_pass_by_ref, + clippy::unnecessary_wraps, + clippy::unused_self, + clippy::used_underscore_binding, + clippy::vec_init_then_push +)] + +#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))] +compile_error! {"\ + Something is not right. If you've tried to turn on \ + procmacro2_semver_exempt, you need to ensure that it \ + is turned on for the compilation of the proc-macro2 \ + build script as well. +"} + +#[cfg(all( + procmacro2_nightly_testing, + feature = "proc-macro", + not(proc_macro_span) +))] +compile_error! {"\ + Build script probe failed to compile. +"} + +extern crate alloc; + +#[cfg(feature = "proc-macro")] +extern crate proc_macro; + +mod marker; +mod parse; +mod rcvec; + +#[cfg(wrap_proc_macro)] +mod detection; + +// Public for proc_macro2::fallback::force() and unforce(), but those are quite +// a niche use case so we omit it from rustdoc. +#[doc(hidden)] +pub mod fallback; + +pub mod extra; + +#[cfg(not(wrap_proc_macro))] +use crate::fallback as imp; +#[path = "wrapper.rs"] +#[cfg(wrap_proc_macro)] +mod imp; + +#[cfg(span_locations)] +mod location; + +use crate::extra::DelimSpan; +use crate::marker::{ProcMacroAutoTraits, MARKER}; +use core::cmp::Ordering; +use core::fmt::{self, Debug, Display}; +use core::hash::{Hash, Hasher}; +#[cfg(span_locations)] +use core::ops::Range; +use core::ops::RangeBounds; +use core::str::FromStr; +use std::error::Error; +use std::ffi::CStr; +#[cfg(procmacro2_semver_exempt)] +use std::path::PathBuf; + +#[cfg(span_locations)] +#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] +pub use crate::location::LineColumn; + +/// An abstract stream of tokens, or more concretely a sequence of token trees. +/// +/// This type provides interfaces for iterating over token trees and for +/// collecting token trees into one stream. +/// +/// Token stream is both the input and output of `#[proc_macro]`, +/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions. +#[derive(Clone)] +pub struct TokenStream { + inner: imp::TokenStream, + _marker: ProcMacroAutoTraits, +} + +/// Error returned from `TokenStream::from_str`. +pub struct LexError { + inner: imp::LexError, + _marker: ProcMacroAutoTraits, +} + +impl TokenStream { + fn _new(inner: imp::TokenStream) -> Self { + TokenStream { + inner, + _marker: MARKER, + } + } + + fn _new_fallback(inner: fallback::TokenStream) -> Self { + TokenStream { + inner: inner.into(), + _marker: MARKER, + } + } + + /// Returns an empty `TokenStream` containing no token trees. + pub fn new() -> Self { + TokenStream::_new(imp::TokenStream::new()) + } + + /// Checks if this `TokenStream` is empty. + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } +} + +/// `TokenStream::default()` returns an empty stream, +/// i.e. this is equivalent with `TokenStream::new()`. +impl Default for TokenStream { + fn default() -> Self { + TokenStream::new() + } +} + +/// Attempts to break the string into tokens and parse those tokens into a token +/// stream. +/// +/// May fail for a number of reasons, for example, if the string contains +/// unbalanced delimiters or characters not existing in the language. +/// +/// NOTE: Some errors may cause panics instead of returning `LexError`. We +/// reserve the right to change these errors into `LexError`s later. +impl FromStr for TokenStream { + type Err = LexError; + + fn from_str(src: &str) -> Result { + let e = src.parse().map_err(|e| LexError { + inner: e, + _marker: MARKER, + })?; + Ok(TokenStream::_new(e)) + } +} + +#[cfg(feature = "proc-macro")] +#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))] +impl From for TokenStream { + fn from(inner: proc_macro::TokenStream) -> Self { + TokenStream::_new(inner.into()) + } +} + +#[cfg(feature = "proc-macro")] +#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))] +impl From for proc_macro::TokenStream { + fn from(inner: TokenStream) -> Self { + inner.inner.into() + } +} + +impl From for TokenStream { + fn from(token: TokenTree) -> Self { + TokenStream::_new(imp::TokenStream::from(token)) + } +} + +impl Extend for TokenStream { + fn extend>(&mut self, streams: I) { + self.inner.extend(streams); + } +} + +impl Extend for TokenStream { + fn extend>(&mut self, streams: I) { + self.inner + .extend(streams.into_iter().map(|stream| stream.inner)); + } +} + +/// Collects a number of token trees into a single stream. +impl FromIterator for TokenStream { + fn from_iter>(streams: I) -> Self { + TokenStream::_new(streams.into_iter().collect()) + } +} +impl FromIterator for TokenStream { + fn from_iter>(streams: I) -> Self { + TokenStream::_new(streams.into_iter().map(|i| i.inner).collect()) + } +} + +/// Prints the token stream as a string that is supposed to be losslessly +/// convertible back into the same token stream (modulo spans), except for +/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative +/// numeric literals. +impl Display for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.inner, f) + } +} + +/// Prints token in a form convenient for debugging. +impl Debug for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.inner, f) + } +} + +impl LexError { + pub fn span(&self) -> Span { + Span::_new(self.inner.span()) + } +} + +impl Debug for LexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.inner, f) + } +} + +impl Display for LexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.inner, f) + } +} + +impl Error for LexError {} + +/// The source file of a given `Span`. +/// +/// This type is semver exempt and not exposed by default. +#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] +#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))] +#[derive(Clone, PartialEq, Eq)] +pub struct SourceFile { + inner: imp::SourceFile, + _marker: ProcMacroAutoTraits, +} + +#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] +impl SourceFile { + fn _new(inner: imp::SourceFile) -> Self { + SourceFile { + inner, + _marker: MARKER, + } + } + + /// Get the path to this source file. + /// + /// ### Note + /// + /// If the code span associated with this `SourceFile` was generated by an + /// external macro, this may not be an actual path on the filesystem. Use + /// [`is_real`] to check. + /// + /// Also note that even if `is_real` returns `true`, if + /// `--remap-path-prefix` was passed on the command line, the path as given + /// may not actually be valid. + /// + /// [`is_real`]: #method.is_real + pub fn path(&self) -> PathBuf { + self.inner.path() + } + + /// Returns `true` if this source file is a real source file, and not + /// generated by an external macro's expansion. + pub fn is_real(&self) -> bool { + self.inner.is_real() + } +} + +#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] +impl Debug for SourceFile { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.inner, f) + } +} + +/// A region of source code, along with macro expansion information. +#[derive(Copy, Clone)] +pub struct Span { + inner: imp::Span, + _marker: ProcMacroAutoTraits, +} + +impl Span { + fn _new(inner: imp::Span) -> Self { + Span { + inner, + _marker: MARKER, + } + } + + fn _new_fallback(inner: fallback::Span) -> Self { + Span { + inner: inner.into(), + _marker: MARKER, + } + } + + /// The span of the invocation of the current procedural macro. + /// + /// Identifiers created with this span will be resolved as if they were + /// written directly at the macro call location (call-site hygiene) and + /// other code at the macro call site will be able to refer to them as well. + pub fn call_site() -> Self { + Span::_new(imp::Span::call_site()) + } + + /// The span located at the invocation of the procedural macro, but with + /// local variables, labels, and `$crate` resolved at the definition site + /// of the macro. This is the same hygiene behavior as `macro_rules`. + pub fn mixed_site() -> Self { + Span::_new(imp::Span::mixed_site()) + } + + /// A span that resolves at the macro definition site. + /// + /// This method is semver exempt and not exposed by default. + #[cfg(procmacro2_semver_exempt)] + #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))] + pub fn def_site() -> Self { + Span::_new(imp::Span::def_site()) + } + + /// Creates a new span with the same line/column information as `self` but + /// that resolves symbols as though it were at `other`. + pub fn resolved_at(&self, other: Span) -> Span { + Span::_new(self.inner.resolved_at(other.inner)) + } + + /// Creates a new span with the same name resolution behavior as `self` but + /// with the line/column information of `other`. + pub fn located_at(&self, other: Span) -> Span { + Span::_new(self.inner.located_at(other.inner)) + } + + /// Convert `proc_macro2::Span` to `proc_macro::Span`. + /// + /// This method is available when building with a nightly compiler, or when + /// building with rustc 1.29+ *without* semver exempt features. + /// + /// # Panics + /// + /// Panics if called from outside of a procedural macro. Unlike + /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within + /// the context of a procedural macro invocation. + #[cfg(wrap_proc_macro)] + pub fn unwrap(self) -> proc_macro::Span { + self.inner.unwrap() + } + + // Soft deprecated. Please use Span::unwrap. + #[cfg(wrap_proc_macro)] + #[doc(hidden)] + pub fn unstable(self) -> proc_macro::Span { + self.unwrap() + } + + /// The original source file into which this span points. + /// + /// This method is semver exempt and not exposed by default. + #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] + #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))] + pub fn source_file(&self) -> SourceFile { + SourceFile::_new(self.inner.source_file()) + } + + /// Returns the span's byte position range in the source file. + /// + /// This method requires the `"span-locations"` feature to be enabled. + /// + /// When executing in a procedural macro context, the returned range is only + /// accurate if compiled with a nightly toolchain. The stable toolchain does + /// not have this information available. When executing outside of a + /// procedural macro, such as main.rs or build.rs, the byte range is always + /// accurate regardless of toolchain. + #[cfg(span_locations)] + #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] + pub fn byte_range(&self) -> Range { + self.inner.byte_range() + } + + /// Get the starting line/column in the source file for this span. + /// + /// This method requires the `"span-locations"` feature to be enabled. + /// + /// When executing in a procedural macro context, the returned line/column + /// are only meaningful if compiled with a nightly toolchain. The stable + /// toolchain does not have this information available. When executing + /// outside of a procedural macro, such as main.rs or build.rs, the + /// line/column are always meaningful regardless of toolchain. + #[cfg(span_locations)] + #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] + pub fn start(&self) -> LineColumn { + self.inner.start() + } + + /// Get the ending line/column in the source file for this span. + /// + /// This method requires the `"span-locations"` feature to be enabled. + /// + /// When executing in a procedural macro context, the returned line/column + /// are only meaningful if compiled with a nightly toolchain. The stable + /// toolchain does not have this information available. When executing + /// outside of a procedural macro, such as main.rs or build.rs, the + /// line/column are always meaningful regardless of toolchain. + #[cfg(span_locations)] + #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] + pub fn end(&self) -> LineColumn { + self.inner.end() + } + + /// Create a new span encompassing `self` and `other`. + /// + /// Returns `None` if `self` and `other` are from different files. + /// + /// Warning: the underlying [`proc_macro::Span::join`] method is + /// nightly-only. When called from within a procedural macro not using a + /// nightly compiler, this method will always return `None`. + /// + /// [`proc_macro::Span::join`]: https://doc.rust-lang.org/proc_macro/struct.Span.html#method.join + pub fn join(&self, other: Span) -> Option { + self.inner.join(other.inner).map(Span::_new) + } + + /// Compares two spans to see if they're equal. + /// + /// This method is semver exempt and not exposed by default. + #[cfg(procmacro2_semver_exempt)] + #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))] + pub fn eq(&self, other: &Span) -> bool { + self.inner.eq(&other.inner) + } + + /// Returns the source text behind a span. This preserves the original + /// source code, including spaces and comments. It only returns a result if + /// the span corresponds to real source code. + /// + /// Note: The observable result of a macro should only rely on the tokens + /// and not on this source text. The result of this function is a best + /// effort to be used for diagnostics only. + pub fn source_text(&self) -> Option { + self.inner.source_text() + } +} + +/// Prints a span in a form convenient for debugging. +impl Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.inner, f) + } +} + +/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`). +#[derive(Clone)] +pub enum TokenTree { + /// A token stream surrounded by bracket delimiters. + Group(Group), + /// An identifier. + Ident(Ident), + /// A single punctuation character (`+`, `,`, `$`, etc.). + Punct(Punct), + /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc. + Literal(Literal), +} + +impl TokenTree { + /// Returns the span of this tree, delegating to the `span` method of + /// the contained token or a delimited stream. + pub fn span(&self) -> Span { + match self { + TokenTree::Group(t) => t.span(), + TokenTree::Ident(t) => t.span(), + TokenTree::Punct(t) => t.span(), + TokenTree::Literal(t) => t.span(), + } + } + + /// Configures the span for *only this token*. + /// + /// Note that if this token is a `Group` then this method will not configure + /// the span of each of the internal tokens, this will simply delegate to + /// the `set_span` method of each variant. + pub fn set_span(&mut self, span: Span) { + match self { + TokenTree::Group(t) => t.set_span(span), + TokenTree::Ident(t) => t.set_span(span), + TokenTree::Punct(t) => t.set_span(span), + TokenTree::Literal(t) => t.set_span(span), + } + } +} + +impl From for TokenTree { + fn from(g: Group) -> Self { + TokenTree::Group(g) + } +} + +impl From for TokenTree { + fn from(g: Ident) -> Self { + TokenTree::Ident(g) + } +} + +impl From for TokenTree { + fn from(g: Punct) -> Self { + TokenTree::Punct(g) + } +} + +impl From for TokenTree { + fn from(g: Literal) -> Self { + TokenTree::Literal(g) + } +} + +/// Prints the token tree as a string that is supposed to be losslessly +/// convertible back into the same token tree (modulo spans), except for +/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative +/// numeric literals. +impl Display for TokenTree { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + TokenTree::Group(t) => Display::fmt(t, f), + TokenTree::Ident(t) => Display::fmt(t, f), + TokenTree::Punct(t) => Display::fmt(t, f), + TokenTree::Literal(t) => Display::fmt(t, f), + } + } +} + +/// Prints token tree in a form convenient for debugging. +impl Debug for TokenTree { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Each of these has the name in the struct type in the derived debug, + // so don't bother with an extra layer of indirection + match self { + TokenTree::Group(t) => Debug::fmt(t, f), + TokenTree::Ident(t) => { + let mut debug = f.debug_struct("Ident"); + debug.field("sym", &format_args!("{}", t)); + imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner); + debug.finish() + } + TokenTree::Punct(t) => Debug::fmt(t, f), + TokenTree::Literal(t) => Debug::fmt(t, f), + } + } +} + +/// A delimited token stream. +/// +/// A `Group` internally contains a `TokenStream` which is surrounded by +/// `Delimiter`s. +#[derive(Clone)] +pub struct Group { + inner: imp::Group, +} + +/// Describes how a sequence of token trees is delimited. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Delimiter { + /// `( ... )` + Parenthesis, + /// `{ ... }` + Brace, + /// `[ ... ]` + Bracket, + /// `∅ ... ∅` + /// + /// An invisible delimiter, that may, for example, appear around tokens + /// coming from a "macro variable" `$var`. It is important to preserve + /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`. + /// Invisible delimiters may not survive roundtrip of a token stream through + /// a string. + /// + ///
+ /// + /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output + /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input + /// of a proc_macro macro are preserved, and only in very specific circumstances. + /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve + /// operator priorities as indicated above. The other `Delimiter` variants should be used + /// instead in this context. This is a rustc bug. For details, see + /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062). + /// + ///
+ None, +} + +impl Group { + fn _new(inner: imp::Group) -> Self { + Group { inner } + } + + fn _new_fallback(inner: fallback::Group) -> Self { + Group { + inner: inner.into(), + } + } + + /// Creates a new `Group` with the given delimiter and token stream. + /// + /// This constructor will set the span for this group to + /// `Span::call_site()`. To change the span you can use the `set_span` + /// method below. + pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { + Group { + inner: imp::Group::new(delimiter, stream.inner), + } + } + + /// Returns the punctuation used as the delimiter for this group: a set of + /// parentheses, square brackets, or curly braces. + pub fn delimiter(&self) -> Delimiter { + self.inner.delimiter() + } + + /// Returns the `TokenStream` of tokens that are delimited in this `Group`. + /// + /// Note that the returned token stream does not include the delimiter + /// returned above. + pub fn stream(&self) -> TokenStream { + TokenStream::_new(self.inner.stream()) + } + + /// Returns the span for the delimiters of this token stream, spanning the + /// entire `Group`. + /// + /// ```text + /// pub fn span(&self) -> Span { + /// ^^^^^^^ + /// ``` + pub fn span(&self) -> Span { + Span::_new(self.inner.span()) + } + + /// Returns the span pointing to the opening delimiter of this group. + /// + /// ```text + /// pub fn span_open(&self) -> Span { + /// ^ + /// ``` + pub fn span_open(&self) -> Span { + Span::_new(self.inner.span_open()) + } + + /// Returns the span pointing to the closing delimiter of this group. + /// + /// ```text + /// pub fn span_close(&self) -> Span { + /// ^ + /// ``` + pub fn span_close(&self) -> Span { + Span::_new(self.inner.span_close()) + } + + /// Returns an object that holds this group's `span_open()` and + /// `span_close()` together (in a more compact representation than holding + /// those 2 spans individually). + pub fn delim_span(&self) -> DelimSpan { + DelimSpan::new(&self.inner) + } + + /// Configures the span for this `Group`'s delimiters, but not its internal + /// tokens. + /// + /// This method will **not** set the span of all the internal tokens spanned + /// by this group, but rather it will only set the span of the delimiter + /// tokens at the level of the `Group`. + pub fn set_span(&mut self, span: Span) { + self.inner.set_span(span.inner); + } +} + +/// Prints the group as a string that should be losslessly convertible back +/// into the same group (modulo spans), except for possibly `TokenTree::Group`s +/// with `Delimiter::None` delimiters. +impl Display for Group { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.inner, formatter) + } +} + +impl Debug for Group { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.inner, formatter) + } +} + +/// A `Punct` is a single punctuation character like `+`, `-` or `#`. +/// +/// Multicharacter operators like `+=` are represented as two instances of +/// `Punct` with different forms of `Spacing` returned. +#[derive(Clone)] +pub struct Punct { + ch: char, + spacing: Spacing, + span: Span, +} + +/// Whether a `Punct` is followed immediately by another `Punct` or followed by +/// another token or whitespace. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Spacing { + /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`. + Alone, + /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`. + /// + /// Additionally, single quote `'` can join with identifiers to form + /// lifetimes `'ident`. + Joint, +} + +impl Punct { + /// Creates a new `Punct` from the given character and spacing. + /// + /// The `ch` argument must be a valid punctuation character permitted by the + /// language, otherwise the function will panic. + /// + /// The returned `Punct` will have the default span of `Span::call_site()` + /// which can be further configured with the `set_span` method below. + pub fn new(ch: char, spacing: Spacing) -> Self { + if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' + | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch + { + Punct { + ch, + spacing, + span: Span::call_site(), + } + } else { + panic!("unsupported proc macro punctuation character {:?}", ch); + } + } + + /// Returns the value of this punctuation character as `char`. + pub fn as_char(&self) -> char { + self.ch + } + + /// Returns the spacing of this punctuation character, indicating whether + /// it's immediately followed by another `Punct` in the token stream, so + /// they can potentially be combined into a multicharacter operator + /// (`Joint`), or it's followed by some other token or whitespace (`Alone`) + /// so the operator has certainly ended. + pub fn spacing(&self) -> Spacing { + self.spacing + } + + /// Returns the span for this punctuation character. + pub fn span(&self) -> Span { + self.span + } + + /// Configure the span for this punctuation character. + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + +/// Prints the punctuation character as a string that should be losslessly +/// convertible back into the same character. +impl Display for Punct { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.ch, f) + } +} + +impl Debug for Punct { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut debug = fmt.debug_struct("Punct"); + debug.field("char", &self.ch); + debug.field("spacing", &self.spacing); + imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner); + debug.finish() + } +} + +/// A word of Rust code, which may be a keyword or legal variable name. +/// +/// An identifier consists of at least one Unicode code point, the first of +/// which has the XID_Start property and the rest of which have the XID_Continue +/// property. +/// +/// - The empty string is not an identifier. Use `Option`. +/// - A lifetime is not an identifier. Use `syn::Lifetime` instead. +/// +/// An identifier constructed with `Ident::new` is permitted to be a Rust +/// keyword, though parsing one through its [`Parse`] implementation rejects +/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the +/// behaviour of `Ident::new`. +/// +/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html +/// +/// # Examples +/// +/// A new ident can be created from a string using the `Ident::new` function. +/// A span must be provided explicitly which governs the name resolution +/// behavior of the resulting identifier. +/// +/// ``` +/// use proc_macro2::{Ident, Span}; +/// +/// fn main() { +/// let call_ident = Ident::new("calligraphy", Span::call_site()); +/// +/// println!("{}", call_ident); +/// } +/// ``` +/// +/// An ident can be interpolated into a token stream using the `quote!` macro. +/// +/// ``` +/// use proc_macro2::{Ident, Span}; +/// use quote::quote; +/// +/// fn main() { +/// let ident = Ident::new("demo", Span::call_site()); +/// +/// // Create a variable binding whose name is this ident. +/// let expanded = quote! { let #ident = 10; }; +/// +/// // Create a variable binding with a slightly different name. +/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site()); +/// let expanded = quote! { let #temp_ident = 10; }; +/// } +/// ``` +/// +/// A string representation of the ident is available through the `to_string()` +/// method. +/// +/// ``` +/// # use proc_macro2::{Ident, Span}; +/// # +/// # let ident = Ident::new("another_identifier", Span::call_site()); +/// # +/// // Examine the ident as a string. +/// let ident_string = ident.to_string(); +/// if ident_string.len() > 60 { +/// println!("Very long identifier: {}", ident_string) +/// } +/// ``` +#[derive(Clone)] +pub struct Ident { + inner: imp::Ident, + _marker: ProcMacroAutoTraits, +} + +impl Ident { + fn _new(inner: imp::Ident) -> Self { + Ident { + inner, + _marker: MARKER, + } + } + + /// Creates a new `Ident` with the given `string` as well as the specified + /// `span`. + /// + /// The `string` argument must be a valid identifier permitted by the + /// language, otherwise the function will panic. + /// + /// Note that `span`, currently in rustc, configures the hygiene information + /// for this identifier. + /// + /// As of this time `Span::call_site()` explicitly opts-in to "call-site" + /// hygiene meaning that identifiers created with this span will be resolved + /// as if they were written directly at the location of the macro call, and + /// other code at the macro call site will be able to refer to them as well. + /// + /// Later spans like `Span::def_site()` will allow to opt-in to + /// "definition-site" hygiene meaning that identifiers created with this + /// span will be resolved at the location of the macro definition and other + /// code at the macro call site will not be able to refer to them. + /// + /// Due to the current importance of hygiene this constructor, unlike other + /// tokens, requires a `Span` to be specified at construction. + /// + /// # Panics + /// + /// Panics if the input string is neither a keyword nor a legal variable + /// name. If you are not sure whether the string contains an identifier and + /// need to handle an error case, use + /// syn::parse_str::<Ident> + /// rather than `Ident::new`. + #[track_caller] + pub fn new(string: &str, span: Span) -> Self { + Ident::_new(imp::Ident::new_checked(string, span.inner)) + } + + /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The + /// `string` argument must be a valid identifier permitted by the language + /// (including keywords, e.g. `fn`). Keywords which are usable in path + /// segments (e.g. `self`, `super`) are not supported, and will cause a + /// panic. + #[track_caller] + pub fn new_raw(string: &str, span: Span) -> Self { + Ident::_new(imp::Ident::new_raw_checked(string, span.inner)) + } + + /// Returns the span of this `Ident`. + pub fn span(&self) -> Span { + Span::_new(self.inner.span()) + } + + /// Configures the span of this `Ident`, possibly changing its hygiene + /// context. + pub fn set_span(&mut self, span: Span) { + self.inner.set_span(span.inner); + } +} + +impl PartialEq for Ident { + fn eq(&self, other: &Ident) -> bool { + self.inner == other.inner + } +} + +impl PartialEq for Ident +where + T: ?Sized + AsRef, +{ + fn eq(&self, other: &T) -> bool { + self.inner == other + } +} + +impl Eq for Ident {} + +impl PartialOrd for Ident { + fn partial_cmp(&self, other: &Ident) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Ident { + fn cmp(&self, other: &Ident) -> Ordering { + self.to_string().cmp(&other.to_string()) + } +} + +impl Hash for Ident { + fn hash(&self, hasher: &mut H) { + self.to_string().hash(hasher); + } +} + +/// Prints the identifier as a string that should be losslessly convertible back +/// into the same identifier. +impl Display for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.inner, f) + } +} + +impl Debug for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.inner, f) + } +} + +/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`), +/// byte character (`b'a'`), an integer or floating point number with or without +/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`). +/// +/// Boolean literals like `true` and `false` do not belong here, they are +/// `Ident`s. +#[derive(Clone)] +pub struct Literal { + inner: imp::Literal, + _marker: ProcMacroAutoTraits, +} + +macro_rules! suffixed_int_literals { + ($($name:ident => $kind:ident,)*) => ($( + /// Creates a new suffixed integer literal with the specified value. + /// + /// This function will create an integer like `1u32` where the integer + /// value specified is the first part of the token and the integral is + /// also suffixed at the end. Literals created from negative numbers may + /// not survive roundtrips through `TokenStream` or strings and may be + /// broken into two tokens (`-` and positive literal). + /// + /// Literals created through this method have the `Span::call_site()` + /// span by default, which can be configured with the `set_span` method + /// below. + pub fn $name(n: $kind) -> Literal { + Literal::_new(imp::Literal::$name(n)) + } + )*) +} + +macro_rules! unsuffixed_int_literals { + ($($name:ident => $kind:ident,)*) => ($( + /// Creates a new unsuffixed integer literal with the specified value. + /// + /// This function will create an integer like `1` where the integer + /// value specified is the first part of the token. No suffix is + /// specified on this token, meaning that invocations like + /// `Literal::i8_unsuffixed(1)` are equivalent to + /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers + /// may not survive roundtrips through `TokenStream` or strings and may + /// be broken into two tokens (`-` and positive literal). + /// + /// Literals created through this method have the `Span::call_site()` + /// span by default, which can be configured with the `set_span` method + /// below. + pub fn $name(n: $kind) -> Literal { + Literal::_new(imp::Literal::$name(n)) + } + )*) +} + +impl Literal { + fn _new(inner: imp::Literal) -> Self { + Literal { + inner, + _marker: MARKER, + } + } + + fn _new_fallback(inner: fallback::Literal) -> Self { + Literal { + inner: inner.into(), + _marker: MARKER, + } + } + + suffixed_int_literals! { + u8_suffixed => u8, + u16_suffixed => u16, + u32_suffixed => u32, + u64_suffixed => u64, + u128_suffixed => u128, + usize_suffixed => usize, + i8_suffixed => i8, + i16_suffixed => i16, + i32_suffixed => i32, + i64_suffixed => i64, + i128_suffixed => i128, + isize_suffixed => isize, + } + + unsuffixed_int_literals! { + u8_unsuffixed => u8, + u16_unsuffixed => u16, + u32_unsuffixed => u32, + u64_unsuffixed => u64, + u128_unsuffixed => u128, + usize_unsuffixed => usize, + i8_unsuffixed => i8, + i16_unsuffixed => i16, + i32_unsuffixed => i32, + i64_unsuffixed => i64, + i128_unsuffixed => i128, + isize_unsuffixed => isize, + } + + /// Creates a new unsuffixed floating-point literal. + /// + /// This constructor is similar to those like `Literal::i8_unsuffixed` where + /// the float's value is emitted directly into the token but no suffix is + /// used, so it may be inferred to be a `f64` later in the compiler. + /// Literals created from negative numbers may not survive round-trips + /// through `TokenStream` or strings and may be broken into two tokens (`-` + /// and positive literal). + /// + /// # Panics + /// + /// This function requires that the specified float is finite, for example + /// if it is infinity or NaN this function will panic. + pub fn f64_unsuffixed(f: f64) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f64_unsuffixed(f)) + } + + /// Creates a new suffixed floating-point literal. + /// + /// This constructor will create a literal like `1.0f64` where the value + /// specified is the preceding part of the token and `f64` is the suffix of + /// the token. This token will always be inferred to be an `f64` in the + /// compiler. Literals created from negative numbers may not survive + /// round-trips through `TokenStream` or strings and may be broken into two + /// tokens (`-` and positive literal). + /// + /// # Panics + /// + /// This function requires that the specified float is finite, for example + /// if it is infinity or NaN this function will panic. + pub fn f64_suffixed(f: f64) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f64_suffixed(f)) + } + + /// Creates a new unsuffixed floating-point literal. + /// + /// This constructor is similar to those like `Literal::i8_unsuffixed` where + /// the float's value is emitted directly into the token but no suffix is + /// used, so it may be inferred to be a `f64` later in the compiler. + /// Literals created from negative numbers may not survive round-trips + /// through `TokenStream` or strings and may be broken into two tokens (`-` + /// and positive literal). + /// + /// # Panics + /// + /// This function requires that the specified float is finite, for example + /// if it is infinity or NaN this function will panic. + pub fn f32_unsuffixed(f: f32) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f32_unsuffixed(f)) + } + + /// Creates a new suffixed floating-point literal. + /// + /// This constructor will create a literal like `1.0f32` where the value + /// specified is the preceding part of the token and `f32` is the suffix of + /// the token. This token will always be inferred to be an `f32` in the + /// compiler. Literals created from negative numbers may not survive + /// round-trips through `TokenStream` or strings and may be broken into two + /// tokens (`-` and positive literal). + /// + /// # Panics + /// + /// This function requires that the specified float is finite, for example + /// if it is infinity or NaN this function will panic. + pub fn f32_suffixed(f: f32) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f32_suffixed(f)) + } + + /// String literal. + pub fn string(string: &str) -> Literal { + Literal::_new(imp::Literal::string(string)) + } + + /// Character literal. + pub fn character(ch: char) -> Literal { + Literal::_new(imp::Literal::character(ch)) + } + + /// Byte character literal. + pub fn byte_character(byte: u8) -> Literal { + Literal::_new(imp::Literal::byte_character(byte)) + } + + /// Byte string literal. + pub fn byte_string(bytes: &[u8]) -> Literal { + Literal::_new(imp::Literal::byte_string(bytes)) + } + + /// C string literal. + pub fn c_string(string: &CStr) -> Literal { + Literal::_new(imp::Literal::c_string(string)) + } + + /// Returns the span encompassing this literal. + pub fn span(&self) -> Span { + Span::_new(self.inner.span()) + } + + /// Configures the span associated for this literal. + pub fn set_span(&mut self, span: Span) { + self.inner.set_span(span.inner); + } + + /// Returns a `Span` that is a subset of `self.span()` containing only + /// the source bytes in range `range`. Returns `None` if the would-be + /// trimmed span is outside the bounds of `self`. + /// + /// Warning: the underlying [`proc_macro::Literal::subspan`] method is + /// nightly-only. When called from within a procedural macro not using a + /// nightly compiler, this method will always return `None`. + /// + /// [`proc_macro::Literal::subspan`]: https://doc.rust-lang.org/proc_macro/struct.Literal.html#method.subspan + pub fn subspan>(&self, range: R) -> Option { + self.inner.subspan(range).map(Span::_new) + } + + // Intended for the `quote!` macro to use when constructing a proc-macro2 + // token out of a macro_rules $:literal token, which is already known to be + // a valid literal. This avoids reparsing/validating the literal's string + // representation. This is not public API other than for quote. + #[doc(hidden)] + pub unsafe fn from_str_unchecked(repr: &str) -> Self { + Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) }) + } +} + +impl FromStr for Literal { + type Err = LexError; + + fn from_str(repr: &str) -> Result { + repr.parse().map(Literal::_new).map_err(|inner| LexError { + inner, + _marker: MARKER, + }) + } +} + +impl Debug for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.inner, f) + } +} + +impl Display for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.inner, f) + } +} + +/// Public implementation details for the `TokenStream` type, such as iterators. +pub mod token_stream { + use crate::marker::{ProcMacroAutoTraits, MARKER}; + use crate::{imp, TokenTree}; + use core::fmt::{self, Debug}; + + pub use crate::TokenStream; + + /// An iterator over `TokenStream`'s `TokenTree`s. + /// + /// The iteration is "shallow", e.g. the iterator doesn't recurse into + /// delimited groups, and returns whole groups as token trees. + #[derive(Clone)] + pub struct IntoIter { + inner: imp::TokenTreeIter, + _marker: ProcMacroAutoTraits, + } + + impl Iterator for IntoIter { + type Item = TokenTree; + + fn next(&mut self) -> Option { + self.inner.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } + } + + impl Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("TokenStream ")?; + f.debug_list().entries(self.clone()).finish() + } + } + + impl IntoIterator for TokenStream { + type Item = TokenTree; + type IntoIter = IntoIter; + + fn into_iter(self) -> IntoIter { + IntoIter { + inner: self.inner.into_iter(), + _marker: MARKER, + } + } + } +} diff --git a/bitbox02-bt/vendor/proc-macro2/src/location.rs b/bitbox02-bt/vendor/proc-macro2/src/location.rs new file mode 100644 index 0000000..7190e2d --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/location.rs @@ -0,0 +1,29 @@ +use core::cmp::Ordering; + +/// A line-column pair representing the start or end of a `Span`. +/// +/// This type is semver exempt and not exposed by default. +#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct LineColumn { + /// The 1-indexed line in the source file on which the span starts or ends + /// (inclusive). + pub line: usize, + /// The 0-indexed column (in UTF-8 characters) in the source file on which + /// the span starts or ends (inclusive). + pub column: usize, +} + +impl Ord for LineColumn { + fn cmp(&self, other: &Self) -> Ordering { + self.line + .cmp(&other.line) + .then(self.column.cmp(&other.column)) + } +} + +impl PartialOrd for LineColumn { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} diff --git a/bitbox02-bt/vendor/proc-macro2/src/marker.rs b/bitbox02-bt/vendor/proc-macro2/src/marker.rs new file mode 100644 index 0000000..23b94ce --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/marker.rs @@ -0,0 +1,17 @@ +use alloc::rc::Rc; +use core::marker::PhantomData; +use core::panic::{RefUnwindSafe, UnwindSafe}; + +// Zero sized marker with the correct set of autotrait impls we want all proc +// macro types to have. +#[derive(Copy, Clone)] +#[cfg_attr( + all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)), + derive(PartialEq, Eq) +)] +pub(crate) struct ProcMacroAutoTraits(PhantomData>); + +pub(crate) const MARKER: ProcMacroAutoTraits = ProcMacroAutoTraits(PhantomData); + +impl UnwindSafe for ProcMacroAutoTraits {} +impl RefUnwindSafe for ProcMacroAutoTraits {} diff --git a/bitbox02-bt/vendor/proc-macro2/src/parse.rs b/bitbox02-bt/vendor/proc-macro2/src/parse.rs new file mode 100644 index 0000000..07239bc --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/parse.rs @@ -0,0 +1,996 @@ +use crate::fallback::{ + self, is_ident_continue, is_ident_start, Group, LexError, Literal, Span, TokenStream, + TokenStreamBuilder, +}; +use crate::{Delimiter, Punct, Spacing, TokenTree}; +use core::char; +use core::str::{Bytes, CharIndices, Chars}; + +#[derive(Copy, Clone, Eq, PartialEq)] +pub(crate) struct Cursor<'a> { + pub rest: &'a str, + #[cfg(span_locations)] + pub off: u32, +} + +impl<'a> Cursor<'a> { + pub fn advance(&self, bytes: usize) -> Cursor<'a> { + let (_front, rest) = self.rest.split_at(bytes); + Cursor { + rest, + #[cfg(span_locations)] + off: self.off + _front.chars().count() as u32, + } + } + + pub fn starts_with(&self, s: &str) -> bool { + self.rest.starts_with(s) + } + + pub fn starts_with_char(&self, ch: char) -> bool { + self.rest.starts_with(ch) + } + + pub fn starts_with_fn(&self, f: Pattern) -> bool + where + Pattern: FnMut(char) -> bool, + { + self.rest.starts_with(f) + } + + pub fn is_empty(&self) -> bool { + self.rest.is_empty() + } + + fn len(&self) -> usize { + self.rest.len() + } + + fn as_bytes(&self) -> &'a [u8] { + self.rest.as_bytes() + } + + fn bytes(&self) -> Bytes<'a> { + self.rest.bytes() + } + + fn chars(&self) -> Chars<'a> { + self.rest.chars() + } + + fn char_indices(&self) -> CharIndices<'a> { + self.rest.char_indices() + } + + fn parse(&self, tag: &str) -> Result, Reject> { + if self.starts_with(tag) { + Ok(self.advance(tag.len())) + } else { + Err(Reject) + } + } +} + +pub(crate) struct Reject; +type PResult<'a, O> = Result<(Cursor<'a>, O), Reject>; + +fn skip_whitespace(input: Cursor) -> Cursor { + let mut s = input; + + while !s.is_empty() { + let byte = s.as_bytes()[0]; + if byte == b'/' { + if s.starts_with("//") + && (!s.starts_with("///") || s.starts_with("////")) + && !s.starts_with("//!") + { + let (cursor, _) = take_until_newline_or_eof(s); + s = cursor; + continue; + } else if s.starts_with("/**/") { + s = s.advance(4); + continue; + } else if s.starts_with("/*") + && (!s.starts_with("/**") || s.starts_with("/***")) + && !s.starts_with("/*!") + { + match block_comment(s) { + Ok((rest, _)) => { + s = rest; + continue; + } + Err(Reject) => return s, + } + } + } + match byte { + b' ' | 0x09..=0x0d => { + s = s.advance(1); + continue; + } + b if b.is_ascii() => {} + _ => { + let ch = s.chars().next().unwrap(); + if is_whitespace(ch) { + s = s.advance(ch.len_utf8()); + continue; + } + } + } + return s; + } + s +} + +fn block_comment(input: Cursor) -> PResult<&str> { + if !input.starts_with("/*") { + return Err(Reject); + } + + let mut depth = 0usize; + let bytes = input.as_bytes(); + let mut i = 0usize; + let upper = bytes.len() - 1; + + while i < upper { + if bytes[i] == b'/' && bytes[i + 1] == b'*' { + depth += 1; + i += 1; // eat '*' + } else if bytes[i] == b'*' && bytes[i + 1] == b'/' { + depth -= 1; + if depth == 0 { + return Ok((input.advance(i + 2), &input.rest[..i + 2])); + } + i += 1; // eat '/' + } + i += 1; + } + + Err(Reject) +} + +fn is_whitespace(ch: char) -> bool { + // Rust treats left-to-right mark and right-to-left mark as whitespace + ch.is_whitespace() || ch == '\u{200e}' || ch == '\u{200f}' +} + +fn word_break(input: Cursor) -> Result { + match input.chars().next() { + Some(ch) if is_ident_continue(ch) => Err(Reject), + Some(_) | None => Ok(input), + } +} + +// Rustc's representation of a macro expansion error in expression position or +// type position. +const ERROR: &str = "(/*ERROR*/)"; + +pub(crate) fn token_stream(mut input: Cursor) -> Result { + let mut trees = TokenStreamBuilder::new(); + let mut stack = Vec::new(); + + loop { + input = skip_whitespace(input); + + if let Ok((rest, ())) = doc_comment(input, &mut trees) { + input = rest; + continue; + } + + #[cfg(span_locations)] + let lo = input.off; + + let first = match input.bytes().next() { + Some(first) => first, + None => match stack.last() { + None => return Ok(trees.build()), + #[cfg(span_locations)] + Some((lo, _frame)) => { + return Err(LexError { + span: Span { lo: *lo, hi: *lo }, + }) + } + #[cfg(not(span_locations))] + Some(_frame) => return Err(LexError { span: Span {} }), + }, + }; + + if let Some(open_delimiter) = match first { + b'(' if !input.starts_with(ERROR) => Some(Delimiter::Parenthesis), + b'[' => Some(Delimiter::Bracket), + b'{' => Some(Delimiter::Brace), + _ => None, + } { + input = input.advance(1); + let frame = (open_delimiter, trees); + #[cfg(span_locations)] + let frame = (lo, frame); + stack.push(frame); + trees = TokenStreamBuilder::new(); + } else if let Some(close_delimiter) = match first { + b')' => Some(Delimiter::Parenthesis), + b']' => Some(Delimiter::Bracket), + b'}' => Some(Delimiter::Brace), + _ => None, + } { + let frame = match stack.pop() { + Some(frame) => frame, + None => return Err(lex_error(input)), + }; + #[cfg(span_locations)] + let (lo, frame) = frame; + let (open_delimiter, outer) = frame; + if open_delimiter != close_delimiter { + return Err(lex_error(input)); + } + input = input.advance(1); + let mut g = Group::new(open_delimiter, trees.build()); + g.set_span(Span { + #[cfg(span_locations)] + lo, + #[cfg(span_locations)] + hi: input.off, + }); + trees = outer; + trees.push_token_from_parser(TokenTree::Group(crate::Group::_new_fallback(g))); + } else { + let (rest, mut tt) = match leaf_token(input) { + Ok((rest, tt)) => (rest, tt), + Err(Reject) => return Err(lex_error(input)), + }; + tt.set_span(crate::Span::_new_fallback(Span { + #[cfg(span_locations)] + lo, + #[cfg(span_locations)] + hi: rest.off, + })); + trees.push_token_from_parser(tt); + input = rest; + } + } +} + +fn lex_error(cursor: Cursor) -> LexError { + #[cfg(not(span_locations))] + let _ = cursor; + LexError { + span: Span { + #[cfg(span_locations)] + lo: cursor.off, + #[cfg(span_locations)] + hi: cursor.off, + }, + } +} + +fn leaf_token(input: Cursor) -> PResult { + if let Ok((input, l)) = literal(input) { + // must be parsed before ident + Ok((input, TokenTree::Literal(crate::Literal::_new_fallback(l)))) + } else if let Ok((input, p)) = punct(input) { + Ok((input, TokenTree::Punct(p))) + } else if let Ok((input, i)) = ident(input) { + Ok((input, TokenTree::Ident(i))) + } else if input.starts_with(ERROR) { + let rest = input.advance(ERROR.len()); + let repr = crate::Literal::_new_fallback(Literal::_new(ERROR.to_owned())); + Ok((rest, TokenTree::Literal(repr))) + } else { + Err(Reject) + } +} + +fn ident(input: Cursor) -> PResult { + if [ + "r\"", "r#\"", "r##", "b\"", "b\'", "br\"", "br#", "c\"", "cr\"", "cr#", + ] + .iter() + .any(|prefix| input.starts_with(prefix)) + { + Err(Reject) + } else { + ident_any(input) + } +} + +fn ident_any(input: Cursor) -> PResult { + let raw = input.starts_with("r#"); + let rest = input.advance((raw as usize) << 1); + + let (rest, sym) = ident_not_raw(rest)?; + + if !raw { + let ident = crate::Ident::_new(crate::imp::Ident::new_unchecked( + sym, + fallback::Span::call_site(), + )); + return Ok((rest, ident)); + } + + match sym { + "_" | "super" | "self" | "Self" | "crate" => return Err(Reject), + _ => {} + } + + let ident = crate::Ident::_new(crate::imp::Ident::new_raw_unchecked( + sym, + fallback::Span::call_site(), + )); + Ok((rest, ident)) +} + +fn ident_not_raw(input: Cursor) -> PResult<&str> { + let mut chars = input.char_indices(); + + match chars.next() { + Some((_, ch)) if is_ident_start(ch) => {} + _ => return Err(Reject), + } + + let mut end = input.len(); + for (i, ch) in chars { + if !is_ident_continue(ch) { + end = i; + break; + } + } + + Ok((input.advance(end), &input.rest[..end])) +} + +pub(crate) fn literal(input: Cursor) -> PResult { + let rest = literal_nocapture(input)?; + let end = input.len() - rest.len(); + Ok((rest, Literal::_new(input.rest[..end].to_string()))) +} + +fn literal_nocapture(input: Cursor) -> Result { + if let Ok(ok) = string(input) { + Ok(ok) + } else if let Ok(ok) = byte_string(input) { + Ok(ok) + } else if let Ok(ok) = c_string(input) { + Ok(ok) + } else if let Ok(ok) = byte(input) { + Ok(ok) + } else if let Ok(ok) = character(input) { + Ok(ok) + } else if let Ok(ok) = float(input) { + Ok(ok) + } else if let Ok(ok) = int(input) { + Ok(ok) + } else { + Err(Reject) + } +} + +fn literal_suffix(input: Cursor) -> Cursor { + match ident_not_raw(input) { + Ok((input, _)) => input, + Err(Reject) => input, + } +} + +fn string(input: Cursor) -> Result { + if let Ok(input) = input.parse("\"") { + cooked_string(input) + } else if let Ok(input) = input.parse("r") { + raw_string(input) + } else { + Err(Reject) + } +} + +fn cooked_string(mut input: Cursor) -> Result { + let mut chars = input.char_indices(); + + while let Some((i, ch)) = chars.next() { + match ch { + '"' => { + let input = input.advance(i + 1); + return Ok(literal_suffix(input)); + } + '\r' => match chars.next() { + Some((_, '\n')) => {} + _ => break, + }, + '\\' => match chars.next() { + Some((_, 'x')) => { + backslash_x_char(&mut chars)?; + } + Some((_, 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0')) => {} + Some((_, 'u')) => { + backslash_u(&mut chars)?; + } + Some((newline, ch @ ('\n' | '\r'))) => { + input = input.advance(newline + 1); + trailing_backslash(&mut input, ch as u8)?; + chars = input.char_indices(); + } + _ => break, + }, + _ch => {} + } + } + Err(Reject) +} + +fn raw_string(input: Cursor) -> Result { + let (input, delimiter) = delimiter_of_raw_string(input)?; + let mut bytes = input.bytes().enumerate(); + while let Some((i, byte)) = bytes.next() { + match byte { + b'"' if input.rest[i + 1..].starts_with(delimiter) => { + let rest = input.advance(i + 1 + delimiter.len()); + return Ok(literal_suffix(rest)); + } + b'\r' => match bytes.next() { + Some((_, b'\n')) => {} + _ => break, + }, + _ => {} + } + } + Err(Reject) +} + +fn byte_string(input: Cursor) -> Result { + if let Ok(input) = input.parse("b\"") { + cooked_byte_string(input) + } else if let Ok(input) = input.parse("br") { + raw_byte_string(input) + } else { + Err(Reject) + } +} + +fn cooked_byte_string(mut input: Cursor) -> Result { + let mut bytes = input.bytes().enumerate(); + while let Some((offset, b)) = bytes.next() { + match b { + b'"' => { + let input = input.advance(offset + 1); + return Ok(literal_suffix(input)); + } + b'\r' => match bytes.next() { + Some((_, b'\n')) => {} + _ => break, + }, + b'\\' => match bytes.next() { + Some((_, b'x')) => { + backslash_x_byte(&mut bytes)?; + } + Some((_, b'n' | b'r' | b't' | b'\\' | b'0' | b'\'' | b'"')) => {} + Some((newline, b @ (b'\n' | b'\r'))) => { + input = input.advance(newline + 1); + trailing_backslash(&mut input, b)?; + bytes = input.bytes().enumerate(); + } + _ => break, + }, + b if b.is_ascii() => {} + _ => break, + } + } + Err(Reject) +} + +fn delimiter_of_raw_string(input: Cursor) -> PResult<&str> { + for (i, byte) in input.bytes().enumerate() { + match byte { + b'"' => { + if i > 255 { + // https://github.com/rust-lang/rust/pull/95251 + return Err(Reject); + } + return Ok((input.advance(i + 1), &input.rest[..i])); + } + b'#' => {} + _ => break, + } + } + Err(Reject) +} + +fn raw_byte_string(input: Cursor) -> Result { + let (input, delimiter) = delimiter_of_raw_string(input)?; + let mut bytes = input.bytes().enumerate(); + while let Some((i, byte)) = bytes.next() { + match byte { + b'"' if input.rest[i + 1..].starts_with(delimiter) => { + let rest = input.advance(i + 1 + delimiter.len()); + return Ok(literal_suffix(rest)); + } + b'\r' => match bytes.next() { + Some((_, b'\n')) => {} + _ => break, + }, + other => { + if !other.is_ascii() { + break; + } + } + } + } + Err(Reject) +} + +fn c_string(input: Cursor) -> Result { + if let Ok(input) = input.parse("c\"") { + cooked_c_string(input) + } else if let Ok(input) = input.parse("cr") { + raw_c_string(input) + } else { + Err(Reject) + } +} + +fn raw_c_string(input: Cursor) -> Result { + let (input, delimiter) = delimiter_of_raw_string(input)?; + let mut bytes = input.bytes().enumerate(); + while let Some((i, byte)) = bytes.next() { + match byte { + b'"' if input.rest[i + 1..].starts_with(delimiter) => { + let rest = input.advance(i + 1 + delimiter.len()); + return Ok(literal_suffix(rest)); + } + b'\r' => match bytes.next() { + Some((_, b'\n')) => {} + _ => break, + }, + b'\0' => break, + _ => {} + } + } + Err(Reject) +} + +fn cooked_c_string(mut input: Cursor) -> Result { + let mut chars = input.char_indices(); + + while let Some((i, ch)) = chars.next() { + match ch { + '"' => { + let input = input.advance(i + 1); + return Ok(literal_suffix(input)); + } + '\r' => match chars.next() { + Some((_, '\n')) => {} + _ => break, + }, + '\\' => match chars.next() { + Some((_, 'x')) => { + backslash_x_nonzero(&mut chars)?; + } + Some((_, 'n' | 'r' | 't' | '\\' | '\'' | '"')) => {} + Some((_, 'u')) => { + if backslash_u(&mut chars)? == '\0' { + break; + } + } + Some((newline, ch @ ('\n' | '\r'))) => { + input = input.advance(newline + 1); + trailing_backslash(&mut input, ch as u8)?; + chars = input.char_indices(); + } + _ => break, + }, + '\0' => break, + _ch => {} + } + } + Err(Reject) +} + +fn byte(input: Cursor) -> Result { + let input = input.parse("b'")?; + let mut bytes = input.bytes().enumerate(); + let ok = match bytes.next().map(|(_, b)| b) { + Some(b'\\') => match bytes.next().map(|(_, b)| b) { + Some(b'x') => backslash_x_byte(&mut bytes).is_ok(), + Some(b'n' | b'r' | b't' | b'\\' | b'0' | b'\'' | b'"') => true, + _ => false, + }, + b => b.is_some(), + }; + if !ok { + return Err(Reject); + } + let (offset, _) = bytes.next().ok_or(Reject)?; + if !input.chars().as_str().is_char_boundary(offset) { + return Err(Reject); + } + let input = input.advance(offset).parse("'")?; + Ok(literal_suffix(input)) +} + +fn character(input: Cursor) -> Result { + let input = input.parse("'")?; + let mut chars = input.char_indices(); + let ok = match chars.next().map(|(_, ch)| ch) { + Some('\\') => match chars.next().map(|(_, ch)| ch) { + Some('x') => backslash_x_char(&mut chars).is_ok(), + Some('u') => backslash_u(&mut chars).is_ok(), + Some('n' | 'r' | 't' | '\\' | '0' | '\'' | '"') => true, + _ => false, + }, + ch => ch.is_some(), + }; + if !ok { + return Err(Reject); + } + let (idx, _) = chars.next().ok_or(Reject)?; + let input = input.advance(idx).parse("'")?; + Ok(literal_suffix(input)) +} + +macro_rules! next_ch { + ($chars:ident @ $pat:pat) => { + match $chars.next() { + Some((_, ch)) => match ch { + $pat => ch, + _ => return Err(Reject), + }, + None => return Err(Reject), + } + }; +} + +fn backslash_x_char(chars: &mut I) -> Result<(), Reject> +where + I: Iterator, +{ + next_ch!(chars @ '0'..='7'); + next_ch!(chars @ '0'..='9' | 'a'..='f' | 'A'..='F'); + Ok(()) +} + +fn backslash_x_byte(chars: &mut I) -> Result<(), Reject> +where + I: Iterator, +{ + next_ch!(chars @ b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F'); + next_ch!(chars @ b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F'); + Ok(()) +} + +fn backslash_x_nonzero(chars: &mut I) -> Result<(), Reject> +where + I: Iterator, +{ + let first = next_ch!(chars @ '0'..='9' | 'a'..='f' | 'A'..='F'); + let second = next_ch!(chars @ '0'..='9' | 'a'..='f' | 'A'..='F'); + if first == '0' && second == '0' { + Err(Reject) + } else { + Ok(()) + } +} + +fn backslash_u(chars: &mut I) -> Result +where + I: Iterator, +{ + next_ch!(chars @ '{'); + let mut value = 0; + let mut len = 0; + for (_, ch) in chars { + let digit = match ch { + '0'..='9' => ch as u8 - b'0', + 'a'..='f' => 10 + ch as u8 - b'a', + 'A'..='F' => 10 + ch as u8 - b'A', + '_' if len > 0 => continue, + '}' if len > 0 => return char::from_u32(value).ok_or(Reject), + _ => break, + }; + if len == 6 { + break; + } + value *= 0x10; + value += u32::from(digit); + len += 1; + } + Err(Reject) +} + +fn trailing_backslash(input: &mut Cursor, mut last: u8) -> Result<(), Reject> { + let mut whitespace = input.bytes().enumerate(); + loop { + if last == b'\r' && whitespace.next().map_or(true, |(_, b)| b != b'\n') { + return Err(Reject); + } + match whitespace.next() { + Some((_, b @ (b' ' | b'\t' | b'\n' | b'\r'))) => { + last = b; + } + Some((offset, _)) => { + *input = input.advance(offset); + return Ok(()); + } + None => return Err(Reject), + } + } +} + +fn float(input: Cursor) -> Result { + let mut rest = float_digits(input)?; + if let Some(ch) = rest.chars().next() { + if is_ident_start(ch) { + rest = ident_not_raw(rest)?.0; + } + } + word_break(rest) +} + +fn float_digits(input: Cursor) -> Result { + let mut chars = input.chars().peekable(); + match chars.next() { + Some(ch) if '0' <= ch && ch <= '9' => {} + _ => return Err(Reject), + } + + let mut len = 1; + let mut has_dot = false; + let mut has_exp = false; + while let Some(&ch) = chars.peek() { + match ch { + '0'..='9' | '_' => { + chars.next(); + len += 1; + } + '.' => { + if has_dot { + break; + } + chars.next(); + if chars + .peek() + .map_or(false, |&ch| ch == '.' || is_ident_start(ch)) + { + return Err(Reject); + } + len += 1; + has_dot = true; + } + 'e' | 'E' => { + chars.next(); + len += 1; + has_exp = true; + break; + } + _ => break, + } + } + + if !(has_dot || has_exp) { + return Err(Reject); + } + + if has_exp { + let token_before_exp = if has_dot { + Ok(input.advance(len - 1)) + } else { + Err(Reject) + }; + let mut has_sign = false; + let mut has_exp_value = false; + while let Some(&ch) = chars.peek() { + match ch { + '+' | '-' => { + if has_exp_value { + break; + } + if has_sign { + return token_before_exp; + } + chars.next(); + len += 1; + has_sign = true; + } + '0'..='9' => { + chars.next(); + len += 1; + has_exp_value = true; + } + '_' => { + chars.next(); + len += 1; + } + _ => break, + } + } + if !has_exp_value { + return token_before_exp; + } + } + + Ok(input.advance(len)) +} + +fn int(input: Cursor) -> Result { + let mut rest = digits(input)?; + if let Some(ch) = rest.chars().next() { + if is_ident_start(ch) { + rest = ident_not_raw(rest)?.0; + } + } + word_break(rest) +} + +fn digits(mut input: Cursor) -> Result { + let base = if input.starts_with("0x") { + input = input.advance(2); + 16 + } else if input.starts_with("0o") { + input = input.advance(2); + 8 + } else if input.starts_with("0b") { + input = input.advance(2); + 2 + } else { + 10 + }; + + let mut len = 0; + let mut empty = true; + for b in input.bytes() { + match b { + b'0'..=b'9' => { + let digit = (b - b'0') as u64; + if digit >= base { + return Err(Reject); + } + } + b'a'..=b'f' => { + let digit = 10 + (b - b'a') as u64; + if digit >= base { + break; + } + } + b'A'..=b'F' => { + let digit = 10 + (b - b'A') as u64; + if digit >= base { + break; + } + } + b'_' => { + if empty && base == 10 { + return Err(Reject); + } + len += 1; + continue; + } + _ => break, + }; + len += 1; + empty = false; + } + if empty { + Err(Reject) + } else { + Ok(input.advance(len)) + } +} + +fn punct(input: Cursor) -> PResult { + let (rest, ch) = punct_char(input)?; + if ch == '\'' { + if ident_any(rest)?.0.starts_with_char('\'') { + Err(Reject) + } else { + Ok((rest, Punct::new('\'', Spacing::Joint))) + } + } else { + let kind = match punct_char(rest) { + Ok(_) => Spacing::Joint, + Err(Reject) => Spacing::Alone, + }; + Ok((rest, Punct::new(ch, kind))) + } +} + +fn punct_char(input: Cursor) -> PResult { + if input.starts_with("//") || input.starts_with("/*") { + // Do not accept `/` of a comment as a punct. + return Err(Reject); + } + + let mut chars = input.chars(); + let first = match chars.next() { + Some(ch) => ch, + None => { + return Err(Reject); + } + }; + let recognized = "~!@#$%^&*-=+|;:,<.>/?'"; + if recognized.contains(first) { + Ok((input.advance(first.len_utf8()), first)) + } else { + Err(Reject) + } +} + +fn doc_comment<'a>(input: Cursor<'a>, trees: &mut TokenStreamBuilder) -> PResult<'a, ()> { + #[cfg(span_locations)] + let lo = input.off; + let (rest, (comment, inner)) = doc_comment_contents(input)?; + let fallback_span = Span { + #[cfg(span_locations)] + lo, + #[cfg(span_locations)] + hi: rest.off, + }; + let span = crate::Span::_new_fallback(fallback_span); + + let mut scan_for_bare_cr = comment; + while let Some(cr) = scan_for_bare_cr.find('\r') { + let rest = &scan_for_bare_cr[cr + 1..]; + if !rest.starts_with('\n') { + return Err(Reject); + } + scan_for_bare_cr = rest; + } + + let mut pound = Punct::new('#', Spacing::Alone); + pound.set_span(span); + trees.push_token_from_parser(TokenTree::Punct(pound)); + + if inner { + let mut bang = Punct::new('!', Spacing::Alone); + bang.set_span(span); + trees.push_token_from_parser(TokenTree::Punct(bang)); + } + + let doc_ident = crate::Ident::_new(crate::imp::Ident::new_unchecked("doc", fallback_span)); + let mut equal = Punct::new('=', Spacing::Alone); + equal.set_span(span); + let mut literal = crate::Literal::string(comment); + literal.set_span(span); + let mut bracketed = TokenStreamBuilder::with_capacity(3); + bracketed.push_token_from_parser(TokenTree::Ident(doc_ident)); + bracketed.push_token_from_parser(TokenTree::Punct(equal)); + bracketed.push_token_from_parser(TokenTree::Literal(literal)); + let group = Group::new(Delimiter::Bracket, bracketed.build()); + let mut group = crate::Group::_new_fallback(group); + group.set_span(span); + trees.push_token_from_parser(TokenTree::Group(group)); + + Ok((rest, ())) +} + +fn doc_comment_contents(input: Cursor) -> PResult<(&str, bool)> { + if input.starts_with("//!") { + let input = input.advance(3); + let (input, s) = take_until_newline_or_eof(input); + Ok((input, (s, true))) + } else if input.starts_with("/*!") { + let (input, s) = block_comment(input)?; + Ok((input, (&s[3..s.len() - 2], true))) + } else if input.starts_with("///") { + let input = input.advance(3); + if input.starts_with_char('/') { + return Err(Reject); + } + let (input, s) = take_until_newline_or_eof(input); + Ok((input, (s, false))) + } else if input.starts_with("/**") && !input.rest[3..].starts_with('*') { + let (input, s) = block_comment(input)?; + Ok((input, (&s[3..s.len() - 2], false))) + } else { + Err(Reject) + } +} + +fn take_until_newline_or_eof(input: Cursor) -> (Cursor, &str) { + let chars = input.char_indices(); + + for (i, ch) in chars { + if ch == '\n' { + return (input.advance(i), &input.rest[..i]); + } else if ch == '\r' && input.rest[i + 1..].starts_with('\n') { + return (input.advance(i + 1), &input.rest[..i]); + } + } + + (input.advance(input.len()), input.rest) +} diff --git a/bitbox02-bt/vendor/proc-macro2/src/rcvec.rs b/bitbox02-bt/vendor/proc-macro2/src/rcvec.rs new file mode 100644 index 0000000..37955af --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/rcvec.rs @@ -0,0 +1,145 @@ +use alloc::rc::Rc; +use alloc::vec; +use core::mem; +use core::panic::RefUnwindSafe; +use core::slice; + +pub(crate) struct RcVec { + inner: Rc>, +} + +pub(crate) struct RcVecBuilder { + inner: Vec, +} + +pub(crate) struct RcVecMut<'a, T> { + inner: &'a mut Vec, +} + +#[derive(Clone)] +pub(crate) struct RcVecIntoIter { + inner: vec::IntoIter, +} + +impl RcVec { + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + pub fn len(&self) -> usize { + self.inner.len() + } + + pub fn iter(&self) -> slice::Iter { + self.inner.iter() + } + + pub fn make_mut(&mut self) -> RcVecMut + where + T: Clone, + { + RcVecMut { + inner: Rc::make_mut(&mut self.inner), + } + } + + pub fn get_mut(&mut self) -> Option> { + let inner = Rc::get_mut(&mut self.inner)?; + Some(RcVecMut { inner }) + } + + pub fn make_owned(mut self) -> RcVecBuilder + where + T: Clone, + { + let vec = if let Some(owned) = Rc::get_mut(&mut self.inner) { + mem::take(owned) + } else { + Vec::clone(&self.inner) + }; + RcVecBuilder { inner: vec } + } +} + +impl RcVecBuilder { + pub fn new() -> Self { + RcVecBuilder { inner: Vec::new() } + } + + pub fn with_capacity(cap: usize) -> Self { + RcVecBuilder { + inner: Vec::with_capacity(cap), + } + } + + pub fn push(&mut self, element: T) { + self.inner.push(element); + } + + pub fn extend(&mut self, iter: impl IntoIterator) { + self.inner.extend(iter); + } + + pub fn as_mut(&mut self) -> RcVecMut { + RcVecMut { + inner: &mut self.inner, + } + } + + pub fn build(self) -> RcVec { + RcVec { + inner: Rc::new(self.inner), + } + } +} + +impl<'a, T> RcVecMut<'a, T> { + pub fn push(&mut self, element: T) { + self.inner.push(element); + } + + pub fn extend(&mut self, iter: impl IntoIterator) { + self.inner.extend(iter); + } + + pub fn pop(&mut self) -> Option { + self.inner.pop() + } + + pub fn as_mut(&mut self) -> RcVecMut { + RcVecMut { inner: self.inner } + } +} + +impl Clone for RcVec { + fn clone(&self) -> Self { + RcVec { + inner: Rc::clone(&self.inner), + } + } +} + +impl IntoIterator for RcVecBuilder { + type Item = T; + type IntoIter = RcVecIntoIter; + + fn into_iter(self) -> Self::IntoIter { + RcVecIntoIter { + inner: self.inner.into_iter(), + } + } +} + +impl Iterator for RcVecIntoIter { + type Item = T; + + fn next(&mut self) -> Option { + self.inner.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +impl RefUnwindSafe for RcVec where T: RefUnwindSafe {} diff --git a/bitbox02-bt/vendor/proc-macro2/src/wrapper.rs b/bitbox02-bt/vendor/proc-macro2/src/wrapper.rs new file mode 100644 index 0000000..87e348d --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/src/wrapper.rs @@ -0,0 +1,993 @@ +use crate::detection::inside_proc_macro; +#[cfg(span_locations)] +use crate::location::LineColumn; +use crate::{fallback, Delimiter, Punct, Spacing, TokenTree}; +use core::fmt::{self, Debug, Display}; +#[cfg(span_locations)] +use core::ops::Range; +use core::ops::RangeBounds; +use core::str::FromStr; +use std::ffi::CStr; +use std::panic; +#[cfg(super_unstable)] +use std::path::PathBuf; + +#[derive(Clone)] +pub(crate) enum TokenStream { + Compiler(DeferredTokenStream), + Fallback(fallback::TokenStream), +} + +// Work around https://github.com/rust-lang/rust/issues/65080. +// In `impl Extend for TokenStream` which is used heavily by quote, +// we hold on to the appended tokens and do proc_macro::TokenStream::extend as +// late as possible to batch together consecutive uses of the Extend impl. +#[derive(Clone)] +pub(crate) struct DeferredTokenStream { + stream: proc_macro::TokenStream, + extra: Vec, +} + +pub(crate) enum LexError { + Compiler(proc_macro::LexError), + Fallback(fallback::LexError), + + // Rustc was supposed to return a LexError, but it panicked instead. + // https://github.com/rust-lang/rust/issues/58736 + CompilerPanic, +} + +#[cold] +fn mismatch(line: u32) -> ! { + #[cfg(procmacro2_backtrace)] + { + let backtrace = std::backtrace::Backtrace::force_capture(); + panic!("compiler/fallback mismatch #{}\n\n{}", line, backtrace) + } + #[cfg(not(procmacro2_backtrace))] + { + panic!("compiler/fallback mismatch #{}", line) + } +} + +impl DeferredTokenStream { + fn new(stream: proc_macro::TokenStream) -> Self { + DeferredTokenStream { + stream, + extra: Vec::new(), + } + } + + fn is_empty(&self) -> bool { + self.stream.is_empty() && self.extra.is_empty() + } + + fn evaluate_now(&mut self) { + // If-check provides a fast short circuit for the common case of `extra` + // being empty, which saves a round trip over the proc macro bridge. + // Improves macro expansion time in winrt by 6% in debug mode. + if !self.extra.is_empty() { + self.stream.extend(self.extra.drain(..)); + } + } + + fn into_token_stream(mut self) -> proc_macro::TokenStream { + self.evaluate_now(); + self.stream + } +} + +impl TokenStream { + pub fn new() -> Self { + if inside_proc_macro() { + TokenStream::Compiler(DeferredTokenStream::new(proc_macro::TokenStream::new())) + } else { + TokenStream::Fallback(fallback::TokenStream::new()) + } + } + + pub fn is_empty(&self) -> bool { + match self { + TokenStream::Compiler(tts) => tts.is_empty(), + TokenStream::Fallback(tts) => tts.is_empty(), + } + } + + fn unwrap_nightly(self) -> proc_macro::TokenStream { + match self { + TokenStream::Compiler(s) => s.into_token_stream(), + TokenStream::Fallback(_) => mismatch(line!()), + } + } + + fn unwrap_stable(self) -> fallback::TokenStream { + match self { + TokenStream::Compiler(_) => mismatch(line!()), + TokenStream::Fallback(s) => s, + } + } +} + +impl FromStr for TokenStream { + type Err = LexError; + + fn from_str(src: &str) -> Result { + if inside_proc_macro() { + Ok(TokenStream::Compiler(DeferredTokenStream::new( + proc_macro_parse(src)?, + ))) + } else { + Ok(TokenStream::Fallback(src.parse()?)) + } + } +} + +// Work around https://github.com/rust-lang/rust/issues/58736. +fn proc_macro_parse(src: &str) -> Result { + let result = panic::catch_unwind(|| src.parse().map_err(LexError::Compiler)); + result.unwrap_or_else(|_| Err(LexError::CompilerPanic)) +} + +impl Display for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + TokenStream::Compiler(tts) => Display::fmt(&tts.clone().into_token_stream(), f), + TokenStream::Fallback(tts) => Display::fmt(tts, f), + } + } +} + +impl From for TokenStream { + fn from(inner: proc_macro::TokenStream) -> Self { + TokenStream::Compiler(DeferredTokenStream::new(inner)) + } +} + +impl From for proc_macro::TokenStream { + fn from(inner: TokenStream) -> Self { + match inner { + TokenStream::Compiler(inner) => inner.into_token_stream(), + TokenStream::Fallback(inner) => inner.to_string().parse().unwrap(), + } + } +} + +impl From for TokenStream { + fn from(inner: fallback::TokenStream) -> Self { + TokenStream::Fallback(inner) + } +} + +// Assumes inside_proc_macro(). +fn into_compiler_token(token: TokenTree) -> proc_macro::TokenTree { + match token { + TokenTree::Group(tt) => tt.inner.unwrap_nightly().into(), + TokenTree::Punct(tt) => { + let spacing = match tt.spacing() { + Spacing::Joint => proc_macro::Spacing::Joint, + Spacing::Alone => proc_macro::Spacing::Alone, + }; + let mut punct = proc_macro::Punct::new(tt.as_char(), spacing); + punct.set_span(tt.span().inner.unwrap_nightly()); + punct.into() + } + TokenTree::Ident(tt) => tt.inner.unwrap_nightly().into(), + TokenTree::Literal(tt) => tt.inner.unwrap_nightly().into(), + } +} + +impl From for TokenStream { + fn from(token: TokenTree) -> Self { + if inside_proc_macro() { + TokenStream::Compiler(DeferredTokenStream::new(into_compiler_token(token).into())) + } else { + TokenStream::Fallback(token.into()) + } + } +} + +impl FromIterator for TokenStream { + fn from_iter>(trees: I) -> Self { + if inside_proc_macro() { + TokenStream::Compiler(DeferredTokenStream::new( + trees.into_iter().map(into_compiler_token).collect(), + )) + } else { + TokenStream::Fallback(trees.into_iter().collect()) + } + } +} + +impl FromIterator for TokenStream { + fn from_iter>(streams: I) -> Self { + let mut streams = streams.into_iter(); + match streams.next() { + Some(TokenStream::Compiler(mut first)) => { + first.evaluate_now(); + first.stream.extend(streams.map(|s| match s { + TokenStream::Compiler(s) => s.into_token_stream(), + TokenStream::Fallback(_) => mismatch(line!()), + })); + TokenStream::Compiler(first) + } + Some(TokenStream::Fallback(mut first)) => { + first.extend(streams.map(|s| match s { + TokenStream::Fallback(s) => s, + TokenStream::Compiler(_) => mismatch(line!()), + })); + TokenStream::Fallback(first) + } + None => TokenStream::new(), + } + } +} + +impl Extend for TokenStream { + fn extend>(&mut self, stream: I) { + match self { + TokenStream::Compiler(tts) => { + // Here is the reason for DeferredTokenStream. + for token in stream { + tts.extra.push(into_compiler_token(token)); + } + } + TokenStream::Fallback(tts) => tts.extend(stream), + } + } +} + +impl Extend for TokenStream { + fn extend>(&mut self, streams: I) { + match self { + TokenStream::Compiler(tts) => { + tts.evaluate_now(); + tts.stream + .extend(streams.into_iter().map(TokenStream::unwrap_nightly)); + } + TokenStream::Fallback(tts) => { + tts.extend(streams.into_iter().map(TokenStream::unwrap_stable)); + } + } + } +} + +impl Debug for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + TokenStream::Compiler(tts) => Debug::fmt(&tts.clone().into_token_stream(), f), + TokenStream::Fallback(tts) => Debug::fmt(tts, f), + } + } +} + +impl LexError { + pub(crate) fn span(&self) -> Span { + match self { + LexError::Compiler(_) | LexError::CompilerPanic => Span::call_site(), + LexError::Fallback(e) => Span::Fallback(e.span()), + } + } +} + +impl From for LexError { + fn from(e: proc_macro::LexError) -> Self { + LexError::Compiler(e) + } +} + +impl From for LexError { + fn from(e: fallback::LexError) -> Self { + LexError::Fallback(e) + } +} + +impl Debug for LexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + LexError::Compiler(e) => Debug::fmt(e, f), + LexError::Fallback(e) => Debug::fmt(e, f), + LexError::CompilerPanic => { + let fallback = fallback::LexError::call_site(); + Debug::fmt(&fallback, f) + } + } + } +} + +impl Display for LexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + LexError::Compiler(e) => Display::fmt(e, f), + LexError::Fallback(e) => Display::fmt(e, f), + LexError::CompilerPanic => { + let fallback = fallback::LexError::call_site(); + Display::fmt(&fallback, f) + } + } + } +} + +#[derive(Clone)] +pub(crate) enum TokenTreeIter { + Compiler(proc_macro::token_stream::IntoIter), + Fallback(fallback::TokenTreeIter), +} + +impl IntoIterator for TokenStream { + type Item = TokenTree; + type IntoIter = TokenTreeIter; + + fn into_iter(self) -> TokenTreeIter { + match self { + TokenStream::Compiler(tts) => { + TokenTreeIter::Compiler(tts.into_token_stream().into_iter()) + } + TokenStream::Fallback(tts) => TokenTreeIter::Fallback(tts.into_iter()), + } + } +} + +impl Iterator for TokenTreeIter { + type Item = TokenTree; + + fn next(&mut self) -> Option { + let token = match self { + TokenTreeIter::Compiler(iter) => iter.next()?, + TokenTreeIter::Fallback(iter) => return iter.next(), + }; + Some(match token { + proc_macro::TokenTree::Group(tt) => crate::Group::_new(Group::Compiler(tt)).into(), + proc_macro::TokenTree::Punct(tt) => { + let spacing = match tt.spacing() { + proc_macro::Spacing::Joint => Spacing::Joint, + proc_macro::Spacing::Alone => Spacing::Alone, + }; + let mut o = Punct::new(tt.as_char(), spacing); + o.set_span(crate::Span::_new(Span::Compiler(tt.span()))); + o.into() + } + proc_macro::TokenTree::Ident(s) => crate::Ident::_new(Ident::Compiler(s)).into(), + proc_macro::TokenTree::Literal(l) => crate::Literal::_new(Literal::Compiler(l)).into(), + }) + } + + fn size_hint(&self) -> (usize, Option) { + match self { + TokenTreeIter::Compiler(tts) => tts.size_hint(), + TokenTreeIter::Fallback(tts) => tts.size_hint(), + } + } +} + +#[derive(Clone, PartialEq, Eq)] +#[cfg(super_unstable)] +pub(crate) enum SourceFile { + Compiler(proc_macro::SourceFile), + Fallback(fallback::SourceFile), +} + +#[cfg(super_unstable)] +impl SourceFile { + fn nightly(sf: proc_macro::SourceFile) -> Self { + SourceFile::Compiler(sf) + } + + /// Get the path to this source file as a string. + pub fn path(&self) -> PathBuf { + match self { + SourceFile::Compiler(a) => a.path(), + SourceFile::Fallback(a) => a.path(), + } + } + + pub fn is_real(&self) -> bool { + match self { + SourceFile::Compiler(a) => a.is_real(), + SourceFile::Fallback(a) => a.is_real(), + } + } +} + +#[cfg(super_unstable)] +impl Debug for SourceFile { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + SourceFile::Compiler(a) => Debug::fmt(a, f), + SourceFile::Fallback(a) => Debug::fmt(a, f), + } + } +} + +#[derive(Copy, Clone)] +pub(crate) enum Span { + Compiler(proc_macro::Span), + Fallback(fallback::Span), +} + +impl Span { + pub fn call_site() -> Self { + if inside_proc_macro() { + Span::Compiler(proc_macro::Span::call_site()) + } else { + Span::Fallback(fallback::Span::call_site()) + } + } + + pub fn mixed_site() -> Self { + if inside_proc_macro() { + Span::Compiler(proc_macro::Span::mixed_site()) + } else { + Span::Fallback(fallback::Span::mixed_site()) + } + } + + #[cfg(super_unstable)] + pub fn def_site() -> Self { + if inside_proc_macro() { + Span::Compiler(proc_macro::Span::def_site()) + } else { + Span::Fallback(fallback::Span::def_site()) + } + } + + pub fn resolved_at(&self, other: Span) -> Span { + match (self, other) { + (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.resolved_at(b)), + (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.resolved_at(b)), + (Span::Compiler(_), Span::Fallback(_)) => mismatch(line!()), + (Span::Fallback(_), Span::Compiler(_)) => mismatch(line!()), + } + } + + pub fn located_at(&self, other: Span) -> Span { + match (self, other) { + (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.located_at(b)), + (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.located_at(b)), + (Span::Compiler(_), Span::Fallback(_)) => mismatch(line!()), + (Span::Fallback(_), Span::Compiler(_)) => mismatch(line!()), + } + } + + pub fn unwrap(self) -> proc_macro::Span { + match self { + Span::Compiler(s) => s, + Span::Fallback(_) => panic!("proc_macro::Span is only available in procedural macros"), + } + } + + #[cfg(super_unstable)] + pub fn source_file(&self) -> SourceFile { + match self { + Span::Compiler(s) => SourceFile::nightly(s.source_file()), + Span::Fallback(s) => SourceFile::Fallback(s.source_file()), + } + } + + #[cfg(span_locations)] + pub fn byte_range(&self) -> Range { + match self { + #[cfg(proc_macro_span)] + Span::Compiler(s) => s.byte_range(), + #[cfg(not(proc_macro_span))] + Span::Compiler(_) => 0..0, + Span::Fallback(s) => s.byte_range(), + } + } + + #[cfg(span_locations)] + pub fn start(&self) -> LineColumn { + match self { + Span::Compiler(_) => LineColumn { line: 0, column: 0 }, + Span::Fallback(s) => s.start(), + } + } + + #[cfg(span_locations)] + pub fn end(&self) -> LineColumn { + match self { + Span::Compiler(_) => LineColumn { line: 0, column: 0 }, + Span::Fallback(s) => s.end(), + } + } + + pub fn join(&self, other: Span) -> Option { + let ret = match (self, other) { + #[cfg(proc_macro_span)] + (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.join(b)?), + (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.join(b)?), + _ => return None, + }; + Some(ret) + } + + #[cfg(super_unstable)] + pub fn eq(&self, other: &Span) -> bool { + match (self, other) { + (Span::Compiler(a), Span::Compiler(b)) => a.eq(b), + (Span::Fallback(a), Span::Fallback(b)) => a.eq(b), + _ => false, + } + } + + pub fn source_text(&self) -> Option { + match self { + #[cfg(not(no_source_text))] + Span::Compiler(s) => s.source_text(), + #[cfg(no_source_text)] + Span::Compiler(_) => None, + Span::Fallback(s) => s.source_text(), + } + } + + fn unwrap_nightly(self) -> proc_macro::Span { + match self { + Span::Compiler(s) => s, + Span::Fallback(_) => mismatch(line!()), + } + } +} + +impl From for crate::Span { + fn from(proc_span: proc_macro::Span) -> Self { + crate::Span::_new(Span::Compiler(proc_span)) + } +} + +impl From for Span { + fn from(inner: fallback::Span) -> Self { + Span::Fallback(inner) + } +} + +impl Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Span::Compiler(s) => Debug::fmt(s, f), + Span::Fallback(s) => Debug::fmt(s, f), + } + } +} + +pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) { + match span { + Span::Compiler(s) => { + debug.field("span", &s); + } + Span::Fallback(s) => fallback::debug_span_field_if_nontrivial(debug, s), + } +} + +#[derive(Clone)] +pub(crate) enum Group { + Compiler(proc_macro::Group), + Fallback(fallback::Group), +} + +impl Group { + pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { + match stream { + TokenStream::Compiler(tts) => { + let delimiter = match delimiter { + Delimiter::Parenthesis => proc_macro::Delimiter::Parenthesis, + Delimiter::Bracket => proc_macro::Delimiter::Bracket, + Delimiter::Brace => proc_macro::Delimiter::Brace, + Delimiter::None => proc_macro::Delimiter::None, + }; + Group::Compiler(proc_macro::Group::new(delimiter, tts.into_token_stream())) + } + TokenStream::Fallback(stream) => { + Group::Fallback(fallback::Group::new(delimiter, stream)) + } + } + } + + pub fn delimiter(&self) -> Delimiter { + match self { + Group::Compiler(g) => match g.delimiter() { + proc_macro::Delimiter::Parenthesis => Delimiter::Parenthesis, + proc_macro::Delimiter::Bracket => Delimiter::Bracket, + proc_macro::Delimiter::Brace => Delimiter::Brace, + proc_macro::Delimiter::None => Delimiter::None, + }, + Group::Fallback(g) => g.delimiter(), + } + } + + pub fn stream(&self) -> TokenStream { + match self { + Group::Compiler(g) => TokenStream::Compiler(DeferredTokenStream::new(g.stream())), + Group::Fallback(g) => TokenStream::Fallback(g.stream()), + } + } + + pub fn span(&self) -> Span { + match self { + Group::Compiler(g) => Span::Compiler(g.span()), + Group::Fallback(g) => Span::Fallback(g.span()), + } + } + + pub fn span_open(&self) -> Span { + match self { + Group::Compiler(g) => Span::Compiler(g.span_open()), + Group::Fallback(g) => Span::Fallback(g.span_open()), + } + } + + pub fn span_close(&self) -> Span { + match self { + Group::Compiler(g) => Span::Compiler(g.span_close()), + Group::Fallback(g) => Span::Fallback(g.span_close()), + } + } + + pub fn set_span(&mut self, span: Span) { + match (self, span) { + (Group::Compiler(g), Span::Compiler(s)) => g.set_span(s), + (Group::Fallback(g), Span::Fallback(s)) => g.set_span(s), + (Group::Compiler(_), Span::Fallback(_)) => mismatch(line!()), + (Group::Fallback(_), Span::Compiler(_)) => mismatch(line!()), + } + } + + fn unwrap_nightly(self) -> proc_macro::Group { + match self { + Group::Compiler(g) => g, + Group::Fallback(_) => mismatch(line!()), + } + } +} + +impl From for Group { + fn from(g: fallback::Group) -> Self { + Group::Fallback(g) + } +} + +impl Display for Group { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Group::Compiler(group) => Display::fmt(group, formatter), + Group::Fallback(group) => Display::fmt(group, formatter), + } + } +} + +impl Debug for Group { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Group::Compiler(group) => Debug::fmt(group, formatter), + Group::Fallback(group) => Debug::fmt(group, formatter), + } + } +} + +#[derive(Clone)] +pub(crate) enum Ident { + Compiler(proc_macro::Ident), + Fallback(fallback::Ident), +} + +impl Ident { + #[track_caller] + pub fn new_checked(string: &str, span: Span) -> Self { + match span { + Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new(string, s)), + Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_checked(string, s)), + } + } + + pub fn new_unchecked(string: &str, span: fallback::Span) -> Self { + Ident::Fallback(fallback::Ident::new_unchecked(string, span)) + } + + #[track_caller] + pub fn new_raw_checked(string: &str, span: Span) -> Self { + match span { + Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new_raw(string, s)), + Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_raw_checked(string, s)), + } + } + + pub fn new_raw_unchecked(string: &str, span: fallback::Span) -> Self { + Ident::Fallback(fallback::Ident::new_raw_unchecked(string, span)) + } + + pub fn span(&self) -> Span { + match self { + Ident::Compiler(t) => Span::Compiler(t.span()), + Ident::Fallback(t) => Span::Fallback(t.span()), + } + } + + pub fn set_span(&mut self, span: Span) { + match (self, span) { + (Ident::Compiler(t), Span::Compiler(s)) => t.set_span(s), + (Ident::Fallback(t), Span::Fallback(s)) => t.set_span(s), + (Ident::Compiler(_), Span::Fallback(_)) => mismatch(line!()), + (Ident::Fallback(_), Span::Compiler(_)) => mismatch(line!()), + } + } + + fn unwrap_nightly(self) -> proc_macro::Ident { + match self { + Ident::Compiler(s) => s, + Ident::Fallback(_) => mismatch(line!()), + } + } +} + +impl PartialEq for Ident { + fn eq(&self, other: &Ident) -> bool { + match (self, other) { + (Ident::Compiler(t), Ident::Compiler(o)) => t.to_string() == o.to_string(), + (Ident::Fallback(t), Ident::Fallback(o)) => t == o, + (Ident::Compiler(_), Ident::Fallback(_)) => mismatch(line!()), + (Ident::Fallback(_), Ident::Compiler(_)) => mismatch(line!()), + } + } +} + +impl PartialEq for Ident +where + T: ?Sized + AsRef, +{ + fn eq(&self, other: &T) -> bool { + let other = other.as_ref(); + match self { + Ident::Compiler(t) => t.to_string() == other, + Ident::Fallback(t) => t == other, + } + } +} + +impl Display for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Ident::Compiler(t) => Display::fmt(t, f), + Ident::Fallback(t) => Display::fmt(t, f), + } + } +} + +impl Debug for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Ident::Compiler(t) => Debug::fmt(t, f), + Ident::Fallback(t) => Debug::fmt(t, f), + } + } +} + +#[derive(Clone)] +pub(crate) enum Literal { + Compiler(proc_macro::Literal), + Fallback(fallback::Literal), +} + +macro_rules! suffixed_numbers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::$name(n)) + } else { + Literal::Fallback(fallback::Literal::$name(n)) + } + } + )*) +} + +macro_rules! unsuffixed_integers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::$name(n)) + } else { + Literal::Fallback(fallback::Literal::$name(n)) + } + } + )*) +} + +impl Literal { + pub unsafe fn from_str_unchecked(repr: &str) -> Self { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::from_str(repr).expect("invalid literal")) + } else { + Literal::Fallback(unsafe { fallback::Literal::from_str_unchecked(repr) }) + } + } + + suffixed_numbers! { + u8_suffixed => u8, + u16_suffixed => u16, + u32_suffixed => u32, + u64_suffixed => u64, + u128_suffixed => u128, + usize_suffixed => usize, + i8_suffixed => i8, + i16_suffixed => i16, + i32_suffixed => i32, + i64_suffixed => i64, + i128_suffixed => i128, + isize_suffixed => isize, + + f32_suffixed => f32, + f64_suffixed => f64, + } + + unsuffixed_integers! { + u8_unsuffixed => u8, + u16_unsuffixed => u16, + u32_unsuffixed => u32, + u64_unsuffixed => u64, + u128_unsuffixed => u128, + usize_unsuffixed => usize, + i8_unsuffixed => i8, + i16_unsuffixed => i16, + i32_unsuffixed => i32, + i64_unsuffixed => i64, + i128_unsuffixed => i128, + isize_unsuffixed => isize, + } + + pub fn f32_unsuffixed(f: f32) -> Literal { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::f32_unsuffixed(f)) + } else { + Literal::Fallback(fallback::Literal::f32_unsuffixed(f)) + } + } + + pub fn f64_unsuffixed(f: f64) -> Literal { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::f64_unsuffixed(f)) + } else { + Literal::Fallback(fallback::Literal::f64_unsuffixed(f)) + } + } + + pub fn string(string: &str) -> Literal { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::string(string)) + } else { + Literal::Fallback(fallback::Literal::string(string)) + } + } + + pub fn character(ch: char) -> Literal { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::character(ch)) + } else { + Literal::Fallback(fallback::Literal::character(ch)) + } + } + + pub fn byte_character(byte: u8) -> Literal { + if inside_proc_macro() { + Literal::Compiler({ + #[cfg(not(no_literal_byte_character))] + { + proc_macro::Literal::byte_character(byte) + } + + #[cfg(no_literal_byte_character)] + { + let fallback = fallback::Literal::byte_character(byte); + fallback.repr.parse::().unwrap() + } + }) + } else { + Literal::Fallback(fallback::Literal::byte_character(byte)) + } + } + + pub fn byte_string(bytes: &[u8]) -> Literal { + if inside_proc_macro() { + Literal::Compiler(proc_macro::Literal::byte_string(bytes)) + } else { + Literal::Fallback(fallback::Literal::byte_string(bytes)) + } + } + + pub fn c_string(string: &CStr) -> Literal { + if inside_proc_macro() { + Literal::Compiler({ + #[cfg(not(no_literal_c_string))] + { + proc_macro::Literal::c_string(string) + } + + #[cfg(no_literal_c_string)] + { + let fallback = fallback::Literal::c_string(string); + fallback.repr.parse::().unwrap() + } + }) + } else { + Literal::Fallback(fallback::Literal::c_string(string)) + } + } + + pub fn span(&self) -> Span { + match self { + Literal::Compiler(lit) => Span::Compiler(lit.span()), + Literal::Fallback(lit) => Span::Fallback(lit.span()), + } + } + + pub fn set_span(&mut self, span: Span) { + match (self, span) { + (Literal::Compiler(lit), Span::Compiler(s)) => lit.set_span(s), + (Literal::Fallback(lit), Span::Fallback(s)) => lit.set_span(s), + (Literal::Compiler(_), Span::Fallback(_)) => mismatch(line!()), + (Literal::Fallback(_), Span::Compiler(_)) => mismatch(line!()), + } + } + + pub fn subspan>(&self, range: R) -> Option { + match self { + #[cfg(proc_macro_span)] + Literal::Compiler(lit) => lit.subspan(range).map(Span::Compiler), + #[cfg(not(proc_macro_span))] + Literal::Compiler(_lit) => None, + Literal::Fallback(lit) => lit.subspan(range).map(Span::Fallback), + } + } + + fn unwrap_nightly(self) -> proc_macro::Literal { + match self { + Literal::Compiler(s) => s, + Literal::Fallback(_) => mismatch(line!()), + } + } +} + +impl From for Literal { + fn from(s: fallback::Literal) -> Self { + Literal::Fallback(s) + } +} + +impl FromStr for Literal { + type Err = LexError; + + fn from_str(repr: &str) -> Result { + if inside_proc_macro() { + let literal = proc_macro::Literal::from_str(repr)?; + Ok(Literal::Compiler(literal)) + } else { + let literal = fallback::Literal::from_str(repr)?; + Ok(Literal::Fallback(literal)) + } + } +} + +impl Display for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Literal::Compiler(t) => Display::fmt(t, f), + Literal::Fallback(t) => Display::fmt(t, f), + } + } +} + +impl Debug for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Literal::Compiler(t) => Debug::fmt(t, f), + Literal::Fallback(t) => Debug::fmt(t, f), + } + } +} + +#[cfg(span_locations)] +pub(crate) fn invalidate_current_thread_spans() { + if inside_proc_macro() { + panic!( + "proc_macro2::extra::invalidate_current_thread_spans is not available in procedural macros" + ); + } else { + crate::fallback::invalidate_current_thread_spans(); + } +} diff --git a/bitbox02-bt/vendor/proc-macro2/tests/comments.rs b/bitbox02-bt/vendor/proc-macro2/tests/comments.rs new file mode 100644 index 0000000..4f7236d --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/tests/comments.rs @@ -0,0 +1,105 @@ +#![allow(clippy::assertions_on_result_states)] + +use proc_macro2::{Delimiter, Literal, Spacing, TokenStream, TokenTree}; + +// #[doc = "..."] -> "..." +fn lit_of_outer_doc_comment(tokens: &TokenStream) -> Literal { + lit_of_doc_comment(tokens, false) +} + +// #![doc = "..."] -> "..." +fn lit_of_inner_doc_comment(tokens: &TokenStream) -> Literal { + lit_of_doc_comment(tokens, true) +} + +fn lit_of_doc_comment(tokens: &TokenStream, inner: bool) -> Literal { + let mut iter = tokens.clone().into_iter(); + match iter.next().unwrap() { + TokenTree::Punct(punct) => { + assert_eq!(punct.as_char(), '#'); + assert_eq!(punct.spacing(), Spacing::Alone); + } + _ => panic!("wrong token {:?}", tokens), + } + if inner { + match iter.next().unwrap() { + TokenTree::Punct(punct) => { + assert_eq!(punct.as_char(), '!'); + assert_eq!(punct.spacing(), Spacing::Alone); + } + _ => panic!("wrong token {:?}", tokens), + } + } + iter = match iter.next().unwrap() { + TokenTree::Group(group) => { + assert_eq!(group.delimiter(), Delimiter::Bracket); + assert!(iter.next().is_none(), "unexpected token {:?}", tokens); + group.stream().into_iter() + } + _ => panic!("wrong token {:?}", tokens), + }; + match iter.next().unwrap() { + TokenTree::Ident(ident) => assert_eq!(ident.to_string(), "doc"), + _ => panic!("wrong token {:?}", tokens), + } + match iter.next().unwrap() { + TokenTree::Punct(punct) => { + assert_eq!(punct.as_char(), '='); + assert_eq!(punct.spacing(), Spacing::Alone); + } + _ => panic!("wrong token {:?}", tokens), + } + match iter.next().unwrap() { + TokenTree::Literal(literal) => { + assert!(iter.next().is_none(), "unexpected token {:?}", tokens); + literal + } + _ => panic!("wrong token {:?}", tokens), + } +} + +#[test] +fn closed_immediately() { + let stream = "/**/".parse::().unwrap(); + let tokens = stream.into_iter().collect::>(); + assert!(tokens.is_empty(), "not empty -- {:?}", tokens); +} + +#[test] +fn incomplete() { + assert!("/*/".parse::().is_err()); +} + +#[test] +fn lit() { + let stream = "/// doc".parse::().unwrap(); + let lit = lit_of_outer_doc_comment(&stream); + assert_eq!(lit.to_string(), "\" doc\""); + + let stream = "//! doc".parse::().unwrap(); + let lit = lit_of_inner_doc_comment(&stream); + assert_eq!(lit.to_string(), "\" doc\""); + + let stream = "/** doc */".parse::().unwrap(); + let lit = lit_of_outer_doc_comment(&stream); + assert_eq!(lit.to_string(), "\" doc \""); + + let stream = "/*! doc */".parse::().unwrap(); + let lit = lit_of_inner_doc_comment(&stream); + assert_eq!(lit.to_string(), "\" doc \""); +} + +#[test] +fn carriage_return() { + let stream = "///\r\n".parse::().unwrap(); + let lit = lit_of_outer_doc_comment(&stream); + assert_eq!(lit.to_string(), "\"\""); + + let stream = "/**\r\n*/".parse::().unwrap(); + let lit = lit_of_outer_doc_comment(&stream); + assert_eq!(lit.to_string(), "\"\\r\\n\""); + + "///\r".parse::().unwrap_err(); + "///\r \n".parse::().unwrap_err(); + "/**\r \n*/".parse::().unwrap_err(); +} diff --git a/bitbox02-bt/vendor/proc-macro2/tests/features.rs b/bitbox02-bt/vendor/proc-macro2/tests/features.rs new file mode 100644 index 0000000..073f6e6 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/tests/features.rs @@ -0,0 +1,8 @@ +#[test] +#[ignore] +fn make_sure_no_proc_macro() { + assert!( + !cfg!(feature = "proc-macro"), + "still compiled with proc_macro?" + ); +} diff --git a/bitbox02-bt/vendor/proc-macro2/tests/marker.rs b/bitbox02-bt/vendor/proc-macro2/tests/marker.rs new file mode 100644 index 0000000..99f64c0 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/tests/marker.rs @@ -0,0 +1,100 @@ +#![allow(clippy::extra_unused_type_parameters)] + +use proc_macro2::{ + Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree, +}; + +macro_rules! assert_impl { + ($ty:ident is $($marker:ident) and +) => { + #[test] + #[allow(non_snake_case)] + fn $ty() { + fn assert_implemented() {} + assert_implemented::<$ty>(); + } + }; + + ($ty:ident is not $($marker:ident) or +) => { + #[test] + #[allow(non_snake_case)] + fn $ty() { + $( + { + // Implemented for types that implement $marker. + #[allow(dead_code)] + trait IsNotImplemented { + fn assert_not_implemented() {} + } + impl IsNotImplemented for T {} + + // Implemented for the type being tested. + trait IsImplemented { + fn assert_not_implemented() {} + } + impl IsImplemented for $ty {} + + // If $ty does not implement $marker, there is no ambiguity + // in the following trait method call. + <$ty>::assert_not_implemented(); + } + )+ + } + }; +} + +assert_impl!(Delimiter is Send and Sync); +assert_impl!(Spacing is Send and Sync); + +assert_impl!(Group is not Send or Sync); +assert_impl!(Ident is not Send or Sync); +assert_impl!(LexError is not Send or Sync); +assert_impl!(Literal is not Send or Sync); +assert_impl!(Punct is not Send or Sync); +assert_impl!(Span is not Send or Sync); +assert_impl!(TokenStream is not Send or Sync); +assert_impl!(TokenTree is not Send or Sync); + +#[cfg(procmacro2_semver_exempt)] +mod semver_exempt { + use proc_macro2::{LineColumn, SourceFile}; + + assert_impl!(LineColumn is Send and Sync); + + assert_impl!(SourceFile is not Send or Sync); +} + +mod unwind_safe { + use proc_macro2::{ + Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree, + }; + #[cfg(procmacro2_semver_exempt)] + use proc_macro2::{LineColumn, SourceFile}; + use std::panic::{RefUnwindSafe, UnwindSafe}; + + macro_rules! assert_unwind_safe { + ($($types:ident)*) => { + $( + assert_impl!($types is UnwindSafe and RefUnwindSafe); + )* + }; + } + + assert_unwind_safe! { + Delimiter + Group + Ident + LexError + Literal + Punct + Spacing + Span + TokenStream + TokenTree + } + + #[cfg(procmacro2_semver_exempt)] + assert_unwind_safe! { + LineColumn + SourceFile + } +} diff --git a/bitbox02-bt/vendor/proc-macro2/tests/test.rs b/bitbox02-bt/vendor/proc-macro2/tests/test.rs new file mode 100644 index 0000000..0d7c88d --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/tests/test.rs @@ -0,0 +1,905 @@ +#![allow( + clippy::assertions_on_result_states, + clippy::items_after_statements, + clippy::needless_pass_by_value, + clippy::needless_raw_string_hashes, + clippy::non_ascii_literal, + clippy::octal_escapes +)] + +use proc_macro2::{Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::ffi::CStr; +use std::iter; +use std::str::{self, FromStr}; + +#[test] +fn idents() { + assert_eq!( + Ident::new("String", Span::call_site()).to_string(), + "String" + ); + assert_eq!(Ident::new("fn", Span::call_site()).to_string(), "fn"); + assert_eq!(Ident::new("_", Span::call_site()).to_string(), "_"); +} + +#[test] +fn raw_idents() { + assert_eq!( + Ident::new_raw("String", Span::call_site()).to_string(), + "r#String" + ); + assert_eq!(Ident::new_raw("fn", Span::call_site()).to_string(), "r#fn"); +} + +#[test] +#[should_panic(expected = "`r#_` cannot be a raw identifier")] +fn ident_raw_underscore() { + Ident::new_raw("_", Span::call_site()); +} + +#[test] +#[should_panic(expected = "`r#super` cannot be a raw identifier")] +fn ident_raw_reserved() { + Ident::new_raw("super", Span::call_site()); +} + +#[test] +#[should_panic(expected = "Ident is not allowed to be empty; use Option")] +fn ident_empty() { + Ident::new("", Span::call_site()); +} + +#[test] +#[should_panic(expected = "Ident cannot be a number; use Literal instead")] +fn ident_number() { + Ident::new("255", Span::call_site()); +} + +#[test] +#[should_panic(expected = "\"a#\" is not a valid Ident")] +fn ident_invalid() { + Ident::new("a#", Span::call_site()); +} + +#[test] +#[should_panic(expected = "not a valid Ident")] +fn raw_ident_empty() { + Ident::new("r#", Span::call_site()); +} + +#[test] +#[should_panic(expected = "not a valid Ident")] +fn raw_ident_number() { + Ident::new("r#255", Span::call_site()); +} + +#[test] +#[should_panic(expected = "\"r#a#\" is not a valid Ident")] +fn raw_ident_invalid() { + Ident::new("r#a#", Span::call_site()); +} + +#[test] +#[should_panic(expected = "not a valid Ident")] +fn lifetime_empty() { + Ident::new("'", Span::call_site()); +} + +#[test] +#[should_panic(expected = "not a valid Ident")] +fn lifetime_number() { + Ident::new("'255", Span::call_site()); +} + +#[test] +#[should_panic(expected = r#""'a#" is not a valid Ident"#)] +fn lifetime_invalid() { + Ident::new("'a#", Span::call_site()); +} + +#[test] +fn literal_string() { + #[track_caller] + fn assert(literal: Literal, expected: &str) { + assert_eq!(literal.to_string(), expected.trim()); + } + + assert(Literal::string(""), r#" "" "#); + assert(Literal::string("aA"), r#" "aA" "#); + assert(Literal::string("\t"), r#" "\t" "#); + assert(Literal::string("❤"), r#" "❤" "#); + assert(Literal::string("'"), r#" "'" "#); + assert(Literal::string("\""), r#" "\"" "#); + assert(Literal::string("\0"), r#" "\0" "#); + assert(Literal::string("\u{1}"), r#" "\u{1}" "#); + assert( + Literal::string("a\00b\07c\08d\0e\0"), + r#" "a\x000b\x007c\08d\0e\0" "#, + ); + + "\"\\\r\n x\"".parse::().unwrap(); + "\"\\\r\n \rx\"".parse::().unwrap_err(); +} + +#[test] +fn literal_raw_string() { + "r\"\r\n\"".parse::().unwrap(); + + fn raw_string_literal_with_hashes(n: usize) -> String { + let mut literal = String::new(); + literal.push('r'); + literal.extend(iter::repeat('#').take(n)); + literal.push('"'); + literal.push('"'); + literal.extend(iter::repeat('#').take(n)); + literal + } + + raw_string_literal_with_hashes(255) + .parse::() + .unwrap(); + + // https://github.com/rust-lang/rust/pull/95251 + raw_string_literal_with_hashes(256) + .parse::() + .unwrap_err(); +} + +#[test] +fn literal_byte_character() { + #[track_caller] + fn assert(literal: Literal, expected: &str) { + assert_eq!(literal.to_string(), expected.trim()); + } + + assert(Literal::byte_character(b'a'), r#" b'a' "#); + assert(Literal::byte_character(b'\0'), r#" b'\0' "#); + assert(Literal::byte_character(b'\t'), r#" b'\t' "#); + assert(Literal::byte_character(b'\n'), r#" b'\n' "#); + assert(Literal::byte_character(b'\r'), r#" b'\r' "#); + assert(Literal::byte_character(b'\''), r#" b'\'' "#); + assert(Literal::byte_character(b'\\'), r#" b'\\' "#); + assert(Literal::byte_character(b'\x1f'), r#" b'\x1F' "#); + assert(Literal::byte_character(b'"'), r#" b'"' "#); +} + +#[test] +fn literal_byte_string() { + #[track_caller] + fn assert(literal: Literal, expected: &str) { + assert_eq!(literal.to_string(), expected.trim()); + } + + assert(Literal::byte_string(b""), r#" b"" "#); + assert(Literal::byte_string(b"\0"), r#" b"\0" "#); + assert(Literal::byte_string(b"\t"), r#" b"\t" "#); + assert(Literal::byte_string(b"\n"), r#" b"\n" "#); + assert(Literal::byte_string(b"\r"), r#" b"\r" "#); + assert(Literal::byte_string(b"\""), r#" b"\"" "#); + assert(Literal::byte_string(b"\\"), r#" b"\\" "#); + assert(Literal::byte_string(b"\x1f"), r#" b"\x1F" "#); + assert(Literal::byte_string(b"'"), r#" b"'" "#); + assert( + Literal::byte_string(b"a\00b\07c\08d\0e\0"), + r#" b"a\x000b\x007c\08d\0e\0" "#, + ); + + "b\"\\\r\n x\"".parse::().unwrap(); + "b\"\\\r\n \rx\"".parse::().unwrap_err(); + "b\"\\\r\n \u{a0}x\"".parse::().unwrap_err(); + "br\"\u{a0}\"".parse::().unwrap_err(); +} + +#[test] +fn literal_c_string() { + #[track_caller] + fn assert(literal: Literal, expected: &str) { + assert_eq!(literal.to_string(), expected.trim()); + } + + assert(Literal::c_string(<&CStr>::default()), r#" c"" "#); + assert( + Literal::c_string(CStr::from_bytes_with_nul(b"aA\0").unwrap()), + r#" c"aA" "#, + ); + assert( + Literal::c_string(CStr::from_bytes_with_nul(b"aA\0").unwrap()), + r#" c"aA" "#, + ); + assert( + Literal::c_string(CStr::from_bytes_with_nul(b"\t\0").unwrap()), + r#" c"\t" "#, + ); + assert( + Literal::c_string(CStr::from_bytes_with_nul(b"\xE2\x9D\xA4\0").unwrap()), + r#" c"❤" "#, + ); + assert( + Literal::c_string(CStr::from_bytes_with_nul(b"'\0").unwrap()), + r#" c"'" "#, + ); + assert( + Literal::c_string(CStr::from_bytes_with_nul(b"\"\0").unwrap()), + r#" c"\"" "#, + ); + assert( + Literal::c_string(CStr::from_bytes_with_nul(b"\x7F\xFF\xFE\xCC\xB3\0").unwrap()), + r#" c"\u{7f}\xFF\xFE\u{333}" "#, + ); + + let strings = r###" + c"hello\x80我叫\u{1F980}" // from the RFC + cr"\" + cr##"Hello "world"!"## + c"\t\n\r\"\\" + "###; + + let mut tokens = strings.parse::().unwrap().into_iter(); + + for expected in &[ + r#"c"hello\x80我叫\u{1F980}""#, + r#"cr"\""#, + r###"cr##"Hello "world"!"##"###, + r#"c"\t\n\r\"\\""#, + ] { + match tokens.next().unwrap() { + TokenTree::Literal(literal) => { + assert_eq!(literal.to_string(), *expected); + } + unexpected => panic!("unexpected token: {:?}", unexpected), + } + } + + if let Some(unexpected) = tokens.next() { + panic!("unexpected token: {:?}", unexpected); + } + + for invalid in &[r#"c"\0""#, r#"c"\x00""#, r#"c"\u{0}""#, "c\"\0\""] { + if let Ok(unexpected) = invalid.parse::() { + panic!("unexpected token: {:?}", unexpected); + } + } +} + +#[test] +fn literal_character() { + #[track_caller] + fn assert(literal: Literal, expected: &str) { + assert_eq!(literal.to_string(), expected.trim()); + } + + assert(Literal::character('a'), r#" 'a' "#); + assert(Literal::character('\t'), r#" '\t' "#); + assert(Literal::character('❤'), r#" '❤' "#); + assert(Literal::character('\''), r#" '\'' "#); + assert(Literal::character('"'), r#" '"' "#); + assert(Literal::character('\0'), r#" '\0' "#); + assert(Literal::character('\u{1}'), r#" '\u{1}' "#); +} + +#[test] +fn literal_integer() { + #[track_caller] + fn assert(literal: Literal, expected: &str) { + assert_eq!(literal.to_string(), expected); + } + + assert(Literal::u8_suffixed(10), "10u8"); + assert(Literal::u16_suffixed(10), "10u16"); + assert(Literal::u32_suffixed(10), "10u32"); + assert(Literal::u64_suffixed(10), "10u64"); + assert(Literal::u128_suffixed(10), "10u128"); + assert(Literal::usize_suffixed(10), "10usize"); + + assert(Literal::i8_suffixed(10), "10i8"); + assert(Literal::i16_suffixed(10), "10i16"); + assert(Literal::i32_suffixed(10), "10i32"); + assert(Literal::i64_suffixed(10), "10i64"); + assert(Literal::i128_suffixed(10), "10i128"); + assert(Literal::isize_suffixed(10), "10isize"); + + assert(Literal::u8_unsuffixed(10), "10"); + assert(Literal::u16_unsuffixed(10), "10"); + assert(Literal::u32_unsuffixed(10), "10"); + assert(Literal::u64_unsuffixed(10), "10"); + assert(Literal::u128_unsuffixed(10), "10"); + assert(Literal::usize_unsuffixed(10), "10"); + + assert(Literal::i8_unsuffixed(10), "10"); + assert(Literal::i16_unsuffixed(10), "10"); + assert(Literal::i32_unsuffixed(10), "10"); + assert(Literal::i64_unsuffixed(10), "10"); + assert(Literal::i128_unsuffixed(10), "10"); + assert(Literal::isize_unsuffixed(10), "10"); + + assert(Literal::i32_suffixed(-10), "-10i32"); + assert(Literal::i32_unsuffixed(-10), "-10"); +} + +#[test] +fn literal_float() { + #[track_caller] + fn assert(literal: Literal, expected: &str) { + assert_eq!(literal.to_string(), expected); + } + + assert(Literal::f32_suffixed(10.0), "10f32"); + assert(Literal::f32_suffixed(-10.0), "-10f32"); + assert(Literal::f64_suffixed(10.0), "10f64"); + assert(Literal::f64_suffixed(-10.0), "-10f64"); + + assert(Literal::f32_unsuffixed(10.0), "10.0"); + assert(Literal::f32_unsuffixed(-10.0), "-10.0"); + assert(Literal::f64_unsuffixed(10.0), "10.0"); + assert(Literal::f64_unsuffixed(-10.0), "-10.0"); + + assert( + Literal::f64_unsuffixed(1e100), + "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0", + ); +} + +#[test] +fn literal_suffix() { + fn token_count(p: &str) -> usize { + p.parse::().unwrap().into_iter().count() + } + + assert_eq!(token_count("999u256"), 1); + assert_eq!(token_count("999r#u256"), 3); + assert_eq!(token_count("1."), 1); + assert_eq!(token_count("1.f32"), 3); + assert_eq!(token_count("1.0_0"), 1); + assert_eq!(token_count("1._0"), 3); + assert_eq!(token_count("1._m"), 3); + assert_eq!(token_count("\"\"s"), 1); + assert_eq!(token_count("r\"\"r"), 1); + assert_eq!(token_count("r#\"\"#r"), 1); + assert_eq!(token_count("b\"\"b"), 1); + assert_eq!(token_count("br\"\"br"), 1); + assert_eq!(token_count("br#\"\"#br"), 1); + assert_eq!(token_count("c\"\"c"), 1); + assert_eq!(token_count("cr\"\"cr"), 1); + assert_eq!(token_count("cr#\"\"#cr"), 1); + assert_eq!(token_count("'c'c"), 1); + assert_eq!(token_count("b'b'b"), 1); + assert_eq!(token_count("0E"), 1); + assert_eq!(token_count("0o0A"), 1); + assert_eq!(token_count("0E--0"), 4); + assert_eq!(token_count("0.0ECMA"), 1); +} + +#[test] +fn literal_iter_negative() { + let negative_literal = Literal::i32_suffixed(-3); + let tokens = TokenStream::from(TokenTree::Literal(negative_literal)); + let mut iter = tokens.into_iter(); + match iter.next().unwrap() { + TokenTree::Punct(punct) => { + assert_eq!(punct.as_char(), '-'); + assert_eq!(punct.spacing(), Spacing::Alone); + } + unexpected => panic!("unexpected token {:?}", unexpected), + } + match iter.next().unwrap() { + TokenTree::Literal(literal) => { + assert_eq!(literal.to_string(), "3i32"); + } + unexpected => panic!("unexpected token {:?}", unexpected), + } + assert!(iter.next().is_none()); +} + +#[test] +fn literal_parse() { + assert!("1".parse::().is_ok()); + assert!("-1".parse::().is_ok()); + assert!("-1u12".parse::().is_ok()); + assert!("1.0".parse::().is_ok()); + assert!("-1.0".parse::().is_ok()); + assert!("-1.0f12".parse::().is_ok()); + assert!("'a'".parse::().is_ok()); + assert!("\"\n\"".parse::().is_ok()); + assert!("0 1".parse::().is_err()); + assert!(" 0".parse::().is_err()); + assert!("0 ".parse::().is_err()); + assert!("/* comment */0".parse::().is_err()); + assert!("0/* comment */".parse::().is_err()); + assert!("0// comment".parse::().is_err()); + assert!("- 1".parse::().is_err()); + assert!("- 1.0".parse::().is_err()); + assert!("-\"\"".parse::().is_err()); +} + +#[test] +fn literal_span() { + let positive = "0.1".parse::().unwrap(); + let negative = "-0.1".parse::().unwrap(); + let subspan = positive.subspan(1..2); + + #[cfg(not(span_locations))] + { + let _ = negative; + assert!(subspan.is_none()); + } + + #[cfg(span_locations)] + { + assert_eq!(positive.span().start().column, 0); + assert_eq!(positive.span().end().column, 3); + assert_eq!(negative.span().start().column, 0); + assert_eq!(negative.span().end().column, 4); + assert_eq!(subspan.unwrap().source_text().unwrap(), "."); + } + + assert!(positive.subspan(1..4).is_none()); +} + +#[cfg(span_locations)] +#[test] +fn source_text() { + let input = " 𓀕 a z "; + let mut tokens = input + .parse::() + .unwrap() + .into_iter(); + + let first = tokens.next().unwrap(); + assert_eq!("𓀕", first.span().source_text().unwrap()); + + let second = tokens.next().unwrap(); + let third = tokens.next().unwrap(); + assert_eq!("z", third.span().source_text().unwrap()); + assert_eq!("a", second.span().source_text().unwrap()); +} + +#[test] +fn roundtrip() { + fn roundtrip(p: &str) { + println!("parse: {}", p); + let s = p.parse::().unwrap().to_string(); + println!("first: {}", s); + let s2 = s.parse::().unwrap().to_string(); + assert_eq!(s, s2); + } + roundtrip("a"); + roundtrip("<<"); + roundtrip("<<="); + roundtrip( + " + 1 + 1.0 + 1f32 + 2f64 + 1usize + 4isize + 4e10 + 1_000 + 1_0i32 + 8u8 + 9 + 0 + 0xffffffffffffffffffffffffffffffff + 1x + 1u80 + 1f320 + ", + ); + roundtrip("'a"); + roundtrip("'_"); + roundtrip("'static"); + roundtrip(r"'\u{10__FFFF}'"); + roundtrip("\"\\u{10_F0FF__}foo\\u{1_0_0_0__}\""); +} + +#[test] +fn fail() { + fn fail(p: &str) { + if let Ok(s) = p.parse::() { + panic!("should have failed to parse: {}\n{:#?}", p, s); + } + } + fail("' static"); + fail("r#1"); + fail("r#_"); + fail("\"\\u{0000000}\""); // overlong unicode escape (rust allows at most 6 hex digits) + fail("\"\\u{999999}\""); // outside of valid range of char + fail("\"\\u{_0}\""); // leading underscore + fail("\"\\u{}\""); // empty + fail("b\"\r\""); // bare carriage return in byte string + fail("r\"\r\""); // bare carriage return in raw string + fail("\"\\\r \""); // backslash carriage return + fail("'aa'aa"); + fail("br##\"\"#"); + fail("cr##\"\"#"); + fail("\"\\\n\u{85}\r\""); +} + +#[cfg(span_locations)] +#[test] +fn span_test() { + check_spans( + "\ +/// This is a document comment +testing 123 +{ + testing 234 +}", + &[ + (1, 0, 1, 30), // # + (1, 0, 1, 30), // [ ... ] + (1, 0, 1, 30), // doc + (1, 0, 1, 30), // = + (1, 0, 1, 30), // "This is..." + (2, 0, 2, 7), // testing + (2, 8, 2, 11), // 123 + (3, 0, 5, 1), // { ... } + (4, 2, 4, 9), // testing + (4, 10, 4, 13), // 234 + ], + ); +} + +#[cfg(procmacro2_semver_exempt)] +#[test] +fn default_span() { + let start = Span::call_site().start(); + assert_eq!(start.line, 1); + assert_eq!(start.column, 0); + let end = Span::call_site().end(); + assert_eq!(end.line, 1); + assert_eq!(end.column, 0); + let source_file = Span::call_site().source_file(); + assert_eq!(source_file.path().to_string_lossy(), ""); + assert!(!source_file.is_real()); +} + +#[cfg(procmacro2_semver_exempt)] +#[test] +fn span_join() { + let source1 = "aaa\nbbb" + .parse::() + .unwrap() + .into_iter() + .collect::>(); + let source2 = "ccc\nddd" + .parse::() + .unwrap() + .into_iter() + .collect::>(); + + assert!(source1[0].span().source_file() != source2[0].span().source_file()); + assert_eq!( + source1[0].span().source_file(), + source1[1].span().source_file() + ); + + let joined1 = source1[0].span().join(source1[1].span()); + let joined2 = source1[0].span().join(source2[0].span()); + assert!(joined1.is_some()); + assert!(joined2.is_none()); + + let start = joined1.unwrap().start(); + let end = joined1.unwrap().end(); + assert_eq!(start.line, 1); + assert_eq!(start.column, 0); + assert_eq!(end.line, 2); + assert_eq!(end.column, 3); + + assert_eq!( + joined1.unwrap().source_file(), + source1[0].span().source_file() + ); +} + +#[test] +fn no_panic() { + let s = str::from_utf8(b"b\'\xc2\x86 \x00\x00\x00^\"").unwrap(); + assert!(s.parse::().is_err()); +} + +#[test] +fn punct_before_comment() { + let mut tts = TokenStream::from_str("~// comment").unwrap().into_iter(); + match tts.next().unwrap() { + TokenTree::Punct(tt) => { + assert_eq!(tt.as_char(), '~'); + assert_eq!(tt.spacing(), Spacing::Alone); + } + wrong => panic!("wrong token {:?}", wrong), + } +} + +#[test] +fn joint_last_token() { + // This test verifies that we match the behavior of libproc_macro *not* in + // the range nightly-2020-09-06 through nightly-2020-09-10, in which this + // behavior was temporarily broken. + // See https://github.com/rust-lang/rust/issues/76399 + + let joint_punct = Punct::new(':', Spacing::Joint); + let stream = TokenStream::from(TokenTree::Punct(joint_punct)); + let punct = match stream.into_iter().next().unwrap() { + TokenTree::Punct(punct) => punct, + _ => unreachable!(), + }; + assert_eq!(punct.spacing(), Spacing::Joint); +} + +#[test] +fn raw_identifier() { + let mut tts = TokenStream::from_str("r#dyn").unwrap().into_iter(); + match tts.next().unwrap() { + TokenTree::Ident(raw) => assert_eq!("r#dyn", raw.to_string()), + wrong => panic!("wrong token {:?}", wrong), + } + assert!(tts.next().is_none()); +} + +#[test] +fn test_debug_ident() { + let ident = Ident::new("proc_macro", Span::call_site()); + + #[cfg(not(span_locations))] + let expected = "Ident(proc_macro)"; + + #[cfg(span_locations)] + let expected = "Ident { sym: proc_macro }"; + + assert_eq!(expected, format!("{:?}", ident)); +} + +#[test] +fn test_debug_tokenstream() { + let tts = TokenStream::from_str("[a + 1]").unwrap(); + + #[cfg(not(span_locations))] + let expected = "\ +TokenStream [ + Group { + delimiter: Bracket, + stream: TokenStream [ + Ident { + sym: a, + }, + Punct { + char: '+', + spacing: Alone, + }, + Literal { + lit: 1, + }, + ], + }, +]\ + "; + + #[cfg(not(span_locations))] + let expected_before_trailing_commas = "\ +TokenStream [ + Group { + delimiter: Bracket, + stream: TokenStream [ + Ident { + sym: a + }, + Punct { + char: '+', + spacing: Alone + }, + Literal { + lit: 1 + } + ] + } +]\ + "; + + #[cfg(span_locations)] + let expected = "\ +TokenStream [ + Group { + delimiter: Bracket, + stream: TokenStream [ + Ident { + sym: a, + span: bytes(2..3), + }, + Punct { + char: '+', + spacing: Alone, + span: bytes(4..5), + }, + Literal { + lit: 1, + span: bytes(6..7), + }, + ], + span: bytes(1..8), + }, +]\ + "; + + #[cfg(span_locations)] + let expected_before_trailing_commas = "\ +TokenStream [ + Group { + delimiter: Bracket, + stream: TokenStream [ + Ident { + sym: a, + span: bytes(2..3) + }, + Punct { + char: '+', + spacing: Alone, + span: bytes(4..5) + }, + Literal { + lit: 1, + span: bytes(6..7) + } + ], + span: bytes(1..8) + } +]\ + "; + + let actual = format!("{:#?}", tts); + if actual.ends_with(",\n]") { + assert_eq!(expected, actual); + } else { + assert_eq!(expected_before_trailing_commas, actual); + } +} + +#[test] +fn default_tokenstream_is_empty() { + let default_token_stream = ::default(); + + assert!(default_token_stream.is_empty()); +} + +#[test] +fn tokenstream_size_hint() { + let tokens = "a b (c d) e".parse::().unwrap(); + + assert_eq!(tokens.into_iter().size_hint(), (4, Some(4))); +} + +#[test] +fn tuple_indexing() { + // This behavior may change depending on https://github.com/rust-lang/rust/pull/71322 + let mut tokens = "tuple.0.0".parse::().unwrap().into_iter(); + assert_eq!("tuple", tokens.next().unwrap().to_string()); + assert_eq!(".", tokens.next().unwrap().to_string()); + assert_eq!("0.0", tokens.next().unwrap().to_string()); + assert!(tokens.next().is_none()); +} + +#[cfg(span_locations)] +#[test] +fn non_ascii_tokens() { + check_spans("// abc", &[]); + check_spans("// ábc", &[]); + check_spans("// abc x", &[]); + check_spans("// ábc x", &[]); + check_spans("/* abc */ x", &[(1, 10, 1, 11)]); + check_spans("/* ábc */ x", &[(1, 10, 1, 11)]); + check_spans("/* ab\nc */ x", &[(2, 5, 2, 6)]); + check_spans("/* áb\nc */ x", &[(2, 5, 2, 6)]); + check_spans("/*** abc */ x", &[(1, 12, 1, 13)]); + check_spans("/*** ábc */ x", &[(1, 12, 1, 13)]); + check_spans(r#""abc""#, &[(1, 0, 1, 5)]); + check_spans(r#""ábc""#, &[(1, 0, 1, 5)]); + check_spans(r##"r#"abc"#"##, &[(1, 0, 1, 8)]); + check_spans(r##"r#"ábc"#"##, &[(1, 0, 1, 8)]); + check_spans("r#\"a\nc\"#", &[(1, 0, 2, 3)]); + check_spans("r#\"á\nc\"#", &[(1, 0, 2, 3)]); + check_spans("'a'", &[(1, 0, 1, 3)]); + check_spans("'á'", &[(1, 0, 1, 3)]); + check_spans("//! abc", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("//! ábc", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("//! abc\n", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("//! ábc\n", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("/*! abc */", &[(1, 0, 1, 10), (1, 0, 1, 10), (1, 0, 1, 10)]); + check_spans("/*! ábc */", &[(1, 0, 1, 10), (1, 0, 1, 10), (1, 0, 1, 10)]); + check_spans("/*! a\nc */", &[(1, 0, 2, 4), (1, 0, 2, 4), (1, 0, 2, 4)]); + check_spans("/*! á\nc */", &[(1, 0, 2, 4), (1, 0, 2, 4), (1, 0, 2, 4)]); + check_spans("abc", &[(1, 0, 1, 3)]); + check_spans("ábc", &[(1, 0, 1, 3)]); + check_spans("ábć", &[(1, 0, 1, 3)]); + check_spans("abc// foo", &[(1, 0, 1, 3)]); + check_spans("ábc// foo", &[(1, 0, 1, 3)]); + check_spans("ábć// foo", &[(1, 0, 1, 3)]); + check_spans("b\"a\\\n c\"", &[(1, 0, 2, 3)]); +} + +#[cfg(span_locations)] +fn check_spans(p: &str, mut lines: &[(usize, usize, usize, usize)]) { + let ts = p.parse::().unwrap(); + check_spans_internal(ts, &mut lines); + assert!(lines.is_empty(), "leftover ranges: {:?}", lines); +} + +#[cfg(span_locations)] +fn check_spans_internal(ts: TokenStream, lines: &mut &[(usize, usize, usize, usize)]) { + for i in ts { + if let Some((&(sline, scol, eline, ecol), rest)) = lines.split_first() { + *lines = rest; + + let start = i.span().start(); + assert_eq!(start.line, sline, "sline did not match for {}", i); + assert_eq!(start.column, scol, "scol did not match for {}", i); + + let end = i.span().end(); + assert_eq!(end.line, eline, "eline did not match for {}", i); + assert_eq!(end.column, ecol, "ecol did not match for {}", i); + + if let TokenTree::Group(g) = i { + check_spans_internal(g.stream().clone(), lines); + } + } + } +} + +#[test] +fn whitespace() { + // space, horizontal tab, vertical tab, form feed, carriage return, line + // feed, non-breaking space, left-to-right mark, right-to-left mark + let various_spaces = " \t\u{b}\u{c}\r\n\u{a0}\u{200e}\u{200f}"; + let tokens = various_spaces.parse::().unwrap(); + assert_eq!(tokens.into_iter().count(), 0); + + let lone_carriage_returns = " \r \r\r\n "; + lone_carriage_returns.parse::().unwrap(); +} + +#[test] +fn byte_order_mark() { + let string = "\u{feff}foo"; + let tokens = string.parse::().unwrap(); + match tokens.into_iter().next().unwrap() { + TokenTree::Ident(ident) => assert_eq!(ident, "foo"), + _ => unreachable!(), + } + + let string = "foo\u{feff}"; + string.parse::().unwrap_err(); +} + +#[cfg(span_locations)] +fn create_span() -> proc_macro2::Span { + let tts: TokenStream = "1".parse().unwrap(); + match tts.into_iter().next().unwrap() { + TokenTree::Literal(literal) => literal.span(), + _ => unreachable!(), + } +} + +#[cfg(span_locations)] +#[test] +fn test_invalidate_current_thread_spans() { + let actual = format!("{:#?}", create_span()); + assert_eq!(actual, "bytes(1..2)"); + let actual = format!("{:#?}", create_span()); + assert_eq!(actual, "bytes(3..4)"); + + proc_macro2::extra::invalidate_current_thread_spans(); + + let actual = format!("{:#?}", create_span()); + // Test that span offsets have been reset after the call + // to invalidate_current_thread_spans() + assert_eq!(actual, "bytes(1..2)"); +} + +#[cfg(span_locations)] +#[test] +#[should_panic(expected = "Invalid span with no related FileInfo!")] +fn test_use_span_after_invalidation() { + let span = create_span(); + + proc_macro2::extra::invalidate_current_thread_spans(); + + span.source_text(); +} diff --git a/bitbox02-bt/vendor/proc-macro2/tests/test_fmt.rs b/bitbox02-bt/vendor/proc-macro2/tests/test_fmt.rs new file mode 100644 index 0000000..86a4c38 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/tests/test_fmt.rs @@ -0,0 +1,28 @@ +#![allow(clippy::from_iter_instead_of_collect)] + +use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; +use std::iter; + +#[test] +fn test_fmt_group() { + let ident = Ident::new("x", Span::call_site()); + let inner = TokenStream::from_iter(iter::once(TokenTree::Ident(ident))); + let parens_empty = Group::new(Delimiter::Parenthesis, TokenStream::new()); + let parens_nonempty = Group::new(Delimiter::Parenthesis, inner.clone()); + let brackets_empty = Group::new(Delimiter::Bracket, TokenStream::new()); + let brackets_nonempty = Group::new(Delimiter::Bracket, inner.clone()); + let braces_empty = Group::new(Delimiter::Brace, TokenStream::new()); + let braces_nonempty = Group::new(Delimiter::Brace, inner.clone()); + let none_empty = Group::new(Delimiter::None, TokenStream::new()); + let none_nonempty = Group::new(Delimiter::None, inner); + + // Matches libproc_macro. + assert_eq!("()", parens_empty.to_string()); + assert_eq!("(x)", parens_nonempty.to_string()); + assert_eq!("[]", brackets_empty.to_string()); + assert_eq!("[x]", brackets_nonempty.to_string()); + assert_eq!("{ }", braces_empty.to_string()); + assert_eq!("{ x }", braces_nonempty.to_string()); + assert_eq!("", none_empty.to_string()); + assert_eq!("x", none_nonempty.to_string()); +} diff --git a/bitbox02-bt/vendor/proc-macro2/tests/test_size.rs b/bitbox02-bt/vendor/proc-macro2/tests/test_size.rs new file mode 100644 index 0000000..8b67915 --- /dev/null +++ b/bitbox02-bt/vendor/proc-macro2/tests/test_size.rs @@ -0,0 +1,81 @@ +#![allow(unused_attributes)] + +extern crate proc_macro; + +use std::mem; + +#[rustversion::attr(before(1.64), ignore = "requires Rust 1.64+")] +#[cfg_attr(not(target_pointer_width = "64"), ignore = "only applicable to 64-bit")] +#[cfg_attr(randomize_layout, ignore = "disabled due to randomized layout")] +#[test] +fn test_proc_macro_size() { + assert_eq!(mem::size_of::(), 4); + assert_eq!(mem::size_of::>(), 4); + assert_eq!(mem::size_of::(), 20); + assert_eq!(mem::size_of::(), 12); + assert_eq!(mem::size_of::(), 8); + assert_eq!(mem::size_of::(), 16); + assert_eq!(mem::size_of::(), 4); +} + +#[cfg_attr(not(target_pointer_width = "64"), ignore = "only applicable to 64-bit")] +#[cfg_attr(randomize_layout, ignore = "disabled due to randomized layout")] +#[cfg_attr(wrap_proc_macro, ignore = "wrapper mode")] +#[cfg_attr(span_locations, ignore = "span locations are on")] +#[test] +fn test_proc_macro2_fallback_size_without_locations() { + assert_eq!(mem::size_of::(), 0); + assert_eq!(mem::size_of::>(), 1); + assert_eq!(mem::size_of::(), 16); + assert_eq!(mem::size_of::(), 24); + assert_eq!(mem::size_of::(), 8); + assert_eq!(mem::size_of::(), 24); + assert_eq!(mem::size_of::(), 8); +} + +#[cfg_attr(not(target_pointer_width = "64"), ignore = "only applicable to 64-bit")] +#[cfg_attr(randomize_layout, ignore = "disabled due to randomized layout")] +#[cfg_attr(wrap_proc_macro, ignore = "wrapper mode")] +#[cfg_attr(not(span_locations), ignore = "span locations are off")] +#[test] +fn test_proc_macro2_fallback_size_with_locations() { + assert_eq!(mem::size_of::(), 8); + assert_eq!(mem::size_of::>(), 12); + assert_eq!(mem::size_of::(), 24); + assert_eq!(mem::size_of::(), 32); + assert_eq!(mem::size_of::(), 16); + assert_eq!(mem::size_of::(), 32); + assert_eq!(mem::size_of::(), 8); +} + +#[rustversion::attr(before(1.71), ignore = "requires Rust 1.71+")] +#[cfg_attr(not(target_pointer_width = "64"), ignore = "only applicable to 64-bit")] +#[cfg_attr(randomize_layout, ignore = "disabled due to randomized layout")] +#[cfg_attr(not(wrap_proc_macro), ignore = "fallback mode")] +#[cfg_attr(span_locations, ignore = "span locations are on")] +#[test] +fn test_proc_macro2_wrapper_size_without_locations() { + assert_eq!(mem::size_of::(), 4); + assert_eq!(mem::size_of::>(), 8); + assert_eq!(mem::size_of::(), 24); + assert_eq!(mem::size_of::(), 24); + assert_eq!(mem::size_of::(), 12); + assert_eq!(mem::size_of::(), 24); + assert_eq!(mem::size_of::(), 32); +} + +#[rustversion::attr(before(1.65), ignore = "requires Rust 1.65+")] +#[cfg_attr(not(target_pointer_width = "64"), ignore = "only applicable to 64-bit")] +#[cfg_attr(randomize_layout, ignore = "disabled due to randomized layout")] +#[cfg_attr(not(wrap_proc_macro), ignore = "fallback mode")] +#[cfg_attr(not(span_locations), ignore = "span locations are off")] +#[test] +fn test_proc_macro2_wrapper_size_with_locations() { + assert_eq!(mem::size_of::(), 12); + assert_eq!(mem::size_of::>(), 12); + assert_eq!(mem::size_of::(), 32); + assert_eq!(mem::size_of::(), 32); + assert_eq!(mem::size_of::(), 20); + assert_eq!(mem::size_of::(), 32); + assert_eq!(mem::size_of::(), 32); +} diff --git a/bitbox02-bt/vendor/quote/.cargo-checksum.json b/bitbox02-bt/vendor/quote/.cargo-checksum.json new file mode 100644 index 0000000..2c547c3 --- /dev/null +++ b/bitbox02-bt/vendor/quote/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"8bdca3d4bf8c01d302dc8f779c5c546c7e0357601ed3d62771b7cd7a05b459ee","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"edb299daa2373254c96147303289002b9f424944176a26e5520ee82869caedc6","rust-toolchain.toml":"6bbb61302978c736b2da03e4fb40e3beab908f85d533ab46fd541e637b5f3e0f","src/ext.rs":"9881576cac3e476a4bf04f9b601cf9a53b79399fb0ca9634e8b861ac91709843","src/format.rs":"c595015418f35e6992e710441b9999f09b2afe4678b138039d670d100c0bdd86","src/ident_fragment.rs":"0b3e6c2129e55910fd2d240e1e7efba6f1796801d24352d1c0bfbceb0e8b678f","src/lib.rs":"bdc2340e5f1e84972d2f8d65393465dd4aea20001ae2cd484e867d0d653d60ae","src/runtime.rs":"7f37326edaeac2c42ed806b447eeba12e36dd4b1bc25fbf52f8eb23140f3be7a","src/spanned.rs":"3ccf5120593f35787442c0a37d243e802c5262e7f8b35aed503873008ec035c5","src/to_tokens.rs":"caca09d649e9394d37f065a41d481318c4cb86c345b9cb01f36fbf0f73868e86","tests/compiletest.rs":"4e381aa8ca3eabb7ac14d1e0c3700b3223e47640547a6988cfa13ad68255f60f","tests/test.rs":"05584957f1c30b180c31ef849ee9ec48e6b847f3e655efc0983c20dcfce2131e","tests/ui/does-not-have-iter-interpolated-dup.rs":"ad13eea21d4cdd2ab6c082f633392e1ff20fb0d1af5f2177041e0bf7f30da695","tests/ui/does-not-have-iter-interpolated-dup.stderr":"90a4bdb9267535f5d2785940148338d6b7d905548051d2c9c5dcbd58f2c11d8e","tests/ui/does-not-have-iter-interpolated.rs":"83a5b3f240651adcbe4b6e51076d76d653ad439b37442cf4054f1fd3c073f3b7","tests/ui/does-not-have-iter-interpolated.stderr":"ae7c2739554c862b331705e82781aa4687a4375210cef6ae899a4be4a4ec2d97","tests/ui/does-not-have-iter-separated.rs":"fe413c48331d5e3a7ae5fef6a5892a90c72f610d54595879eb49d0a94154ba3f","tests/ui/does-not-have-iter-separated.stderr":"03fd560979ebcd5aa6f83858bc2c3c01ba6546c16335101275505304895c1ae9","tests/ui/does-not-have-iter.rs":"09dc9499d861b63cebb0848b855b78e2dc9497bfde37ba6339f3625ae009a62f","tests/ui/does-not-have-iter.stderr":"d6da483c29e232ced72059bbdf05d31afb1df9e02954edaa9cfaea1ec6df72dc","tests/ui/not-quotable.rs":"5759d0884943417609f28faadc70254a3e2fd3d9bd6ff7297a3fb70a77fafd8a","tests/ui/not-quotable.stderr":"62f32911c891d7e4617c6f32dca2723598a5c321979fe7ec89b159bd8d9445d9","tests/ui/not-repeatable.rs":"a4b115c04e4e41049a05f5b69450503fbffeba031218b4189cb931839f7f9a9c","tests/ui/not-repeatable.stderr":"bbfb702638374001061251f81d63476851ac28ed743f13db9d65e30dd9bdcf52","tests/ui/wrong-type-span.rs":"6195e35ea844c0c52ba1cff5d790c3a371af6915d137d377834ad984229ef9ea","tests/ui/wrong-type-span.stderr":"cad072e40e0ecc04f375122ae41aede2f0da2a9244492b3fcf70249e59d1b128"},"package":"b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/quote/Cargo.toml b/bitbox02-bt/vendor/quote/Cargo.toml new file mode 100644 index 0000000..af97fc7 --- /dev/null +++ b/bitbox02-bt/vendor/quote/Cargo.toml @@ -0,0 +1,64 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.56" +name = "quote" +version = "1.0.37" +authors = ["David Tolnay "] +build = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Quasi-quoting macro quote!(...)" +documentation = "https://docs.rs/quote/" +readme = "README.md" +keywords = [ + "macros", + "syn", +] +categories = ["development-tools::procedural-macro-helpers"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/quote" + +[package.metadata.docs.rs] +rustdoc-args = ["--generate-link-to-definition"] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +name = "quote" +path = "src/lib.rs" +doc-scrape-examples = false + +[[test]] +name = "compiletest" +path = "tests/compiletest.rs" + +[[test]] +name = "test" +path = "tests/test.rs" + +[dependencies.proc-macro2] +version = "1.0.80" +default-features = false + +[dev-dependencies.rustversion] +version = "1.0" + +[dev-dependencies.trybuild] +version = "1.0.66" +features = ["diff"] + +[features] +default = ["proc-macro"] +proc-macro = ["proc-macro2/proc-macro"] diff --git a/bitbox02-bt/vendor/quote/LICENSE-APACHE b/bitbox02-bt/vendor/quote/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/quote/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/quote/LICENSE-MIT b/bitbox02-bt/vendor/quote/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/quote/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/quote/README.md b/bitbox02-bt/vendor/quote/README.md new file mode 100644 index 0000000..58bbf21 --- /dev/null +++ b/bitbox02-bt/vendor/quote/README.md @@ -0,0 +1,271 @@ +Rust Quasi-Quoting +================== + +[github](https://github.com/dtolnay/quote) +[crates.io](https://crates.io/crates/quote) +[docs.rs](https://docs.rs/quote) +[build status](https://github.com/dtolnay/quote/actions?query=branch%3Amaster) + +This crate provides the [`quote!`] macro for turning Rust syntax tree data +structures into tokens of source code. + +[`quote!`]: https://docs.rs/quote/1.0/quote/macro.quote.html + +Procedural macros in Rust receive a stream of tokens as input, execute arbitrary +Rust code to determine how to manipulate those tokens, and produce a stream of +tokens to hand back to the compiler to compile into the caller's crate. +Quasi-quoting is a solution to one piece of that — producing tokens to +return to the compiler. + +The idea of quasi-quoting is that we write *code* that we treat as *data*. +Within the `quote!` macro, we can write what looks like code to our text editor +or IDE. We get all the benefits of the editor's brace matching, syntax +highlighting, indentation, and maybe autocompletion. But rather than compiling +that as code into the current crate, we can treat it as data, pass it around, +mutate it, and eventually hand it back to the compiler as tokens to compile into +the macro caller's crate. + +This crate is motivated by the procedural macro use case, but is a +general-purpose Rust quasi-quoting library and is not specific to procedural +macros. + +```toml +[dependencies] +quote = "1.0" +``` + +*Version requirement: Quote supports rustc 1.56 and up.*
+[*Release notes*](https://github.com/dtolnay/quote/releases) + +
+ +## Syntax + +The quote crate provides a [`quote!`] macro within which you can write Rust code +that gets packaged into a [`TokenStream`] and can be treated as data. You should +think of `TokenStream` as representing a fragment of Rust source code. + +[`TokenStream`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.TokenStream.html + +Within the `quote!` macro, interpolation is done with `#var`. Any type +implementing the [`quote::ToTokens`] trait can be interpolated. This includes +most Rust primitive types as well as most of the syntax tree types from [`syn`]. + +[`quote::ToTokens`]: https://docs.rs/quote/1.0/quote/trait.ToTokens.html +[`syn`]: https://github.com/dtolnay/syn + +```rust +let tokens = quote! { + struct SerializeWith #generics #where_clause { + value: &'a #field_ty, + phantom: core::marker::PhantomData<#item_ty>, + } + + impl #generics serde::Serialize for SerializeWith #generics #where_clause { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + #path(self.value, serializer) + } + } + + SerializeWith { + value: #value, + phantom: core::marker::PhantomData::<#item_ty>, + } +}; +``` + +
+ +## Repetition + +Repetition is done using `#(...)*` or `#(...),*` similar to `macro_rules!`. This +iterates through the elements of any variable interpolated within the repetition +and inserts a copy of the repetition body for each one. The variables in an +interpolation may be a `Vec`, slice, `BTreeSet`, or any `Iterator`. + +- `#(#var)*` — no separators +- `#(#var),*` — the character before the asterisk is used as a separator +- `#( struct #var; )*` — the repetition can contain other things +- `#( #k => println!("{}", #v), )*` — even multiple interpolations + +Note that there is a difference between `#(#var ,)*` and `#(#var),*`—the latter +does not produce a trailing comma. This matches the behavior of delimiters in +`macro_rules!`. + +
+ +## Returning tokens to the compiler + +The `quote!` macro evaluates to an expression of type +`proc_macro2::TokenStream`. Meanwhile Rust procedural macros are expected to +return the type `proc_macro::TokenStream`. + +The difference between the two types is that `proc_macro` types are entirely +specific to procedural macros and cannot ever exist in code outside of a +procedural macro, while `proc_macro2` types may exist anywhere including tests +and non-macro code like main.rs and build.rs. This is why even the procedural +macro ecosystem is largely built around `proc_macro2`, because that ensures the +libraries are unit testable and accessible in non-macro contexts. + +There is a [`From`]-conversion in both directions so returning the output of +`quote!` from a procedural macro usually looks like `tokens.into()` or +`proc_macro::TokenStream::from(tokens)`. + +[`From`]: https://doc.rust-lang.org/std/convert/trait.From.html + +
+ +## Examples + +### Combining quoted fragments + +Usually you don't end up constructing an entire final `TokenStream` in one +piece. Different parts may come from different helper functions. The tokens +produced by `quote!` themselves implement `ToTokens` and so can be interpolated +into later `quote!` invocations to build up a final result. + +```rust +let type_definition = quote! {...}; +let methods = quote! {...}; + +let tokens = quote! { + #type_definition + #methods +}; +``` + +### Constructing identifiers + +Suppose we have an identifier `ident` which came from somewhere in a macro +input and we need to modify it in some way for the macro output. Let's consider +prepending the identifier with an underscore. + +Simply interpolating the identifier next to an underscore will not have the +behavior of concatenating them. The underscore and the identifier will continue +to be two separate tokens as if you had written `_ x`. + +```rust +// incorrect +quote! { + let mut _#ident = 0; +} +``` + +The solution is to build a new identifier token with the correct value. As this +is such a common case, the `format_ident!` macro provides a convenient utility +for doing so correctly. + +```rust +let varname = format_ident!("_{}", ident); +quote! { + let mut #varname = 0; +} +``` + +Alternatively, the APIs provided by Syn and proc-macro2 can be used to directly +build the identifier. This is roughly equivalent to the above, but will not +handle `ident` being a raw identifier. + +```rust +let concatenated = format!("_{}", ident); +let varname = syn::Ident::new(&concatenated, ident.span()); +quote! { + let mut #varname = 0; +} +``` + +### Making method calls + +Let's say our macro requires some type specified in the macro input to have a +constructor called `new`. We have the type in a variable called `field_type` of +type `syn::Type` and want to invoke the constructor. + +```rust +// incorrect +quote! { + let value = #field_type::new(); +} +``` + +This works only sometimes. If `field_type` is `String`, the expanded code +contains `String::new()` which is fine. But if `field_type` is something like +`Vec` then the expanded code is `Vec::new()` which is invalid syntax. +Ordinarily in handwritten Rust we would write `Vec::::new()` but for macros +often the following is more convenient. + +```rust +quote! { + let value = <#field_type>::new(); +} +``` + +This expands to `>::new()` which behaves correctly. + +A similar pattern is appropriate for trait methods. + +```rust +quote! { + let value = <#field_type as core::default::Default>::default(); +} +``` + +
+ +## Hygiene + +Any interpolated tokens preserve the `Span` information provided by their +`ToTokens` implementation. Tokens that originate within a `quote!` invocation +are spanned with [`Span::call_site()`]. + +[`Span::call_site()`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.Span.html#method.call_site + +A different span can be provided explicitly through the [`quote_spanned!`] +macro. + +[`quote_spanned!`]: https://docs.rs/quote/1.0/quote/macro.quote_spanned.html + +
+ +## Non-macro code generators + +When using `quote` in a build.rs or main.rs and writing the output out to a +file, consider having the code generator pass the tokens through [prettyplease] +before writing. This way if an error occurs in the generated code it is +convenient for a human to read and debug. + +Be aware that no kind of hygiene or span information is retained when tokens are +written to a file; the conversion from tokens to source code is lossy. + +Example usage in build.rs: + +```rust +let output = quote! { ... }; +let syntax_tree = syn::parse2(output).unwrap(); +let formatted = prettyplease::unparse(&syntax_tree); + +let out_dir = env::var_os("OUT_DIR").unwrap(); +let dest_path = Path::new(&out_dir).join("out.rs"); +fs::write(dest_path, formatted).unwrap(); +``` + +[prettyplease]: https://github.com/dtolnay/prettyplease + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/quote/rust-toolchain.toml b/bitbox02-bt/vendor/quote/rust-toolchain.toml new file mode 100644 index 0000000..20fe888 --- /dev/null +++ b/bitbox02-bt/vendor/quote/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +components = ["rust-src"] diff --git a/bitbox02-bt/vendor/quote/src/ext.rs b/bitbox02-bt/vendor/quote/src/ext.rs new file mode 100644 index 0000000..92c2315 --- /dev/null +++ b/bitbox02-bt/vendor/quote/src/ext.rs @@ -0,0 +1,110 @@ +use super::ToTokens; +use core::iter; +use proc_macro2::{TokenStream, TokenTree}; + +/// TokenStream extension trait with methods for appending tokens. +/// +/// This trait is sealed and cannot be implemented outside of the `quote` crate. +pub trait TokenStreamExt: private::Sealed { + /// For use by `ToTokens` implementations. + /// + /// Appends the token specified to this list of tokens. + fn append(&mut self, token: U) + where + U: Into; + + /// For use by `ToTokens` implementations. + /// + /// ``` + /// # use quote::{quote, TokenStreamExt, ToTokens}; + /// # use proc_macro2::TokenStream; + /// # + /// struct X; + /// + /// impl ToTokens for X { + /// fn to_tokens(&self, tokens: &mut TokenStream) { + /// tokens.append_all(&[true, false]); + /// } + /// } + /// + /// let tokens = quote!(#X); + /// assert_eq!(tokens.to_string(), "true false"); + /// ``` + fn append_all(&mut self, iter: I) + where + I: IntoIterator, + I::Item: ToTokens; + + /// For use by `ToTokens` implementations. + /// + /// Appends all of the items in the iterator `I`, separated by the tokens + /// `U`. + fn append_separated(&mut self, iter: I, op: U) + where + I: IntoIterator, + I::Item: ToTokens, + U: ToTokens; + + /// For use by `ToTokens` implementations. + /// + /// Appends all tokens in the iterator `I`, appending `U` after each + /// element, including after the last element of the iterator. + fn append_terminated(&mut self, iter: I, term: U) + where + I: IntoIterator, + I::Item: ToTokens, + U: ToTokens; +} + +impl TokenStreamExt for TokenStream { + fn append(&mut self, token: U) + where + U: Into, + { + self.extend(iter::once(token.into())); + } + + fn append_all(&mut self, iter: I) + where + I: IntoIterator, + I::Item: ToTokens, + { + for token in iter { + token.to_tokens(self); + } + } + + fn append_separated(&mut self, iter: I, op: U) + where + I: IntoIterator, + I::Item: ToTokens, + U: ToTokens, + { + for (i, token) in iter.into_iter().enumerate() { + if i > 0 { + op.to_tokens(self); + } + token.to_tokens(self); + } + } + + fn append_terminated(&mut self, iter: I, term: U) + where + I: IntoIterator, + I::Item: ToTokens, + U: ToTokens, + { + for token in iter { + token.to_tokens(self); + term.to_tokens(self); + } + } +} + +mod private { + use proc_macro2::TokenStream; + + pub trait Sealed {} + + impl Sealed for TokenStream {} +} diff --git a/bitbox02-bt/vendor/quote/src/format.rs b/bitbox02-bt/vendor/quote/src/format.rs new file mode 100644 index 0000000..3cddbd2 --- /dev/null +++ b/bitbox02-bt/vendor/quote/src/format.rs @@ -0,0 +1,168 @@ +/// Formatting macro for constructing `Ident`s. +/// +///
+/// +/// # Syntax +/// +/// Syntax is copied from the [`format!`] macro, supporting both positional and +/// named arguments. +/// +/// Only a limited set of formatting traits are supported. The current mapping +/// of format types to traits is: +/// +/// * `{}` ⇒ [`IdentFragment`] +/// * `{:o}` ⇒ [`Octal`](std::fmt::Octal) +/// * `{:x}` ⇒ [`LowerHex`](std::fmt::LowerHex) +/// * `{:X}` ⇒ [`UpperHex`](std::fmt::UpperHex) +/// * `{:b}` ⇒ [`Binary`](std::fmt::Binary) +/// +/// See [`std::fmt`] for more information. +/// +///
+/// +/// # IdentFragment +/// +/// Unlike `format!`, this macro uses the [`IdentFragment`] formatting trait by +/// default. This trait is like `Display`, with a few differences: +/// +/// * `IdentFragment` is only implemented for a limited set of types, such as +/// unsigned integers and strings. +/// * [`Ident`] arguments will have their `r#` prefixes stripped, if present. +/// +/// [`IdentFragment`]: crate::IdentFragment +/// [`Ident`]: proc_macro2::Ident +/// +///
+/// +/// # Hygiene +/// +/// The [`Span`] of the first `Ident` argument is used as the span of the final +/// identifier, falling back to [`Span::call_site`] when no identifiers are +/// provided. +/// +/// ``` +/// # use quote::format_ident; +/// # let ident = format_ident!("Ident"); +/// // If `ident` is an Ident, the span of `my_ident` will be inherited from it. +/// let my_ident = format_ident!("My{}{}", ident, "IsCool"); +/// assert_eq!(my_ident, "MyIdentIsCool"); +/// ``` +/// +/// Alternatively, the span can be overridden by passing the `span` named +/// argument. +/// +/// ``` +/// # use quote::format_ident; +/// # const IGNORE_TOKENS: &'static str = stringify! { +/// let my_span = /* ... */; +/// # }; +/// # let my_span = proc_macro2::Span::call_site(); +/// format_ident!("MyIdent", span = my_span); +/// ``` +/// +/// [`Span`]: proc_macro2::Span +/// [`Span::call_site`]: proc_macro2::Span::call_site +/// +///


+/// +/// # Panics +/// +/// This method will panic if the resulting formatted string is not a valid +/// identifier. +/// +///
+/// +/// # Examples +/// +/// Composing raw and non-raw identifiers: +/// ``` +/// # use quote::format_ident; +/// let my_ident = format_ident!("My{}", "Ident"); +/// assert_eq!(my_ident, "MyIdent"); +/// +/// let raw = format_ident!("r#Raw"); +/// assert_eq!(raw, "r#Raw"); +/// +/// let my_ident_raw = format_ident!("{}Is{}", my_ident, raw); +/// assert_eq!(my_ident_raw, "MyIdentIsRaw"); +/// ``` +/// +/// Integer formatting options: +/// ``` +/// # use quote::format_ident; +/// let num: u32 = 10; +/// +/// let decimal = format_ident!("Id_{}", num); +/// assert_eq!(decimal, "Id_10"); +/// +/// let octal = format_ident!("Id_{:o}", num); +/// assert_eq!(octal, "Id_12"); +/// +/// let binary = format_ident!("Id_{:b}", num); +/// assert_eq!(binary, "Id_1010"); +/// +/// let lower_hex = format_ident!("Id_{:x}", num); +/// assert_eq!(lower_hex, "Id_a"); +/// +/// let upper_hex = format_ident!("Id_{:X}", num); +/// assert_eq!(upper_hex, "Id_A"); +/// ``` +#[macro_export] +macro_rules! format_ident { + ($fmt:expr) => { + $crate::format_ident_impl!([ + $crate::__private::Option::None, + $fmt + ]) + }; + + ($fmt:expr, $($rest:tt)*) => { + $crate::format_ident_impl!([ + $crate::__private::Option::None, + $fmt + ] $($rest)*) + }; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! format_ident_impl { + // Final state + ([$span:expr, $($fmt:tt)*]) => { + $crate::__private::mk_ident( + &$crate::__private::format!($($fmt)*), + $span, + ) + }; + + // Span argument + ([$old:expr, $($fmt:tt)*] span = $span:expr) => { + $crate::format_ident_impl!([$old, $($fmt)*] span = $span,) + }; + ([$old:expr, $($fmt:tt)*] span = $span:expr, $($rest:tt)*) => { + $crate::format_ident_impl!([ + $crate::__private::Option::Some::<$crate::__private::Span>($span), + $($fmt)* + ] $($rest)*) + }; + + // Named argument + ([$span:expr, $($fmt:tt)*] $name:ident = $arg:expr) => { + $crate::format_ident_impl!([$span, $($fmt)*] $name = $arg,) + }; + ([$span:expr, $($fmt:tt)*] $name:ident = $arg:expr, $($rest:tt)*) => { + match $crate::__private::IdentFragmentAdapter(&$arg) { + arg => $crate::format_ident_impl!([$span.or(arg.span()), $($fmt)*, $name = arg] $($rest)*), + } + }; + + // Positional argument + ([$span:expr, $($fmt:tt)*] $arg:expr) => { + $crate::format_ident_impl!([$span, $($fmt)*] $arg,) + }; + ([$span:expr, $($fmt:tt)*] $arg:expr, $($rest:tt)*) => { + match $crate::__private::IdentFragmentAdapter(&$arg) { + arg => $crate::format_ident_impl!([$span.or(arg.span()), $($fmt)*, arg] $($rest)*), + } + }; +} diff --git a/bitbox02-bt/vendor/quote/src/ident_fragment.rs b/bitbox02-bt/vendor/quote/src/ident_fragment.rs new file mode 100644 index 0000000..6c2a9a8 --- /dev/null +++ b/bitbox02-bt/vendor/quote/src/ident_fragment.rs @@ -0,0 +1,88 @@ +use alloc::borrow::Cow; +use core::fmt; +use proc_macro2::{Ident, Span}; + +/// Specialized formatting trait used by `format_ident!`. +/// +/// [`Ident`] arguments formatted using this trait will have their `r#` prefix +/// stripped, if present. +/// +/// See [`format_ident!`] for more information. +/// +/// [`format_ident!`]: crate::format_ident +pub trait IdentFragment { + /// Format this value as an identifier fragment. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result; + + /// Span associated with this `IdentFragment`. + /// + /// If non-`None`, may be inherited by formatted identifiers. + fn span(&self) -> Option { + None + } +} + +impl IdentFragment for &T { + fn span(&self) -> Option { + ::span(*self) + } + + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + IdentFragment::fmt(*self, f) + } +} + +impl IdentFragment for &mut T { + fn span(&self) -> Option { + ::span(*self) + } + + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + IdentFragment::fmt(*self, f) + } +} + +impl IdentFragment for Ident { + fn span(&self) -> Option { + Some(self.span()) + } + + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let id = self.to_string(); + if let Some(id) = id.strip_prefix("r#") { + fmt::Display::fmt(id, f) + } else { + fmt::Display::fmt(&id[..], f) + } + } +} + +impl IdentFragment for Cow<'_, T> +where + T: IdentFragment + ToOwned + ?Sized, +{ + fn span(&self) -> Option { + T::span(self) + } + + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + T::fmt(self, f) + } +} + +// Limited set of types which this is implemented for, as we want to avoid types +// which will often include non-identifier characters in their `Display` impl. +macro_rules! ident_fragment_display { + ($($T:ty),*) => { + $( + impl IdentFragment for $T { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } + } + )* + }; +} + +ident_fragment_display!(bool, str, String, char); +ident_fragment_display!(u8, u16, u32, u64, u128, usize); diff --git a/bitbox02-bt/vendor/quote/src/lib.rs b/bitbox02-bt/vendor/quote/src/lib.rs new file mode 100644 index 0000000..2c72da2 --- /dev/null +++ b/bitbox02-bt/vendor/quote/src/lib.rs @@ -0,0 +1,1464 @@ +//! [![github]](https://github.com/dtolnay/quote) [![crates-io]](https://crates.io/crates/quote) [![docs-rs]](https://docs.rs/quote) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs +//! +//!
+//! +//! This crate provides the [`quote!`] macro for turning Rust syntax tree data +//! structures into tokens of source code. +//! +//! [`quote!`]: macro.quote.html +//! +//! Procedural macros in Rust receive a stream of tokens as input, execute +//! arbitrary Rust code to determine how to manipulate those tokens, and produce +//! a stream of tokens to hand back to the compiler to compile into the caller's +//! crate. Quasi-quoting is a solution to one piece of that — producing +//! tokens to return to the compiler. +//! +//! The idea of quasi-quoting is that we write *code* that we treat as *data*. +//! Within the `quote!` macro, we can write what looks like code to our text +//! editor or IDE. We get all the benefits of the editor's brace matching, +//! syntax highlighting, indentation, and maybe autocompletion. But rather than +//! compiling that as code into the current crate, we can treat it as data, pass +//! it around, mutate it, and eventually hand it back to the compiler as tokens +//! to compile into the macro caller's crate. +//! +//! This crate is motivated by the procedural macro use case, but is a +//! general-purpose Rust quasi-quoting library and is not specific to procedural +//! macros. +//! +//! ```toml +//! [dependencies] +//! quote = "1.0" +//! ``` +//! +//!
+//! +//! # Example +//! +//! The following quasi-quoted block of code is something you might find in [a] +//! procedural macro having to do with data structure serialization. The `#var` +//! syntax performs interpolation of runtime variables into the quoted tokens. +//! Check out the documentation of the [`quote!`] macro for more detail about +//! the syntax. See also the [`quote_spanned!`] macro which is important for +//! implementing hygienic procedural macros. +//! +//! [a]: https://serde.rs/ +//! [`quote_spanned!`]: macro.quote_spanned.html +//! +//! ``` +//! # use quote::quote; +//! # +//! # let generics = ""; +//! # let where_clause = ""; +//! # let field_ty = ""; +//! # let item_ty = ""; +//! # let path = ""; +//! # let value = ""; +//! # +//! let tokens = quote! { +//! struct SerializeWith #generics #where_clause { +//! value: &'a #field_ty, +//! phantom: core::marker::PhantomData<#item_ty>, +//! } +//! +//! impl #generics serde::Serialize for SerializeWith #generics #where_clause { +//! fn serialize(&self, serializer: S) -> Result +//! where +//! S: serde::Serializer, +//! { +//! #path(self.value, serializer) +//! } +//! } +//! +//! SerializeWith { +//! value: #value, +//! phantom: core::marker::PhantomData::<#item_ty>, +//! } +//! }; +//! ``` +//! +//!
+//! +//! # Non-macro code generators +//! +//! When using `quote` in a build.rs or main.rs and writing the output out to a +//! file, consider having the code generator pass the tokens through +//! [prettyplease] before writing. This way if an error occurs in the generated +//! code it is convenient for a human to read and debug. +//! +//! [prettyplease]: https://github.com/dtolnay/prettyplease + +// Quote types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/quote/1.0.37")] +#![allow( + clippy::doc_markdown, + clippy::missing_errors_doc, + clippy::missing_panics_doc, + clippy::module_name_repetitions, + // false positive https://github.com/rust-lang/rust-clippy/issues/6983 + clippy::wrong_self_convention, +)] + +extern crate alloc; + +#[cfg(feature = "proc-macro")] +extern crate proc_macro; + +mod ext; +mod format; +mod ident_fragment; +mod to_tokens; + +// Not public API. +#[doc(hidden)] +#[path = "runtime.rs"] +pub mod __private; + +pub use crate::ext::TokenStreamExt; +pub use crate::ident_fragment::IdentFragment; +pub use crate::to_tokens::ToTokens; + +// Not public API. +#[doc(hidden)] +pub mod spanned; + +macro_rules! __quote { + ($quote:item) => { + /// The whole point. + /// + /// Performs variable interpolation against the input and produces it as + /// [`proc_macro2::TokenStream`]. + /// + /// Note: for returning tokens to the compiler in a procedural macro, use + /// `.into()` on the result to convert to [`proc_macro::TokenStream`]. + /// + /// [`TokenStream`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.TokenStream.html + /// + ///
+ /// + /// # Interpolation + /// + /// Variable interpolation is done with `#var` (similar to `$var` in + /// `macro_rules!` macros). This grabs the `var` variable that is currently in + /// scope and inserts it in that location in the output tokens. Any type + /// implementing the [`ToTokens`] trait can be interpolated. This includes most + /// Rust primitive types as well as most of the syntax tree types from the [Syn] + /// crate. + /// + /// [`ToTokens`]: trait.ToTokens.html + /// [Syn]: https://github.com/dtolnay/syn + /// + /// Repetition is done using `#(...)*` or `#(...),*` again similar to + /// `macro_rules!`. This iterates through the elements of any variable + /// interpolated within the repetition and inserts a copy of the repetition body + /// for each one. The variables in an interpolation may be a `Vec`, slice, + /// `BTreeSet`, or any `Iterator`. + /// + /// - `#(#var)*` — no separators + /// - `#(#var),*` — the character before the asterisk is used as a separator + /// - `#( struct #var; )*` — the repetition can contain other tokens + /// - `#( #k => println!("{}", #v), )*` — even multiple interpolations + /// + ///
+ /// + /// # Hygiene + /// + /// Any interpolated tokens preserve the `Span` information provided by their + /// `ToTokens` implementation. Tokens that originate within the `quote!` + /// invocation are spanned with [`Span::call_site()`]. + /// + /// [`Span::call_site()`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.Span.html#method.call_site + /// + /// A different span can be provided through the [`quote_spanned!`] macro. + /// + /// [`quote_spanned!`]: macro.quote_spanned.html + /// + ///
+ /// + /// # Return type + /// + /// The macro evaluates to an expression of type `proc_macro2::TokenStream`. + /// Meanwhile Rust procedural macros are expected to return the type + /// `proc_macro::TokenStream`. + /// + /// The difference between the two types is that `proc_macro` types are entirely + /// specific to procedural macros and cannot ever exist in code outside of a + /// procedural macro, while `proc_macro2` types may exist anywhere including + /// tests and non-macro code like main.rs and build.rs. This is why even the + /// procedural macro ecosystem is largely built around `proc_macro2`, because + /// that ensures the libraries are unit testable and accessible in non-macro + /// contexts. + /// + /// There is a [`From`]-conversion in both directions so returning the output of + /// `quote!` from a procedural macro usually looks like `tokens.into()` or + /// `proc_macro::TokenStream::from(tokens)`. + /// + /// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html + /// + ///
+ /// + /// # Examples + /// + /// ### Procedural macro + /// + /// The structure of a basic procedural macro is as follows. Refer to the [Syn] + /// crate for further useful guidance on using `quote!` as part of a procedural + /// macro. + /// + /// [Syn]: https://github.com/dtolnay/syn + /// + /// ``` + /// # #[cfg(any())] + /// extern crate proc_macro; + /// # extern crate proc_macro2; + /// + /// # #[cfg(any())] + /// use proc_macro::TokenStream; + /// # use proc_macro2::TokenStream; + /// use quote::quote; + /// + /// # const IGNORE_TOKENS: &'static str = stringify! { + /// #[proc_macro_derive(HeapSize)] + /// # }; + /// pub fn derive_heap_size(input: TokenStream) -> TokenStream { + /// // Parse the input and figure out what implementation to generate... + /// # const IGNORE_TOKENS: &'static str = stringify! { + /// let name = /* ... */; + /// let expr = /* ... */; + /// # }; + /// # + /// # let name = 0; + /// # let expr = 0; + /// + /// let expanded = quote! { + /// // The generated impl. + /// impl heapsize::HeapSize for #name { + /// fn heap_size_of_children(&self) -> usize { + /// #expr + /// } + /// } + /// }; + /// + /// // Hand the output tokens back to the compiler. + /// TokenStream::from(expanded) + /// } + /// ``` + /// + ///


+ /// + /// ### Combining quoted fragments + /// + /// Usually you don't end up constructing an entire final `TokenStream` in one + /// piece. Different parts may come from different helper functions. The tokens + /// produced by `quote!` themselves implement `ToTokens` and so can be + /// interpolated into later `quote!` invocations to build up a final result. + /// + /// ``` + /// # use quote::quote; + /// # + /// let type_definition = quote! {...}; + /// let methods = quote! {...}; + /// + /// let tokens = quote! { + /// #type_definition + /// #methods + /// }; + /// ``` + /// + ///


+ /// + /// ### Constructing identifiers + /// + /// Suppose we have an identifier `ident` which came from somewhere in a macro + /// input and we need to modify it in some way for the macro output. Let's + /// consider prepending the identifier with an underscore. + /// + /// Simply interpolating the identifier next to an underscore will not have the + /// behavior of concatenating them. The underscore and the identifier will + /// continue to be two separate tokens as if you had written `_ x`. + /// + /// ``` + /// # use proc_macro2::{self as syn, Span}; + /// # use quote::quote; + /// # + /// # let ident = syn::Ident::new("i", Span::call_site()); + /// # + /// // incorrect + /// quote! { + /// let mut _#ident = 0; + /// } + /// # ; + /// ``` + /// + /// The solution is to build a new identifier token with the correct value. As + /// this is such a common case, the [`format_ident!`] macro provides a + /// convenient utility for doing so correctly. + /// + /// ``` + /// # use proc_macro2::{Ident, Span}; + /// # use quote::{format_ident, quote}; + /// # + /// # let ident = Ident::new("i", Span::call_site()); + /// # + /// let varname = format_ident!("_{}", ident); + /// quote! { + /// let mut #varname = 0; + /// } + /// # ; + /// ``` + /// + /// Alternatively, the APIs provided by Syn and proc-macro2 can be used to + /// directly build the identifier. This is roughly equivalent to the above, but + /// will not handle `ident` being a raw identifier. + /// + /// ``` + /// # use proc_macro2::{self as syn, Span}; + /// # use quote::quote; + /// # + /// # let ident = syn::Ident::new("i", Span::call_site()); + /// # + /// let concatenated = format!("_{}", ident); + /// let varname = syn::Ident::new(&concatenated, ident.span()); + /// quote! { + /// let mut #varname = 0; + /// } + /// # ; + /// ``` + /// + ///


+ /// + /// ### Making method calls + /// + /// Let's say our macro requires some type specified in the macro input to have + /// a constructor called `new`. We have the type in a variable called + /// `field_type` of type `syn::Type` and want to invoke the constructor. + /// + /// ``` + /// # use quote::quote; + /// # + /// # let field_type = quote!(...); + /// # + /// // incorrect + /// quote! { + /// let value = #field_type::new(); + /// } + /// # ; + /// ``` + /// + /// This works only sometimes. If `field_type` is `String`, the expanded code + /// contains `String::new()` which is fine. But if `field_type` is something + /// like `Vec` then the expanded code is `Vec::new()` which is invalid + /// syntax. Ordinarily in handwritten Rust we would write `Vec::::new()` + /// but for macros often the following is more convenient. + /// + /// ``` + /// # use quote::quote; + /// # + /// # let field_type = quote!(...); + /// # + /// quote! { + /// let value = <#field_type>::new(); + /// } + /// # ; + /// ``` + /// + /// This expands to `>::new()` which behaves correctly. + /// + /// A similar pattern is appropriate for trait methods. + /// + /// ``` + /// # use quote::quote; + /// # + /// # let field_type = quote!(...); + /// # + /// quote! { + /// let value = <#field_type as core::default::Default>::default(); + /// } + /// # ; + /// ``` + /// + ///


+ /// + /// ### Interpolating text inside of doc comments + /// + /// Neither doc comments nor string literals get interpolation behavior in + /// quote: + /// + /// ```compile_fail + /// quote! { + /// /// try to interpolate: #ident + /// /// + /// /// ... + /// } + /// ``` + /// + /// ```compile_fail + /// quote! { + /// #[doc = "try to interpolate: #ident"] + /// } + /// ``` + /// + /// Instead the best way to build doc comments that involve variables is by + /// formatting the doc string literal outside of quote. + /// + /// ```rust + /// # use proc_macro2::{Ident, Span}; + /// # use quote::quote; + /// # + /// # const IGNORE: &str = stringify! { + /// let msg = format!(...); + /// # }; + /// # + /// # let ident = Ident::new("var", Span::call_site()); + /// # let msg = format!("try to interpolate: {}", ident); + /// quote! { + /// #[doc = #msg] + /// /// + /// /// ... + /// } + /// # ; + /// ``` + /// + ///


+ /// + /// ### Indexing into a tuple struct + /// + /// When interpolating indices of a tuple or tuple struct, we need them not to + /// appears suffixed as integer literals by interpolating them as [`syn::Index`] + /// instead. + /// + /// [`syn::Index`]: https://docs.rs/syn/2.0/syn/struct.Index.html + /// + /// ```compile_fail + /// let i = 0usize..self.fields.len(); + /// + /// // expands to 0 + self.0usize.heap_size() + self.1usize.heap_size() + ... + /// // which is not valid syntax + /// quote! { + /// 0 #( + self.#i.heap_size() )* + /// } + /// ``` + /// + /// ``` + /// # use proc_macro2::{Ident, TokenStream}; + /// # use quote::quote; + /// # + /// # mod syn { + /// # use proc_macro2::{Literal, TokenStream}; + /// # use quote::{ToTokens, TokenStreamExt}; + /// # + /// # pub struct Index(usize); + /// # + /// # impl From for Index { + /// # fn from(i: usize) -> Self { + /// # Index(i) + /// # } + /// # } + /// # + /// # impl ToTokens for Index { + /// # fn to_tokens(&self, tokens: &mut TokenStream) { + /// # tokens.append(Literal::usize_unsuffixed(self.0)); + /// # } + /// # } + /// # } + /// # + /// # struct Struct { + /// # fields: Vec, + /// # } + /// # + /// # impl Struct { + /// # fn example(&self) -> TokenStream { + /// let i = (0..self.fields.len()).map(syn::Index::from); + /// + /// // expands to 0 + self.0.heap_size() + self.1.heap_size() + ... + /// quote! { + /// 0 #( + self.#i.heap_size() )* + /// } + /// # } + /// # } + /// ``` + $quote + }; +} + +#[cfg(doc)] +__quote![ + #[macro_export] + macro_rules! quote { + ($($tt:tt)*) => { + ... + }; + } +]; + +#[cfg(not(doc))] +__quote![ + #[macro_export] + macro_rules! quote { + () => { + $crate::__private::TokenStream::new() + }; + + // Special case rule for a single tt, for performance. + ($tt:tt) => {{ + let mut _s = $crate::__private::TokenStream::new(); + $crate::quote_token!{$tt _s} + _s + }}; + + // Special case rules for two tts, for performance. + (# $var:ident) => {{ + let mut _s = $crate::__private::TokenStream::new(); + $crate::ToTokens::to_tokens(&$var, &mut _s); + _s + }}; + ($tt1:tt $tt2:tt) => {{ + let mut _s = $crate::__private::TokenStream::new(); + $crate::quote_token!{$tt1 _s} + $crate::quote_token!{$tt2 _s} + _s + }}; + + // Rule for any other number of tokens. + ($($tt:tt)*) => {{ + let mut _s = $crate::__private::TokenStream::new(); + $crate::quote_each_token!{_s $($tt)*} + _s + }}; + } +]; + +macro_rules! __quote_spanned { + ($quote_spanned:item) => { + /// Same as `quote!`, but applies a given span to all tokens originating within + /// the macro invocation. + /// + ///
+ /// + /// # Syntax + /// + /// A span expression of type [`Span`], followed by `=>`, followed by the tokens + /// to quote. The span expression should be brief — use a variable for + /// anything more than a few characters. There should be no space before the + /// `=>` token. + /// + /// [`Span`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.Span.html + /// + /// ``` + /// # use proc_macro2::Span; + /// # use quote::quote_spanned; + /// # + /// # const IGNORE_TOKENS: &'static str = stringify! { + /// let span = /* ... */; + /// # }; + /// # let span = Span::call_site(); + /// # let init = 0; + /// + /// // On one line, use parentheses. + /// let tokens = quote_spanned!(span=> Box::into_raw(Box::new(#init))); + /// + /// // On multiple lines, place the span at the top and use braces. + /// let tokens = quote_spanned! {span=> + /// Box::into_raw(Box::new(#init)) + /// }; + /// ``` + /// + /// The lack of space before the `=>` should look jarring to Rust programmers + /// and this is intentional. The formatting is designed to be visibly + /// off-balance and draw the eye a particular way, due to the span expression + /// being evaluated in the context of the procedural macro and the remaining + /// tokens being evaluated in the generated code. + /// + ///
+ /// + /// # Hygiene + /// + /// Any interpolated tokens preserve the `Span` information provided by their + /// `ToTokens` implementation. Tokens that originate within the `quote_spanned!` + /// invocation are spanned with the given span argument. + /// + ///
+ /// + /// # Example + /// + /// The following procedural macro code uses `quote_spanned!` to assert that a + /// particular Rust type implements the [`Sync`] trait so that references can be + /// safely shared between threads. + /// + /// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html + /// + /// ``` + /// # use quote::{quote_spanned, TokenStreamExt, ToTokens}; + /// # use proc_macro2::{Span, TokenStream}; + /// # + /// # struct Type; + /// # + /// # impl Type { + /// # fn span(&self) -> Span { + /// # Span::call_site() + /// # } + /// # } + /// # + /// # impl ToTokens for Type { + /// # fn to_tokens(&self, _tokens: &mut TokenStream) {} + /// # } + /// # + /// # let ty = Type; + /// # let call_site = Span::call_site(); + /// # + /// let ty_span = ty.span(); + /// let assert_sync = quote_spanned! {ty_span=> + /// struct _AssertSync where #ty: Sync; + /// }; + /// ``` + /// + /// If the assertion fails, the user will see an error like the following. The + /// input span of their type is highlighted in the error. + /// + /// ```text + /// error[E0277]: the trait bound `*const (): std::marker::Sync` is not satisfied + /// --> src/main.rs:10:21 + /// | + /// 10 | static ref PTR: *const () = &(); + /// | ^^^^^^^^^ `*const ()` cannot be shared between threads safely + /// ``` + /// + /// In this example it is important for the where-clause to be spanned with the + /// line/column information of the user's input type so that error messages are + /// placed appropriately by the compiler. + $quote_spanned + }; +} + +#[cfg(doc)] +__quote_spanned![ + #[macro_export] + macro_rules! quote_spanned { + ($span:expr=> $($tt:tt)*) => { + ... + }; + } +]; + +#[cfg(not(doc))] +__quote_spanned![ + #[macro_export] + macro_rules! quote_spanned { + ($span:expr=>) => {{ + let _: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); + $crate::__private::TokenStream::new() + }}; + + // Special case rule for a single tt, for performance. + ($span:expr=> $tt:tt) => {{ + let mut _s = $crate::__private::TokenStream::new(); + let _span: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); + $crate::quote_token_spanned!{$tt _s _span} + _s + }}; + + // Special case rules for two tts, for performance. + ($span:expr=> # $var:ident) => {{ + let mut _s = $crate::__private::TokenStream::new(); + let _: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); + $crate::ToTokens::to_tokens(&$var, &mut _s); + _s + }}; + ($span:expr=> $tt1:tt $tt2:tt) => {{ + let mut _s = $crate::__private::TokenStream::new(); + let _span: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); + $crate::quote_token_spanned!{$tt1 _s _span} + $crate::quote_token_spanned!{$tt2 _s _span} + _s + }}; + + // Rule for any other number of tokens. + ($span:expr=> $($tt:tt)*) => {{ + let mut _s = $crate::__private::TokenStream::new(); + let _span: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); + $crate::quote_each_token_spanned!{_s _span $($tt)*} + _s + }}; + } +]; + +// Extract the names of all #metavariables and pass them to the $call macro. +// +// in: pounded_var_names!(then!(...) a #b c #( #d )* #e) +// out: then!(... b); +// then!(... d); +// then!(... e); +#[macro_export] +#[doc(hidden)] +macro_rules! pounded_var_names { + ($call:ident! $extra:tt $($tts:tt)*) => { + $crate::pounded_var_names_with_context!{$call! $extra + (@ $($tts)*) + ($($tts)* @) + } + }; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! pounded_var_names_with_context { + ($call:ident! $extra:tt ($($b1:tt)*) ($($curr:tt)*)) => { + $( + $crate::pounded_var_with_context!{$call! $extra $b1 $curr} + )* + }; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! pounded_var_with_context { + ($call:ident! $extra:tt $b1:tt ( $($inner:tt)* )) => { + $crate::pounded_var_names!{$call! $extra $($inner)*} + }; + + ($call:ident! $extra:tt $b1:tt [ $($inner:tt)* ]) => { + $crate::pounded_var_names!{$call! $extra $($inner)*} + }; + + ($call:ident! $extra:tt $b1:tt { $($inner:tt)* }) => { + $crate::pounded_var_names!{$call! $extra $($inner)*} + }; + + ($call:ident!($($extra:tt)*) # $var:ident) => { + $crate::$call!($($extra)* $var); + }; + + ($call:ident! $extra:tt $b1:tt $curr:tt) => {}; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! quote_bind_into_iter { + ($has_iter:ident $var:ident) => { + // `mut` may be unused if $var occurs multiple times in the list. + #[allow(unused_mut)] + let (mut $var, i) = $var.quote_into_iter(); + let $has_iter = $has_iter | i; + }; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! quote_bind_next_or_break { + ($var:ident) => { + let $var = match $var.next() { + Some(_x) => $crate::__private::RepInterp(_x), + None => break, + }; + }; +} + +// The obvious way to write this macro is as a tt muncher. This implementation +// does something more complex for two reasons. +// +// - With a tt muncher it's easy to hit Rust's built-in recursion_limit, which +// this implementation avoids because it isn't tail recursive. +// +// - Compile times for a tt muncher are quadratic relative to the length of +// the input. This implementation is linear, so it will be faster +// (potentially much faster) for big inputs. However, the constant factors +// of this implementation are higher than that of a tt muncher, so it is +// somewhat slower than a tt muncher if there are many invocations with +// short inputs. +// +// An invocation like this: +// +// quote_each_token!(_s a b c d e f g h i j); +// +// expands to this: +// +// quote_tokens_with_context!(_s +// (@ @ @ @ @ @ a b c d e f g h i j) +// (@ @ @ @ @ a b c d e f g h i j @) +// (@ @ @ @ a b c d e f g h i j @ @) +// (@ @ @ (a) (b) (c) (d) (e) (f) (g) (h) (i) (j) @ @ @) +// (@ @ a b c d e f g h i j @ @ @ @) +// (@ a b c d e f g h i j @ @ @ @ @) +// (a b c d e f g h i j @ @ @ @ @ @) +// ); +// +// which gets transposed and expanded to this: +// +// quote_token_with_context!(_s @ @ @ @ @ @ a); +// quote_token_with_context!(_s @ @ @ @ @ a b); +// quote_token_with_context!(_s @ @ @ @ a b c); +// quote_token_with_context!(_s @ @ @ (a) b c d); +// quote_token_with_context!(_s @ @ a (b) c d e); +// quote_token_with_context!(_s @ a b (c) d e f); +// quote_token_with_context!(_s a b c (d) e f g); +// quote_token_with_context!(_s b c d (e) f g h); +// quote_token_with_context!(_s c d e (f) g h i); +// quote_token_with_context!(_s d e f (g) h i j); +// quote_token_with_context!(_s e f g (h) i j @); +// quote_token_with_context!(_s f g h (i) j @ @); +// quote_token_with_context!(_s g h i (j) @ @ @); +// quote_token_with_context!(_s h i j @ @ @ @); +// quote_token_with_context!(_s i j @ @ @ @ @); +// quote_token_with_context!(_s j @ @ @ @ @ @); +// +// Without having used muncher-style recursion, we get one invocation of +// quote_token_with_context for each original tt, with three tts of context on +// either side. This is enough for the longest possible interpolation form (a +// repetition with separator, as in `# (#var) , *`) to be fully represented with +// the first or last tt in the middle. +// +// The middle tt (surrounded by parentheses) is the tt being processed. +// +// - When it is a `#`, quote_token_with_context can do an interpolation. The +// interpolation kind will depend on the three subsequent tts. +// +// - When it is within a later part of an interpolation, it can be ignored +// because the interpolation has already been done. +// +// - When it is not part of an interpolation it can be pushed as a single +// token into the output. +// +// - When the middle token is an unparenthesized `@`, that call is one of the +// first 3 or last 3 calls of quote_token_with_context and does not +// correspond to one of the original input tokens, so turns into nothing. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_each_token { + ($tokens:ident $($tts:tt)*) => { + $crate::quote_tokens_with_context!{$tokens + (@ @ @ @ @ @ $($tts)*) + (@ @ @ @ @ $($tts)* @) + (@ @ @ @ $($tts)* @ @) + (@ @ @ $(($tts))* @ @ @) + (@ @ $($tts)* @ @ @ @) + (@ $($tts)* @ @ @ @ @) + ($($tts)* @ @ @ @ @ @) + } + }; +} + +// See the explanation on quote_each_token. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_each_token_spanned { + ($tokens:ident $span:ident $($tts:tt)*) => { + $crate::quote_tokens_with_context_spanned!{$tokens $span + (@ @ @ @ @ @ $($tts)*) + (@ @ @ @ @ $($tts)* @) + (@ @ @ @ $($tts)* @ @) + (@ @ @ $(($tts))* @ @ @) + (@ @ $($tts)* @ @ @ @) + (@ $($tts)* @ @ @ @ @) + ($($tts)* @ @ @ @ @ @) + } + }; +} + +// See the explanation on quote_each_token. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_tokens_with_context { + ($tokens:ident + ($($b3:tt)*) ($($b2:tt)*) ($($b1:tt)*) + ($($curr:tt)*) + ($($a1:tt)*) ($($a2:tt)*) ($($a3:tt)*) + ) => { + $( + $crate::quote_token_with_context!{$tokens $b3 $b2 $b1 $curr $a1 $a2 $a3} + )* + }; +} + +// See the explanation on quote_each_token. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_tokens_with_context_spanned { + ($tokens:ident $span:ident + ($($b3:tt)*) ($($b2:tt)*) ($($b1:tt)*) + ($($curr:tt)*) + ($($a1:tt)*) ($($a2:tt)*) ($($a3:tt)*) + ) => { + $( + $crate::quote_token_with_context_spanned!{$tokens $span $b3 $b2 $b1 $curr $a1 $a2 $a3} + )* + }; +} + +// See the explanation on quote_each_token. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_token_with_context { + // Unparenthesized `@` indicates this call does not correspond to one of the + // original input tokens. Ignore it. + ($tokens:ident $b3:tt $b2:tt $b1:tt @ $a1:tt $a2:tt $a3:tt) => {}; + + // A repetition with no separator. + ($tokens:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) * $a3:tt) => {{ + use $crate::__private::ext::*; + let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; + $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} + let _: $crate::__private::HasIterator = has_iter; + // This is `while true` instead of `loop` because if there are no + // iterators used inside of this repetition then the body would not + // contain any `break`, so the compiler would emit unreachable code + // warnings on anything below the loop. We use has_iter to detect and + // fail to compile when there are no iterators, so here we just work + // around the unneeded extra warning. + while true { + $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} + $crate::quote_each_token!{$tokens $($inner)*} + } + }}; + // ... and one step later. + ($tokens:ident $b3:tt $b2:tt # (( $($inner:tt)* )) * $a2:tt $a3:tt) => {}; + // ... and one step later. + ($tokens:ident $b3:tt # ( $($inner:tt)* ) (*) $a1:tt $a2:tt $a3:tt) => {}; + + // A repetition with separator. + ($tokens:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) $sep:tt *) => {{ + use $crate::__private::ext::*; + let mut _i = 0usize; + let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; + $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} + let _: $crate::__private::HasIterator = has_iter; + while true { + $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} + if _i > 0 { + $crate::quote_token!{$sep $tokens} + } + _i += 1; + $crate::quote_each_token!{$tokens $($inner)*} + } + }}; + // ... and one step later. + ($tokens:ident $b3:tt $b2:tt # (( $($inner:tt)* )) $sep:tt * $a3:tt) => {}; + // ... and one step later. + ($tokens:ident $b3:tt # ( $($inner:tt)* ) ($sep:tt) * $a2:tt $a3:tt) => {}; + // (A special case for `#(var)**`, where the first `*` is treated as the + // repetition symbol and the second `*` is treated as an ordinary token.) + ($tokens:ident # ( $($inner:tt)* ) * (*) $a1:tt $a2:tt $a3:tt) => { + // https://github.com/dtolnay/quote/issues/130 + $crate::quote_token!{* $tokens} + }; + // ... and one step later. + ($tokens:ident # ( $($inner:tt)* ) $sep:tt (*) $a1:tt $a2:tt $a3:tt) => {}; + + // A non-repetition interpolation. + ($tokens:ident $b3:tt $b2:tt $b1:tt (#) $var:ident $a2:tt $a3:tt) => { + $crate::ToTokens::to_tokens(&$var, &mut $tokens); + }; + // ... and one step later. + ($tokens:ident $b3:tt $b2:tt # ($var:ident) $a1:tt $a2:tt $a3:tt) => {}; + + // An ordinary token, not part of any interpolation. + ($tokens:ident $b3:tt $b2:tt $b1:tt ($curr:tt) $a1:tt $a2:tt $a3:tt) => { + $crate::quote_token!{$curr $tokens} + }; +} + +// See the explanation on quote_each_token, and on the individual rules of +// quote_token_with_context. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_token_with_context_spanned { + ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt @ $a1:tt $a2:tt $a3:tt) => {}; + + ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) * $a3:tt) => {{ + use $crate::__private::ext::*; + let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; + $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} + let _: $crate::__private::HasIterator = has_iter; + while true { + $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} + $crate::quote_each_token_spanned!{$tokens $span $($inner)*} + } + }}; + ($tokens:ident $span:ident $b3:tt $b2:tt # (( $($inner:tt)* )) * $a2:tt $a3:tt) => {}; + ($tokens:ident $span:ident $b3:tt # ( $($inner:tt)* ) (*) $a1:tt $a2:tt $a3:tt) => {}; + + ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) $sep:tt *) => {{ + use $crate::__private::ext::*; + let mut _i = 0usize; + let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; + $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} + let _: $crate::__private::HasIterator = has_iter; + while true { + $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} + if _i > 0 { + $crate::quote_token_spanned!{$sep $tokens $span} + } + _i += 1; + $crate::quote_each_token_spanned!{$tokens $span $($inner)*} + } + }}; + ($tokens:ident $span:ident $b3:tt $b2:tt # (( $($inner:tt)* )) $sep:tt * $a3:tt) => {}; + ($tokens:ident $span:ident $b3:tt # ( $($inner:tt)* ) ($sep:tt) * $a2:tt $a3:tt) => {}; + ($tokens:ident $span:ident # ( $($inner:tt)* ) * (*) $a1:tt $a2:tt $a3:tt) => { + // https://github.com/dtolnay/quote/issues/130 + $crate::quote_token_spanned!{* $tokens $span} + }; + ($tokens:ident $span:ident # ( $($inner:tt)* ) $sep:tt (*) $a1:tt $a2:tt $a3:tt) => {}; + + ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt (#) $var:ident $a2:tt $a3:tt) => { + $crate::ToTokens::to_tokens(&$var, &mut $tokens); + }; + ($tokens:ident $span:ident $b3:tt $b2:tt # ($var:ident) $a1:tt $a2:tt $a3:tt) => {}; + + ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt ($curr:tt) $a1:tt $a2:tt $a3:tt) => { + $crate::quote_token_spanned!{$curr $tokens $span} + }; +} + +// These rules are ordered by approximate token frequency, at least for the +// first 10 or so, to improve compile times. Having `ident` first is by far the +// most important because it's typically 2-3x more common than the next most +// common token. +// +// Separately, we put the token being matched in the very front so that failing +// rules may fail to match as quickly as possible. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_token { + ($ident:ident $tokens:ident) => { + $crate::__private::push_ident(&mut $tokens, stringify!($ident)); + }; + + (:: $tokens:ident) => { + $crate::__private::push_colon2(&mut $tokens); + }; + + (( $($inner:tt)* ) $tokens:ident) => { + $crate::__private::push_group( + &mut $tokens, + $crate::__private::Delimiter::Parenthesis, + $crate::quote!($($inner)*), + ); + }; + + ([ $($inner:tt)* ] $tokens:ident) => { + $crate::__private::push_group( + &mut $tokens, + $crate::__private::Delimiter::Bracket, + $crate::quote!($($inner)*), + ); + }; + + ({ $($inner:tt)* } $tokens:ident) => { + $crate::__private::push_group( + &mut $tokens, + $crate::__private::Delimiter::Brace, + $crate::quote!($($inner)*), + ); + }; + + (# $tokens:ident) => { + $crate::__private::push_pound(&mut $tokens); + }; + + (, $tokens:ident) => { + $crate::__private::push_comma(&mut $tokens); + }; + + (. $tokens:ident) => { + $crate::__private::push_dot(&mut $tokens); + }; + + (; $tokens:ident) => { + $crate::__private::push_semi(&mut $tokens); + }; + + (: $tokens:ident) => { + $crate::__private::push_colon(&mut $tokens); + }; + + (+ $tokens:ident) => { + $crate::__private::push_add(&mut $tokens); + }; + + (+= $tokens:ident) => { + $crate::__private::push_add_eq(&mut $tokens); + }; + + (& $tokens:ident) => { + $crate::__private::push_and(&mut $tokens); + }; + + (&& $tokens:ident) => { + $crate::__private::push_and_and(&mut $tokens); + }; + + (&= $tokens:ident) => { + $crate::__private::push_and_eq(&mut $tokens); + }; + + (@ $tokens:ident) => { + $crate::__private::push_at(&mut $tokens); + }; + + (! $tokens:ident) => { + $crate::__private::push_bang(&mut $tokens); + }; + + (^ $tokens:ident) => { + $crate::__private::push_caret(&mut $tokens); + }; + + (^= $tokens:ident) => { + $crate::__private::push_caret_eq(&mut $tokens); + }; + + (/ $tokens:ident) => { + $crate::__private::push_div(&mut $tokens); + }; + + (/= $tokens:ident) => { + $crate::__private::push_div_eq(&mut $tokens); + }; + + (.. $tokens:ident) => { + $crate::__private::push_dot2(&mut $tokens); + }; + + (... $tokens:ident) => { + $crate::__private::push_dot3(&mut $tokens); + }; + + (..= $tokens:ident) => { + $crate::__private::push_dot_dot_eq(&mut $tokens); + }; + + (= $tokens:ident) => { + $crate::__private::push_eq(&mut $tokens); + }; + + (== $tokens:ident) => { + $crate::__private::push_eq_eq(&mut $tokens); + }; + + (>= $tokens:ident) => { + $crate::__private::push_ge(&mut $tokens); + }; + + (> $tokens:ident) => { + $crate::__private::push_gt(&mut $tokens); + }; + + (<= $tokens:ident) => { + $crate::__private::push_le(&mut $tokens); + }; + + (< $tokens:ident) => { + $crate::__private::push_lt(&mut $tokens); + }; + + (*= $tokens:ident) => { + $crate::__private::push_mul_eq(&mut $tokens); + }; + + (!= $tokens:ident) => { + $crate::__private::push_ne(&mut $tokens); + }; + + (| $tokens:ident) => { + $crate::__private::push_or(&mut $tokens); + }; + + (|= $tokens:ident) => { + $crate::__private::push_or_eq(&mut $tokens); + }; + + (|| $tokens:ident) => { + $crate::__private::push_or_or(&mut $tokens); + }; + + (? $tokens:ident) => { + $crate::__private::push_question(&mut $tokens); + }; + + (-> $tokens:ident) => { + $crate::__private::push_rarrow(&mut $tokens); + }; + + (<- $tokens:ident) => { + $crate::__private::push_larrow(&mut $tokens); + }; + + (% $tokens:ident) => { + $crate::__private::push_rem(&mut $tokens); + }; + + (%= $tokens:ident) => { + $crate::__private::push_rem_eq(&mut $tokens); + }; + + (=> $tokens:ident) => { + $crate::__private::push_fat_arrow(&mut $tokens); + }; + + (<< $tokens:ident) => { + $crate::__private::push_shl(&mut $tokens); + }; + + (<<= $tokens:ident) => { + $crate::__private::push_shl_eq(&mut $tokens); + }; + + (>> $tokens:ident) => { + $crate::__private::push_shr(&mut $tokens); + }; + + (>>= $tokens:ident) => { + $crate::__private::push_shr_eq(&mut $tokens); + }; + + (* $tokens:ident) => { + $crate::__private::push_star(&mut $tokens); + }; + + (- $tokens:ident) => { + $crate::__private::push_sub(&mut $tokens); + }; + + (-= $tokens:ident) => { + $crate::__private::push_sub_eq(&mut $tokens); + }; + + ($lifetime:lifetime $tokens:ident) => { + $crate::__private::push_lifetime(&mut $tokens, stringify!($lifetime)); + }; + + (_ $tokens:ident) => { + $crate::__private::push_underscore(&mut $tokens); + }; + + ($other:tt $tokens:ident) => { + $crate::__private::parse(&mut $tokens, stringify!($other)); + }; +} + +// See the comment above `quote_token!` about the rule ordering. +#[macro_export] +#[doc(hidden)] +macro_rules! quote_token_spanned { + ($ident:ident $tokens:ident $span:ident) => { + $crate::__private::push_ident_spanned(&mut $tokens, $span, stringify!($ident)); + }; + + (:: $tokens:ident $span:ident) => { + $crate::__private::push_colon2_spanned(&mut $tokens, $span); + }; + + (( $($inner:tt)* ) $tokens:ident $span:ident) => { + $crate::__private::push_group_spanned( + &mut $tokens, + $span, + $crate::__private::Delimiter::Parenthesis, + $crate::quote_spanned!($span=> $($inner)*), + ); + }; + + ([ $($inner:tt)* ] $tokens:ident $span:ident) => { + $crate::__private::push_group_spanned( + &mut $tokens, + $span, + $crate::__private::Delimiter::Bracket, + $crate::quote_spanned!($span=> $($inner)*), + ); + }; + + ({ $($inner:tt)* } $tokens:ident $span:ident) => { + $crate::__private::push_group_spanned( + &mut $tokens, + $span, + $crate::__private::Delimiter::Brace, + $crate::quote_spanned!($span=> $($inner)*), + ); + }; + + (# $tokens:ident $span:ident) => { + $crate::__private::push_pound_spanned(&mut $tokens, $span); + }; + + (, $tokens:ident $span:ident) => { + $crate::__private::push_comma_spanned(&mut $tokens, $span); + }; + + (. $tokens:ident $span:ident) => { + $crate::__private::push_dot_spanned(&mut $tokens, $span); + }; + + (; $tokens:ident $span:ident) => { + $crate::__private::push_semi_spanned(&mut $tokens, $span); + }; + + (: $tokens:ident $span:ident) => { + $crate::__private::push_colon_spanned(&mut $tokens, $span); + }; + + (+ $tokens:ident $span:ident) => { + $crate::__private::push_add_spanned(&mut $tokens, $span); + }; + + (+= $tokens:ident $span:ident) => { + $crate::__private::push_add_eq_spanned(&mut $tokens, $span); + }; + + (& $tokens:ident $span:ident) => { + $crate::__private::push_and_spanned(&mut $tokens, $span); + }; + + (&& $tokens:ident $span:ident) => { + $crate::__private::push_and_and_spanned(&mut $tokens, $span); + }; + + (&= $tokens:ident $span:ident) => { + $crate::__private::push_and_eq_spanned(&mut $tokens, $span); + }; + + (@ $tokens:ident $span:ident) => { + $crate::__private::push_at_spanned(&mut $tokens, $span); + }; + + (! $tokens:ident $span:ident) => { + $crate::__private::push_bang_spanned(&mut $tokens, $span); + }; + + (^ $tokens:ident $span:ident) => { + $crate::__private::push_caret_spanned(&mut $tokens, $span); + }; + + (^= $tokens:ident $span:ident) => { + $crate::__private::push_caret_eq_spanned(&mut $tokens, $span); + }; + + (/ $tokens:ident $span:ident) => { + $crate::__private::push_div_spanned(&mut $tokens, $span); + }; + + (/= $tokens:ident $span:ident) => { + $crate::__private::push_div_eq_spanned(&mut $tokens, $span); + }; + + (.. $tokens:ident $span:ident) => { + $crate::__private::push_dot2_spanned(&mut $tokens, $span); + }; + + (... $tokens:ident $span:ident) => { + $crate::__private::push_dot3_spanned(&mut $tokens, $span); + }; + + (..= $tokens:ident $span:ident) => { + $crate::__private::push_dot_dot_eq_spanned(&mut $tokens, $span); + }; + + (= $tokens:ident $span:ident) => { + $crate::__private::push_eq_spanned(&mut $tokens, $span); + }; + + (== $tokens:ident $span:ident) => { + $crate::__private::push_eq_eq_spanned(&mut $tokens, $span); + }; + + (>= $tokens:ident $span:ident) => { + $crate::__private::push_ge_spanned(&mut $tokens, $span); + }; + + (> $tokens:ident $span:ident) => { + $crate::__private::push_gt_spanned(&mut $tokens, $span); + }; + + (<= $tokens:ident $span:ident) => { + $crate::__private::push_le_spanned(&mut $tokens, $span); + }; + + (< $tokens:ident $span:ident) => { + $crate::__private::push_lt_spanned(&mut $tokens, $span); + }; + + (*= $tokens:ident $span:ident) => { + $crate::__private::push_mul_eq_spanned(&mut $tokens, $span); + }; + + (!= $tokens:ident $span:ident) => { + $crate::__private::push_ne_spanned(&mut $tokens, $span); + }; + + (| $tokens:ident $span:ident) => { + $crate::__private::push_or_spanned(&mut $tokens, $span); + }; + + (|= $tokens:ident $span:ident) => { + $crate::__private::push_or_eq_spanned(&mut $tokens, $span); + }; + + (|| $tokens:ident $span:ident) => { + $crate::__private::push_or_or_spanned(&mut $tokens, $span); + }; + + (? $tokens:ident $span:ident) => { + $crate::__private::push_question_spanned(&mut $tokens, $span); + }; + + (-> $tokens:ident $span:ident) => { + $crate::__private::push_rarrow_spanned(&mut $tokens, $span); + }; + + (<- $tokens:ident $span:ident) => { + $crate::__private::push_larrow_spanned(&mut $tokens, $span); + }; + + (% $tokens:ident $span:ident) => { + $crate::__private::push_rem_spanned(&mut $tokens, $span); + }; + + (%= $tokens:ident $span:ident) => { + $crate::__private::push_rem_eq_spanned(&mut $tokens, $span); + }; + + (=> $tokens:ident $span:ident) => { + $crate::__private::push_fat_arrow_spanned(&mut $tokens, $span); + }; + + (<< $tokens:ident $span:ident) => { + $crate::__private::push_shl_spanned(&mut $tokens, $span); + }; + + (<<= $tokens:ident $span:ident) => { + $crate::__private::push_shl_eq_spanned(&mut $tokens, $span); + }; + + (>> $tokens:ident $span:ident) => { + $crate::__private::push_shr_spanned(&mut $tokens, $span); + }; + + (>>= $tokens:ident $span:ident) => { + $crate::__private::push_shr_eq_spanned(&mut $tokens, $span); + }; + + (* $tokens:ident $span:ident) => { + $crate::__private::push_star_spanned(&mut $tokens, $span); + }; + + (- $tokens:ident $span:ident) => { + $crate::__private::push_sub_spanned(&mut $tokens, $span); + }; + + (-= $tokens:ident $span:ident) => { + $crate::__private::push_sub_eq_spanned(&mut $tokens, $span); + }; + + ($lifetime:lifetime $tokens:ident $span:ident) => { + $crate::__private::push_lifetime_spanned(&mut $tokens, $span, stringify!($lifetime)); + }; + + (_ $tokens:ident $span:ident) => { + $crate::__private::push_underscore_spanned(&mut $tokens, $span); + }; + + ($other:tt $tokens:ident $span:ident) => { + $crate::__private::parse_spanned(&mut $tokens, $span, stringify!($other)); + }; +} diff --git a/bitbox02-bt/vendor/quote/src/runtime.rs b/bitbox02-bt/vendor/quote/src/runtime.rs new file mode 100644 index 0000000..eff044a --- /dev/null +++ b/bitbox02-bt/vendor/quote/src/runtime.rs @@ -0,0 +1,530 @@ +use self::get_span::{GetSpan, GetSpanBase, GetSpanInner}; +use crate::{IdentFragment, ToTokens, TokenStreamExt}; +use core::fmt; +use core::iter; +use core::ops::BitOr; +use proc_macro2::{Group, Ident, Punct, Spacing, TokenTree}; + +#[doc(hidden)] +pub use alloc::format; +#[doc(hidden)] +pub use core::option::Option; + +#[doc(hidden)] +pub type Delimiter = proc_macro2::Delimiter; +#[doc(hidden)] +pub type Span = proc_macro2::Span; +#[doc(hidden)] +pub type TokenStream = proc_macro2::TokenStream; + +#[doc(hidden)] +pub struct HasIterator; // True +#[doc(hidden)] +pub struct ThereIsNoIteratorInRepetition; // False + +impl BitOr for ThereIsNoIteratorInRepetition { + type Output = ThereIsNoIteratorInRepetition; + fn bitor(self, _rhs: ThereIsNoIteratorInRepetition) -> ThereIsNoIteratorInRepetition { + ThereIsNoIteratorInRepetition + } +} + +impl BitOr for HasIterator { + type Output = HasIterator; + fn bitor(self, _rhs: ThereIsNoIteratorInRepetition) -> HasIterator { + HasIterator + } +} + +impl BitOr for ThereIsNoIteratorInRepetition { + type Output = HasIterator; + fn bitor(self, _rhs: HasIterator) -> HasIterator { + HasIterator + } +} + +impl BitOr for HasIterator { + type Output = HasIterator; + fn bitor(self, _rhs: HasIterator) -> HasIterator { + HasIterator + } +} + +/// Extension traits used by the implementation of `quote!`. These are defined +/// in separate traits, rather than as a single trait due to ambiguity issues. +/// +/// These traits expose a `quote_into_iter` method which should allow calling +/// whichever impl happens to be applicable. Calling that method repeatedly on +/// the returned value should be idempotent. +#[doc(hidden)] +pub mod ext { + use super::RepInterp; + use super::{HasIterator as HasIter, ThereIsNoIteratorInRepetition as DoesNotHaveIter}; + use crate::ToTokens; + use alloc::collections::btree_set::{self, BTreeSet}; + use core::slice; + + /// Extension trait providing the `quote_into_iter` method on iterators. + #[doc(hidden)] + pub trait RepIteratorExt: Iterator + Sized { + fn quote_into_iter(self) -> (Self, HasIter) { + (self, HasIter) + } + } + + impl RepIteratorExt for T {} + + /// Extension trait providing the `quote_into_iter` method for + /// non-iterable types. These types interpolate the same value in each + /// iteration of the repetition. + #[doc(hidden)] + pub trait RepToTokensExt { + /// Pretend to be an iterator for the purposes of `quote_into_iter`. + /// This allows repeated calls to `quote_into_iter` to continue + /// correctly returning DoesNotHaveIter. + fn next(&self) -> Option<&Self> { + Some(self) + } + + fn quote_into_iter(&self) -> (&Self, DoesNotHaveIter) { + (self, DoesNotHaveIter) + } + } + + impl RepToTokensExt for T {} + + /// Extension trait providing the `quote_into_iter` method for types that + /// can be referenced as an iterator. + #[doc(hidden)] + pub trait RepAsIteratorExt<'q> { + type Iter: Iterator; + + fn quote_into_iter(&'q self) -> (Self::Iter, HasIter); + } + + impl<'q, 'a, T: RepAsIteratorExt<'q> + ?Sized> RepAsIteratorExt<'q> for &'a T { + type Iter = T::Iter; + + fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { + ::quote_into_iter(*self) + } + } + + impl<'q, 'a, T: RepAsIteratorExt<'q> + ?Sized> RepAsIteratorExt<'q> for &'a mut T { + type Iter = T::Iter; + + fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { + ::quote_into_iter(*self) + } + } + + impl<'q, T: 'q> RepAsIteratorExt<'q> for [T] { + type Iter = slice::Iter<'q, T>; + + fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { + (self.iter(), HasIter) + } + } + + impl<'q, T: 'q> RepAsIteratorExt<'q> for Vec { + type Iter = slice::Iter<'q, T>; + + fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { + (self.iter(), HasIter) + } + } + + impl<'q, T: 'q> RepAsIteratorExt<'q> for BTreeSet { + type Iter = btree_set::Iter<'q, T>; + + fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { + (self.iter(), HasIter) + } + } + + impl<'q, T: RepAsIteratorExt<'q>> RepAsIteratorExt<'q> for RepInterp { + type Iter = T::Iter; + + fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { + self.0.quote_into_iter() + } + } +} + +// Helper type used within interpolations to allow for repeated binding names. +// Implements the relevant traits, and exports a dummy `next()` method. +#[derive(Copy, Clone)] +#[doc(hidden)] +pub struct RepInterp(pub T); + +impl RepInterp { + // This method is intended to look like `Iterator::next`, and is called when + // a name is bound multiple times, as the previous binding will shadow the + // original `Iterator` object. This allows us to avoid advancing the + // iterator multiple times per iteration. + pub fn next(self) -> Option { + Some(self.0) + } +} + +impl Iterator for RepInterp { + type Item = T::Item; + + fn next(&mut self) -> Option { + self.0.next() + } +} + +impl ToTokens for RepInterp { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.0.to_tokens(tokens); + } +} + +#[doc(hidden)] +#[inline] +pub fn get_span(span: T) -> GetSpan { + GetSpan(GetSpanInner(GetSpanBase(span))) +} + +mod get_span { + use core::ops::Deref; + use proc_macro2::extra::DelimSpan; + use proc_macro2::Span; + + pub struct GetSpan(pub(crate) GetSpanInner); + + pub struct GetSpanInner(pub(crate) GetSpanBase); + + pub struct GetSpanBase(pub(crate) T); + + impl GetSpan { + #[inline] + pub fn __into_span(self) -> Span { + ((self.0).0).0 + } + } + + impl GetSpanInner { + #[inline] + pub fn __into_span(&self) -> Span { + (self.0).0.join() + } + } + + impl GetSpanBase { + #[allow(clippy::unused_self)] + pub fn __into_span(&self) -> T { + unreachable!() + } + } + + impl Deref for GetSpan { + type Target = GetSpanInner; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl Deref for GetSpanInner { + type Target = GetSpanBase; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } + } +} + +#[doc(hidden)] +pub fn push_group(tokens: &mut TokenStream, delimiter: Delimiter, inner: TokenStream) { + tokens.append(Group::new(delimiter, inner)); +} + +#[doc(hidden)] +pub fn push_group_spanned( + tokens: &mut TokenStream, + span: Span, + delimiter: Delimiter, + inner: TokenStream, +) { + let mut g = Group::new(delimiter, inner); + g.set_span(span); + tokens.append(g); +} + +#[doc(hidden)] +pub fn parse(tokens: &mut TokenStream, s: &str) { + let s: TokenStream = s.parse().expect("invalid token stream"); + tokens.extend(iter::once(s)); +} + +#[doc(hidden)] +pub fn parse_spanned(tokens: &mut TokenStream, span: Span, s: &str) { + let s: TokenStream = s.parse().expect("invalid token stream"); + tokens.extend(s.into_iter().map(|t| respan_token_tree(t, span))); +} + +// Token tree with every span replaced by the given one. +fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree { + match &mut token { + TokenTree::Group(g) => { + let stream = g + .stream() + .into_iter() + .map(|token| respan_token_tree(token, span)) + .collect(); + *g = Group::new(g.delimiter(), stream); + g.set_span(span); + } + other => other.set_span(span), + } + token +} + +#[doc(hidden)] +pub fn push_ident(tokens: &mut TokenStream, s: &str) { + let span = Span::call_site(); + push_ident_spanned(tokens, span, s); +} + +#[doc(hidden)] +pub fn push_ident_spanned(tokens: &mut TokenStream, span: Span, s: &str) { + tokens.append(ident_maybe_raw(s, span)); +} + +#[doc(hidden)] +pub fn push_lifetime(tokens: &mut TokenStream, lifetime: &str) { + struct Lifetime<'a> { + name: &'a str, + state: u8, + } + + impl<'a> Iterator for Lifetime<'a> { + type Item = TokenTree; + + fn next(&mut self) -> Option { + match self.state { + 0 => { + self.state = 1; + Some(TokenTree::Punct(Punct::new('\'', Spacing::Joint))) + } + 1 => { + self.state = 2; + Some(TokenTree::Ident(Ident::new(self.name, Span::call_site()))) + } + _ => None, + } + } + } + + tokens.extend(Lifetime { + name: &lifetime[1..], + state: 0, + }); +} + +#[doc(hidden)] +pub fn push_lifetime_spanned(tokens: &mut TokenStream, span: Span, lifetime: &str) { + struct Lifetime<'a> { + name: &'a str, + span: Span, + state: u8, + } + + impl<'a> Iterator for Lifetime<'a> { + type Item = TokenTree; + + fn next(&mut self) -> Option { + match self.state { + 0 => { + self.state = 1; + let mut apostrophe = Punct::new('\'', Spacing::Joint); + apostrophe.set_span(self.span); + Some(TokenTree::Punct(apostrophe)) + } + 1 => { + self.state = 2; + Some(TokenTree::Ident(Ident::new(self.name, self.span))) + } + _ => None, + } + } + } + + tokens.extend(Lifetime { + name: &lifetime[1..], + span, + state: 0, + }); +} + +macro_rules! push_punct { + ($name:ident $spanned:ident $char1:tt) => { + #[doc(hidden)] + pub fn $name(tokens: &mut TokenStream) { + tokens.append(Punct::new($char1, Spacing::Alone)); + } + #[doc(hidden)] + pub fn $spanned(tokens: &mut TokenStream, span: Span) { + let mut punct = Punct::new($char1, Spacing::Alone); + punct.set_span(span); + tokens.append(punct); + } + }; + ($name:ident $spanned:ident $char1:tt $char2:tt) => { + #[doc(hidden)] + pub fn $name(tokens: &mut TokenStream) { + tokens.append(Punct::new($char1, Spacing::Joint)); + tokens.append(Punct::new($char2, Spacing::Alone)); + } + #[doc(hidden)] + pub fn $spanned(tokens: &mut TokenStream, span: Span) { + let mut punct = Punct::new($char1, Spacing::Joint); + punct.set_span(span); + tokens.append(punct); + let mut punct = Punct::new($char2, Spacing::Alone); + punct.set_span(span); + tokens.append(punct); + } + }; + ($name:ident $spanned:ident $char1:tt $char2:tt $char3:tt) => { + #[doc(hidden)] + pub fn $name(tokens: &mut TokenStream) { + tokens.append(Punct::new($char1, Spacing::Joint)); + tokens.append(Punct::new($char2, Spacing::Joint)); + tokens.append(Punct::new($char3, Spacing::Alone)); + } + #[doc(hidden)] + pub fn $spanned(tokens: &mut TokenStream, span: Span) { + let mut punct = Punct::new($char1, Spacing::Joint); + punct.set_span(span); + tokens.append(punct); + let mut punct = Punct::new($char2, Spacing::Joint); + punct.set_span(span); + tokens.append(punct); + let mut punct = Punct::new($char3, Spacing::Alone); + punct.set_span(span); + tokens.append(punct); + } + }; +} + +push_punct!(push_add push_add_spanned '+'); +push_punct!(push_add_eq push_add_eq_spanned '+' '='); +push_punct!(push_and push_and_spanned '&'); +push_punct!(push_and_and push_and_and_spanned '&' '&'); +push_punct!(push_and_eq push_and_eq_spanned '&' '='); +push_punct!(push_at push_at_spanned '@'); +push_punct!(push_bang push_bang_spanned '!'); +push_punct!(push_caret push_caret_spanned '^'); +push_punct!(push_caret_eq push_caret_eq_spanned '^' '='); +push_punct!(push_colon push_colon_spanned ':'); +push_punct!(push_colon2 push_colon2_spanned ':' ':'); +push_punct!(push_comma push_comma_spanned ','); +push_punct!(push_div push_div_spanned '/'); +push_punct!(push_div_eq push_div_eq_spanned '/' '='); +push_punct!(push_dot push_dot_spanned '.'); +push_punct!(push_dot2 push_dot2_spanned '.' '.'); +push_punct!(push_dot3 push_dot3_spanned '.' '.' '.'); +push_punct!(push_dot_dot_eq push_dot_dot_eq_spanned '.' '.' '='); +push_punct!(push_eq push_eq_spanned '='); +push_punct!(push_eq_eq push_eq_eq_spanned '=' '='); +push_punct!(push_ge push_ge_spanned '>' '='); +push_punct!(push_gt push_gt_spanned '>'); +push_punct!(push_le push_le_spanned '<' '='); +push_punct!(push_lt push_lt_spanned '<'); +push_punct!(push_mul_eq push_mul_eq_spanned '*' '='); +push_punct!(push_ne push_ne_spanned '!' '='); +push_punct!(push_or push_or_spanned '|'); +push_punct!(push_or_eq push_or_eq_spanned '|' '='); +push_punct!(push_or_or push_or_or_spanned '|' '|'); +push_punct!(push_pound push_pound_spanned '#'); +push_punct!(push_question push_question_spanned '?'); +push_punct!(push_rarrow push_rarrow_spanned '-' '>'); +push_punct!(push_larrow push_larrow_spanned '<' '-'); +push_punct!(push_rem push_rem_spanned '%'); +push_punct!(push_rem_eq push_rem_eq_spanned '%' '='); +push_punct!(push_fat_arrow push_fat_arrow_spanned '=' '>'); +push_punct!(push_semi push_semi_spanned ';'); +push_punct!(push_shl push_shl_spanned '<' '<'); +push_punct!(push_shl_eq push_shl_eq_spanned '<' '<' '='); +push_punct!(push_shr push_shr_spanned '>' '>'); +push_punct!(push_shr_eq push_shr_eq_spanned '>' '>' '='); +push_punct!(push_star push_star_spanned '*'); +push_punct!(push_sub push_sub_spanned '-'); +push_punct!(push_sub_eq push_sub_eq_spanned '-' '='); + +#[doc(hidden)] +pub fn push_underscore(tokens: &mut TokenStream) { + push_underscore_spanned(tokens, Span::call_site()); +} + +#[doc(hidden)] +pub fn push_underscore_spanned(tokens: &mut TokenStream, span: Span) { + tokens.append(Ident::new("_", span)); +} + +// Helper method for constructing identifiers from the `format_ident!` macro, +// handling `r#` prefixes. +#[doc(hidden)] +pub fn mk_ident(id: &str, span: Option) -> Ident { + let span = span.unwrap_or_else(Span::call_site); + ident_maybe_raw(id, span) +} + +fn ident_maybe_raw(id: &str, span: Span) -> Ident { + if let Some(id) = id.strip_prefix("r#") { + Ident::new_raw(id, span) + } else { + Ident::new(id, span) + } +} + +// Adapts from `IdentFragment` to `fmt::Display` for use by the `format_ident!` +// macro, and exposes span information from these fragments. +// +// This struct also has forwarding implementations of the formatting traits +// `Octal`, `LowerHex`, `UpperHex`, and `Binary` to allow for their use within +// `format_ident!`. +#[derive(Copy, Clone)] +#[doc(hidden)] +pub struct IdentFragmentAdapter(pub T); + +impl IdentFragmentAdapter { + pub fn span(&self) -> Option { + self.0.span() + } +} + +impl fmt::Display for IdentFragmentAdapter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + IdentFragment::fmt(&self.0, f) + } +} + +impl fmt::Octal for IdentFragmentAdapter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Octal::fmt(&self.0, f) + } +} + +impl fmt::LowerHex for IdentFragmentAdapter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::LowerHex::fmt(&self.0, f) + } +} + +impl fmt::UpperHex for IdentFragmentAdapter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::UpperHex::fmt(&self.0, f) + } +} + +impl fmt::Binary for IdentFragmentAdapter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Binary::fmt(&self.0, f) + } +} diff --git a/bitbox02-bt/vendor/quote/src/spanned.rs b/bitbox02-bt/vendor/quote/src/spanned.rs new file mode 100644 index 0000000..6eba644 --- /dev/null +++ b/bitbox02-bt/vendor/quote/src/spanned.rs @@ -0,0 +1,50 @@ +use crate::ToTokens; +use proc_macro2::extra::DelimSpan; +use proc_macro2::{Span, TokenStream}; + +// Not public API other than via the syn crate. Use syn::spanned::Spanned. +pub trait Spanned: private::Sealed { + fn __span(&self) -> Span; +} + +impl Spanned for Span { + fn __span(&self) -> Span { + *self + } +} + +impl Spanned for DelimSpan { + fn __span(&self) -> Span { + self.join() + } +} + +impl Spanned for T { + fn __span(&self) -> Span { + join_spans(self.into_token_stream()) + } +} + +fn join_spans(tokens: TokenStream) -> Span { + let mut iter = tokens.into_iter().map(|tt| tt.span()); + + let first = match iter.next() { + Some(span) => span, + None => return Span::call_site(), + }; + + iter.fold(None, |_prev, next| Some(next)) + .and_then(|last| first.join(last)) + .unwrap_or(first) +} + +mod private { + use crate::ToTokens; + use proc_macro2::extra::DelimSpan; + use proc_macro2::Span; + + pub trait Sealed {} + impl Sealed for Span {} + impl Sealed for DelimSpan {} + impl Sealed for T {} +} diff --git a/bitbox02-bt/vendor/quote/src/to_tokens.rs b/bitbox02-bt/vendor/quote/src/to_tokens.rs new file mode 100644 index 0000000..2bcb961 --- /dev/null +++ b/bitbox02-bt/vendor/quote/src/to_tokens.rs @@ -0,0 +1,275 @@ +use super::TokenStreamExt; +use alloc::borrow::Cow; +use alloc::rc::Rc; +use core::iter; +use proc_macro2::{Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; +use std::ffi::{CStr, CString}; + +/// Types that can be interpolated inside a `quote!` invocation. +/// +/// [`quote!`]: macro.quote.html +pub trait ToTokens { + /// Write `self` to the given `TokenStream`. + /// + /// The token append methods provided by the [`TokenStreamExt`] extension + /// trait may be useful for implementing `ToTokens`. + /// + /// [`TokenStreamExt`]: trait.TokenStreamExt.html + /// + /// # Example + /// + /// Example implementation for a struct representing Rust paths like + /// `std::cmp::PartialEq`: + /// + /// ``` + /// use proc_macro2::{TokenTree, Spacing, Span, Punct, TokenStream}; + /// use quote::{TokenStreamExt, ToTokens}; + /// + /// pub struct Path { + /// pub global: bool, + /// pub segments: Vec, + /// } + /// + /// impl ToTokens for Path { + /// fn to_tokens(&self, tokens: &mut TokenStream) { + /// for (i, segment) in self.segments.iter().enumerate() { + /// if i > 0 || self.global { + /// // Double colon `::` + /// tokens.append(Punct::new(':', Spacing::Joint)); + /// tokens.append(Punct::new(':', Spacing::Alone)); + /// } + /// segment.to_tokens(tokens); + /// } + /// } + /// } + /// # + /// # pub struct PathSegment; + /// # + /// # impl ToTokens for PathSegment { + /// # fn to_tokens(&self, tokens: &mut TokenStream) { + /// # unimplemented!() + /// # } + /// # } + /// ``` + fn to_tokens(&self, tokens: &mut TokenStream); + + /// Convert `self` directly into a `TokenStream` object. + /// + /// This method is implicitly implemented using `to_tokens`, and acts as a + /// convenience method for consumers of the `ToTokens` trait. + fn to_token_stream(&self) -> TokenStream { + let mut tokens = TokenStream::new(); + self.to_tokens(&mut tokens); + tokens + } + + /// Convert `self` directly into a `TokenStream` object. + /// + /// This method is implicitly implemented using `to_tokens`, and acts as a + /// convenience method for consumers of the `ToTokens` trait. + fn into_token_stream(self) -> TokenStream + where + Self: Sized, + { + self.to_token_stream() + } +} + +impl<'a, T: ?Sized + ToTokens> ToTokens for &'a T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens); + } +} + +impl<'a, T: ?Sized + ToTokens> ToTokens for &'a mut T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens); + } +} + +impl<'a, T: ?Sized + ToOwned + ToTokens> ToTokens for Cow<'a, T> { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens); + } +} + +impl ToTokens for Box { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens); + } +} + +impl ToTokens for Rc { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens); + } +} + +impl ToTokens for Option { + fn to_tokens(&self, tokens: &mut TokenStream) { + if let Some(t) = self { + t.to_tokens(tokens); + } + } +} + +impl ToTokens for str { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::string(self)); + } +} + +impl ToTokens for String { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.as_str().to_tokens(tokens); + } +} + +impl ToTokens for i8 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::i8_suffixed(*self)); + } +} + +impl ToTokens for i16 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::i16_suffixed(*self)); + } +} + +impl ToTokens for i32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::i32_suffixed(*self)); + } +} + +impl ToTokens for i64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::i64_suffixed(*self)); + } +} + +impl ToTokens for i128 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::i128_suffixed(*self)); + } +} + +impl ToTokens for isize { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::isize_suffixed(*self)); + } +} + +impl ToTokens for u8 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::u8_suffixed(*self)); + } +} + +impl ToTokens for u16 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::u16_suffixed(*self)); + } +} + +impl ToTokens for u32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::u32_suffixed(*self)); + } +} + +impl ToTokens for u64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::u64_suffixed(*self)); + } +} + +impl ToTokens for u128 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::u128_suffixed(*self)); + } +} + +impl ToTokens for usize { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::usize_suffixed(*self)); + } +} + +impl ToTokens for f32 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::f32_suffixed(*self)); + } +} + +impl ToTokens for f64 { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::f64_suffixed(*self)); + } +} + +impl ToTokens for char { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::character(*self)); + } +} + +impl ToTokens for bool { + fn to_tokens(&self, tokens: &mut TokenStream) { + let word = if *self { "true" } else { "false" }; + tokens.append(Ident::new(word, Span::call_site())); + } +} + +impl ToTokens for CStr { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::c_string(self)); + } +} + +impl ToTokens for CString { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::c_string(self)); + } +} + +impl ToTokens for Group { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(self.clone()); + } +} + +impl ToTokens for Ident { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(self.clone()); + } +} + +impl ToTokens for Punct { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(self.clone()); + } +} + +impl ToTokens for Literal { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(self.clone()); + } +} + +impl ToTokens for TokenTree { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(self.clone()); + } +} + +impl ToTokens for TokenStream { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.extend(iter::once(self.clone())); + } + + fn into_token_stream(self) -> TokenStream { + self + } +} diff --git a/bitbox02-bt/vendor/quote/tests/compiletest.rs b/bitbox02-bt/vendor/quote/tests/compiletest.rs new file mode 100644 index 0000000..23a6a06 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/compiletest.rs @@ -0,0 +1,7 @@ +#[rustversion::attr(not(nightly), ignore = "requires nightly")] +#[cfg_attr(miri, ignore = "incompatible with miri")] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/ui/*.rs"); +} diff --git a/bitbox02-bt/vendor/quote/tests/test.rs b/bitbox02-bt/vendor/quote/tests/test.rs new file mode 100644 index 0000000..6ff1402 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/test.rs @@ -0,0 +1,565 @@ +#![allow( + clippy::disallowed_names, + clippy::let_underscore_untyped, + clippy::shadow_unrelated, + clippy::unseparated_literal_suffix, + clippy::used_underscore_binding +)] + +extern crate proc_macro; + +use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned, TokenStreamExt}; +use std::borrow::Cow; +use std::collections::BTreeSet; +use std::ffi::{CStr, CString}; + +struct X; + +impl quote::ToTokens for X { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Ident::new("X", Span::call_site())); + } +} + +#[test] +fn test_quote_impl() { + let tokens = quote! { + impl<'a, T: ToTokens> ToTokens for &'a T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } + } + }; + + let expected = concat!( + "impl < 'a , T : ToTokens > ToTokens for & 'a T { ", + "fn to_tokens (& self , tokens : & mut TokenStream) { ", + "(* * self) . to_tokens (tokens) ", + "} ", + "}" + ); + + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_quote_spanned_impl() { + let span = Span::call_site(); + let tokens = quote_spanned! {span=> + impl<'a, T: ToTokens> ToTokens for &'a T { + fn to_tokens(&self, tokens: &mut TokenStream) { + (**self).to_tokens(tokens) + } + } + }; + + let expected = concat!( + "impl < 'a , T : ToTokens > ToTokens for & 'a T { ", + "fn to_tokens (& self , tokens : & mut TokenStream) { ", + "(* * self) . to_tokens (tokens) ", + "} ", + "}" + ); + + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_substitution() { + let x = X; + let tokens = quote!(#x <#x> (#x) [#x] {#x}); + + let expected = "X < X > (X) [X] { X }"; + + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_iter() { + let primes = &[X, X, X, X]; + + assert_eq!("X X X X", quote!(#(#primes)*).to_string()); + + assert_eq!("X , X , X , X ,", quote!(#(#primes,)*).to_string()); + + assert_eq!("X , X , X , X", quote!(#(#primes),*).to_string()); +} + +#[test] +fn test_array() { + let array: [u8; 40] = [0; 40]; + let _ = quote!(#(#array #array)*); + + let ref_array: &[u8; 40] = &[0; 40]; + let _ = quote!(#(#ref_array #ref_array)*); + + let ref_slice: &[u8] = &[0; 40]; + let _ = quote!(#(#ref_slice #ref_slice)*); + + let array: [X; 2] = [X, X]; // !Copy + let _ = quote!(#(#array #array)*); + + let ref_array: &[X; 2] = &[X, X]; + let _ = quote!(#(#ref_array #ref_array)*); + + let ref_slice: &[X] = &[X, X]; + let _ = quote!(#(#ref_slice #ref_slice)*); +} + +#[test] +fn test_advanced() { + let generics = quote!( <'a, T> ); + + let where_clause = quote!( where T: Serialize ); + + let field_ty = quote!(String); + + let item_ty = quote!(Cow<'a, str>); + + let path = quote!(SomeTrait::serialize_with); + + let value = quote!(self.x); + + let tokens = quote! { + struct SerializeWith #generics #where_clause { + value: &'a #field_ty, + phantom: ::std::marker::PhantomData<#item_ty>, + } + + impl #generics ::serde::Serialize for SerializeWith #generics #where_clause { + fn serialize(&self, s: &mut S) -> Result<(), S::Error> + where S: ::serde::Serializer + { + #path(self.value, s) + } + } + + SerializeWith { + value: #value, + phantom: ::std::marker::PhantomData::<#item_ty>, + } + }; + + let expected = concat!( + "struct SerializeWith < 'a , T > where T : Serialize { ", + "value : & 'a String , ", + "phantom : :: std :: marker :: PhantomData < Cow < 'a , str > > , ", + "} ", + "impl < 'a , T > :: serde :: Serialize for SerializeWith < 'a , T > where T : Serialize { ", + "fn serialize < S > (& self , s : & mut S) -> Result < () , S :: Error > ", + "where S : :: serde :: Serializer ", + "{ ", + "SomeTrait :: serialize_with (self . value , s) ", + "} ", + "} ", + "SerializeWith { ", + "value : self . x , ", + "phantom : :: std :: marker :: PhantomData :: < Cow < 'a , str > > , ", + "}" + ); + + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_integer() { + let ii8 = -1i8; + let ii16 = -1i16; + let ii32 = -1i32; + let ii64 = -1i64; + let ii128 = -1i128; + let iisize = -1isize; + let uu8 = 1u8; + let uu16 = 1u16; + let uu32 = 1u32; + let uu64 = 1u64; + let uu128 = 1u128; + let uusize = 1usize; + + let tokens = quote! { + 1 1i32 1u256 + #ii8 #ii16 #ii32 #ii64 #ii128 #iisize + #uu8 #uu16 #uu32 #uu64 #uu128 #uusize + }; + let expected = + "1 1i32 1u256 - 1i8 - 1i16 - 1i32 - 1i64 - 1i128 - 1isize 1u8 1u16 1u32 1u64 1u128 1usize"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_floating() { + let e32 = 2.345f32; + + let e64 = 2.345f64; + + let tokens = quote! { + #e32 + #e64 + }; + let expected = concat!("2.345f32 2.345f64"); + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_char() { + let zero = '\u{1}'; + let pound = '#'; + let quote = '"'; + let apost = '\''; + let newline = '\n'; + let heart = '\u{2764}'; + + let tokens = quote! { + #zero #pound #quote #apost #newline #heart + }; + let expected = "'\\u{1}' '#' '\"' '\\'' '\\n' '\u{2764}'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_str() { + let s = "\u{1} a 'b \" c"; + let tokens = quote!(#s); + let expected = "\"\\u{1} a 'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_string() { + let s = "\u{1} a 'b \" c".to_string(); + let tokens = quote!(#s); + let expected = "\"\\u{1} a 'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_c_str() { + let s = CStr::from_bytes_with_nul(b"\x01 a 'b \" c\0").unwrap(); + let tokens = quote!(#s); + let expected = "c\"\\u{1} a 'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_c_string() { + let s = CString::new(&b"\x01 a 'b \" c"[..]).unwrap(); + let tokens = quote!(#s); + let expected = "c\"\\u{1} a 'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_interpolated_literal() { + macro_rules! m { + ($literal:literal) => { + quote!($literal) + }; + } + + let tokens = m!(1); + let expected = "1"; + assert_eq!(expected, tokens.to_string()); + + let tokens = m!(-1); + let expected = "- 1"; + assert_eq!(expected, tokens.to_string()); + + let tokens = m!(true); + let expected = "true"; + assert_eq!(expected, tokens.to_string()); + + let tokens = m!(-true); + let expected = "- true"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_ident() { + let foo = Ident::new("Foo", Span::call_site()); + let bar = Ident::new(&format!("Bar{}", 7), Span::call_site()); + let tokens = quote!(struct #foo; enum #bar {}); + let expected = "struct Foo ; enum Bar7 { }"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_underscore() { + let tokens = quote!(let _;); + let expected = "let _ ;"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_duplicate() { + let ch = 'x'; + + let tokens = quote!(#ch #ch); + + let expected = "'x' 'x'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_fancy_repetition() { + let foo = vec!["a", "b"]; + let bar = vec![true, false]; + + let tokens = quote! { + #(#foo: #bar),* + }; + + let expected = r#""a" : true , "b" : false"#; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_nested_fancy_repetition() { + let nested = vec![vec!['a', 'b', 'c'], vec!['x', 'y', 'z']]; + + let tokens = quote! { + #( + #(#nested)* + ),* + }; + + let expected = "'a' 'b' 'c' , 'x' 'y' 'z'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_duplicate_name_repetition() { + let foo = &["a", "b"]; + + let tokens = quote! { + #(#foo: #foo),* + #(#foo: #foo),* + }; + + let expected = r#""a" : "a" , "b" : "b" "a" : "a" , "b" : "b""#; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_duplicate_name_repetition_no_copy() { + let foo = vec!["a".to_owned(), "b".to_owned()]; + + let tokens = quote! { + #(#foo: #foo),* + }; + + let expected = r#""a" : "a" , "b" : "b""#; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_btreeset_repetition() { + let mut set = BTreeSet::new(); + set.insert("a".to_owned()); + set.insert("b".to_owned()); + + let tokens = quote! { + #(#set: #set),* + }; + + let expected = r#""a" : "a" , "b" : "b""#; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_variable_name_conflict() { + // The implementation of `#(...),*` uses the variable `_i` but it should be + // fine, if a little confusing when debugging. + let _i = vec!['a', 'b']; + let tokens = quote! { #(#_i),* }; + let expected = "'a' , 'b'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_nonrep_in_repetition() { + let rep = vec!["a", "b"]; + let nonrep = "c"; + + let tokens = quote! { + #(#rep #rep : #nonrep #nonrep),* + }; + + let expected = r#""a" "a" : "c" "c" , "b" "b" : "c" "c""#; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_empty_quote() { + let tokens = quote!(); + assert_eq!("", tokens.to_string()); +} + +#[test] +fn test_box_str() { + let b = "str".to_owned().into_boxed_str(); + let tokens = quote! { #b }; + assert_eq!("\"str\"", tokens.to_string()); +} + +#[test] +fn test_cow() { + let owned: Cow = Cow::Owned(Ident::new("owned", Span::call_site())); + + let ident = Ident::new("borrowed", Span::call_site()); + let borrowed = Cow::Borrowed(&ident); + + let tokens = quote! { #owned #borrowed }; + assert_eq!("owned borrowed", tokens.to_string()); +} + +#[test] +fn test_closure() { + fn field_i(i: usize) -> Ident { + format_ident!("__field{}", i) + } + + let fields = (0usize..3) + .map(field_i as fn(_) -> _) + .map(|var| quote! { #var }); + + let tokens = quote! { #(#fields)* }; + assert_eq!("__field0 __field1 __field2", tokens.to_string()); +} + +#[test] +fn test_append_tokens() { + let mut a = quote!(a); + let b = quote!(b); + a.append_all(b); + assert_eq!("a b", a.to_string()); +} + +#[test] +fn test_format_ident() { + let id0 = format_ident!("Aa"); + let id1 = format_ident!("Hello{x}", x = id0); + let id2 = format_ident!("Hello{x}", x = 5usize); + let id3 = format_ident!("Hello{}_{x}", id0, x = 10usize); + let id4 = format_ident!("Aa", span = Span::call_site()); + let id5 = format_ident!("Hello{}", Cow::Borrowed("World")); + + assert_eq!(id0, "Aa"); + assert_eq!(id1, "HelloAa"); + assert_eq!(id2, "Hello5"); + assert_eq!(id3, "HelloAa_10"); + assert_eq!(id4, "Aa"); + assert_eq!(id5, "HelloWorld"); +} + +#[test] +fn test_format_ident_strip_raw() { + let id = format_ident!("r#struct"); + let my_id = format_ident!("MyId{}", id); + let raw_my_id = format_ident!("r#MyId{}", id); + + assert_eq!(id, "r#struct"); + assert_eq!(my_id, "MyIdstruct"); + assert_eq!(raw_my_id, "r#MyIdstruct"); +} + +#[test] +fn test_outer_line_comment() { + let tokens = quote! { + /// doc + }; + let expected = "# [doc = r\" doc\"]"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_inner_line_comment() { + let tokens = quote! { + //! doc + }; + let expected = "# ! [doc = r\" doc\"]"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_outer_block_comment() { + let tokens = quote! { + /** doc */ + }; + let expected = "# [doc = r\" doc \"]"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_inner_block_comment() { + let tokens = quote! { + /*! doc */ + }; + let expected = "# ! [doc = r\" doc \"]"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_outer_attr() { + let tokens = quote! { + #[inline] + }; + let expected = "# [inline]"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_inner_attr() { + let tokens = quote! { + #![no_std] + }; + let expected = "# ! [no_std]"; + assert_eq!(expected, tokens.to_string()); +} + +// https://github.com/dtolnay/quote/issues/130 +#[test] +fn test_star_after_repetition() { + let c = vec!['0', '1']; + let tokens = quote! { + #( + f(#c); + )* + *out = None; + }; + let expected = "f ('0') ; f ('1') ; * out = None ;"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_quote_raw_id() { + let id = quote!(r#raw_id); + assert_eq!(id.to_string(), "r#raw_id"); +} + +#[test] +fn test_type_inference_for_span() { + trait CallSite { + fn get() -> Self; + } + + impl CallSite for Span { + fn get() -> Self { + Span::call_site() + } + } + + let span = Span::call_site(); + let _ = quote_spanned!(span=> ...); + + let delim_span = Group::new(Delimiter::Parenthesis, TokenStream::new()).delim_span(); + let _ = quote_spanned!(delim_span=> ...); + + let inferred = CallSite::get(); + let _ = quote_spanned!(inferred=> ...); + + if false { + let proc_macro_span = proc_macro::Span::call_site(); + let _ = quote_spanned!(proc_macro_span.into()=> ...); + } +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.rs b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.rs new file mode 100644 index 0000000..0a39f41 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.rs @@ -0,0 +1,9 @@ +use quote::quote; + +fn main() { + let nonrep = ""; + + // Without some protection against repetitions with no iterator somewhere + // inside, this would loop infinitely. + quote!(#(#nonrep #nonrep)*); +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.stderr b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.stderr new file mode 100644 index 0000000..99c20a5 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated-dup.stderr @@ -0,0 +1,11 @@ +error[E0308]: mismatched types + --> tests/ui/does-not-have-iter-interpolated-dup.rs:8:5 + | +8 | quote!(#(#nonrep #nonrep)*); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` + | expected due to this + | here the type of `has_iter` is inferred to be `ThereIsNoIteratorInRepetition` + | + = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.rs b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.rs new file mode 100644 index 0000000..2c740cc --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.rs @@ -0,0 +1,9 @@ +use quote::quote; + +fn main() { + let nonrep = ""; + + // Without some protection against repetitions with no iterator somewhere + // inside, this would loop infinitely. + quote!(#(#nonrep)*); +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.stderr b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.stderr new file mode 100644 index 0000000..ef90813 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-interpolated.stderr @@ -0,0 +1,11 @@ +error[E0308]: mismatched types + --> tests/ui/does-not-have-iter-interpolated.rs:8:5 + | +8 | quote!(#(#nonrep)*); + | ^^^^^^^^^^^^^^^^^^^ + | | + | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` + | expected due to this + | here the type of `has_iter` is inferred to be `ThereIsNoIteratorInRepetition` + | + = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.rs b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.rs new file mode 100644 index 0000000..c027243 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.rs @@ -0,0 +1,5 @@ +use quote::quote; + +fn main() { + quote!(#(a b),*); +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.stderr b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.stderr new file mode 100644 index 0000000..7c6e30f --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter-separated.stderr @@ -0,0 +1,10 @@ +error[E0308]: mismatched types + --> tests/ui/does-not-have-iter-separated.rs:4:5 + | +4 | quote!(#(a b),*); + | ^^^^^^^^^^^^^^^^ + | | + | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` + | expected due to this + | + = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.rs b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.rs new file mode 100644 index 0000000..8908353 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.rs @@ -0,0 +1,5 @@ +use quote::quote; + +fn main() { + quote!(#(a b)*); +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.stderr b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.stderr new file mode 100644 index 0000000..0b13e5c --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/does-not-have-iter.stderr @@ -0,0 +1,10 @@ +error[E0308]: mismatched types + --> tests/ui/does-not-have-iter.rs:4:5 + | +4 | quote!(#(a b)*); + | ^^^^^^^^^^^^^^^ + | | + | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` + | expected due to this + | + = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/quote/tests/ui/not-quotable.rs b/bitbox02-bt/vendor/quote/tests/ui/not-quotable.rs new file mode 100644 index 0000000..f991c18 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/not-quotable.rs @@ -0,0 +1,7 @@ +use quote::quote; +use std::net::Ipv4Addr; + +fn main() { + let ip = Ipv4Addr::LOCALHOST; + let _ = quote! { #ip }; +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/not-quotable.stderr b/bitbox02-bt/vendor/quote/tests/ui/not-quotable.stderr new file mode 100644 index 0000000..3196266 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/not-quotable.stderr @@ -0,0 +1,20 @@ +error[E0277]: the trait bound `Ipv4Addr: ToTokens` is not satisfied + --> tests/ui/not-quotable.rs:6:13 + | +6 | let _ = quote! { #ip }; + | ^^^^^^^^^^^^^^ + | | + | the trait `ToTokens` is not implemented for `Ipv4Addr` + | required by a bound introduced by this call + | + = help: the following other types implement trait `ToTokens`: + &'a T + &'a mut T + Box + CStr + CString + Cow<'a, T> + Option + Rc + and $N others + = note: this error originates in the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/quote/tests/ui/not-repeatable.rs b/bitbox02-bt/vendor/quote/tests/ui/not-repeatable.rs new file mode 100644 index 0000000..a8f0fe7 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/not-repeatable.rs @@ -0,0 +1,8 @@ +use quote::quote; + +struct Ipv4Addr; + +fn main() { + let ip = Ipv4Addr; + let _ = quote! { #(#ip)* }; +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/not-repeatable.stderr b/bitbox02-bt/vendor/quote/tests/ui/not-repeatable.stderr new file mode 100644 index 0000000..26932bb --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/not-repeatable.stderr @@ -0,0 +1,34 @@ +error[E0599]: the method `quote_into_iter` exists for struct `Ipv4Addr`, but its trait bounds were not satisfied + --> tests/ui/not-repeatable.rs:7:13 + | +3 | struct Ipv4Addr; + | --------------- method `quote_into_iter` not found for this struct because it doesn't satisfy `Ipv4Addr: Iterator`, `Ipv4Addr: ToTokens`, `Ipv4Addr: ext::RepIteratorExt` or `Ipv4Addr: ext::RepToTokensExt` +... +7 | let _ = quote! { #(#ip)* }; + | ^^^^^^^^^^^^^^^^^^ method cannot be called on `Ipv4Addr` due to unsatisfied trait bounds + | + = note: the following trait bounds were not satisfied: + `Ipv4Addr: Iterator` + which is required by `Ipv4Addr: ext::RepIteratorExt` + `&Ipv4Addr: Iterator` + which is required by `&Ipv4Addr: ext::RepIteratorExt` + `Ipv4Addr: ToTokens` + which is required by `Ipv4Addr: ext::RepToTokensExt` + `&mut Ipv4Addr: Iterator` + which is required by `&mut Ipv4Addr: ext::RepIteratorExt` +note: the traits `Iterator` and `ToTokens` must be implemented + --> src/to_tokens.rs + | + | pub trait ToTokens { + | ^^^^^^^^^^^^^^^^^^ + | + ::: $RUST/core/src/iter/traits/iterator.rs + | + | pub trait Iterator { + | ^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following traits define an item `quote_into_iter`, perhaps you need to implement one of them: + candidate #1: `ext::RepAsIteratorExt` + candidate #2: `ext::RepIteratorExt` + candidate #3: `ext::RepToTokensExt` + = note: this error originates in the macro `$crate::quote_bind_into_iter` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.rs b/bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.rs new file mode 100644 index 0000000..d5601c8 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.rs @@ -0,0 +1,7 @@ +use quote::quote_spanned; + +fn main() { + let span = ""; + let x = 0i32; + quote_spanned!(span=> #x); +} diff --git a/bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.stderr b/bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.stderr new file mode 100644 index 0000000..12ad307 --- /dev/null +++ b/bitbox02-bt/vendor/quote/tests/ui/wrong-type-span.stderr @@ -0,0 +1,10 @@ +error[E0308]: mismatched types + --> tests/ui/wrong-type-span.rs:6:5 + | +6 | quote_spanned!(span=> #x); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | expected `Span`, found `&str` + | expected due to this + | + = note: this error originates in the macro `quote_spanned` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/bitbox02-bt/vendor/rtt-target-0.3.1/.cargo-checksum.json b/bitbox02-bt/vendor/rtt-target-0.3.1/.cargo-checksum.json new file mode 100644 index 0000000..46b5e7e --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target-0.3.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"cc7c5f4011fcc82883b5cbde1c50f4fa426ecee1243c44d7001b37a2d2129f06","src/init.rs":"5b7f7f828e759dcc80be8970d7389e08d8b6b08604fe128122bdb6c1cf232306","src/lib.rs":"67abce11498bf0150d90b6877581f0762ead9ef0aaf570c47e7718b030389624","src/print.rs":"c5fb1ea0f426cba71046fd940393d1aa9a2ec37f45d92656402636eeef629360","src/rtt.rs":"b1ecf9ba57d3a85598b9fa1ad8cc14044415911be3d3c2a5867dff20be39acef"},"package":"065d6058bb1204f51a562a67209e1817cf714759d5cf845aa45c75fa7b0b9d9b"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/rtt-target-0.3.1/Cargo.toml b/bitbox02-bt/vendor/rtt-target-0.3.1/Cargo.toml new file mode 100644 index 0000000..180e108 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target-0.3.1/Cargo.toml @@ -0,0 +1,34 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "rtt-target" +version = "0.3.1" +authors = ["Matti Virkkunen "] +description = "Target side implementation of the RTT (Real-Time Transfer) I/O protocol" +readme = "../README.md" +keywords = ["no-std", "embedded", "debugging", "rtt"] +license = "MIT" +repository = "https://github.com/mvirkkunen/rtt-target" +[package.metadata.docs.rs] +features = ["cortex-m"] +[dependencies.cortex-m] +version = "0.7.1" +optional = true + +[dependencies.riscv] +version = "0.6.0" +optional = true + +[dependencies.ufmt-write] +version = "0.1.0" diff --git a/bitbox02-bt/vendor/rtt-target-0.3.1/src/init.rs b/bitbox02-bt/vendor/rtt-target-0.3.1/src/init.rs new file mode 100644 index 0000000..5e02952 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target-0.3.1/src/init.rs @@ -0,0 +1,206 @@ +/// rtt_init! implementation detail +#[macro_export] +#[doc(hidden)] +macro_rules! rtt_init_repeat { + ({ $($code:tt)+ } { $($acc:tt)* }; $n:literal: { $($_:tt)* } $($tail:tt)*) => { + $crate::rtt_init_repeat!({ $($code)* } { $($code)* $($acc)* }; $($tail)*) + }; + ({ $($code:tt)+ } { $($acc:tt)* };) => { + ($($acc)*) + }; +} + +/// rtt_init! implementation detail +#[macro_export] +#[doc(hidden)] +macro_rules! rtt_init_channels { + ( + $field:expr; + $number:literal: { + size: $size:literal + $( mode: $mode:ident )? + $( name: $name:literal )? + } + $($tail:tt)* + ) => { + let mut name: *const u8 = core::ptr::null(); + $( name = concat!($name, "\0").as_bytes().as_ptr(); )? + + let mut mode = $crate::ChannelMode::NoBlockSkip; + $( mode = $crate::ChannelMode::$mode; )? + + $field[$number].init(name, mode, { + static mut _RTT_CHANNEL_BUFFER: MaybeUninit<[u8; $size]> = MaybeUninit::uninit(); + _RTT_CHANNEL_BUFFER.as_mut_ptr() + }); + + $crate::rtt_init_channels!($field; $($tail)*); + }; + ($field:expr;) => { }; +} + +/// rtt_init! implementation detail +#[macro_export] +#[doc(hidden)] +macro_rules! rtt_init_wrappers { + ($field:expr; $cons:path; { $($acc:tt)* }; $n:literal: { $($_:tt)* } $($tail:tt)*) => { + $crate::rtt_init_wrappers!( + $field; + $cons; + { + $($acc)* + $cons(&mut $field[$n] as *mut _), + }; + $($tail)*) + }; + ($field:expr; $cons:path; { $($acc:tt)* };) => { + ($($acc)*) + }; +} + +/// Initializes RTT with the specified channels. Channel numbers, buffer sizes and names can be +/// defined. +/// +/// The syntax looks as follows (note that commas are not allowed anywhere): +/// +/// ``` +/// let channels = rtt_init! { +/// up: { +/// 0: { // channel number +/// size: 1024 // buffer size in bytes +/// mode: NoBlockSkip // mode (optional, default: NoBlockSkip, see enum ChannelMode) +/// name: "Terminal" // name (optional, default: no name) +/// } +/// 1: { +/// size: 32 +/// } +/// } +/// down: { +/// 0: { +/// size: 16 +/// name: "Terminal" +/// } +/// } +/// }; +/// ``` +/// +/// The channel numbers must start from 0 and not skip any numbers, or otherwise odd things will +/// happen. The order of the channel parameters is fixed, but optional parameters can be left out. +/// This macro should be called once within a function, preferably close to the start of your entry +/// point. The macro must only be called once - if it's called twice in the same program a duplicate +/// symbol error will occur. +/// +/// At compile time the macro will statically reserve space for the RTT control block and the +/// channel buffers. At runtime the macro fills in the structures and prepares them for use. +/// +/// The macro returns a generate struct that contains the channels. The struct for the example above +/// would look as follows: +/// +/// ``` +/// struct Channels { +/// up: (UpChannel, UpChannel), +/// down: (DownChannel,), +/// } +/// ``` +/// +/// The channels can either be accessed by reference or moved out as needed. For example: +/// +/// ``` +/// use core::fmt::Write; +/// +/// let channels = rtt_init! { ... }; +/// let mut output = channels.up.0; +/// writeln!(output, "Hello, world!").ok(); +/// ``` +#[macro_export] +macro_rules! rtt_init { + { + $(up: { $($up:tt)* } )? + $(down: { $($down:tt)* } )? + } => {{ + use core::mem::MaybeUninit; + use core::ptr; + use $crate::UpChannel; + use $crate::DownChannel; + use $crate::rtt::*; + + #[repr(C)] + pub struct RttControlBlock { + header: RttHeader, + up_channels: [RttChannel; $crate::rtt_init_repeat!({ 1 + } { 0 }; $($($up)*)?)], + down_channels: [RttChannel; $crate::rtt_init_repeat!({ 1 + } { 0 }; $($($down)*)?)], + } + + #[used] + #[no_mangle] + #[export_name = "_SEGGER_RTT"] + pub static mut CONTROL_BLOCK: MaybeUninit = MaybeUninit::uninit(); + + unsafe { + ptr::write_bytes(CONTROL_BLOCK.as_mut_ptr(), 0, 1); + + let cb = &mut *CONTROL_BLOCK.as_mut_ptr(); + + $( $crate::rtt_init_channels!(cb.up_channels; $($up)*); )? + $( $crate::rtt_init_channels!(cb.down_channels; $($down)*); )? + + // The header is initialized last to make it less likely an unfinished control block is + // detected by the host. + + cb.header.init(cb.up_channels.len(), cb.down_channels.len()); + + pub struct Channels { + $( up: $crate::rtt_init_repeat!({ UpChannel, } {}; $($up)*), )? + $( down: $crate::rtt_init_repeat!({ DownChannel, } {}; $($down)*), )? + } + + Channels { + $( up: $crate::rtt_init_wrappers!(cb.up_channels; UpChannel::new; {}; $($up)*), )? + $( down: $crate::rtt_init_wrappers!(cb.down_channels; DownChannel::new; {}; $($down)*), )? + } + } + }}; +} + +/// Initializes RTT with default up/down channels. +/// +/// The default channels are up channel 0 with a 1024 byte buffer and down channel 0 with a 16 byte +/// buffer. Both channels are called "Terminal". This macro is equivalent to: +/// +/// ``` +/// rtt_init! { +/// up: { +/// 0: { +/// size: 1024 +/// name: "Terminal" +/// } +/// } +/// down: { +/// 0: { +/// size: 16 +/// name: "Terminal" +/// } +/// } +/// }; +/// ``` +/// +/// See [`rtt_init`] for more details. +#[macro_export] +macro_rules! rtt_init_default { + () => { + $crate::rtt_init! { + up: { + 0: { + size: 1024 + name: "Terminal" + } + } + down: { + 0: { + size: 16 + name: "Terminal" + } + } + }; + }; +} diff --git a/bitbox02-bt/vendor/rtt-target-0.3.1/src/lib.rs b/bitbox02-bt/vendor/rtt-target-0.3.1/src/lib.rs new file mode 100644 index 0000000..4d81951 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target-0.3.1/src/lib.rs @@ -0,0 +1,355 @@ +//! Target side implementation of the RTT (Real-Time Transfer) I/O protocol +//! +//! RTT implements input and output to/from a debug probe using in-memory ring buffers and memory +//! polling. This enables debug logging from the microcontroller with minimal delays and no +//! blocking, making it usable even in real-time applications where e.g. semihosting delays cannot +//! be tolerated. +//! +//! # Hardware support +//! +//! This crate is platform agnostic and can be used on any chip that supports background memory +//! access via its debug interface. The printing macros require a critical section which is +//! platform-dependent. Built-in ARM Cortex-M support can be enabled with the "cortex-m" feature, +//! and RISC-V support can be enabled with the "riscv" feature. +//! +//! To interface with RTT from the host computer, a debug probe such as an ST-Link or J-Link is +//! required. The normal debug protocol (e.g. SWD) is used to access RTT, so no extra connections +//! such as SWO pins are needed. +//! +//! # Initialization +//! +//! RTT must be initialized at the start of your program using one of the init macros. See the +//! macros for more details. +//! +//! The initialization macros return channel objects that can be used for writing and reading. +//! Different channel objects can safely be used concurrently in different contexts without locking. +//! In an interrupt-based application with realtime constraints you could use a separate channel for +//! every interrupt context to allow for lock-free logging. +//! +//! # Channels and virtual terminals +//! +//! RTT supports multiple *channels* in both directions. Up channels go from target to host, and +//! down channels go from host to target. Each channel is identified by its direction and number. +//! +//! By convention channel 0 is reserved for terminal use. In the up direction there is a set of +//! escape sequences that further enable the single channel to be treated as up to 16 *virtual +//! terminals*. This can be used to separate different types of messages (for example, log levels) +//! from each other without having to allocate memory for multiple buffers. As a downside, multiple +//! threads cannot write to the same channel at once, even if using different virtual terminal +//! numbers, so access has to be synchronized. Down channel 0 is conventionally used for keyboard +//! input. +//! +//! **Note:** Some host side programs only display channel 0 by default, so to see the other +//! channels you might need to configure them appropriately. +//! +//! The other channels can be used to either enable concurrent use from multiple sources without +//! locking, or to send e.g. binary data in either direction. +//! +//! Channel 0 can also be used for arbitrary data, but most tools expect it to be plain text. +//! +//! # Channel modes +//! +//! By default, channels start in [`NoBlockSkip`](ChannelMode::NoBlockSkip) mode, which discards +//! data if the buffer is full. This enables RTT to not crash the application if there is no debug +//! probe attached or if the host is not reading the buffers. However if the application outputs +//! faster than the host can read (which is easy to do, because writing is very fast), messages will +//! be lost. Channels can be set to blocking mode if this is desirable, however in that case the +//! application will likely freeze when the buffer fills up if a debugger is not attached. +//! +//! The channel mode can also be changed on the fly by the debug probe. Therefore it may be +//! advantageous to use a non-blocking mode in your microcontroller code, and set a blocking mode as +//! needed when debugging. That way you will never end up with an application that freezes without a +//! debugger connected. +//! +//! # Printing +//! +//! For no-hassle output the [`rprint`] and [`rprintln`] macros are provided. They use a single down +//! channel defined at initialization time, and a critical section for synchronization, and they +//! therefore work exactly like the standard `println` style macros. They can be used from any +//! context. The [`rtt_init_print`] convenience macro initializes printing on channel 0. +//! +//! ``` +//! use rtt_target::{rtt_init_print, rprintln}; +//! +//! fn main() -> ! { +//! rtt_init_print!(); +//! loop { +//! rprintln!("Hello, world!"); +//! } +//! } +//! ``` +//! +//! The macros also support an extended syntax to print to different RTT virtual terminals. +//! +//! Please note that because a critical section is used, printing into a blocking channel will cause +//! the application to block and freeze when the buffer is full. + +#![no_std] + +use core::convert::Infallible; +use core::fmt; +use core::mem::MaybeUninit; +use ufmt_write::uWrite; + +#[macro_use] +mod init; + +/// Public due to access from macro +#[doc(hidden)] +pub mod rtt; + +#[macro_use] +mod print; + +pub use print::*; + +/// RTT up (target to host) channel +/// +/// Supports writing binary data directly, or writing strings via [`core::fmt`] macros such as +/// [`write`] as well as the ufmt crate's `uwrite` macros (use the `u` method). +/// +/// Note that the formatted writing implementations diverge slightly from the trait definitions in +/// that if the channel is in non-blocking mode, writing will *not* block. +pub struct UpChannel(*mut rtt::RttChannel); + +unsafe impl Send for UpChannel {} + +impl UpChannel { + /// Public due to access from macro. + #[doc(hidden)] + pub unsafe fn new(channel: *mut rtt::RttChannel) -> Self { + UpChannel(channel) + } + + fn channel(&self) -> &mut rtt::RttChannel { + unsafe { &mut *self.0 } + } + + /// Writes `buf` to the channel and returns the number of bytes written. Behavior when the + /// buffer is full is subject to the channel blocking mode. + pub fn write(&mut self, buf: &[u8]) -> usize { + let mut writer = self.channel().writer(); + writer.write(buf); + writer.commit() + } + + /// Creates a writer for formatted writing with ufmt. + /// + /// The correct way to use this method is to call it once for each write operation. This is so + /// that non blocking modes will work correctly. + /// + /// ``` + /// let mut output = channels.up.0; + /// uwriteln!(output.u(), "Hello, ufmt!"); + /// ``` + pub fn u(&mut self) -> uWriter { + uWriter(self.channel().writer()) + } + + /// Gets the current blocking mode of the channel. The default is `NoBlockSkip`. + pub fn mode(&self) -> ChannelMode { + self.channel().mode() + } + + /// Sets the blocking mode of the channel + pub fn set_mode(&mut self, mode: ChannelMode) { + self.channel().set_mode(mode) + } + + /// Converts the channel into a virtual terminal that can be used for writing into multiple + /// virtual terminals. + pub fn into_terminal(self) -> TerminalChannel { + TerminalChannel::new(self) + } + + /// Magically creates a channel out of thin air. Return `None` if the channel number is too + /// high, or if the channel has not been initialized. + /// + /// Calling this function will cause a linking error if `rtt_init` has not been called. + /// + /// # Safety + /// + /// It's undefined behavior for something else to access the channel through anything else + /// besides the returned object during or after calling this function. Essentially this function + /// is only safe to use in panic handlers and the like that permanently disable interrupts. + pub unsafe fn conjure(number: usize) -> Option { + extern "C" { + #[link_name = "_SEGGER_RTT"] + static mut CONTROL_BLOCK: MaybeUninit; + } + + if number >= (&*CONTROL_BLOCK.as_ptr()).max_up_channels() { + return None; + } + + // First addition moves to the start of the up channel array, second addition moves to the + // correct channel. + let ptr = (CONTROL_BLOCK.as_ptr().add(1) as *mut rtt::RttChannel).add(number); + + if !(&*ptr).is_initialized() { + return None; + } + + Some(UpChannel(ptr)) + } +} + +impl fmt::Write for UpChannel { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + self.channel().writer().write_str(s) + } + + fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), fmt::Error> { + self.channel().writer().write_fmt(args) + } +} + +/// Writer for ufmt. Don't store an instance of this, but rather create a new one for every write. +#[allow(non_camel_case_types)] +pub struct uWriter<'c>(rtt::RttWriter<'c>); + +impl uWrite for uWriter<'_> { + type Error = Infallible; + + fn write_str(&mut self, s: &str) -> Result<(), Self::Error> { + self.0.write(s.as_bytes()); + Ok(()) + } +} + +/// RTT down (host to target) channel +pub struct DownChannel(*mut rtt::RttChannel); + +unsafe impl Send for DownChannel {} + +impl DownChannel { + /// Public due to access from macro. + #[doc(hidden)] + pub unsafe fn new(channel: *mut rtt::RttChannel) -> Self { + DownChannel(channel) + } + + fn channel(&mut self) -> &mut rtt::RttChannel { + unsafe { &mut *self.0 } + } + + /// Reads up to `buf.len()` bytes from the channel and return the number of bytes read. This + /// method never blocks. + pub fn read(&mut self, buf: &mut [u8]) -> usize { + self.channel().read(buf) + } +} + +/// Specifies what to do when a channel doesn't have enough buffer space for a complete write. +#[derive(Eq, PartialEq)] +#[repr(usize)] +pub enum ChannelMode { + /// Skip writing the data completely if it doesn't fit in its entirety. + NoBlockSkip = 0, + + /// Write as much as possible of the data and ignore the rest. + NoBlockTrim = 1, + + /// Block (spin) if the buffer is full. If within a critical section such as inside + /// [`rprintln`], this will cause the application to freeze until the host reads from the + /// buffer. + BlockIfFull = 2, +} + +/// An up channel that supports writing into multiple virtual terminals within the same buffer. +/// +/// An [`UpChannel`] can be turned into a `TerminalChannel` by using the +/// [`into_terminal`](UpChannel::into_terminal()) method. +/// +/// Virtual terminals allow you to share one buffer for writing multiple streams. The virtual +/// terminals number from 0 to 15 and are implemented with a simple "terminal switch" sequence on +/// the fly, so there is no need to declare them in advance. You could, for example, use different +/// terminal numbers for messages of different priorities to separate them in a viewer program. +/// Printing uses a `TerminalChannel` internally. +pub struct TerminalChannel { + channel: UpChannel, + current: u8, +} + +impl TerminalChannel { + pub(crate) fn new(channel: UpChannel) -> Self { + Self { + channel, + current: 0, + } + } + + /// Creates a writer to write a message to the virtual terminal specified by `number`. + /// + /// The correct way to use this method is to call it once for each write operation. This is so + /// that non blocking modes will work correctly. + /// + /// The writer supports formatted writing with the standard `write` and ufmt's `uwrite`. + pub fn write(&mut self, number: u8) -> TerminalWriter { + const TERMINAL_ID: [u8; 16] = *b"0123456789ABCDEF"; + + let mut writer = self.channel.channel().writer(); + + if number != self.current { + // The terminal switch command must be sent in full so the mode cannot be NoBlockTrim + let mode = self.channel.mode(); + let mode = if mode == ChannelMode::NoBlockTrim { + ChannelMode::NoBlockSkip + } else { + mode + }; + + writer.write_with_mode(mode, &[0xff, TERMINAL_ID[(number & 0x0f) as usize]]); + + self.current = number; + } + + TerminalWriter { + writer, + number, + current: &mut self.current, + } + } + + /// Gets the current blocking mode of the channel. The default is `NoBlockSkip`. + pub fn mode(&self) -> ChannelMode { + self.channel.mode() + } + + /// Sets the blocking mode of the channel + pub fn set_mode(&mut self, mode: ChannelMode) { + self.channel.set_mode(mode) + } +} + +/// Formatted writing operation. Don't store an instance of this, but rather create a new one for +/// every write. +pub struct TerminalWriter<'c> { + writer: rtt::RttWriter<'c>, + number: u8, + current: &'c mut u8, +} + +impl fmt::Write for TerminalWriter<'_> { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + self.writer.write(s.as_bytes()); + Ok(()) + } +} + +impl uWrite for TerminalWriter<'_> { + type Error = Infallible; + + fn write_str(&mut self, s: &str) -> Result<(), Self::Error> { + self.writer.write(s.as_bytes()); + Ok(()) + } +} + +impl Drop for TerminalWriter<'_> { + fn drop(&mut self) { + if !self.writer.is_failed() { + *self.current = self.number; + } + } +} diff --git a/bitbox02-bt/vendor/rtt-target-0.3.1/src/print.rs b/bitbox02-bt/vendor/rtt-target-0.3.1/src/print.rs new file mode 100644 index 0000000..0206135 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target-0.3.1/src/print.rs @@ -0,0 +1,226 @@ +use crate::{TerminalChannel, TerminalWriter, UpChannel}; +use core::fmt::{self, Write as _}; +use core::mem::MaybeUninit; +use core::ptr; +use core::sync::atomic::{AtomicPtr, Ordering}; + +static CRITICAL_SECTION: AtomicPtr = AtomicPtr::new(core::ptr::null_mut()); +static mut PRINT_TERMINAL: MaybeUninit = MaybeUninit::uninit(); + +/// Type-erased critical section function used to synchronize printing. +/// +/// When called, the function must establish a critical section and call `f` within it, passing +/// `arg` as the argument. +pub type CriticalSectionFunc = fn(arg: *mut (), f: fn(arg: *mut ()) -> ()) -> (); + +/// Sets the channel to use for [`rprint`] and [`rprintln`] and the critical section function used +/// to synchronize printing. You should only use this function if the [`set_print_channel`] function +/// isn't available on your platform. +/// +/// # Example +/// +/// Because the function takes a *static reference to a function pointer* as an argument, the call +/// requires a manual cast. Luckily Rust will automatically promote a reference to a suitable +/// closure to `'static`. In this example, `interrupt::free` is a function that establishes a +/// critical section and calls the supplied function. +/// +/// ``` +/// use rtt_target::{rtt_init_detault, rprintln}; +/// use platform_specific::interrupt; +/// +/// fn main() -> ! { +/// let channels = rtt_init_detault!(); +/// +/// unsafe { +/// rtt_target::set_print_channel_cs( +/// channels.up.0, +/// &((|arg, f| interrupt::free(|_| f(arg))) as rtt_target::CriticalSectionFunc), +/// ); +/// } +/// +/// loop { +/// rprintln!("Hello, world!"); +/// } +/// } +/// ``` +/// +/// # Safety +/// +/// This function is unsafe because the user must guarantee that the `cs` function pointer passed in +/// adheres to the [`CriticalSectionFunc`] specification. +pub unsafe fn set_print_channel_cs(channel: UpChannel, cs: &'static CriticalSectionFunc) { + cs(channel.0 as *mut (), |channel_ptr| { + ptr::write( + PRINT_TERMINAL.as_mut_ptr(), + TerminalChannel::new(UpChannel(channel_ptr as *mut crate::rtt::RttChannel)), + ); + }); + + CRITICAL_SECTION.store(cs as *const _ as *mut _, Ordering::SeqCst); +} + +/// Sets the channel to use for [`rprint`] and [`rprintln`]. +/// +/// This function is available only if you have enabled a platform support feature. Otherwise, +/// [`set_print_channel_cs`] must be used. +#[cfg(any(feature = "cortex-m", feature = "riscv"))] +pub fn set_print_channel(channel: UpChannel) { + #[cfg(feature = "cortex-m")] + use cortex_m as arch; + #[cfg(feature = "riscv")] + use riscv as arch; + unsafe { + set_print_channel_cs( + channel, + &((|arg, f| arch::interrupt::free(|_| f(arg))) as CriticalSectionFunc), + ); + } +} + +/// Public due to access from macro. +#[doc(hidden)] +pub mod print_impl { + use super::*; + + fn with_writer ()>(number: u8, f: F) { + let cs = CRITICAL_SECTION.load(Ordering::SeqCst); + + if !cs.is_null() { + // If the critical section pointer has been set, PRINT_TERMINAL must also have been set. + + let args = (number, f); + + unsafe { + (&*cs)(&args as *const _ as *mut (), |args_ptr| { + let args = &*(args_ptr as *const (u8, F)); + let term = &mut *PRINT_TERMINAL.as_mut_ptr(); + + (args.1)(term.write(args.0)); + }); + } + } + } + + /// Public due to access from macro. + #[doc(hidden)] + pub fn write_str(number: u8, s: &str) { + with_writer(number, |mut w| { + w.write_str(s).ok(); + }); + } + + /// Public due to access from macro. + #[doc(hidden)] + pub fn write_fmt(number: u8, arg: fmt::Arguments) { + with_writer(number, |mut w| { + w.write_fmt(arg).ok(); + }); + } +} + +/// Prints to the print RTT channel. Works just like the standard `print`. +/// +/// Before use the print channel has to be set with [`rtt_init_print`] or [`set_print_channel`]. If +/// the channel isn't set, the message is silently discarded. +/// +/// The macro also supports output to multiple virtual terminals on the channel. Use the syntax +/// ```rprint!(=> 1, "Hello!");``` to write to terminal number 1, for example. Terminal numbers +/// range from 0 to 15. +#[macro_export] +macro_rules! rprint { + (=> $terminal:expr, $s:expr) => { + $crate::print_impl::write_str($terminal, $s); + }; + (=> $terminal:expr, $($arg:tt)*) => { + $crate::print_impl::write_fmt($terminal, format_args!($($arg)*)); + }; + ($s:expr) => { + $crate::print_impl::write_str(0, $s); + }; + ($($arg:tt)*) => { + $crate::print_impl::write_fmt(0, format_args!($($arg)*)); + }; +} + +/// Prints to the print RTT channel, with a newline. Works just like the standard `println`. +/// +/// Before use the print channel has to be set with [`rtt_init_print`] or [`set_print_channel`]. If +/// the channel isn't set, the message is silently discarded. +/// +/// The macro also supports output to multiple virtual terminals on the channel. Use the syntax +/// ```rprintln!(=> 1, "Hello!");``` to write to terminal number 1, for example. Terminal numbers +/// range from 0 to 15. +#[macro_export] +macro_rules! rprintln { + (=> $terminal:expr) => { + $crate::print_impl::write_str($terminal, "\n"); + }; + (=> $terminal:expr, $fmt:expr) => { + $crate::print_impl::write_str($terminal, concat!($fmt, "\n")); + }; + (=> $terminal:expr, $fmt:expr, $($arg:tt)*) => { + $crate::print_impl::write_fmt($terminal, format_args!(concat!($fmt, "\n"), $($arg)*)); + }; + () => { + $crate::print_impl::write_str(0, "\n"); + }; + ($fmt:expr) => { + $crate::print_impl::write_str(0, concat!($fmt, "\n")); + }; + ($fmt:expr, $($arg:tt)*) => { + $crate::print_impl::write_fmt(0, format_args!(concat!($fmt, "\n"), $($arg)*)); + }; +} + +/// Initializes RTT with a single up channel and sets it as the print channel for the printing +/// macros. +/// +/// The optional arguments specify the blocking mode (default: `NoBlockSkip`) and size of the buffer +/// in bytes (default: 1024). See [`rtt_init`] for more details. +/// +/// This macro is defined only if the [`set_print_channel`] function is available, i.e. if you have +/// enabled a platform support feature. +#[cfg(any(feature = "cortex-m", feature = "riscv"))] +#[macro_export] +macro_rules! rtt_init_print { + ($mode:ident, $size:literal) => { + let channels = $crate::rtt_init! { + up: { + 0: { + size: $size + mode: $mode + name: "Terminal" + } + } + }; + + $crate::set_print_channel(channels.up.0); + }; + + ($mode:ident) => { + $crate::rtt_init_print!($mode, 1024); + }; + + () => { + $crate::rtt_init_print!(NoBlockSkip, 1024); + }; +} + +/// This version of the macro only is defined if no platform support feature is enabled and outputs +/// a more friendly error message. +#[cfg(not(any(feature = "cortex-m", feature = "riscv")))] +#[macro_export] +macro_rules! rtt_init_print { + ($($_:tt)*) => { + compile_error!(concat!( + "rtt_init_print! is only available if a platform support feature is enabled.\r\n", + "Solutions:\r\n", + "- Enable a platform support feature:\r\n", + " # Cargo.toml\r\n", + " rtt-target = { version = \"x.y.z\", features = [\"cortex-m\"] }\r\n", + " # or", + " rtt-target = { version = \"x.y.z\", features = [\"riscv\"] }\r\n", + "- OR use set_print_channel_cs() instead if you want to provide your own locking.\r\n" + )) + }; +} diff --git a/bitbox02-bt/vendor/rtt-target-0.3.1/src/rtt.rs b/bitbox02-bt/vendor/rtt-target-0.3.1/src/rtt.rs new file mode 100644 index 0000000..95b3999 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target-0.3.1/src/rtt.rs @@ -0,0 +1,289 @@ +//! This module contains the implementation for the RTT protocol. It's not meant to be used directly +//! in user code, and therefore mostly undocumented. The module is only public so that it can be +//! accessed from the rtt_init! macro. + +use crate::ChannelMode; +use core::cmp::min; +use core::fmt; +use core::ptr; +use core::sync::atomic::{fence, AtomicUsize, Ordering::SeqCst}; + +// Note: this is zero-initialized in the initialization macro so all zeros must be a valid value +#[repr(C)] +pub struct RttHeader { + id: [u8; 16], + max_up_channels: usize, + max_down_channels: usize, + // Followed in memory by: + // up_channels: [Channel; max_up_channels] + // down_channels: [Channel; down_up_channels] +} + +impl RttHeader { + /// Initializes the control block header. + /// + /// # Safety + /// + /// The arguments must correspond to the sizes of the arrays that follow the header in memory. + pub unsafe fn init(&mut self, max_up_channels: usize, max_down_channels: usize) { + ptr::write_volatile(&mut self.max_up_channels, max_up_channels); + ptr::write_volatile(&mut self.max_down_channels, max_down_channels); + + // Copy the ID in two parts to avoid having the ID string in memory in full. The ID is + // copied last to make it less likely an unfinished control block is detected by the host. + + ptr::copy_nonoverlapping(b"SEGG_" as *const u8, self.id.as_mut_ptr(), 5); + + fence(SeqCst); + + ptr::copy_nonoverlapping( + b"ER RTT\0\0\0\0\0\0" as *const u8, + self.id.as_mut_ptr().offset(4), + 12, + ); + } + + pub fn max_up_channels(&self) -> usize { + self.max_up_channels + } +} + +// Note: this is zero-initialized in the initialization macro so all zeros must be a valid value +#[repr(C)] +pub struct RttChannel { + name: *const u8, + buffer: *mut u8, + size: usize, + write: AtomicUsize, + read: AtomicUsize, + flags: AtomicUsize, +} + +impl RttChannel { + /// Initializes the channel. + /// + /// # Safety + /// + /// The pointer arguments must point to a valid null-terminated name and writable buffer. + pub unsafe fn init(&mut self, name: *const u8, mode: ChannelMode, buffer: *mut [u8]) { + ptr::write_volatile(&mut self.name, name); + ptr::write_volatile(&mut self.size, (&*buffer).len()); + self.set_mode(mode); + + // Set buffer last as it can be used to detect if the channel has been initialized + ptr::write_volatile(&mut self.buffer, buffer as *mut u8); + } + + pub fn is_initialized(&self) -> bool { + self.buffer != ptr::null_mut() + } + + pub(crate) fn mode(&self) -> ChannelMode { + let mode = self.flags.load(SeqCst) & 3; + + if mode <= 2 { + unsafe { core::mem::transmute(mode) } + } else { + ChannelMode::NoBlockSkip + } + } + + pub(crate) fn set_mode(&self, mode: ChannelMode) { + self.flags + .store((self.flags.load(SeqCst) & !3) | mode as usize, SeqCst); + } + + // This method should only be called for down channels. + pub(crate) fn read(&self, mut buf: &mut [u8]) -> usize { + let (write, mut read) = self.read_pointers(); + + let mut total = 0; + + // Read while buffer contains data and output buffer has space (maximum of two iterations) + while buf.len() > 0 { + let count = min(self.readable_contiguous(write, read), buf.len()); + if count == 0 { + break; + } + + unsafe { + ptr::copy_nonoverlapping( + self.buffer.offset(read as isize), + buf.as_mut_ptr(), + count, + ); + } + + total += count; + read += count; + + if read >= self.size { + // Wrap around to start + read = 0; + } + + buf = &mut buf[count..]; + } + + self.read.store(read, SeqCst); + + total + } + + /// This method should only be called for up channels. + pub(crate) fn writer(&self) -> RttWriter<'_> { + RttWriter { + chan: self, + write: self.read_pointers().0, + total: 0, + state: WriteState::Writable, + } + } + + /// Gets the amount of contiguous data available for reading + fn readable_contiguous(&self, write: usize, read: usize) -> usize { + (if read > write { + self.size - read + } else { + write - read + }) as usize + } + + fn read_pointers(&self) -> (usize, usize) { + let write = self.write.load(SeqCst); + let read = self.read.load(SeqCst); + + if write >= self.size || read >= self.size { + // Pointers have been corrupted. This doesn't happen in well-behaved programs, so + // attempt to reset the buffer. + + self.write.store(0, SeqCst); + self.read.store(0, SeqCst); + return (0, 0); + } + + (write, read) + } +} + +/// A cancellable write operation to an RTT channel. +pub(crate) struct RttWriter<'c> { + chan: &'c RttChannel, + write: usize, + total: usize, + state: WriteState, +} + +#[derive(Eq, PartialEq)] +enum WriteState { + /// Operation can continue + Writable, + + /// Buffer space ran out but the written data will still be committed + Full, + + /// The operation failed and won't be committed, or it has already been committed. + Finished, +} + +impl RttWriter<'_> { + pub fn write(&mut self, buf: &[u8]) { + self.write_with_mode(self.chan.mode(), buf); + } + + pub fn write_with_mode(&mut self, mode: ChannelMode, mut buf: &[u8]) { + while self.state == WriteState::Writable && !buf.is_empty() { + let count = min(self.writable_contiguous(), buf.len()); + + if count == 0 { + // Buffer is full + + match mode { + ChannelMode::NoBlockSkip => { + // Mark the entire operation as failed if even one part cannot be written in + // full. + self.state = WriteState::Finished; + return; + } + + ChannelMode::NoBlockTrim => { + // If the buffer is full, write as much as possible (note: no return), and + // mark the operation as full, which prevents further writes. + self.state = WriteState::Full; + } + + ChannelMode::BlockIfFull => { + // Commit everything written so far and spin until more can be written + self.chan.write.store(self.write, SeqCst); + continue; + } + } + } + + unsafe { + ptr::copy_nonoverlapping( + buf.as_ptr(), + self.chan.buffer.offset(self.write as isize), + count, + ); + } + + self.write += count; + self.total += count; + + if self.write >= self.chan.size { + // Wrap around to start + self.write = 0; + } + + buf = &buf[count..]; + } + } + + /// Gets the amount of contiguous space available for writing + fn writable_contiguous(&self) -> usize { + let read = self.chan.read_pointers().1; + + (if read > self.write { + read - self.write - 1 + } else if read == 0 { + self.chan.size - self.write - 1 + } else { + self.chan.size - self.write + }) as usize + } + + pub fn is_failed(&self) -> bool { + self.state != WriteState::Finished + } + + pub fn commit(mut self) -> usize { + self.commit_impl(); + + self.total + } + + fn commit_impl(&mut self) { + match self.state { + WriteState::Finished => return, + WriteState::Full | WriteState::Writable => { + // Commit the write pointer so the host can see the new data + self.chan.write.store(self.write, SeqCst); + self.state = WriteState::Finished; + } + } + } +} + +impl Drop for RttWriter<'_> { + fn drop(&mut self) { + self.commit_impl(); + } +} + +impl fmt::Write for RttWriter<'_> { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + self.write(s.as_bytes()); + Ok(()) + } +} diff --git a/bitbox02-bt/vendor/rtt-target/.cargo-checksum.json b/bitbox02-bt/vendor/rtt-target/.cargo-checksum.json new file mode 100644 index 0000000..793a22e --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"818a196728fad94c60bca925a6979ca47bc9cd1d00efa8587bdfb084424051bb","LICENSE":"9a427daacf9c7eedb6f0c4e2b517d8278fe8634cd72a4e38af59c78f7f6a3a2e","README.md":"cba83f91adc5a37c9e0932f863d0b8b6c0729f06da879117e1e7f747a2600123","src/debug.rs":"54b72035d3c6474667432b9c6892c958f74eb455bffeab6ad232d00b0f8811a8","src/init.rs":"1e3d7e0439123f9b457a2a190189fda77ac77d0e16b88bea4269e76e091272db","src/lib.rs":"90dafe887c03ef524a112db090ab955a68f8434fdd0e149a79ebcb1ba961532c","src/print.rs":"84754003f56360117b7e5b45b3f870249464a8c265d06e7f7a825ff735eabac2","src/rtt.rs":"51b288c4df8f04008d9a2d01ecb0e42857fed8d07b7d2abc15794d4c4dac300c"},"package":"10b34c9e6832388e45f3c01f1bb60a016384a0a4ad80cdd7d34913bed25037f0"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/rtt-target/Cargo.toml b/bitbox02-bt/vendor/rtt-target/Cargo.toml new file mode 100644 index 0000000..ce9122d --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/Cargo.toml @@ -0,0 +1,33 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "rtt-target" +version = "0.5.0" +authors = ["Matti Virkkunen "] +description = "Target side implementation of the RTT (Real-Time Transfer) I/O protocol" +readme = "README.md" +keywords = [ + "no-std", + "embedded", + "debugging", + "rtt", +] +license = "MIT" +license-file = "LICENSE" +repository = "https://github.com/probe-rs/rtt-target" + +[dependencies.critical-section] +version = "1.0.0" + +[dependencies.ufmt-write] +version = "0.1.0" diff --git a/bitbox02-bt/vendor/rtt-target/LICENSE b/bitbox02-bt/vendor/rtt-target/LICENSE new file mode 100644 index 0000000..fcba9a1 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Matti Virkkunen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bitbox02-bt/vendor/rtt-target/README.md b/bitbox02-bt/vendor/rtt-target/README.md new file mode 100644 index 0000000..93bf872 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/README.md @@ -0,0 +1,32 @@ +# rtt-target + +[![crates.io](https://img.shields.io/crates/v/rtt-target.svg)](https://crates.io/crates/rtt-target) [![documentation](https://docs.rs/rtt-target/badge.svg)](https://docs.rs/rtt-target) + +Target side implementation of the RTT (Real-Time Transfer) I/O protocol. RTT implements input and output via a debug probe using in-memory ring buffers and polling. This enables debug logging from the microcontroller with minimal delays and no blocking, making it usable even in real-time applications where e.g. semihosting delays cannot be tolerated. + +## [Documentation](https://docs.rs/rtt-target) + +## Platform support + +To use the global `rprintln!` macro, a platform-specific [`critical-section`](https://github.com/rust-embedded/critical-section) implementation is needed for locking. + +Output directly to a channel object with `write!` or the binary `write` method does not require locking and therefore does not need any platform-specific critical section. + +## Usage + +With a platform-specific critical section in use, printing is as simple as: + +```rust +use rtt_target::{rtt_init_print, rprintln}; + +fn main() { + rtt_init_print!(); + loop { + rprintln!("Hello, world!"); + } +} +``` + +## Development + +The examples-cortex-m and panic-test crates come with build files for the venerable STM32F103C8xx by default, but can be easily adapted for any chip as they contain only minimal platform-specific runtime code to get `fn main` to run. diff --git a/bitbox02-bt/vendor/rtt-target/src/debug.rs b/bitbox02-bt/vendor/rtt-target/src/debug.rs new file mode 100644 index 0000000..8078f8f --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/src/debug.rs @@ -0,0 +1,45 @@ +//! This module contains macros that work exactly like thier equivalents without `debug_*` + +/* From init.rs */ + +/// The same as [`rtt_init`] macro but works only in debug +/// +/// [`rtt_init`](crate::rtt_init) +#[macro_export] +macro_rules! debug_rtt_init { + ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::rtt_init!($($arg)*); }) +} + +/// The same as [`rtt_init_default`] macro but works only in debug +/// +/// [`rtt_init_default`](crate::rtt_init_default) +#[macro_export] +macro_rules! debug_rtt_init_default { + ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::rtt_init_default!($($arg)*); }) +} + +/* From print.rs */ + +/// The same as [`rtt_init_print`] macro but works only in debug +/// +/// [`rtt_init_print`](crate::rtt_init_print) +#[macro_export] +macro_rules! debug_rtt_init_print { + ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::rtt_init_print!($($arg)*); }) +} + +/// The same as [`rprintln`] macro but works only in debug +/// +/// [`rprintln`](crate::rprintln) +#[macro_export] +macro_rules! debug_rprintln { + ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::rprintln!($($arg)*); }) +} + +/// The same as [`rprint`] macro but works only in debug +/// +/// [`rprint`](crate::rprint) +#[macro_export] +macro_rules! debug_rprint { + ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::rprint!($($arg)*); }) +} diff --git a/bitbox02-bt/vendor/rtt-target/src/init.rs b/bitbox02-bt/vendor/rtt-target/src/init.rs new file mode 100644 index 0000000..0f632f1 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/src/init.rs @@ -0,0 +1,207 @@ +/// rtt_init! implementation detail +#[macro_export] +#[doc(hidden)] +macro_rules! rtt_init_repeat { + ({ $($code:tt)+ } { $($acc:tt)* }; $n:literal: { $($_:tt)* } $($tail:tt)*) => { + $crate::rtt_init_repeat!({ $($code)* } { $($code)* $($acc)* }; $($tail)*) + }; + ({ $($code:tt)+ } { $($acc:tt)* };) => { + ($($acc)*) + }; +} + +/// rtt_init! implementation detail +#[macro_export] +#[doc(hidden)] +macro_rules! rtt_init_channels { + ( + $field:expr; + $number:literal: { + size: $size:expr + $(, mode: $mode:path )? + $(, name: $name:literal )? + $(,)? + } + $($tail:tt)* + ) => { + let mut name: *const u8 = core::ptr::null(); + $( name = concat!($name, "\0").as_bytes().as_ptr(); )? + + let mut mode = $crate::ChannelMode::NoBlockSkip; + $( mode = $mode; )? + + $field[$number].init(name, mode, { + static mut _RTT_CHANNEL_BUFFER: MaybeUninit<[u8; $size]> = MaybeUninit::uninit(); + _RTT_CHANNEL_BUFFER.as_mut_ptr() + }); + + $crate::rtt_init_channels!($field; $($tail)*); + }; + ($field:expr;) => { }; +} + +/// rtt_init! implementation detail +#[macro_export] +#[doc(hidden)] +macro_rules! rtt_init_wrappers { + ($field:expr; $cons:path; { $($acc:tt)* }; $n:literal: { $($_:tt)* } $($tail:tt)*) => { + $crate::rtt_init_wrappers!( + $field; + $cons; + { + $($acc)* + $cons(&mut $field[$n] as *mut _), + }; + $($tail)*) + }; + ($field:expr; $cons:path; { $($acc:tt)* };) => { + ($($acc)*) + }; +} + +/// Initializes RTT with the specified channels. Channel numbers, buffer sizes and names can be +/// defined. +/// +/// The syntax looks as follows (note that commas are not allowed anywhere): +/// +/// ``` +/// let channels = rtt_init! { +/// up: { +/// 0: { // channel number +/// size: 1024, // buffer size in bytes +/// mode: NoBlockSkip, // mode (optional, default: NoBlockSkip, see enum ChannelMode) +/// name: "Terminal" // name (optional, default: no name) +/// } +/// 1: { +/// size: 32 +/// } +/// } +/// down: { +/// 0: { +/// size: 16, +/// name: "Terminal" +/// } +/// } +/// }; +/// ``` +/// +/// The channel numbers must start from 0 and not skip any numbers, or otherwise odd things will +/// happen. The order of the channel parameters is fixed, but optional parameters can be left out. +/// This macro should be called once within a function, preferably close to the start of your entry +/// point. The macro must only be called once - if it's called twice in the same program a duplicate +/// symbol error will occur. +/// +/// At compile time the macro will statically reserve space for the RTT control block and the +/// channel buffers. At runtime the macro fills in the structures and prepares them for use. +/// +/// The macro returns a generate struct that contains the channels. The struct for the example above +/// would look as follows: +/// +/// ``` +/// struct Channels { +/// up: (UpChannel, UpChannel), +/// down: (DownChannel,), +/// } +/// ``` +/// +/// The channels can either be accessed by reference or moved out as needed. For example: +/// +/// ``` +/// use core::fmt::Write; +/// +/// let channels = rtt_init! { ... }; +/// let mut output = channels.up.0; +/// writeln!(output, "Hello, world!").ok(); +/// ``` +#[macro_export] +macro_rules! rtt_init { + { + $(up: { $($up:tt)* } )? + $(down: { $($down:tt)* } )? + } => {{ + use core::mem::MaybeUninit; + use core::ptr; + use $crate::UpChannel; + use $crate::DownChannel; + use $crate::rtt::*; + + #[repr(C)] + pub struct RttControlBlock { + header: RttHeader, + up_channels: [RttChannel; $crate::rtt_init_repeat!({ 1 + } { 0 }; $($($up)*)?)], + down_channels: [RttChannel; $crate::rtt_init_repeat!({ 1 + } { 0 }; $($($down)*)?)], + } + + #[used] + #[no_mangle] + #[export_name = "_SEGGER_RTT"] + pub static mut CONTROL_BLOCK: MaybeUninit = MaybeUninit::uninit(); + + unsafe { + ptr::write_bytes(CONTROL_BLOCK.as_mut_ptr(), 0, 1); + + let cb = &mut *CONTROL_BLOCK.as_mut_ptr(); + + $( $crate::rtt_init_channels!(cb.up_channels; $($up)*); )? + $( $crate::rtt_init_channels!(cb.down_channels; $($down)*); )? + + // The header is initialized last to make it less likely an unfinished control block is + // detected by the host. + + cb.header.init(cb.up_channels.len(), cb.down_channels.len()); + + pub struct Channels { + $( pub up: $crate::rtt_init_repeat!({ UpChannel, } {}; $($up)*), )? + $( pub down: $crate::rtt_init_repeat!({ DownChannel, } {}; $($down)*), )? + } + + Channels { + $( up: $crate::rtt_init_wrappers!(cb.up_channels; UpChannel::new; {}; $($up)*), )? + $( down: $crate::rtt_init_wrappers!(cb.down_channels; DownChannel::new; {}; $($down)*), )? + } + } + }}; +} + +/// Initializes RTT with default up/down channels. +/// +/// The default channels are up channel 0 with a 1024 byte buffer and down channel 0 with a 16 byte +/// buffer. Both channels are called "Terminal". This macro is equivalent to: +/// +/// ``` +/// rtt_init! { +/// up: { +/// 0: { +/// size: 1024, +/// name: "Terminal" +/// } +/// } +/// down: { +/// 0: { +/// size: 16, +/// name: "Terminal" +/// } +/// } +/// }; +/// ``` +/// +/// See [`rtt_init`] for more details. +#[macro_export] +macro_rules! rtt_init_default { + () => { + $crate::rtt_init! { + up: { + 0: { + size: 1024, + name: "Terminal" + } + } + down: { + 0: { + size: 16, + name: "Terminal" + } + } + }; + }; +} diff --git a/bitbox02-bt/vendor/rtt-target/src/lib.rs b/bitbox02-bt/vendor/rtt-target/src/lib.rs new file mode 100644 index 0000000..a395829 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/src/lib.rs @@ -0,0 +1,404 @@ +//! Target side implementation of the RTT (Real-Time Transfer) I/O protocol +//! +//! RTT implements input and output to/from a debug probe using in-memory ring buffers and memory +//! polling. This enables debug logging from the microcontroller with minimal delays and no +//! blocking, making it usable even in real-time applications where e.g. semihosting delays cannot +//! be tolerated. +//! +//! # Hardware support +//! +//! This crate is platform agnostic and can be used on any chip that supports background memory +//! access via its debug interface. The printing macros require a critical section which is +//! platform-dependent. Built-in ARM Cortex-M support can be enabled with the "cortex-m" feature, +//! and RISC-V support can be enabled with the "riscv" feature. +//! +//! To interface with RTT from the host computer, a debug probe such as an ST-Link or J-Link is +//! required. The normal debug protocol (e.g. SWD) is used to access RTT, so no extra connections +//! such as SWO pins are needed. +//! +//! # Initialization +//! +//! RTT must be initialized at the start of your program using one of the init macros. See the +//! macros for more details. +//! +//! The initialization macros return channel objects that can be used for writing and reading. +//! Different channel objects can safely be used concurrently in different contexts without locking. +//! In an interrupt-based application with realtime constraints you could use a separate channel for +//! every interrupt context to allow for lock-free logging. +//! +//! # Channels and virtual terminals +//! +//! RTT supports multiple *channels* in both directions. Up channels go from target to host, and +//! down channels go from host to target. Each channel is identified by its direction and number. +//! +//! By convention channel 0 is reserved for terminal use. In the up direction there is a set of +//! escape sequences that further enable the single channel to be treated as up to 16 *virtual +//! terminals*. This can be used to separate different types of messages (for example, log levels) +//! from each other without having to allocate memory for multiple buffers. As a downside, multiple +//! threads cannot write to the same channel at once, even if using different virtual terminal +//! numbers, so access has to be synchronized. Down channel 0 is conventionally used for keyboard +//! input. +//! +//! **Note:** Some host side programs only display channel 0 by default, so to see the other +//! channels you might need to configure them appropriately. +//! +//! The other channels can be used to either enable concurrent use from multiple sources without +//! locking, or to send e.g. binary data in either direction. +//! +//! Channel 0 can also be used for arbitrary data, but most tools expect it to be plain text. +//! +//! # Channel modes +//! +//! By default, channels start in [`NoBlockSkip`](ChannelMode::NoBlockSkip) mode, which discards +//! data if the buffer is full. This enables RTT to not crash the application if there is no debug +//! probe attached or if the host is not reading the buffers. However if the application outputs +//! faster than the host can read (which is easy to do, because writing is very fast), messages will +//! be lost. Channels can be set to blocking mode if this is desirable, however in that case the +//! application will likely freeze when the buffer fills up if a debugger is not attached. +//! +//! The channel mode can also be changed on the fly by the debug probe. Therefore it may be +//! advantageous to use a non-blocking mode in your microcontroller code, and set a blocking mode as +//! needed when debugging. That way you will never end up with an application that freezes without a +//! debugger connected. +//! +//! # Printing +//! +//! For no-hassle output the [`rprint`] and [`rprintln`] macros are provided. They use a single down +//! channel defined at initialization time, and a critical section for synchronization, and they +//! therefore work exactly like the standard `println` style macros. They can be used from any +//! context. The [`rtt_init_print`] convenience macro initializes printing on channel 0. +//! +//! +//! ``` +//! use rtt_target::{rtt_init_print, rprintln}; +//! +//! fn main() -> ! { +//! rtt_init_print!(); +//! loop { +//! rprintln!("Hello, world!"); +//! } +//! } +//! ``` +//! # Debug +//! +//! To use rtt functionality only in debug builds use macros prefixed with `debug_*`. They have +//! exactly the same functionality as without debug - the only difference is that they are removed +//! when built with `--release`. It's save to use [`debug_rprintln`] and [`debug_rprint`] even if +//! rtt was initialized with [`rtt_init`] instead of [`debug_rtt_init`]. +//! +//! Under the hood this uses the [`debug-assertions`] flag. Set this flag to true to include all debug +//! macros also in release mode. +//! +//! [debug-assertions]: https://doc.rust-lang.org/cargo/reference/profiles.html#debug-assertions +//! +//! ``` +//! use rtt_target::{debug_rtt_init_print, debug_rprintln}; +//! +//! fn main() -> ! { +//! debug_rtt_init_print!(); // nop in --release +//! loop { +//! debug_rprintln!("Hello, world!"); // not present in --release +//! } +//! } +//! ``` +//! +//! The macros also support an extended syntax to print to different RTT virtual terminals. +//! +//! Please note that because a critical section is used, printing into a blocking channel will cause +//! the application to block and freeze when the buffer is full. +//! +//! # Reading +//! +//! The following example shows how to set up the RTT to read simple input sent from the host +//! to the target. +//! +//! ``` +//! use rtt_target::{rtt_init_default, rprintln}; +//! +//! fn main() -> ! { +//! let mode = loop { +//! read = channels.down.0.read(&mut read_buf); +//! for i in 0..read { +//! match read_buf[i] as char { +//! '0' => break 0, +//! '1' => break 1, +//! _ => {} +//! } +//! } +//! }; +//! } +//! ``` + +#![no_std] + +use core::convert::Infallible; +use core::fmt; +use core::mem::MaybeUninit; +use ufmt_write::uWrite; + +#[macro_use] +mod init; + +#[doc(hidden)] +/// Public due to access from macro +pub mod debug; +/// Public due to access from macro +#[doc(hidden)] +pub mod rtt; + +#[macro_use] +mod print; + +pub use print::*; + +/// RTT up (target to host) channel +/// +/// Supports writing binary data directly, or writing strings via [`core::fmt`] macros such as +/// [`write`] as well as the ufmt crate's `uwrite` macros (use the `u` method). +/// +/// Note that the formatted writing implementations diverge slightly from the trait definitions in +/// that if the channel is in non-blocking mode, writing will *not* block. +pub struct UpChannel(*mut rtt::RttChannel); + +unsafe impl Send for UpChannel {} + +impl UpChannel { + /// Public due to access from macro. + #[doc(hidden)] + pub unsafe fn new(channel: *mut rtt::RttChannel) -> Self { + UpChannel(channel) + } + + #[allow(clippy::mut_from_ref)] + fn channel(&self) -> &mut rtt::RttChannel { + unsafe { &mut *self.0 } + } + + /// Writes `buf` to the channel and returns the number of bytes written. Behavior when the + /// buffer is full is subject to the channel blocking mode. + pub fn write(&mut self, buf: &[u8]) -> usize { + let mut writer = self.channel().writer(); + writer.write(buf); + writer.commit() + } + + /// Creates a writer for formatted writing with ufmt. + /// + /// The correct way to use this method is to call it once for each write operation. This is so + /// that non blocking modes will work correctly. + /// + /// ``` + /// let mut output = channels.up.0; + /// uwriteln!(output.u(), "Hello, ufmt!"); + /// ``` + pub fn u(&mut self) -> uWriter { + uWriter(self.channel().writer()) + } + + /// Gets the current blocking mode of the channel. The default is `NoBlockSkip`. + pub fn mode(&self) -> ChannelMode { + self.channel().mode() + } + + /// Sets the blocking mode of the channel + pub fn set_mode(&mut self, mode: ChannelMode) { + self.channel().set_mode(mode) + } + + /// Converts the channel into a virtual terminal that can be used for writing into multiple + /// virtual terminals. + pub fn into_terminal(self) -> TerminalChannel { + TerminalChannel::new(self) + } + + /// Magically creates a channel out of thin air. Return `None` if the channel number is too + /// high, or if the channel has not been initialized. + /// + /// Calling this function will cause a linking error if `rtt_init` has not been called. + /// + /// # Safety + /// + /// It's undefined behavior for something else to access the channel through anything else + /// besides the returned object during or after calling this function. Essentially this function + /// is only safe to use in panic handlers and the like that permanently disable interrupts. + pub unsafe fn conjure(number: usize) -> Option { + extern "C" { + #[link_name = "_SEGGER_RTT"] + static mut CONTROL_BLOCK: MaybeUninit; + } + + if number >= (*CONTROL_BLOCK.as_ptr()).max_up_channels() { + return None; + } + + // First addition moves to the start of the up channel array, second addition moves to the + // correct channel. + let ptr = (CONTROL_BLOCK.as_ptr().add(1) as *mut rtt::RttChannel).add(number); + + if !(*ptr).is_initialized() { + return None; + } + + Some(UpChannel(ptr)) + } +} + +impl fmt::Write for UpChannel { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + self.channel().writer().write_str(s) + } + + fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), fmt::Error> { + self.channel().writer().write_fmt(args) + } +} + +/// Writer for ufmt. Don't store an instance of this, but rather create a new one for every write. +#[allow(non_camel_case_types)] +pub struct uWriter<'c>(rtt::RttWriter<'c>); + +impl uWrite for uWriter<'_> { + type Error = Infallible; + + fn write_str(&mut self, s: &str) -> Result<(), Self::Error> { + self.0.write(s.as_bytes()); + Ok(()) + } +} + +/// RTT down (host to target) channel +pub struct DownChannel(*mut rtt::RttChannel); + +unsafe impl Send for DownChannel {} + +impl DownChannel { + /// Public due to access from macro. + #[doc(hidden)] + pub unsafe fn new(channel: *mut rtt::RttChannel) -> Self { + DownChannel(channel) + } + + fn channel(&mut self) -> &mut rtt::RttChannel { + unsafe { &mut *self.0 } + } + + /// Reads up to `buf.len()` bytes from the channel and return the number of bytes read. This + /// method never blocks. + pub fn read(&mut self, buf: &mut [u8]) -> usize { + self.channel().read(buf) + } +} + +/// Specifies what to do when a channel doesn't have enough buffer space for a complete write. +#[derive(Eq, PartialEq)] +#[repr(usize)] +pub enum ChannelMode { + /// Skip writing the data completely if it doesn't fit in its entirety. + NoBlockSkip = 0, + + /// Write as much as possible of the data and ignore the rest. + NoBlockTrim = 1, + + /// Block (spin) if the buffer is full. If within a critical section such as inside + /// [`rprintln`], this will cause the application to freeze until the host reads from the + /// buffer. + BlockIfFull = 2, +} + +/// An up channel that supports writing into multiple virtual terminals within the same buffer. +/// +/// An [`UpChannel`] can be turned into a `TerminalChannel` by using the +/// [`into_terminal`](UpChannel::into_terminal()) method. +/// +/// Virtual terminals allow you to share one buffer for writing multiple streams. The virtual +/// terminals number from 0 to 15 and are implemented with a simple "terminal switch" sequence on +/// the fly, so there is no need to declare them in advance. You could, for example, use different +/// terminal numbers for messages of different priorities to separate them in a viewer program. +/// Printing uses a `TerminalChannel` internally. +pub struct TerminalChannel { + channel: UpChannel, + current: u8, +} + +impl TerminalChannel { + pub(crate) fn new(channel: UpChannel) -> Self { + Self { + channel, + current: 0, + } + } + + /// Creates a writer to write a message to the virtual terminal specified by `number`. + /// + /// The correct way to use this method is to call it once for each write operation. This is so + /// that non blocking modes will work correctly. + /// + /// The writer supports formatted writing with the standard `write` and ufmt's `uwrite`. + pub fn write(&mut self, number: u8) -> TerminalWriter { + const TERMINAL_ID: [u8; 16] = *b"0123456789ABCDEF"; + + let mut writer = self.channel.channel().writer(); + + if number != self.current { + // The terminal switch command must be sent in full so the mode cannot be NoBlockTrim + let mode = self.channel.mode(); + let mode = if mode == ChannelMode::NoBlockTrim { + ChannelMode::NoBlockSkip + } else { + mode + }; + + writer.write_with_mode(mode, &[0xff, TERMINAL_ID[(number & 0x0f) as usize]]); + + self.current = number; + } + + TerminalWriter { + writer, + number, + current: &mut self.current, + } + } + + /// Gets the current blocking mode of the channel. The default is `NoBlockSkip`. + pub fn mode(&self) -> ChannelMode { + self.channel.mode() + } + + /// Sets the blocking mode of the channel + pub fn set_mode(&mut self, mode: ChannelMode) { + self.channel.set_mode(mode) + } +} + +/// Formatted writing operation. Don't store an instance of this, but rather create a new one for +/// every write. +pub struct TerminalWriter<'c> { + writer: rtt::RttWriter<'c>, + number: u8, + current: &'c mut u8, +} + +impl fmt::Write for TerminalWriter<'_> { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + self.writer.write(s.as_bytes()); + Ok(()) + } +} + +impl uWrite for TerminalWriter<'_> { + type Error = Infallible; + + fn write_str(&mut self, s: &str) -> Result<(), Self::Error> { + self.writer.write(s.as_bytes()); + Ok(()) + } +} + +impl Drop for TerminalWriter<'_> { + fn drop(&mut self) { + if !self.writer.is_failed() { + *self.current = self.number; + } + } +} diff --git a/bitbox02-bt/vendor/rtt-target/src/print.rs b/bitbox02-bt/vendor/rtt-target/src/print.rs new file mode 100644 index 0000000..87e0d18 --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/src/print.rs @@ -0,0 +1,169 @@ +use core::cell::RefCell; +use core::fmt::{self, Write as _}; +use critical_section::Mutex; + +use crate::{TerminalChannel, TerminalWriter, UpChannel}; + +static PRINT_TERMINAL: Mutex>> = Mutex::new(RefCell::new(None)); + +/// Sets the channel to use for [`rprint`], [`rprintln`], [`debug_rptint`] and [`debug_rprintln`]. +pub fn set_print_channel(channel: UpChannel) { + critical_section::with(|cs| { + *PRINT_TERMINAL.borrow_ref_mut(cs) = Some(TerminalChannel::new(UpChannel(channel.0))) + }); +} + +/// Public due to access from macro. +#[doc(hidden)] +pub mod print_impl { + use super::*; + + fn with_writer(number: u8, f: F) { + critical_section::with(|cs| { + if let Some(term) = &mut *PRINT_TERMINAL.borrow_ref_mut(cs) { + f(term.write(number)) + } + }); + } + + /// Public due to access from macro. + #[doc(hidden)] + pub fn write_str(number: u8, s: &str) { + with_writer(number, |mut w| { + w.write_str(s).ok(); + }); + } + + /// Public due to access from macro. + #[doc(hidden)] + pub fn write_fmt(number: u8, arg: fmt::Arguments) { + with_writer(number, |mut w| { + w.write_fmt(arg).ok(); + }); + } +} + +/// Prints to the print RTT channel. Works just like the standard `print`. +/// +/// Before use the print channel has to be set with [`rtt_init_print`] or [`set_print_channel`]. If +/// the channel isn't set, the message is silently discarded. +/// +/// The macro also supports output to multiple virtual terminals on the channel. Use the syntax +/// ```rprint!(=> 1, "Hello!");``` to write to terminal number 1, for example. Terminal numbers +/// range from 0 to 15. +#[macro_export] +macro_rules! rprint { + (=> $terminal:expr, $s:expr) => { + $crate::print_impl::write_str($terminal, $s); + }; + (=> $terminal:expr, $($arg:tt)*) => { + $crate::print_impl::write_fmt($terminal, format_args!($($arg)*)); + }; + ($s:expr) => { + $crate::print_impl::write_str(0, $s); + }; + ($($arg:tt)*) => { + $crate::print_impl::write_fmt(0, format_args!($($arg)*)); + }; +} + +/// Prints to the print RTT channel, with a newline. Works just like the standard `println`. +/// +/// Before use the print channel has to be set with [`rtt_init_print`] or [`set_print_channel`]. If +/// the channel isn't set, the message is silently discarded. +/// +/// The macro also supports output to multiple virtual terminals on the channel. Use the syntax +/// ```rprintln!(=> 1, "Hello!");``` to write to terminal number 1, for example. Terminal numbers +/// range from 0 to 15. +#[macro_export] +macro_rules! rprintln { + (=> $terminal:expr) => { + $crate::print_impl::write_str($terminal, "\n"); + }; + (=> $terminal:expr, $fmt:expr) => { + $crate::print_impl::write_str($terminal, concat!($fmt, "\n")); + }; + (=> $terminal:expr, $fmt:expr, $($arg:tt)*) => { + $crate::print_impl::write_fmt($terminal, format_args!(concat!($fmt, "\n"), $($arg)*)); + }; + () => { + $crate::print_impl::write_str(0, "\n"); + }; + ($fmt:expr) => { + $crate::print_impl::write_str(0, concat!($fmt, "\n")); + }; + ($fmt:expr, $($arg:tt)*) => { + $crate::print_impl::write_fmt(0, format_args!(concat!($fmt, "\n"), $($arg)*)); + }; +} + +/// Print to RTT and return the value of a given expression for quick debugging. This is equivalent +/// to Rust's `std::dbg!()` macro. +#[macro_export] +macro_rules! rdbg { + (=> $terminal:expr) => { + $crate::rprintln!(=> $terminal, "[{}:{}]", ::core::file!(), ::core::line!()) + }; + (=> $terminal:expr, $val:expr $(,)?) => { + // Use of `match` here is intentional because it affects the lifetimes + // of temporaries - https://stackoverflow.com/a/48732525/1063961 + match $val { + tmp => { + $crate::rprintln!(=> $terminal, "[{}:{}] {} = {:#?}", + ::core::file!(), ::core::line!(), ::core::stringify!($val), &tmp); + tmp + } + } + }; + (=> $terminal:expr, $($val:expr),+ $(,)?) => { + ($($crate::rdbg!(=> $terminal, $val)),+,) + }; + () => { + $crate::rprintln!("[{}:{}]", ::core::file!(), ::core::line!()) + }; + ($val:expr $(,)?) => { + // Use of `match` here is intentional because it affects the lifetimes + // of temporaries - https://stackoverflow.com/a/48732525/1063961 + match $val { + tmp => { + $crate::rprintln!("[{}:{}] {} = {:#?}", + ::core::file!(), ::core::line!(), ::core::stringify!($val), &tmp); + tmp + } + } + }; + ($($val:expr),+ $(,)?) => { + ($($crate::rdbg!($val)),+,) + }; +} + +/// Initializes RTT with a single up channel and sets it as the print channel for the printing +/// macros. +/// +/// The optional arguments specify the blocking mode (default: `NoBlockSkip`) and size of the buffer +/// in bytes (default: 1024). See [`rtt_init`] for more details. +#[macro_export] +macro_rules! rtt_init_print { + ($mode:path, $size:expr) => { + let channels = $crate::rtt_init! { + up: { + 0: { + size: $size, + mode: $mode, + name: "Terminal" + } + } + }; + + $crate::set_print_channel(channels.up.0); + }; + + ($mode:path) => { + $crate::rtt_init_print!($mode, 1024); + }; + + () => { + use $crate::ChannelMode::NoBlockSkip; + $crate::rtt_init_print!(NoBlockSkip, 1024); + }; +} diff --git a/bitbox02-bt/vendor/rtt-target/src/rtt.rs b/bitbox02-bt/vendor/rtt-target/src/rtt.rs new file mode 100644 index 0000000..765963e --- /dev/null +++ b/bitbox02-bt/vendor/rtt-target/src/rtt.rs @@ -0,0 +1,282 @@ +//! This module contains the implementation for the RTT protocol. It's not meant to be used directly +//! in user code, and therefore mostly undocumented. The module is only public so that it can be +//! accessed from the rtt_init! macro. + +use crate::ChannelMode; +use core::cmp::min; +use core::fmt; +use core::ptr; +use core::sync::atomic::{fence, AtomicUsize, Ordering::SeqCst}; + +// Note: this is zero-initialized in the initialization macro so all zeros must be a valid value +#[repr(C)] +pub struct RttHeader { + id: [u8; 16], + max_up_channels: usize, + max_down_channels: usize, + // Followed in memory by: + // up_channels: [Channel; max_up_channels] + // down_channels: [Channel; down_up_channels] +} + +impl RttHeader { + /// Initializes the control block header. + /// + /// # Safety + /// + /// The arguments must correspond to the sizes of the arrays that follow the header in memory. + pub unsafe fn init(&mut self, max_up_channels: usize, max_down_channels: usize) { + ptr::write_volatile(&mut self.max_up_channels, max_up_channels); + ptr::write_volatile(&mut self.max_down_channels, max_down_channels); + + // Copy the ID in two parts to avoid having the ID string in memory in full. The ID is + // copied last to make it less likely an unfinished control block is detected by the host. + + ptr::copy_nonoverlapping(b"SEGG_" as *const u8, self.id.as_mut_ptr(), 5); + + fence(SeqCst); + + ptr::copy_nonoverlapping( + b"ER RTT\0\0\0\0\0\0" as *const u8, + self.id.as_mut_ptr().offset(4), + 12, + ); + } + + pub fn max_up_channels(&self) -> usize { + self.max_up_channels + } +} + +// Note: this is zero-initialized in the initialization macro so all zeros must be a valid value +#[repr(C)] +pub struct RttChannel { + name: *const u8, + buffer: *mut u8, + size: usize, + write: AtomicUsize, + read: AtomicUsize, + flags: AtomicUsize, +} + +impl RttChannel { + /// Initializes the channel. + /// + /// # Safety + /// + /// The pointer arguments must point to a valid null-terminated name and writable buffer. + pub unsafe fn init(&mut self, name: *const u8, mode: ChannelMode, buffer: *mut [u8]) { + ptr::write_volatile(&mut self.name, name); + ptr::write_volatile(&mut self.size, (*buffer).len()); + self.set_mode(mode); + + // Set buffer last as it can be used to detect if the channel has been initialized + ptr::write_volatile(&mut self.buffer, buffer as *mut u8); + } + + /// Returns true on a non-null value of the (raw) buffer pointerh + pub fn is_initialized(&self) -> bool { + !self.buffer.is_null() + } + + pub(crate) fn mode(&self) -> ChannelMode { + let mode = self.flags.load(SeqCst) & 3; + + if mode <= 2 { + unsafe { core::mem::transmute(mode) } + } else { + ChannelMode::NoBlockSkip + } + } + + pub(crate) fn set_mode(&self, mode: ChannelMode) { + self.flags + .store((self.flags.load(SeqCst) & !3) | mode as usize, SeqCst); + } + + // This method should only be called for down channels. + pub(crate) fn read(&self, mut buf: &mut [u8]) -> usize { + let (write, mut read) = self.read_pointers(); + + let mut total = 0; + + // Read while buffer contains data and output buffer has space (maximum of two iterations) + while !buf.is_empty() { + let count = min(self.readable_contiguous(write, read), buf.len()); + if count == 0 { + break; + } + + unsafe { + ptr::copy_nonoverlapping(self.buffer.add(read), buf.as_mut_ptr(), count); + } + + total += count; + read += count; + + if read >= self.size { + // Wrap around to start + read = 0; + } + + buf = &mut buf[count..]; + } + + self.read.store(read, SeqCst); + + total + } + + /// This method should only be called for up channels. + pub(crate) fn writer(&self) -> RttWriter<'_> { + RttWriter { + chan: self, + write: self.read_pointers().0, + total: 0, + state: WriteState::Writable, + } + } + + /// Gets the amount of contiguous data available for reading + fn readable_contiguous(&self, write: usize, read: usize) -> usize { + if read > write { + self.size - read + } else { + write - read + } + } + + fn read_pointers(&self) -> (usize, usize) { + let write = self.write.load(SeqCst); + let read = self.read.load(SeqCst); + + if write >= self.size || read >= self.size { + // Pointers have been corrupted. This doesn't happen in well-behaved programs, so + // attempt to reset the buffer. + + self.write.store(0, SeqCst); + self.read.store(0, SeqCst); + return (0, 0); + } + + (write, read) + } +} + +/// A cancellable write operation to an RTT channel. +pub(crate) struct RttWriter<'c> { + chan: &'c RttChannel, + write: usize, + total: usize, + state: WriteState, +} + +#[derive(Eq, PartialEq)] +enum WriteState { + /// Operation can continue + Writable, + + /// Buffer space ran out but the written data will still be committed + Full, + + /// The operation failed and won't be committed, or it has already been committed. + Finished, +} + +impl RttWriter<'_> { + pub fn write(&mut self, buf: &[u8]) { + self.write_with_mode(self.chan.mode(), buf); + } + + pub fn write_with_mode(&mut self, mode: ChannelMode, mut buf: &[u8]) { + while self.state == WriteState::Writable && !buf.is_empty() { + let count = min(self.writable_contiguous(), buf.len()); + + if count == 0 { + // Buffer is full + + match mode { + ChannelMode::NoBlockSkip => { + // Mark the entire operation as failed if even one part cannot be written in + // full. + self.state = WriteState::Finished; + return; + } + + ChannelMode::NoBlockTrim => { + // If the buffer is full, write as much as possible (note: no return), and + // mark the operation as full, which prevents further writes. + self.state = WriteState::Full; + } + + ChannelMode::BlockIfFull => { + // Commit everything written so far and spin until more can be written + self.chan.write.store(self.write, SeqCst); + continue; + } + } + } + + unsafe { + ptr::copy_nonoverlapping(buf.as_ptr(), self.chan.buffer.add(self.write), count); + } + + self.write += count; + self.total += count; + + if self.write >= self.chan.size { + // Wrap around to start + self.write = 0; + } + + buf = &buf[count..]; + } + } + + /// Gets the amount of contiguous space available for writing + fn writable_contiguous(&self) -> usize { + let read = self.chan.read_pointers().1; + + if read > self.write { + read - self.write - 1 + } else if read == 0 { + self.chan.size - self.write - 1 + } else { + self.chan.size - self.write + } + } + + pub fn is_failed(&self) -> bool { + self.state != WriteState::Finished + } + + pub fn commit(mut self) -> usize { + self.commit_impl(); + + self.total + } + + fn commit_impl(&mut self) { + match self.state { + WriteState::Finished => (), + WriteState::Full | WriteState::Writable => { + // Commit the write pointer so the host can see the new data + self.chan.write.store(self.write, SeqCst); + self.state = WriteState::Finished; + } + } + } +} + +impl Drop for RttWriter<'_> { + fn drop(&mut self) { + self.commit_impl(); + } +} + +impl fmt::Write for RttWriter<'_> { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + self.write(s.as_bytes()); + Ok(()) + } +} diff --git a/bitbox02-bt/vendor/rustc_version/.cargo-checksum.json b/bitbox02-bt/vendor/rustc_version/.cargo-checksum.json new file mode 100644 index 0000000..f86fe1c --- /dev/null +++ b/bitbox02-bt/vendor/rustc_version/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"80b9fb136c8c2945b4875b05b0f5a4b11e4722997e751f17d8d3f241d7c684db","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","README.md":"58bd14a1dfa1d828e6e99f35c3b7c2149d08e2d990d6ca93f92ab8ffb43275b7","src/errors.rs":"b28c2eeb1278fc3e8d68a64b177034faed67f6762335729d3a6d1e61be8fb034","src/lib.rs":"92a32673f77961724bc52b872781f06d22d166f06838c9582c5adae3c5214f51"},"package":"138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/rustc_version/Cargo.toml b/bitbox02-bt/vendor/rustc_version/Cargo.toml new file mode 100644 index 0000000..3b252b8 --- /dev/null +++ b/bitbox02-bt/vendor/rustc_version/Cargo.toml @@ -0,0 +1,26 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rustc_version" +version = "0.2.3" +authors = ["Marvin Löbel "] +description = "A library for querying the version of a installed rustc compiler" +documentation = "https://docs.rs/rustc_version/" +readme = "README.md" +keywords = ["version", "rustc"] +license = "MIT/Apache-2.0" +repository = "https://github.com/Kimundi/rustc-version-rs" +[dependencies.semver] +version = "0.9" +[badges.travis-ci] +repository = "Kimundi/rustc-version-rs" diff --git a/bitbox02-bt/vendor/rustc_version/LICENSE-APACHE b/bitbox02-bt/vendor/rustc_version/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/rustc_version/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/rustc_version/LICENSE-MIT b/bitbox02-bt/vendor/rustc_version/LICENSE-MIT new file mode 100644 index 0000000..40b8817 --- /dev/null +++ b/bitbox02-bt/vendor/rustc_version/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/rustc_version/README.md b/bitbox02-bt/vendor/rustc_version/README.md new file mode 100644 index 0000000..f491ca9 --- /dev/null +++ b/bitbox02-bt/vendor/rustc_version/README.md @@ -0,0 +1,75 @@ +rustc-version-rs +============== + +A library for querying the version of a `rustc` compiler. + +This can be used by build scripts or other tools dealing with Rust sources +to make decisions based on the version of the compiler. + +[![Travis-CI Status](https://travis-ci.org/Kimundi/rustc-version-rs.png?branch=master)](https://travis-ci.org/Kimundi/rustc-version-rs) + +# Getting Started + +[rustc-version-rs is available on crates.io](https://crates.io/crates/rustc_version). +It is recommended to look there for the newest released version, as well as links to the newest builds of the docs. + +At the point of the last update of this README, the latest published version could be used like this: + +Add the following dependency to your Cargo manifest... + +```toml +[build-dependencies] +rustc_version = "0.2" +``` + +...and see the [docs](http://kimundi.github.io/rustc-version-rs/rustc_version/index.html) for how to use it. + +# Example + +```rust +// This could be a cargo build script + +extern crate rustc_version; +use rustc_version::{version, version_meta, Channel, Version}; + +fn main() { + // Assert we haven't travelled back in time + assert!(version().unwrap().major >= 1); + + // Set cfg flags depending on release channel + match version_meta().unwrap().channel { + Channel::Stable => { + println!("cargo:rustc-cfg=RUSTC_IS_STABLE"); + } + Channel::Beta => { + println!("cargo:rustc-cfg=RUSTC_IS_BETA"); + } + Channel::Nightly => { + println!("cargo:rustc-cfg=RUSTC_IS_NIGHTLY"); + } + Channel::Dev => { + println!("cargo:rustc-cfg=RUSTC_IS_DEV"); + } + } + + // Check for a minimum version + if version().unwrap() >= Version::parse("1.4.0").unwrap() { + println!("cargo:rustc-cfg=compiler_has_important_bugfix"); + } +} +``` + +## License + +Licensed under either of + + * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/bitbox02-bt/vendor/rustc_version/src/errors.rs b/bitbox02-bt/vendor/rustc_version/src/errors.rs new file mode 100644 index 0000000..54557b6 --- /dev/null +++ b/bitbox02-bt/vendor/rustc_version/src/errors.rs @@ -0,0 +1,79 @@ +use std::{self, error, fmt, io, str}; +use semver::{self, Identifier}; + +/// The error type for this crate. +#[derive(Debug)] +pub enum Error { + /// An error ocurrend when executing the `rustc` command. + CouldNotExecuteCommand(io::Error), + /// The output of `rustc -vV` was not valid utf-8. + Utf8Error(str::Utf8Error), + /// The output of `rustc -vV` was not in the expected format. + UnexpectedVersionFormat, + /// An error ocurred in parsing a `VersionReq`. + ReqParseError(semver::ReqParseError), + /// An error ocurred in parsing the semver. + SemVerError(semver::SemVerError), + /// The pre-release tag is unknown. + UnknownPreReleaseTag(Identifier), +} +use Error::*; + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use std::error::Error; + match *self { + CouldNotExecuteCommand(ref e) => write!(f, "{}: {}", self.description(), e), + Utf8Error(_) => write!(f, "{}", self.description()), + UnexpectedVersionFormat => write!(f, "{}", self.description()), + ReqParseError(ref e) => write!(f, "{}: {}", self.description(), e), + SemVerError(ref e) => write!(f, "{}: {}", self.description(), e), + UnknownPreReleaseTag(ref i) => write!(f, "{}: {}", self.description(), i), + } + } +} + +impl error::Error for Error { + fn cause(&self) -> Option<&error::Error> { + match *self { + CouldNotExecuteCommand(ref e) => Some(e), + Utf8Error(ref e) => Some(e), + UnexpectedVersionFormat => None, + ReqParseError(ref e) => Some(e), + SemVerError(ref e) => Some(e), + UnknownPreReleaseTag(_) => None, + } + } + + fn description(&self) -> &str { + match *self { + CouldNotExecuteCommand(_) => "could not execute command", + Utf8Error(_) => "invalid UTF-8 output from `rustc -vV`", + UnexpectedVersionFormat => "unexpected `rustc -vV` format", + ReqParseError(_) => "error parsing version requirement", + SemVerError(_) => "error parsing version", + UnknownPreReleaseTag(_) => "unknown pre-release tag", + } + } +} + +macro_rules! impl_from { + ($($err_ty:ty => $variant:ident),* $(,)*) => { + $( + impl From<$err_ty> for Error { + fn from(e: $err_ty) -> Error { + Error::$variant(e) + } + } + )* + } +} + +impl_from! { + str::Utf8Error => Utf8Error, + semver::SemVerError => SemVerError, + semver::ReqParseError => ReqParseError, +} + +/// The result type for this crate. +pub type Result = std::result::Result; diff --git a/bitbox02-bt/vendor/rustc_version/src/lib.rs b/bitbox02-bt/vendor/rustc_version/src/lib.rs new file mode 100644 index 0000000..c038288 --- /dev/null +++ b/bitbox02-bt/vendor/rustc_version/src/lib.rs @@ -0,0 +1,347 @@ +// Copyright 2016 rustc-version-rs developers +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![warn(missing_docs)] + +//! Simple library for getting the version information of a `rustc` +//! compiler. +//! +//! This can be used by build scripts or other tools dealing with Rust sources +//! to make decisions based on the version of the compiler. +//! +//! It calls `$RUSTC --version -v` and parses the output, falling +//! back to `rustc` if `$RUSTC` is not set. +//! +//! # Example +//! +//! ```rust +//! // This could be a cargo build script +//! +//! extern crate rustc_version; +//! use rustc_version::{version, version_meta, Channel, Version}; +//! +//! fn main() { +//! // Assert we haven't travelled back in time +//! assert!(version().unwrap().major >= 1); +//! +//! // Set cfg flags depending on release channel +//! match version_meta().unwrap().channel { +//! Channel::Stable => { +//! println!("cargo:rustc-cfg=RUSTC_IS_STABLE"); +//! } +//! Channel::Beta => { +//! println!("cargo:rustc-cfg=RUSTC_IS_BETA"); +//! } +//! Channel::Nightly => { +//! println!("cargo:rustc-cfg=RUSTC_IS_NIGHTLY"); +//! } +//! Channel::Dev => { +//! println!("cargo:rustc-cfg=RUSTC_IS_DEV"); +//! } +//! } +//! +//! // Check for a minimum version +//! if version().unwrap() >= Version::parse("1.4.0").unwrap() { +//! println!("cargo:rustc-cfg=compiler_has_important_bugfix"); +//! } +//! } +//! ``` + +extern crate semver; +use semver::Identifier; +use std::process::Command; +use std::{env, str}; +use std::ffi::OsString; + +// Convenience re-export to allow version comparison without needing to add +// semver crate. +pub use semver::Version; + +mod errors; +pub use errors::{Error, Result}; + +/// Release channel of the compiler. +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] +pub enum Channel { + /// Development release channel + Dev, + /// Nightly release channel + Nightly, + /// Beta release channel + Beta, + /// Stable release channel + Stable, +} + +/// Rustc version plus metada like git short hash and build date. +#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct VersionMeta { + /// Version of the compiler + pub semver: Version, + + /// Git short hash of the build of the compiler + pub commit_hash: Option, + + /// Commit date of the compiler + pub commit_date: Option, + + /// Build date of the compiler; this was removed between Rust 1.0.0 and 1.1.0. + pub build_date: Option, + + /// Release channel of the compiler + pub channel: Channel, + + /// Host target triple of the compiler + pub host: String, + + /// Short version string of the compiler + pub short_version_string: String, +} + +impl VersionMeta { + /// Returns the version metadata for `cmd`, which should be a `rustc` command. + pub fn for_command(cmd: Command) -> Result { + let mut cmd = cmd; + + let out = cmd.arg("-vV").output().map_err(Error::CouldNotExecuteCommand)?; + let out = str::from_utf8(&out.stdout)?; + + version_meta_for(out) + } +} + +/// Returns the `rustc` SemVer version. +pub fn version() -> Result { + Ok(version_meta()?.semver) +} + +/// Returns the `rustc` SemVer version and additional metadata +/// like the git short hash and build date. +pub fn version_meta() -> Result { + let cmd = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc")); + + VersionMeta::for_command(Command::new(cmd)) +} + +/// Parses a "rustc -vV" output string and returns +/// the SemVer version and additional metadata +/// like the git short hash and build date. +pub fn version_meta_for(verbose_version_string: &str) -> Result { + let out: Vec<_> = verbose_version_string.lines().collect(); + + if !(out.len() >= 6 && out.len() <= 8) { + return Err(Error::UnexpectedVersionFormat); + } + + let short_version_string = out[0]; + + fn expect_prefix<'a>(line: &'a str, prefix: &str) -> Result<&'a str> { + if line.starts_with(prefix) { + Ok(&line[prefix.len()..]) + } else { + Err(Error::UnexpectedVersionFormat) + } + } + + let commit_hash = match expect_prefix(out[2], "commit-hash: ")? { + "unknown" => None, + hash => Some(hash.to_owned()), + }; + + let commit_date = match expect_prefix(out[3], "commit-date: ")? { + "unknown" => None, + hash => Some(hash.to_owned()), + }; + + // Handle that the build date may or may not be present. + let mut idx = 4; + let mut build_date = None; + if out[idx].starts_with("build-date") { + build_date = match expect_prefix(out[idx], "build-date: ")? { + "unknown" => None, + s => Some(s.to_owned()), + }; + idx += 1; + } + + let host = expect_prefix(out[idx], "host: ")?; + idx += 1; + let release = expect_prefix(out[idx], "release: ")?; + + let semver: Version = release.parse()?; + + let channel = if semver.pre.is_empty() { + Channel::Stable + } else { + match semver.pre[0] { + Identifier::AlphaNumeric(ref s) if s == "dev" => Channel::Dev, + Identifier::AlphaNumeric(ref s) if s == "beta" => Channel::Beta, + Identifier::AlphaNumeric(ref s) if s == "nightly" => Channel::Nightly, + ref x => return Err(Error::UnknownPreReleaseTag(x.clone())), + } + }; + + Ok(VersionMeta { + semver: semver, + commit_hash: commit_hash, + commit_date: commit_date, + build_date: build_date, + channel: channel, + host: host.into(), + short_version_string: short_version_string.into(), + }) +} + +#[test] +fn smoketest() { + let v = version().unwrap(); + assert!(v.major >= 1); + + let v = version_meta().unwrap(); + assert!(v.semver.major >= 1); + + assert!(version().unwrap() >= Version::parse("1.0.0").unwrap()); +} + +#[test] +fn parse_unexpected() { + let res = version_meta_for( +"rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) +binary: rustc +commit-hash: a59de37e99060162a2674e3ff45409ac73595c0e +commit-date: 2015-05-13 +rust-birthday: 2015-05-14 +host: x86_64-unknown-linux-gnu +release: 1.0.0"); + + assert!(match res { + Err(Error::UnexpectedVersionFormat) => true, + _ => false, + }); + +} + +#[test] +fn parse_1_0_0() { + let version = version_meta_for( +"rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) +binary: rustc +commit-hash: a59de37e99060162a2674e3ff45409ac73595c0e +commit-date: 2015-05-13 +build-date: 2015-05-14 +host: x86_64-unknown-linux-gnu +release: 1.0.0").unwrap(); + + assert_eq!(version.semver, Version::parse("1.0.0").unwrap()); + assert_eq!(version.commit_hash, Some("a59de37e99060162a2674e3ff45409ac73595c0e".into())); + assert_eq!(version.commit_date, Some("2015-05-13".into())); + assert_eq!(version.build_date, Some("2015-05-14".into())); + assert_eq!(version.channel, Channel::Stable); + assert_eq!(version.host, "x86_64-unknown-linux-gnu"); + assert_eq!(version.short_version_string, "rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)"); +} + + +#[test] +fn parse_unknown() { + let version = version_meta_for( +"rustc 1.3.0 +binary: rustc +commit-hash: unknown +commit-date: unknown +host: x86_64-unknown-linux-gnu +release: 1.3.0").unwrap(); + + assert_eq!(version.semver, Version::parse("1.3.0").unwrap()); + assert_eq!(version.commit_hash, None); + assert_eq!(version.commit_date, None); + assert_eq!(version.channel, Channel::Stable); + assert_eq!(version.host, "x86_64-unknown-linux-gnu"); + assert_eq!(version.short_version_string, "rustc 1.3.0"); +} + +#[test] +fn parse_nightly() { + let version = version_meta_for( +"rustc 1.5.0-nightly (65d5c0833 2015-09-29) +binary: rustc +commit-hash: 65d5c083377645a115c4ac23a620d3581b9562b6 +commit-date: 2015-09-29 +host: x86_64-unknown-linux-gnu +release: 1.5.0-nightly").unwrap(); + + assert_eq!(version.semver, Version::parse("1.5.0-nightly").unwrap()); + assert_eq!(version.commit_hash, Some("65d5c083377645a115c4ac23a620d3581b9562b6".into())); + assert_eq!(version.commit_date, Some("2015-09-29".into())); + assert_eq!(version.channel, Channel::Nightly); + assert_eq!(version.host, "x86_64-unknown-linux-gnu"); + assert_eq!(version.short_version_string, "rustc 1.5.0-nightly (65d5c0833 2015-09-29)"); +} + +#[test] +fn parse_stable() { + let version = version_meta_for( +"rustc 1.3.0 (9a92aaf19 2015-09-15) +binary: rustc +commit-hash: 9a92aaf19a64603b02b4130fe52958cc12488900 +commit-date: 2015-09-15 +host: x86_64-unknown-linux-gnu +release: 1.3.0").unwrap(); + + assert_eq!(version.semver, Version::parse("1.3.0").unwrap()); + assert_eq!(version.commit_hash, Some("9a92aaf19a64603b02b4130fe52958cc12488900".into())); + assert_eq!(version.commit_date, Some("2015-09-15".into())); + assert_eq!(version.channel, Channel::Stable); + assert_eq!(version.host, "x86_64-unknown-linux-gnu"); + assert_eq!(version.short_version_string, "rustc 1.3.0 (9a92aaf19 2015-09-15)"); +} + +#[test] +fn parse_1_16_0_nightly() { + let version = version_meta_for( +"rustc 1.16.0-nightly (5d994d8b7 2017-01-05) +binary: rustc +commit-hash: 5d994d8b7e482e87467d4a521911477bd8284ce3 +commit-date: 2017-01-05 +host: x86_64-unknown-linux-gnu +release: 1.16.0-nightly +LLVM version: 3.9").unwrap(); + + assert_eq!(version.semver, Version::parse("1.16.0-nightly").unwrap()); + assert_eq!(version.commit_hash, Some("5d994d8b7e482e87467d4a521911477bd8284ce3".into())); + assert_eq!(version.commit_date, Some("2017-01-05".into())); + assert_eq!(version.channel, Channel::Nightly); + assert_eq!(version.host, "x86_64-unknown-linux-gnu"); + assert_eq!(version.short_version_string, "rustc 1.16.0-nightly (5d994d8b7 2017-01-05)"); +} + +/* +#[test] +fn version_matches_replacement() { + let f = |s1: &str, s2: &str| { + let a = Version::parse(s1).unwrap(); + let b = Version::parse(s2).unwrap(); + println!("{} <= {} : {}", s1, s2, a <= b); + }; + + println!(); + + f("1.5.0", "1.5.0"); + f("1.5.0-nightly", "1.5.0"); + f("1.5.0", "1.5.0-nightly"); + f("1.5.0-nightly", "1.5.0-nightly"); + + f("1.5.0", "1.6.0"); + f("1.5.0-nightly", "1.6.0"); + f("1.5.0", "1.6.0-nightly"); + f("1.5.0-nightly", "1.6.0-nightly"); + + panic!(); + +} +*/ diff --git a/bitbox02-bt/vendor/ryu/.cargo-checksum.json b/bitbox02-bt/vendor/ryu/.cargo-checksum.json new file mode 100644 index 0000000..da5e42e --- /dev/null +++ b/bitbox02-bt/vendor/ryu/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"2154f7e5f06489f3b42120f2165661fd552aa03b3d1f4f0cfeb380acad362b22","Cargo.toml":"708b4546804f6c500c45fd048921400f4328fe8f7159e0491faa4a64e38a2b0f","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-BOOST":"c9bff75738922193e67fa726fa225535870d2aa1059f91452c411736284ad566","README.md":"86f0a92cf076f4983f99926607ea272c9650a5996fa3921fc5ca5abceb0f18db","benches/bench.rs":"703521c8cb9c6959ee305776a9971d24754b6fff5c1737741be04f956a3692e8","examples/upstream_benchmark.rs":"f702d3598a8fac59134a8058ebf74ba90163b1f23ebbd6c5978a7bd8a888d357","src/buffer/mod.rs":"e32f3fa7e994ff704796e58e115c5258e94a79a184d1608864772f2f2f5274fc","src/common.rs":"cae347e97fc30c50a964f80425e8c3e69ece2b8ab81f9b81b9baa7fcec64a001","src/d2s.rs":"f2612785ebe510c935b979dc5f66f6b8c818ca8a4cf0364ce1fe1d41fea39592","src/d2s_full_table.rs":"9b0186acbc6d65dc55c17e16125be707a2bfb920d22b35d33234b4cc38566a36","src/d2s_intrinsics.rs":"bbf15472f4299942312e80a992cbc2f47f85f17ed193f24084534434dbfb26e7","src/d2s_small_table.rs":"db3bbe4002d816785b0ee233c330f19fa7002f31dab47dc6f67b266996fe3ae4","src/digit_table.rs":"02351ca54cb8cb3679f635115dd094f32fd91750e9f66103c1ee9ec3db507072","src/f2s.rs":"cb96f61d8c6c6c941803a7b629f2bf835e1a20ad9d3e5d3454a30ed3391c3515","src/f2s_intrinsics.rs":"97bab98093838e30c60f5135f54f5ccb039ff7d9f35553ac8e74437743ca47e2","src/lib.rs":"8020040eaf88b50ffe542691d4c5a63e9f07e8ae6893ab433ef86762655dc941","src/parse.rs":"7f8aa7e007caf5dcb03abdc4238157724bb742d0823a3b8a01646fa1f1129154","src/pretty/exponent.rs":"fa914ec63b3f86cbdaf7933d7c44e1bc1f93c1239a29a5f86934680a7e957570","src/pretty/mantissa.rs":"40cb00efe1c3fab559ab58389bd519d556548aa18fb261a90dd48138911d039b","src/pretty/mod.rs":"eb0a8c78019f55a1767943821340e8b1278455e0d88bb4f63f4bd3dde340e387","src/s2d.rs":"c804518a771654e3786bde2b776c56e94e198ce6d3fe1e4e5e2f2a9cb9e607e3","src/s2f.rs":"11d528931ce1a01a93f39efb3fe99fdc3041b41fefafb2efd6a338d2a12b628c","tests/common_test.rs":"599781a637d9b9756858aabfe5c38a0734a550debd3d94774f33792b7b3c8240","tests/d2s_intrinsics_test.rs":"15d11b70810bf04f33f8b185bf7f010a436a4edb47fa4648b1a036568c2c5d15","tests/d2s_table_test.rs":"819c39cc94e3462138d3be337d06e7334de126642d34bf1394e03d2df9c0c90c","tests/d2s_test.rs":"d72aaf37c76a4042ecc12b7d6faf844696016bb72bb20d142ecab3bd6c87e29f","tests/exhaustive.rs":"f475ed9008a2cd86ce95abb577a4b01e9fed23fc16f7e217ccffb3b834005fa0","tests/f2s_test.rs":"ad9e6fe46e712c488b876428c144c79bdff0349b41c57eee5506fc3c9c156624","tests/macros/mod.rs":"8e90a674b3960f9516cb38f4eea0e0981ff902c3b33572ebdb6c5528d3ffa72c","tests/s2d_test.rs":"75c3a1044881718db65e05f25c9f6e1d005392dddb2e8dafb799668bb6a9a5c3","tests/s2f_test.rs":"1ec06646cb65229bfe866ec913901a0d8d736668f30b812fc4b00136a43f5142"},"package":"f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/ryu/Cargo.lock b/bitbox02-bt/vendor/ryu/Cargo.lock new file mode 100644 index 0000000..9f361d6 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/Cargo.lock @@ -0,0 +1,149 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "libc" +version = "0.2.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" + +[[package]] +name = "no-panic" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8540b7d99a20166178b42a05776aef900cdbfec397f861dfc7819bf1d7760b3d" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "proc-macro2" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_xorshift" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" +dependencies = [ + "rand_core", +] + +[[package]] +name = "ryu" +version = "1.0.18" +dependencies = [ + "no-panic", + "num_cpus", + "rand", + "rand_xorshift", +] + +[[package]] +name = "syn" +version = "2.0.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" diff --git a/bitbox02-bt/vendor/ryu/Cargo.toml b/bitbox02-bt/vendor/ryu/Cargo.toml new file mode 100644 index 0000000..5fa419b --- /dev/null +++ b/bitbox02-bt/vendor/ryu/Cargo.toml @@ -0,0 +1,103 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.36" +name = "ryu" +version = "1.0.18" +authors = ["David Tolnay "] +build = false +exclude = [ + "build.rs", + "performance.png", + "chart/**", +] +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Fast floating point to string conversion" +documentation = "https://docs.rs/ryu" +readme = "README.md" +keywords = ["float"] +categories = [ + "value-formatting", + "no-std", + "no-std::no-alloc", +] +license = "Apache-2.0 OR BSL-1.0" +repository = "https://github.com/dtolnay/ryu" + +[package.metadata.docs.rs] +rustdoc-args = ["--generate-link-to-definition"] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +name = "ryu" +path = "src/lib.rs" +doc-scrape-examples = false + +[[example]] +name = "upstream_benchmark" +path = "examples/upstream_benchmark.rs" + +[[test]] +name = "s2f_test" +path = "tests/s2f_test.rs" + +[[test]] +name = "common_test" +path = "tests/common_test.rs" + +[[test]] +name = "s2d_test" +path = "tests/s2d_test.rs" + +[[test]] +name = "d2s_test" +path = "tests/d2s_test.rs" + +[[test]] +name = "f2s_test" +path = "tests/f2s_test.rs" + +[[test]] +name = "d2s_table_test" +path = "tests/d2s_table_test.rs" + +[[test]] +name = "exhaustive" +path = "tests/exhaustive.rs" + +[[test]] +name = "d2s_intrinsics_test" +path = "tests/d2s_intrinsics_test.rs" + +[[bench]] +name = "bench" +path = "benches/bench.rs" + +[dependencies.no-panic] +version = "0.1" +optional = true + +[dev-dependencies.num_cpus] +version = "1.8" + +[dev-dependencies.rand] +version = "0.8" + +[dev-dependencies.rand_xorshift] +version = "0.3" + +[features] +small = [] diff --git a/bitbox02-bt/vendor/ryu/LICENSE-APACHE b/bitbox02-bt/vendor/ryu/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/ryu/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/ryu/LICENSE-BOOST b/bitbox02-bt/vendor/ryu/LICENSE-BOOST new file mode 100644 index 0000000..36b7cd9 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/LICENSE-BOOST @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/ryu/README.md b/bitbox02-bt/vendor/ryu/README.md new file mode 100644 index 0000000..998ea3e --- /dev/null +++ b/bitbox02-bt/vendor/ryu/README.md @@ -0,0 +1,110 @@ +# Ryū + +[github](https://github.com/dtolnay/ryu) +[crates.io](https://crates.io/crates/ryu) +[docs.rs](https://docs.rs/ryu) +[build status](https://github.com/dtolnay/ryu/actions?query=branch%3Amaster) + +Pure Rust implementation of Ryū, an algorithm to quickly convert floating point +numbers to decimal strings. + +The PLDI'18 paper [*Ryū: fast float-to-string conversion*][paper] by Ulf Adams +includes a complete correctness proof of the algorithm. The paper is available +under the creative commons CC-BY-SA license. + +This Rust implementation is a line-by-line port of Ulf Adams' implementation in +C, [https://github.com/ulfjack/ryu][upstream]. + +*Requirements: this crate supports any compiler version back to rustc 1.36; it +uses nothing from the Rust standard library so is usable from no_std crates.* + +[paper]: https://dl.acm.org/citation.cfm?id=3192369 +[upstream]: https://github.com/ulfjack/ryu/tree/77e767f5e056bab96e895072fc21618ecff2f44b + +```toml +[dependencies] +ryu = "1.0" +``` + +
+ +## Example + +```rust +fn main() { + let mut buffer = ryu::Buffer::new(); + let printed = buffer.format(1.234); + assert_eq!(printed, "1.234"); +} +``` + +
+ +## Performance (lower is better) + +![performance](https://raw.githubusercontent.com/dtolnay/ryu/master/performance.png) + +You can run upstream's benchmarks with: + +```console +$ git clone https://github.com/ulfjack/ryu c-ryu +$ cd c-ryu +$ bazel run -c opt //ryu/benchmark:ryu_benchmark +``` + +And the same benchmark against our implementation with: + +```console +$ git clone https://github.com/dtolnay/ryu rust-ryu +$ cd rust-ryu +$ cargo run --example upstream_benchmark --release +``` + +These benchmarks measure the average time to print a 32-bit float and average +time to print a 64-bit float, where the inputs are distributed as uniform random +bit patterns 32 and 64 bits wide. + +The upstream C code, the unsafe direct Rust port, and the safe pretty Rust API +all perform the same, taking around 21 nanoseconds to format a 32-bit float and +31 nanoseconds to format a 64-bit float. + +There is also a Rust-specific benchmark comparing this implementation to the +standard library which you can run with: + +```console +$ cargo bench +``` + +The benchmark shows Ryū approximately 2-5x faster than the standard library +across a range of f32 and f64 inputs. Measurements are in nanoseconds per +iteration; smaller is better. + +## Formatting + +This library tends to produce more human-readable output than the standard +library's to\_string, which never uses scientific notation. Here are two +examples: + +- *ryu:* 1.23e40, *std:* 12300000000000000000000000000000000000000 +- *ryu:* 1.23e-40, *std:* 0.000000000000000000000000000000000000000123 + +Both libraries print short decimals such as 0.0000123 without scientific +notation. + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or Boost Software License 1.0 at your +option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/ryu/benches/bench.rs b/bitbox02-bt/vendor/ryu/benches/bench.rs new file mode 100644 index 0000000..fbc1b70 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/benches/bench.rs @@ -0,0 +1,62 @@ +// cargo bench + +#![feature(test)] +#![allow( + clippy::approx_constant, + clippy::excessive_precision, + clippy::unreadable_literal +)] + +extern crate test; + +use std::io::Write; +use std::{f32, f64}; +use test::{black_box, Bencher}; + +macro_rules! benches { + ($($name:ident($value:expr),)*) => { + mod bench_ryu { + use super::*; + $( + #[bench] + fn $name(b: &mut Bencher) { + let mut buf = ryu::Buffer::new(); + + b.iter(move || { + let value = black_box($value); + let formatted = buf.format_finite(value); + black_box(formatted); + }); + } + )* + } + + mod bench_std_fmt { + use super::*; + $( + #[bench] + fn $name(b: &mut Bencher) { + let mut buf = Vec::with_capacity(20); + + b.iter(|| { + buf.clear(); + let value = black_box($value); + write!(&mut buf, "{}", value).unwrap(); + black_box(buf.as_slice()); + }); + } + )* + } + }; +} + +benches! { + bench_0_f64(0f64), + bench_short_f64(0.1234f64), + bench_e_f64(2.718281828459045f64), + bench_max_f64(f64::MAX), + bench_0_f32(0f32), + bench_short_f32(0.1234f32), + bench_e_f32(2.718281828459045f32), + bench_max_f32(f32::MAX), +} diff --git a/bitbox02-bt/vendor/ryu/examples/upstream_benchmark.rs b/bitbox02-bt/vendor/ryu/examples/upstream_benchmark.rs new file mode 100644 index 0000000..437855b --- /dev/null +++ b/bitbox02-bt/vendor/ryu/examples/upstream_benchmark.rs @@ -0,0 +1,85 @@ +// cargo run --example upstream_benchmark --release + +use rand::{Rng, SeedableRng}; + +const SAMPLES: usize = 10000; +const ITERATIONS: usize = 1000; + +struct MeanAndVariance { + n: i64, + mean: f64, + m2: f64, +} + +impl MeanAndVariance { + fn new() -> Self { + MeanAndVariance { + n: 0, + mean: 0.0, + m2: 0.0, + } + } + + fn update(&mut self, x: f64) { + self.n += 1; + let d = x - self.mean; + self.mean += d / self.n as f64; + let d2 = x - self.mean; + self.m2 += d * d2; + } + + fn variance(&self) -> f64 { + self.m2 / (self.n - 1) as f64 + } + + fn stddev(&self) -> f64 { + self.variance().sqrt() + } +} + +macro_rules! benchmark { + ($name:ident, $ty:ident) => { + fn $name() -> usize { + let mut rng = rand_xorshift::XorShiftRng::from_seed([123u8; 16]); + let mut mv = MeanAndVariance::new(); + let mut throwaway = 0; + for _ in 0..SAMPLES { + let f = loop { + let f = $ty::from_bits(rng.gen()); + if f.is_finite() { + break f; + } + }; + + let t1 = std::time::SystemTime::now(); + for _ in 0..ITERATIONS { + throwaway += ryu::Buffer::new().format_finite(f).len(); + } + let duration = t1.elapsed().unwrap(); + let nanos = duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64; + mv.update(nanos as f64 / ITERATIONS as f64); + } + println!( + "{:12} {:8.3} {:8.3}", + concat!(stringify!($name), ":"), + mv.mean, + mv.stddev(), + ); + throwaway + } + }; +} + +benchmark!(pretty32, f32); +benchmark!(pretty64, f64); + +fn main() { + println!("{:>20}{:>9}", "Average", "Stddev"); + let mut throwaway = 0; + throwaway += pretty32(); + throwaway += pretty64(); + if std::env::var_os("ryu-benchmark").is_some() { + // Prevent the compiler from optimizing the code away. + println!("{}", throwaway); + } +} diff --git a/bitbox02-bt/vendor/ryu/src/buffer/mod.rs b/bitbox02-bt/vendor/ryu/src/buffer/mod.rs new file mode 100644 index 0000000..905ee2f --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/buffer/mod.rs @@ -0,0 +1,171 @@ +use crate::raw; +use core::mem::MaybeUninit; +use core::{slice, str}; +#[cfg(feature = "no-panic")] +use no_panic::no_panic; + +const NAN: &str = "NaN"; +const INFINITY: &str = "inf"; +const NEG_INFINITY: &str = "-inf"; + +/// Safe API for formatting floating point numbers to text. +/// +/// ## Example +/// +/// ``` +/// let mut buffer = ryu::Buffer::new(); +/// let printed = buffer.format_finite(1.234); +/// assert_eq!(printed, "1.234"); +/// ``` +pub struct Buffer { + bytes: [MaybeUninit; 24], +} + +impl Buffer { + /// This is a cheap operation; you don't need to worry about reusing buffers + /// for efficiency. + #[inline] + #[cfg_attr(feature = "no-panic", no_panic)] + pub fn new() -> Self { + let bytes = [MaybeUninit::::uninit(); 24]; + Buffer { bytes } + } + + /// Print a floating point number into this buffer and return a reference to + /// its string representation within the buffer. + /// + /// # Special cases + /// + /// This function formats NaN as the string "NaN", positive infinity as + /// "inf", and negative infinity as "-inf" to match std::fmt. + /// + /// If your input is known to be finite, you may get better performance by + /// calling the `format_finite` method instead of `format` to avoid the + /// checks for special cases. + #[cfg_attr(feature = "no-panic", inline)] + #[cfg_attr(feature = "no-panic", no_panic)] + pub fn format(&mut self, f: F) -> &str { + if f.is_nonfinite() { + f.format_nonfinite() + } else { + self.format_finite(f) + } + } + + /// Print a floating point number into this buffer and return a reference to + /// its string representation within the buffer. + /// + /// # Special cases + /// + /// This function **does not** check for NaN or infinity. If the input + /// number is not a finite float, the printed representation will be some + /// correctly formatted but unspecified numerical value. + /// + /// Please check [`is_finite`] yourself before calling this function, or + /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself. + /// + /// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite + /// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan + /// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite + #[inline] + #[cfg_attr(feature = "no-panic", no_panic)] + pub fn format_finite(&mut self, f: F) -> &str { + unsafe { + let n = f.write_to_ryu_buffer(self.bytes.as_mut_ptr() as *mut u8); + debug_assert!(n <= self.bytes.len()); + let slice = slice::from_raw_parts(self.bytes.as_ptr() as *const u8, n); + str::from_utf8_unchecked(slice) + } + } +} + +impl Copy for Buffer {} + +impl Clone for Buffer { + #[inline] + #[allow(clippy::non_canonical_clone_impl)] // false positive https://github.com/rust-lang/rust-clippy/issues/11072 + fn clone(&self) -> Self { + Buffer::new() + } +} + +impl Default for Buffer { + #[inline] + #[cfg_attr(feature = "no-panic", no_panic)] + fn default() -> Self { + Buffer::new() + } +} + +/// A floating point number, f32 or f64, that can be written into a +/// [`ryu::Buffer`][Buffer]. +/// +/// This trait is sealed and cannot be implemented for types outside of the +/// `ryu` crate. +pub trait Float: Sealed {} +impl Float for f32 {} +impl Float for f64 {} + +pub trait Sealed: Copy { + fn is_nonfinite(self) -> bool; + fn format_nonfinite(self) -> &'static str; + unsafe fn write_to_ryu_buffer(self, result: *mut u8) -> usize; +} + +impl Sealed for f32 { + #[inline] + fn is_nonfinite(self) -> bool { + const EXP_MASK: u32 = 0x7f800000; + let bits = self.to_bits(); + bits & EXP_MASK == EXP_MASK + } + + #[cold] + #[cfg_attr(feature = "no-panic", inline)] + fn format_nonfinite(self) -> &'static str { + const MANTISSA_MASK: u32 = 0x007fffff; + const SIGN_MASK: u32 = 0x80000000; + let bits = self.to_bits(); + if bits & MANTISSA_MASK != 0 { + NAN + } else if bits & SIGN_MASK != 0 { + NEG_INFINITY + } else { + INFINITY + } + } + + #[inline] + unsafe fn write_to_ryu_buffer(self, result: *mut u8) -> usize { + raw::format32(self, result) + } +} + +impl Sealed for f64 { + #[inline] + fn is_nonfinite(self) -> bool { + const EXP_MASK: u64 = 0x7ff0000000000000; + let bits = self.to_bits(); + bits & EXP_MASK == EXP_MASK + } + + #[cold] + #[cfg_attr(feature = "no-panic", inline)] + fn format_nonfinite(self) -> &'static str { + const MANTISSA_MASK: u64 = 0x000fffffffffffff; + const SIGN_MASK: u64 = 0x8000000000000000; + let bits = self.to_bits(); + if bits & MANTISSA_MASK != 0 { + NAN + } else if bits & SIGN_MASK != 0 { + NEG_INFINITY + } else { + INFINITY + } + } + + #[inline] + unsafe fn write_to_ryu_buffer(self, result: *mut u8) -> usize { + raw::format64(self, result) + } +} diff --git a/bitbox02-bt/vendor/ryu/src/common.rs b/bitbox02-bt/vendor/ryu/src/common.rs new file mode 100644 index 0000000..9613036 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/common.rs @@ -0,0 +1,95 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +// Returns the number of decimal digits in v, which must not contain more than 9 +// digits. +#[cfg_attr(feature = "no-panic", inline)] +pub fn decimal_length9(v: u32) -> u32 { + // Function precondition: v is not a 10-digit number. + // (f2s: 9 digits are sufficient for round-tripping.) + debug_assert!(v < 1000000000); + + if v >= 100000000 { + 9 + } else if v >= 10000000 { + 8 + } else if v >= 1000000 { + 7 + } else if v >= 100000 { + 6 + } else if v >= 10000 { + 5 + } else if v >= 1000 { + 4 + } else if v >= 100 { + 3 + } else if v >= 10 { + 2 + } else { + 1 + } +} + +// Returns e == 0 ? 1 : [log_2(5^e)]; requires 0 <= e <= 3528. +#[cfg_attr(feature = "no-panic", inline)] +#[allow(dead_code)] +pub fn log2_pow5(e: i32) -> i32 /* or u32 -> u32 */ { + // This approximation works up to the point that the multiplication + // overflows at e = 3529. If the multiplication were done in 64 bits, it + // would fail at 5^4004 which is just greater than 2^9297. + debug_assert!(e >= 0); + debug_assert!(e <= 3528); + ((e as u32 * 1217359) >> 19) as i32 +} + +// Returns e == 0 ? 1 : ceil(log_2(5^e)); requires 0 <= e <= 3528. +#[cfg_attr(feature = "no-panic", inline)] +pub fn pow5bits(e: i32) -> i32 /* or u32 -> u32 */ { + // This approximation works up to the point that the multiplication + // overflows at e = 3529. If the multiplication were done in 64 bits, it + // would fail at 5^4004 which is just greater than 2^9297. + debug_assert!(e >= 0); + debug_assert!(e <= 3528); + (((e as u32 * 1217359) >> 19) + 1) as i32 +} + +#[cfg_attr(feature = "no-panic", inline)] +#[allow(dead_code)] +pub fn ceil_log2_pow5(e: i32) -> i32 /* or u32 -> u32 */ { + log2_pow5(e) + 1 +} + +// Returns floor(log_10(2^e)); requires 0 <= e <= 1650. +#[cfg_attr(feature = "no-panic", inline)] +pub fn log10_pow2(e: i32) -> u32 /* or u32 -> u32 */ { + // The first value this approximation fails for is 2^1651 which is just greater than 10^297. + debug_assert!(e >= 0); + debug_assert!(e <= 1650); + (e as u32 * 78913) >> 18 +} + +// Returns floor(log_10(5^e)); requires 0 <= e <= 2620. +#[cfg_attr(feature = "no-panic", inline)] +pub fn log10_pow5(e: i32) -> u32 /* or u32 -> u32 */ { + // The first value this approximation fails for is 5^2621 which is just greater than 10^1832. + debug_assert!(e >= 0); + debug_assert!(e <= 2620); + (e as u32 * 732923) >> 20 +} diff --git a/bitbox02-bt/vendor/ryu/src/d2s.rs b/bitbox02-bt/vendor/ryu/src/d2s.rs new file mode 100644 index 0000000..76a8164 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/d2s.rs @@ -0,0 +1,302 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +use crate::common::{log10_pow2, log10_pow5, pow5bits}; +#[cfg(not(feature = "small"))] +pub use crate::d2s_full_table::{DOUBLE_POW5_INV_SPLIT, DOUBLE_POW5_SPLIT}; +use crate::d2s_intrinsics::{ + div10, div100, div5, mul_shift_all_64, multiple_of_power_of_2, multiple_of_power_of_5, +}; +#[cfg(feature = "small")] +pub use crate::d2s_small_table::{compute_inv_pow5, compute_pow5}; +use core::mem::MaybeUninit; + +pub const DOUBLE_MANTISSA_BITS: u32 = 52; +pub const DOUBLE_EXPONENT_BITS: u32 = 11; +pub const DOUBLE_BIAS: i32 = 1023; +pub const DOUBLE_POW5_INV_BITCOUNT: i32 = 125; +pub const DOUBLE_POW5_BITCOUNT: i32 = 125; + +#[cfg_attr(feature = "no-panic", inline)] +pub fn decimal_length17(v: u64) -> u32 { + // This is slightly faster than a loop. + // The average output length is 16.38 digits, so we check high-to-low. + // Function precondition: v is not an 18, 19, or 20-digit number. + // (17 digits are sufficient for round-tripping.) + debug_assert!(v < 100000000000000000); + + if v >= 10000000000000000 { + 17 + } else if v >= 1000000000000000 { + 16 + } else if v >= 100000000000000 { + 15 + } else if v >= 10000000000000 { + 14 + } else if v >= 1000000000000 { + 13 + } else if v >= 100000000000 { + 12 + } else if v >= 10000000000 { + 11 + } else if v >= 1000000000 { + 10 + } else if v >= 100000000 { + 9 + } else if v >= 10000000 { + 8 + } else if v >= 1000000 { + 7 + } else if v >= 100000 { + 6 + } else if v >= 10000 { + 5 + } else if v >= 1000 { + 4 + } else if v >= 100 { + 3 + } else if v >= 10 { + 2 + } else { + 1 + } +} + +// A floating decimal representing m * 10^e. +pub struct FloatingDecimal64 { + pub mantissa: u64, + // Decimal exponent's range is -324 to 308 + // inclusive, and can fit in i16 if needed. + pub exponent: i32, +} + +#[cfg_attr(feature = "no-panic", inline)] +pub fn d2d(ieee_mantissa: u64, ieee_exponent: u32) -> FloatingDecimal64 { + let (e2, m2) = if ieee_exponent == 0 { + ( + // We subtract 2 so that the bounds computation has 2 additional bits. + 1 - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS as i32 - 2, + ieee_mantissa, + ) + } else { + ( + ieee_exponent as i32 - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS as i32 - 2, + (1u64 << DOUBLE_MANTISSA_BITS) | ieee_mantissa, + ) + }; + let even = (m2 & 1) == 0; + let accept_bounds = even; + + // Step 2: Determine the interval of valid decimal representations. + let mv = 4 * m2; + // Implicit bool -> int conversion. True is 1, false is 0. + let mm_shift = (ieee_mantissa != 0 || ieee_exponent <= 1) as u32; + // We would compute mp and mm like this: + // uint64_t mp = 4 * m2 + 2; + // uint64_t mm = mv - 1 - mm_shift; + + // Step 3: Convert to a decimal power base using 128-bit arithmetic. + let mut vr: u64; + let mut vp: u64; + let mut vm: u64; + let mut vp_uninit: MaybeUninit = MaybeUninit::uninit(); + let mut vm_uninit: MaybeUninit = MaybeUninit::uninit(); + let e10: i32; + let mut vm_is_trailing_zeros = false; + let mut vr_is_trailing_zeros = false; + if e2 >= 0 { + // I tried special-casing q == 0, but there was no effect on performance. + // This expression is slightly faster than max(0, log10_pow2(e2) - 1). + let q = log10_pow2(e2) - (e2 > 3) as u32; + e10 = q as i32; + let k = DOUBLE_POW5_INV_BITCOUNT + pow5bits(q as i32) - 1; + let i = -e2 + q as i32 + k; + vr = unsafe { + mul_shift_all_64( + m2, + #[cfg(feature = "small")] + &compute_inv_pow5(q), + #[cfg(not(feature = "small"))] + { + debug_assert!(q < DOUBLE_POW5_INV_SPLIT.len() as u32); + DOUBLE_POW5_INV_SPLIT.get_unchecked(q as usize) + }, + i as u32, + vp_uninit.as_mut_ptr(), + vm_uninit.as_mut_ptr(), + mm_shift, + ) + }; + vp = unsafe { vp_uninit.assume_init() }; + vm = unsafe { vm_uninit.assume_init() }; + if q <= 21 { + // This should use q <= 22, but I think 21 is also safe. Smaller values + // may still be safe, but it's more difficult to reason about them. + // Only one of mp, mv, and mm can be a multiple of 5, if any. + let mv_mod5 = (mv as u32).wrapping_sub(5u32.wrapping_mul(div5(mv) as u32)); + if mv_mod5 == 0 { + vr_is_trailing_zeros = multiple_of_power_of_5(mv, q); + } else if accept_bounds { + // Same as min(e2 + (~mm & 1), pow5_factor(mm)) >= q + // <=> e2 + (~mm & 1) >= q && pow5_factor(mm) >= q + // <=> true && pow5_factor(mm) >= q, since e2 >= q. + vm_is_trailing_zeros = multiple_of_power_of_5(mv - 1 - mm_shift as u64, q); + } else { + // Same as min(e2 + 1, pow5_factor(mp)) >= q. + vp -= multiple_of_power_of_5(mv + 2, q) as u64; + } + } + } else { + // This expression is slightly faster than max(0, log10_pow5(-e2) - 1). + let q = log10_pow5(-e2) - (-e2 > 1) as u32; + e10 = q as i32 + e2; + let i = -e2 - q as i32; + let k = pow5bits(i) - DOUBLE_POW5_BITCOUNT; + let j = q as i32 - k; + vr = unsafe { + mul_shift_all_64( + m2, + #[cfg(feature = "small")] + &compute_pow5(i as u32), + #[cfg(not(feature = "small"))] + { + debug_assert!(i < DOUBLE_POW5_SPLIT.len() as i32); + DOUBLE_POW5_SPLIT.get_unchecked(i as usize) + }, + j as u32, + vp_uninit.as_mut_ptr(), + vm_uninit.as_mut_ptr(), + mm_shift, + ) + }; + vp = unsafe { vp_uninit.assume_init() }; + vm = unsafe { vm_uninit.assume_init() }; + if q <= 1 { + // {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at least q trailing 0 bits. + // mv = 4 * m2, so it always has at least two trailing 0 bits. + vr_is_trailing_zeros = true; + if accept_bounds { + // mm = mv - 1 - mm_shift, so it has 1 trailing 0 bit iff mm_shift == 1. + vm_is_trailing_zeros = mm_shift == 1; + } else { + // mp = mv + 2, so it always has at least one trailing 0 bit. + vp -= 1; + } + } else if q < 63 { + // TODO(ulfjack): Use a tighter bound here. + // We want to know if the full product has at least q trailing zeros. + // We need to compute min(p2(mv), p5(mv) - e2) >= q + // <=> p2(mv) >= q && p5(mv) - e2 >= q + // <=> p2(mv) >= q (because -e2 >= q) + vr_is_trailing_zeros = multiple_of_power_of_2(mv, q); + } + } + + // Step 4: Find the shortest decimal representation in the interval of valid representations. + let mut removed = 0i32; + let mut last_removed_digit = 0u8; + // On average, we remove ~2 digits. + let output = if vm_is_trailing_zeros || vr_is_trailing_zeros { + // General case, which happens rarely (~0.7%). + loop { + let vp_div10 = div10(vp); + let vm_div10 = div10(vm); + if vp_div10 <= vm_div10 { + break; + } + let vm_mod10 = (vm as u32).wrapping_sub(10u32.wrapping_mul(vm_div10 as u32)); + let vr_div10 = div10(vr); + let vr_mod10 = (vr as u32).wrapping_sub(10u32.wrapping_mul(vr_div10 as u32)); + vm_is_trailing_zeros &= vm_mod10 == 0; + vr_is_trailing_zeros &= last_removed_digit == 0; + last_removed_digit = vr_mod10 as u8; + vr = vr_div10; + vp = vp_div10; + vm = vm_div10; + removed += 1; + } + if vm_is_trailing_zeros { + loop { + let vm_div10 = div10(vm); + let vm_mod10 = (vm as u32).wrapping_sub(10u32.wrapping_mul(vm_div10 as u32)); + if vm_mod10 != 0 { + break; + } + let vp_div10 = div10(vp); + let vr_div10 = div10(vr); + let vr_mod10 = (vr as u32).wrapping_sub(10u32.wrapping_mul(vr_div10 as u32)); + vr_is_trailing_zeros &= last_removed_digit == 0; + last_removed_digit = vr_mod10 as u8; + vr = vr_div10; + vp = vp_div10; + vm = vm_div10; + removed += 1; + } + } + if vr_is_trailing_zeros && last_removed_digit == 5 && vr % 2 == 0 { + // Round even if the exact number is .....50..0. + last_removed_digit = 4; + } + // We need to take vr + 1 if vr is outside bounds or we need to round up. + vr + ((vr == vm && (!accept_bounds || !vm_is_trailing_zeros)) || last_removed_digit >= 5) + as u64 + } else { + // Specialized for the common case (~99.3%). Percentages below are relative to this. + let mut round_up = false; + let vp_div100 = div100(vp); + let vm_div100 = div100(vm); + // Optimization: remove two digits at a time (~86.2%). + if vp_div100 > vm_div100 { + let vr_div100 = div100(vr); + let vr_mod100 = (vr as u32).wrapping_sub(100u32.wrapping_mul(vr_div100 as u32)); + round_up = vr_mod100 >= 50; + vr = vr_div100; + vp = vp_div100; + vm = vm_div100; + removed += 2; + } + // Loop iterations below (approximately), without optimization above: + // 0: 0.03%, 1: 13.8%, 2: 70.6%, 3: 14.0%, 4: 1.40%, 5: 0.14%, 6+: 0.02% + // Loop iterations below (approximately), with optimization above: + // 0: 70.6%, 1: 27.8%, 2: 1.40%, 3: 0.14%, 4+: 0.02% + loop { + let vp_div10 = div10(vp); + let vm_div10 = div10(vm); + if vp_div10 <= vm_div10 { + break; + } + let vr_div10 = div10(vr); + let vr_mod10 = (vr as u32).wrapping_sub(10u32.wrapping_mul(vr_div10 as u32)); + round_up = vr_mod10 >= 5; + vr = vr_div10; + vp = vp_div10; + vm = vm_div10; + removed += 1; + } + // We need to take vr + 1 if vr is outside bounds or we need to round up. + vr + (vr == vm || round_up) as u64 + }; + let exp = e10 + removed; + + FloatingDecimal64 { + exponent: exp, + mantissa: output, + } +} diff --git a/bitbox02-bt/vendor/ryu/src/d2s_full_table.rs b/bitbox02-bt/vendor/ryu/src/d2s_full_table.rs new file mode 100644 index 0000000..7534ddd --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/d2s_full_table.rs @@ -0,0 +1,696 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +const DOUBLE_POW5_INV_TABLE_SIZE: usize = 342; +const DOUBLE_POW5_TABLE_SIZE: usize = 326; + +pub static DOUBLE_POW5_INV_SPLIT: [(u64, u64); DOUBLE_POW5_INV_TABLE_SIZE] = [ + (1, 2305843009213693952), + (11068046444225730970, 1844674407370955161), + (5165088340638674453, 1475739525896764129), + (7821419487252849886, 1180591620717411303), + (8824922364862649494, 1888946593147858085), + (7059937891890119595, 1511157274518286468), + (13026647942995916322, 1208925819614629174), + (9774590264567735146, 1934281311383406679), + (11509021026396098440, 1547425049106725343), + (16585914450600699399, 1237940039285380274), + (15469416676735388068, 1980704062856608439), + (16064882156130220778, 1584563250285286751), + (9162556910162266299, 1267650600228229401), + (7281393426775805432, 2028240960365167042), + (16893161185646375315, 1622592768292133633), + (2446482504291369283, 1298074214633706907), + (7603720821608101175, 2076918743413931051), + (2393627842544570617, 1661534994731144841), + (16672297533003297786, 1329227995784915872), + (11918280793837635165, 2126764793255865396), + (5845275820328197809, 1701411834604692317), + (15744267100488289217, 1361129467683753853), + (3054734472329800808, 2177807148294006166), + (17201182836831481939, 1742245718635204932), + (6382248639981364905, 1393796574908163946), + (2832900194486363201, 2230074519853062314), + (5955668970331000884, 1784059615882449851), + (1075186361522890384, 1427247692705959881), + (12788344622662355584, 2283596308329535809), + (13920024512871794791, 1826877046663628647), + (3757321980813615186, 1461501637330902918), + (10384555214134712795, 1169201309864722334), + (5547241898389809503, 1870722095783555735), + (4437793518711847602, 1496577676626844588), + (10928932444453298728, 1197262141301475670), + (17486291911125277965, 1915619426082361072), + (6610335899416401726, 1532495540865888858), + (12666966349016942027, 1225996432692711086), + (12888448528943286597, 1961594292308337738), + (17689456452638449924, 1569275433846670190), + (14151565162110759939, 1255420347077336152), + (7885109000409574610, 2008672555323737844), + (9997436015069570011, 1606938044258990275), + (7997948812055656009, 1285550435407192220), + (12796718099289049614, 2056880696651507552), + (2858676849947419045, 1645504557321206042), + (13354987924183666206, 1316403645856964833), + (17678631863951955605, 2106245833371143733), + (3074859046935833515, 1684996666696914987), + (13527933681774397782, 1347997333357531989), + (10576647446613305481, 2156795733372051183), + (15840015586774465031, 1725436586697640946), + (8982663654677661702, 1380349269358112757), + (18061610662226169046, 2208558830972980411), + (10759939715039024913, 1766847064778384329), + (12297300586773130254, 1413477651822707463), + (15986332124095098083, 2261564242916331941), + (9099716884534168143, 1809251394333065553), + (14658471137111155161, 1447401115466452442), + (4348079280205103483, 1157920892373161954), + (14335624477811986218, 1852673427797059126), + (7779150767507678651, 1482138742237647301), + (2533971799264232598, 1185710993790117841), + (15122401323048503126, 1897137590064188545), + (12097921058438802501, 1517710072051350836), + (5988988032009131678, 1214168057641080669), + (16961078480698431330, 1942668892225729070), + (13568862784558745064, 1554135113780583256), + (7165741412905085728, 1243308091024466605), + (11465186260648137165, 1989292945639146568), + (16550846638002330379, 1591434356511317254), + (16930026125143774626, 1273147485209053803), + (4951948911778577463, 2037035976334486086), + (272210314680951647, 1629628781067588869), + (3907117066486671641, 1303703024854071095), + (6251387306378674625, 2085924839766513752), + (16069156289328670670, 1668739871813211001), + (9165976216721026213, 1334991897450568801), + (7286864317269821294, 2135987035920910082), + (16897537898041588005, 1708789628736728065), + (13518030318433270404, 1367031702989382452), + (6871453250525591353, 2187250724783011924), + (9186511415162383406, 1749800579826409539), + (11038557946871817048, 1399840463861127631), + (10282995085511086630, 2239744742177804210), + (8226396068408869304, 1791795793742243368), + (13959814484210916090, 1433436634993794694), + (11267656730511734774, 2293498615990071511), + (5324776569667477496, 1834798892792057209), + (7949170070475892320, 1467839114233645767), + (17427382500606444826, 1174271291386916613), + (5747719112518849781, 1878834066219066582), + (15666221734240810795, 1503067252975253265), + (12532977387392648636, 1202453802380202612), + (5295368560860596524, 1923926083808324180), + (4236294848688477220, 1539140867046659344), + (7078384693692692099, 1231312693637327475), + (11325415509908307358, 1970100309819723960), + (9060332407926645887, 1576080247855779168), + (14626963555825137356, 1260864198284623334), + (12335095245094488799, 2017382717255397335), + (9868076196075591040, 1613906173804317868), + (15273158586344293478, 1291124939043454294), + (13369007293925138595, 2065799902469526871), + (7005857020398200553, 1652639921975621497), + (16672732060544291412, 1322111937580497197), + (11918976037903224966, 2115379100128795516), + (5845832015580669650, 1692303280103036413), + (12055363241948356366, 1353842624082429130), + (841837113407818570, 2166148198531886609), + (4362818505468165179, 1732918558825509287), + (14558301248600263113, 1386334847060407429), + (12225235553534690011, 2218135755296651887), + (2401490813343931363, 1774508604237321510), + (1921192650675145090, 1419606883389857208), + (17831303500047873437, 2271371013423771532), + (6886345170554478103, 1817096810739017226), + (1819727321701672159, 1453677448591213781), + (16213177116328979020, 1162941958872971024), + (14873036941900635463, 1860707134196753639), + (15587778368262418694, 1488565707357402911), + (8780873879868024632, 1190852565885922329), + (2981351763563108441, 1905364105417475727), + (13453127855076217722, 1524291284333980581), + (7073153469319063855, 1219433027467184465), + (11317045550910502167, 1951092843947495144), + (12742985255470312057, 1560874275157996115), + (10194388204376249646, 1248699420126396892), + (1553625868034358140, 1997919072202235028), + (8621598323911307159, 1598335257761788022), + (17965325103354776697, 1278668206209430417), + (13987124906400001422, 2045869129935088668), + (121653480894270168, 1636695303948070935), + (97322784715416134, 1309356243158456748), + (14913111714512307107, 2094969989053530796), + (8241140556867935363, 1675975991242824637), + (17660958889720079260, 1340780792994259709), + (17189487779326395846, 2145249268790815535), + (13751590223461116677, 1716199415032652428), + (18379969808252713988, 1372959532026121942), + (14650556434236701088, 2196735251241795108), + (652398703163629901, 1757388200993436087), + (11589965406756634890, 1405910560794748869), + (7475898206584884855, 2249456897271598191), + (2291369750525997561, 1799565517817278553), + (9211793429904618695, 1439652414253822842), + (18428218302589300235, 2303443862806116547), + (7363877012587619542, 1842755090244893238), + (13269799239553916280, 1474204072195914590), + (10615839391643133024, 1179363257756731672), + (2227947767661371545, 1886981212410770676), + (16539753473096738529, 1509584969928616540), + (13231802778477390823, 1207667975942893232), + (6413489186596184024, 1932268761508629172), + (16198837793502678189, 1545815009206903337), + (5580372605318321905, 1236652007365522670), + (8928596168509315048, 1978643211784836272), + (18210923379033183008, 1582914569427869017), + (7190041073742725760, 1266331655542295214), + (436019273762630246, 2026130648867672343), + (7727513048493924843, 1620904519094137874), + (9871359253537050198, 1296723615275310299), + (4726128361433549347, 2074757784440496479), + (7470251503888749801, 1659806227552397183), + (13354898832594820487, 1327844982041917746), + (13989140502667892133, 2124551971267068394), + (14880661216876224029, 1699641577013654715), + (11904528973500979224, 1359713261610923772), + (4289851098633925465, 2175541218577478036), + (18189276137874781665, 1740432974861982428), + (3483374466074094362, 1392346379889585943), + (1884050330976640656, 2227754207823337509), + (5196589079523222848, 1782203366258670007), + (15225317707844309248, 1425762693006936005), + (5913764258841343181, 2281220308811097609), + (8420360221814984868, 1824976247048878087), + (17804334621677718864, 1459980997639102469), + (17932816512084085415, 1167984798111281975), + (10245762345624985047, 1868775676978051161), + (4507261061758077715, 1495020541582440929), + (7295157664148372495, 1196016433265952743), + (7982903447895485668, 1913626293225524389), + (10075671573058298858, 1530901034580419511), + (4371188443704728763, 1224720827664335609), + (14372599139411386667, 1959553324262936974), + (15187428126271019657, 1567642659410349579), + (15839291315758726049, 1254114127528279663), + (3206773216762499739, 2006582604045247462), + (13633465017635730761, 1605266083236197969), + (14596120828850494932, 1284212866588958375), + (4907049252451240275, 2054740586542333401), + (236290587219081897, 1643792469233866721), + (14946427728742906810, 1315033975387093376), + (16535586736504830250, 2104054360619349402), + (5849771759720043554, 1683243488495479522), + (15747863852001765813, 1346594790796383617), + (10439186904235184007, 2154551665274213788), + (15730047152871967852, 1723641332219371030), + (12584037722297574282, 1378913065775496824), + (9066413911450387881, 2206260905240794919), + (10942479943902220628, 1765008724192635935), + (8753983955121776503, 1412006979354108748), + (10317025513452932081, 2259211166966573997), + (874922781278525018, 1807368933573259198), + (8078635854506640661, 1445895146858607358), + (13841606313089133175, 1156716117486885886), + (14767872471458792434, 1850745787979017418), + (746251532941302978, 1480596630383213935), + (597001226353042382, 1184477304306571148), + (15712597221132509104, 1895163686890513836), + (8880728962164096960, 1516130949512411069), + (10793931984473187891, 1212904759609928855), + (17270291175157100626, 1940647615375886168), + (2748186495899949531, 1552518092300708935), + (2198549196719959625, 1242014473840567148), + (18275073973719576693, 1987223158144907436), + (10930710364233751031, 1589778526515925949), + (12433917106128911148, 1271822821212740759), + (8826220925580526867, 2034916513940385215), + (7060976740464421494, 1627933211152308172), + (16716827836597268165, 1302346568921846537), + (11989529279587987770, 2083754510274954460), + (9591623423670390216, 1667003608219963568), + (15051996368420132820, 1333602886575970854), + (13015147745246481542, 2133764618521553367), + (3033420566713364587, 1707011694817242694), + (6116085268112601993, 1365609355853794155), + (9785736428980163188, 2184974969366070648), + (15207286772667951197, 1747979975492856518), + (1097782973908629988, 1398383980394285215), + (1756452758253807981, 2237414368630856344), + (5094511021344956708, 1789931494904685075), + (4075608817075965366, 1431945195923748060), + (6520974107321544586, 2291112313477996896), + (1527430471115325346, 1832889850782397517), + (12289990821117991246, 1466311880625918013), + (17210690286378213644, 1173049504500734410), + (9090360384495590213, 1876879207201175057), + (18340334751822203140, 1501503365760940045), + (14672267801457762512, 1201202692608752036), + (16096930852848599373, 1921924308174003258), + (1809498238053148529, 1537539446539202607), + (12515645034668249793, 1230031557231362085), + (1578287981759648052, 1968050491570179337), + (12330676829633449412, 1574440393256143469), + (13553890278448669853, 1259552314604914775), + (3239480371808320148, 2015283703367863641), + (17348979556414297411, 1612226962694290912), + (6500486015647617283, 1289781570155432730), + (10400777625036187652, 2063650512248692368), + (15699319729512770768, 1650920409798953894), + (16248804598352126938, 1320736327839163115), + (7551343283653851484, 2113178124542660985), + (6041074626923081187, 1690542499634128788), + (12211557331022285596, 1352433999707303030), + (1091747655926105338, 2163894399531684849), + (4562746939482794594, 1731115519625347879), + (7339546366328145998, 1384892415700278303), + (8053925371383123274, 2215827865120445285), + (6443140297106498619, 1772662292096356228), + (12533209867169019542, 1418129833677084982), + (5295740528502789974, 2269007733883335972), + (15304638867027962949, 1815206187106668777), + (4865013464138549713, 1452164949685335022), + (14960057215536570740, 1161731959748268017), + (9178696285890871890, 1858771135597228828), + (14721654658196518159, 1487016908477783062), + (4398626097073393881, 1189613526782226450), + (7037801755317430209, 1903381642851562320), + (5630241404253944167, 1522705314281249856), + (814844308661245011, 1218164251424999885), + (1303750893857992017, 1949062802279999816), + (15800395974054034906, 1559250241823999852), + (5261619149759407279, 1247400193459199882), + (12107939454356961969, 1995840309534719811), + (5997002748743659252, 1596672247627775849), + (8486951013736837725, 1277337798102220679), + (2511075177753209390, 2043740476963553087), + (13076906586428298482, 1634992381570842469), + (14150874083884549109, 1307993905256673975), + (4194654460505726958, 2092790248410678361), + (18113118827372222859, 1674232198728542688), + (3422448617672047318, 1339385758982834151), + (16543964232501006678, 2143017214372534641), + (9545822571258895019, 1714413771498027713), + (15015355686490936662, 1371531017198422170), + (5577825024675947042, 2194449627517475473), + (11840957649224578280, 1755559702013980378), + (16851463748863483271, 1404447761611184302), + (12204946739213931940, 2247116418577894884), + (13453306206113055875, 1797693134862315907), + (3383947335406624054, 1438154507889852726), + (16482362180876329456, 2301047212623764361), + (9496540929959153242, 1840837770099011489), + (11286581558709232917, 1472670216079209191), + (5339916432225476010, 1178136172863367353), + (4854517476818851293, 1885017876581387765), + (3883613981455081034, 1508014301265110212), + (14174937629389795797, 1206411441012088169), + (11611853762797942306, 1930258305619341071), + (5600134195496443521, 1544206644495472857), + (15548153800622885787, 1235365315596378285), + (6430302007287065643, 1976584504954205257), + (16212288050055383484, 1581267603963364205), + (12969830440044306787, 1265014083170691364), + (9683682259845159889, 2024022533073106183), + (15125643437359948558, 1619218026458484946), + (8411165935146048523, 1295374421166787957), + (17147214310975587960, 2072599073866860731), + (10028422634038560045, 1658079259093488585), + (8022738107230848036, 1326463407274790868), + (9147032156827446534, 2122341451639665389), + (11006974540203867551, 1697873161311732311), + (5116230817421183718, 1358298529049385849), + (15564666937357714594, 2173277646479017358), + (1383687105660440706, 1738622117183213887), + (12174996128754083534, 1390897693746571109), + (8411947361780802685, 2225436309994513775), + (6729557889424642148, 1780349047995611020), + (5383646311539713719, 1424279238396488816), + (1235136468979721303, 2278846781434382106), + (15745504434151418335, 1823077425147505684), + (16285752362063044992, 1458461940118004547), + (5649904260166615347, 1166769552094403638), + (5350498001524674232, 1866831283351045821), + (591049586477829062, 1493465026680836657), + (11540886113407994219, 1194772021344669325), + (18673707743239135, 1911635234151470921), + (14772334225162232601, 1529308187321176736), + (8128518565387875758, 1223446549856941389), + (1937583260394870242, 1957514479771106223), + (8928764237799716840, 1566011583816884978), + (14521709019723594119, 1252809267053507982), + (8477339172590109297, 2004494827285612772), + (17849917782297818407, 1603595861828490217), + (6901236596354434079, 1282876689462792174), + (18420676183650915173, 2052602703140467478), + (3668494502695001169, 1642082162512373983), + (10313493231639821582, 1313665730009899186), + (9122891541139893884, 2101865168015838698), + (14677010862395735754, 1681492134412670958), + (673562245690857633, 1345193707530136767), +]; + +pub static DOUBLE_POW5_SPLIT: [(u64, u64); DOUBLE_POW5_TABLE_SIZE] = [ + (0, 1152921504606846976), + (0, 1441151880758558720), + (0, 1801439850948198400), + (0, 2251799813685248000), + (0, 1407374883553280000), + (0, 1759218604441600000), + (0, 2199023255552000000), + (0, 1374389534720000000), + (0, 1717986918400000000), + (0, 2147483648000000000), + (0, 1342177280000000000), + (0, 1677721600000000000), + (0, 2097152000000000000), + (0, 1310720000000000000), + (0, 1638400000000000000), + (0, 2048000000000000000), + (0, 1280000000000000000), + (0, 1600000000000000000), + (0, 2000000000000000000), + (0, 1250000000000000000), + (0, 1562500000000000000), + (0, 1953125000000000000), + (0, 1220703125000000000), + (0, 1525878906250000000), + (0, 1907348632812500000), + (0, 1192092895507812500), + (0, 1490116119384765625), + (4611686018427387904, 1862645149230957031), + (9799832789158199296, 1164153218269348144), + (12249790986447749120, 1455191522836685180), + (15312238733059686400, 1818989403545856475), + (14528612397897220096, 2273736754432320594), + (13692068767113150464, 1421085471520200371), + (12503399940464050176, 1776356839400250464), + (15629249925580062720, 2220446049250313080), + (9768281203487539200, 1387778780781445675), + (7598665485932036096, 1734723475976807094), + (274959820560269312, 2168404344971008868), + (9395221924704944128, 1355252715606880542), + (2520655369026404352, 1694065894508600678), + (12374191248137781248, 2117582368135750847), + (14651398557727195136, 1323488980084844279), + (13702562178731606016, 1654361225106055349), + (3293144668132343808, 2067951531382569187), + (18199116482078572544, 1292469707114105741), + (8913837547316051968, 1615587133892632177), + (15753982952572452864, 2019483917365790221), + (12152082354571476992, 1262177448353618888), + (15190102943214346240, 1577721810442023610), + (9764256642163156992, 1972152263052529513), + (17631875447420442880, 1232595164407830945), + (8204786253993389888, 1540743955509788682), + (1032610780636961552, 1925929944387235853), + (2951224747111794922, 1203706215242022408), + (3689030933889743652, 1504632769052528010), + (13834660704216955373, 1880790961315660012), + (17870034976990372916, 1175494350822287507), + (17725857702810578241, 1469367938527859384), + (3710578054803671186, 1836709923159824231), + (26536550077201078, 2295887403949780289), + (11545800389866720434, 1434929627468612680), + (14432250487333400542, 1793662034335765850), + (8816941072311974870, 2242077542919707313), + (17039803216263454053, 1401298464324817070), + (12076381983474541759, 1751623080406021338), + (5872105442488401391, 2189528850507526673), + (15199280947623720629, 1368455531567204170), + (9775729147674874978, 1710569414459005213), + (16831347453020981627, 2138211768073756516), + (1296220121283337709, 1336382355046097823), + (15455333206886335848, 1670477943807622278), + (10095794471753144002, 2088097429759527848), + (6309871544845715001, 1305060893599704905), + (12499025449484531656, 1631326116999631131), + (11012095793428276666, 2039157646249538914), + (11494245889320060820, 1274473528905961821), + (532749306367912313, 1593091911132452277), + (5277622651387278295, 1991364888915565346), + (7910200175544436838, 1244603055572228341), + (14499436237857933952, 1555753819465285426), + (8900923260467641632, 1944692274331606783), + (12480606065433357876, 1215432671457254239), + (10989071563364309441, 1519290839321567799), + (9124653435777998898, 1899113549151959749), + (8008751406574943263, 1186945968219974843), + (5399253239791291175, 1483682460274968554), + (15972438586593889776, 1854603075343710692), + (759402079766405302, 1159126922089819183), + (14784310654990170340, 1448908652612273978), + (9257016281882937117, 1811135815765342473), + (16182956370781059300, 2263919769706678091), + (7808504722524468110, 1414949856066673807), + (5148944884728197234, 1768687320083342259), + (1824495087482858639, 2210859150104177824), + (1140309429676786649, 1381786968815111140), + (1425386787095983311, 1727233711018888925), + (6393419502297367043, 2159042138773611156), + (13219259225790630210, 1349401336733506972), + (16524074032238287762, 1686751670916883715), + (16043406521870471799, 2108439588646104644), + (803757039314269066, 1317774742903815403), + (14839754354425000045, 1647218428629769253), + (4714634887749086344, 2059023035787211567), + (9864175832484260821, 1286889397367007229), + (16941905809032713930, 1608611746708759036), + (2730638187581340797, 2010764683385948796), + (10930020904093113806, 1256727927116217997), + (18274212148543780162, 1570909908895272496), + (4396021111970173586, 1963637386119090621), + (5053356204195052443, 1227273366324431638), + (15540067292098591362, 1534091707905539547), + (14813398096695851299, 1917614634881924434), + (13870059828862294966, 1198509146801202771), + (12725888767650480803, 1498136433501503464), + (15907360959563101004, 1872670541876879330), + (14553786618154326031, 1170419088673049581), + (4357175217410743827, 1463023860841311977), + (10058155040190817688, 1828779826051639971), + (7961007781811134206, 2285974782564549964), + (14199001900486734687, 1428734239102843727), + (13137066357181030455, 1785917798878554659), + (11809646928048900164, 2232397248598193324), + (16604401366885338411, 1395248280373870827), + (16143815690179285109, 1744060350467338534), + (10956397575869330579, 2180075438084173168), + (6847748484918331612, 1362547148802608230), + (17783057643002690323, 1703183936003260287), + (17617136035325974999, 2128979920004075359), + (17928239049719816230, 1330612450002547099), + (17798612793722382384, 1663265562503183874), + (13024893955298202172, 2079081953128979843), + (5834715712847682405, 1299426220705612402), + (16516766677914378815, 1624282775882015502), + (11422586310538197711, 2030353469852519378), + (11750802462513761473, 1268970918657824611), + (10076817059714813937, 1586213648322280764), + (12596021324643517422, 1982767060402850955), + (5566670318688504437, 1239229412751781847), + (2346651879933242642, 1549036765939727309), + (7545000868343941206, 1936295957424659136), + (4715625542714963254, 1210184973390411960), + (5894531928393704067, 1512731216738014950), + (16591536947346905892, 1890914020922518687), + (17287239619732898039, 1181821263076574179), + (16997363506238734644, 1477276578845717724), + (2799960309088866689, 1846595723557147156), + (10973347230035317489, 1154122327223216972), + (13716684037544146861, 1442652909029021215), + (12534169028502795672, 1803316136286276519), + (11056025267201106687, 2254145170357845649), + (18439230838069161439, 1408840731473653530), + (13825666510731675991, 1761050914342066913), + (3447025083132431277, 2201313642927583642), + (6766076695385157452, 1375821026829739776), + (8457595869231446815, 1719776283537174720), + (10571994836539308519, 2149720354421468400), + (6607496772837067824, 1343575221513417750), + (17482743002901110588, 1679469026891772187), + (17241742735199000331, 2099336283614715234), + (15387775227926763111, 1312085177259197021), + (5399660979626290177, 1640106471573996277), + (11361262242960250625, 2050133089467495346), + (11712474920277544544, 1281333180917184591), + (10028907631919542777, 1601666476146480739), + (7924448521472040567, 2002083095183100924), + (14176152362774801162, 1251301934489438077), + (3885132398186337741, 1564127418111797597), + (9468101516160310080, 1955159272639746996), + (15140935484454969608, 1221974545399841872), + (479425281859160394, 1527468181749802341), + (5210967620751338397, 1909335227187252926), + (17091912818251750210, 1193334516992033078), + (12141518985959911954, 1491668146240041348), + (15176898732449889943, 1864585182800051685), + (11791404716994875166, 1165365739250032303), + (10127569877816206054, 1456707174062540379), + (8047776328842869663, 1820883967578175474), + (836348374198811271, 2276104959472719343), + (7440246761515338900, 1422565599670449589), + (13911994470321561530, 1778206999588061986), + (8166621051047176104, 2222758749485077483), + (2798295147690791113, 1389224218428173427), + (17332926989895652603, 1736530273035216783), + (17054472718942177850, 2170662841294020979), + (8353202440125167204, 1356664275808763112), + (10441503050156459005, 1695830344760953890), + (3828506775840797949, 2119787930951192363), + (86973725686804766, 1324867456844495227), + (13943775212390669669, 1656084321055619033), + (3594660960206173375, 2070105401319523792), + (2246663100128858359, 1293815875824702370), + (12031700912015848757, 1617269844780877962), + (5816254103165035138, 2021587305976097453), + (5941001823691840913, 1263492066235060908), + (7426252279614801142, 1579365082793826135), + (4671129331091113523, 1974206353492282669), + (5225298841145639904, 1233878970932676668), + (6531623551432049880, 1542348713665845835), + (3552843420862674446, 1927935892082307294), + (16055585193321335241, 1204959932551442058), + (10846109454796893243, 1506199915689302573), + (18169322836923504458, 1882749894611628216), + (11355826773077190286, 1176718684132267635), + (9583097447919099954, 1470898355165334544), + (11978871809898874942, 1838622943956668180), + (14973589762373593678, 2298278679945835225), + (2440964573842414192, 1436424174966147016), + (3051205717303017741, 1795530218707683770), + (13037379183483547984, 2244412773384604712), + (8148361989677217490, 1402757983365377945), + (14797138505523909766, 1753447479206722431), + (13884737113477499304, 2191809349008403039), + (15595489723564518921, 1369880843130251899), + (14882676136028260747, 1712351053912814874), + (9379973133180550126, 2140438817391018593), + (17391698254306313589, 1337774260869386620), + (3292878744173340370, 1672217826086733276), + (4116098430216675462, 2090272282608416595), + (266718509671728212, 1306420176630260372), + (333398137089660265, 1633025220787825465), + (5028433689789463235, 2041281525984781831), + (10060300083759496378, 1275800953740488644), + (12575375104699370472, 1594751192175610805), + (1884160825592049379, 1993438990219513507), + (17318501580490888525, 1245899368887195941), + (7813068920331446945, 1557374211108994927), + (5154650131986920777, 1946717763886243659), + (915813323278131534, 1216698602428902287), + (14979824709379828129, 1520873253036127858), + (9501408849870009354, 1901091566295159823), + (12855909558809837702, 1188182228934474889), + (2234828893230133415, 1485227786168093612), + (2793536116537666769, 1856534732710117015), + (8663489100477123587, 1160334207943823134), + (1605989338741628675, 1450417759929778918), + (11230858710281811652, 1813022199912223647), + (9426887369424876662, 2266277749890279559), + (12809333633531629769, 1416423593681424724), + (16011667041914537212, 1770529492101780905), + (6179525747111007803, 2213161865127226132), + (13085575628799155685, 1383226165704516332), + (16356969535998944606, 1729032707130645415), + (15834525901571292854, 2161290883913306769), + (2979049660840976177, 1350806802445816731), + (17558870131333383934, 1688508503057270913), + (8113529608884566205, 2110635628821588642), + (9682642023980241782, 1319147268013492901), + (16714988548402690132, 1648934085016866126), + (11670363648648586857, 2061167606271082658), + (11905663298832754689, 1288229753919426661), + (1047021068258779650, 1610287192399283327), + (15143834390605638274, 2012858990499104158), + (4853210475701136017, 1258036869061940099), + (1454827076199032118, 1572546086327425124), + (1818533845248790147, 1965682607909281405), + (3442426662494187794, 1228551629943300878), + (13526405364972510550, 1535689537429126097), + (3072948650933474476, 1919611921786407622), + (15755650962115585259, 1199757451116504763), + (15082877684217093670, 1499696813895630954), + (9630225068416591280, 1874621017369538693), + (8324733676974063502, 1171638135855961683), + (5794231077790191473, 1464547669819952104), + (7242788847237739342, 1830684587274940130), + (18276858095901949986, 2288355734093675162), + (16034722328366106645, 1430222333808546976), + (1596658836748081690, 1787777917260683721), + (6607509564362490017, 2234722396575854651), + (1823850468512862308, 1396701497859909157), + (6891499104068465790, 1745876872324886446), + (17837745916940358045, 2182346090406108057), + (4231062170446641922, 1363966306503817536), + (5288827713058302403, 1704957883129771920), + (6611034641322878003, 2131197353912214900), + (13355268687681574560, 1331998346195134312), + (16694085859601968200, 1664997932743917890), + (11644235287647684442, 2081247415929897363), + (4971804045566108824, 1300779634956185852), + (6214755056957636030, 1625974543695232315), + (3156757802769657134, 2032468179619040394), + (6584659645158423613, 1270292612261900246), + (17454196593302805324, 1587865765327375307), + (17206059723201118751, 1984832206659219134), + (6142101308573311315, 1240520129162011959), + (3065940617289251240, 1550650161452514949), + (8444111790038951954, 1938312701815643686), + (665883850346957067, 1211445438634777304), + (832354812933696334, 1514306798293471630), + (10263815553021896226, 1892883497866839537), + (17944099766707154901, 1183052186166774710), + (13206752671529167818, 1478815232708468388), + (16508440839411459773, 1848519040885585485), + (12623618533845856310, 1155324400553490928), + (15779523167307320387, 1444155500691863660), + (1277659885424598868, 1805194375864829576), + (1597074856780748586, 2256492969831036970), + (5609857803915355770, 1410308106144398106), + (16235694291748970521, 1762885132680497632), + (1847873790976661535, 2203606415850622041), + (12684136165428883219, 1377254009906638775), + (11243484188358716120, 1721567512383298469), + (219297180166231438, 2151959390479123087), + (7054589765244976505, 1344974619049451929), + (13429923224983608535, 1681218273811814911), + (12175718012802122765, 2101522842264768639), + (14527352785642408584, 1313451776415480399), + (13547504963625622826, 1641814720519350499), + (12322695186104640628, 2052268400649188124), + (16925056528170176201, 1282667750405742577), + (7321262604930556539, 1603334688007178222), + (18374950293017971482, 2004168360008972777), + (4566814905495150320, 1252605225005607986), + (14931890668723713708, 1565756531257009982), + (9441491299049866327, 1957195664071262478), + (1289246043478778550, 1223247290044539049), + (6223243572775861092, 1529059112555673811), + (3167368447542438461, 1911323890694592264), + (1979605279714024038, 1194577431684120165), + (7086192618069917952, 1493221789605150206), + (18081112809442173248, 1866527237006437757), + (13606538515115052232, 1166579523129023598), + (7784801107039039482, 1458224403911279498), + (507629346944023544, 1822780504889099373), + (5246222702107417334, 2278475631111374216), + (3278889188817135834, 1424047269444608885), + (8710297504448807696, 1780059086805761106), +]; diff --git a/bitbox02-bt/vendor/ryu/src/d2s_intrinsics.rs b/bitbox02-bt/vendor/ryu/src/d2s_intrinsics.rs new file mode 100644 index 0000000..a4e1fb1 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/d2s_intrinsics.rs @@ -0,0 +1,89 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +use core::ptr; + +#[cfg_attr(feature = "no-panic", inline)] +pub fn div5(x: u64) -> u64 { + x / 5 +} + +#[cfg_attr(feature = "no-panic", inline)] +pub fn div10(x: u64) -> u64 { + x / 10 +} + +#[cfg_attr(feature = "no-panic", inline)] +pub fn div100(x: u64) -> u64 { + x / 100 +} + +#[cfg_attr(feature = "no-panic", inline)] +pub(crate) fn pow5_factor(mut value: u64) -> u32 { + const M_INV_5: u64 = 14757395258967641293; // 5 * m_inv_5 = 1 (mod 2^64) + const N_DIV_5: u64 = 3689348814741910323; // #{ n | n = 0 (mod 2^64) } = 2^64 / 5 + let mut count = 0u32; + loop { + debug_assert!(value != 0); + value = value.wrapping_mul(M_INV_5); + if value > N_DIV_5 { + break; + } + count += 1; + } + count +} + +// Returns true if value is divisible by 5^p. +#[cfg_attr(feature = "no-panic", inline)] +pub fn multiple_of_power_of_5(value: u64, p: u32) -> bool { + // I tried a case distinction on p, but there was no performance difference. + pow5_factor(value) >= p +} + +// Returns true if value is divisible by 2^p. +#[cfg_attr(feature = "no-panic", inline)] +pub fn multiple_of_power_of_2(value: u64, p: u32) -> bool { + debug_assert!(value != 0); + debug_assert!(p < 64); + // __builtin_ctzll doesn't appear to be faster here. + (value & ((1u64 << p) - 1)) == 0 +} + +#[cfg_attr(feature = "no-panic", inline)] +pub fn mul_shift_64(m: u64, mul: &(u64, u64), j: u32) -> u64 { + let b0 = m as u128 * mul.0 as u128; + let b2 = m as u128 * mul.1 as u128; + (((b0 >> 64) + b2) >> (j - 64)) as u64 +} + +#[cfg_attr(feature = "no-panic", inline)] +pub unsafe fn mul_shift_all_64( + m: u64, + mul: &(u64, u64), + j: u32, + vp: *mut u64, + vm: *mut u64, + mm_shift: u32, +) -> u64 { + ptr::write(vp, mul_shift_64(4 * m + 2, mul, j)); + ptr::write(vm, mul_shift_64(4 * m - 1 - mm_shift as u64, mul, j)); + mul_shift_64(4 * m, mul, j) +} diff --git a/bitbox02-bt/vendor/ryu/src/d2s_small_table.rs b/bitbox02-bt/vendor/ryu/src/d2s_small_table.rs new file mode 100644 index 0000000..b6e3223 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/d2s_small_table.rs @@ -0,0 +1,142 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +use crate::common::pow5bits; + +pub static DOUBLE_POW5_INV_SPLIT2: [(u64, u64); 15] = [ + (1, 2305843009213693952), + (5955668970331000884, 1784059615882449851), + (8982663654677661702, 1380349269358112757), + (7286864317269821294, 2135987035920910082), + (7005857020398200553, 1652639921975621497), + (17965325103354776697, 1278668206209430417), + (8928596168509315048, 1978643211784836272), + (10075671573058298858, 1530901034580419511), + (597001226353042382, 1184477304306571148), + (1527430471115325346, 1832889850782397517), + (12533209867169019542, 1418129833677084982), + (5577825024675947042, 2194449627517475473), + (11006974540203867551, 1697873161311732311), + (10313493231639821582, 1313665730009899186), + (12701016819766672773, 2032799256770390445), +]; + +pub static POW5_INV_OFFSETS: [u32; 19] = [ + 0x54544554, 0x04055545, 0x10041000, 0x00400414, 0x40010000, 0x41155555, 0x00000454, 0x00010044, + 0x40000000, 0x44000041, 0x50454450, 0x55550054, 0x51655554, 0x40004000, 0x01000001, 0x00010500, + 0x51515411, 0x05555554, 0x00000000, +]; + +pub static DOUBLE_POW5_SPLIT2: [(u64, u64); 13] = [ + (0, 1152921504606846976), + (0, 1490116119384765625), + (1032610780636961552, 1925929944387235853), + (7910200175544436838, 1244603055572228341), + (16941905809032713930, 1608611746708759036), + (13024893955298202172, 2079081953128979843), + (6607496772837067824, 1343575221513417750), + (17332926989895652603, 1736530273035216783), + (13037379183483547984, 2244412773384604712), + (1605989338741628675, 1450417759929778918), + (9630225068416591280, 1874621017369538693), + (665883850346957067, 1211445438634777304), + (14931890668723713708, 1565756531257009982), +]; + +pub static POW5_OFFSETS: [u32; 21] = [ + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x40000000, 0x59695995, 0x55545555, 0x56555515, + 0x41150504, 0x40555410, 0x44555145, 0x44504540, 0x45555550, 0x40004000, 0x96440440, 0x55565565, + 0x54454045, 0x40154151, 0x55559155, 0x51405555, 0x00000105, +]; + +pub static DOUBLE_POW5_TABLE: [u64; 26] = [ + 1, + 5, + 25, + 125, + 625, + 3125, + 15625, + 78125, + 390625, + 1953125, + 9765625, + 48828125, + 244140625, + 1220703125, + 6103515625, + 30517578125, + 152587890625, + 762939453125, + 3814697265625, + 19073486328125, + 95367431640625, + 476837158203125, + 2384185791015625, + 11920928955078125, + 59604644775390625, + 298023223876953125, +]; + +// Computes 5^i in the form required by Ryū. +#[cfg_attr(feature = "no-panic", inline)] +pub unsafe fn compute_pow5(i: u32) -> (u64, u64) { + let base = i / DOUBLE_POW5_TABLE.len() as u32; + let base2 = base * DOUBLE_POW5_TABLE.len() as u32; + let offset = i - base2; + debug_assert!(base < DOUBLE_POW5_SPLIT2.len() as u32); + let mul = *DOUBLE_POW5_SPLIT2.get_unchecked(base as usize); + if offset == 0 { + return mul; + } + debug_assert!(offset < DOUBLE_POW5_TABLE.len() as u32); + let m = *DOUBLE_POW5_TABLE.get_unchecked(offset as usize); + let b0 = m as u128 * mul.0 as u128; + let b2 = m as u128 * mul.1 as u128; + let delta = pow5bits(i as i32) - pow5bits(base2 as i32); + debug_assert!(i / 16 < POW5_OFFSETS.len() as u32); + let shifted_sum = (b0 >> delta) + + (b2 << (64 - delta)) + + ((*POW5_OFFSETS.get_unchecked((i / 16) as usize) >> ((i % 16) << 1)) & 3) as u128; + (shifted_sum as u64, (shifted_sum >> 64) as u64) +} + +// Computes 5^-i in the form required by Ryū. +#[cfg_attr(feature = "no-panic", inline)] +pub unsafe fn compute_inv_pow5(i: u32) -> (u64, u64) { + let base = (i + DOUBLE_POW5_TABLE.len() as u32 - 1) / DOUBLE_POW5_TABLE.len() as u32; + let base2 = base * DOUBLE_POW5_TABLE.len() as u32; + let offset = base2 - i; + debug_assert!(base < DOUBLE_POW5_INV_SPLIT2.len() as u32); + let mul = *DOUBLE_POW5_INV_SPLIT2.get_unchecked(base as usize); // 1/5^base2 + if offset == 0 { + return mul; + } + debug_assert!(offset < DOUBLE_POW5_TABLE.len() as u32); + let m = *DOUBLE_POW5_TABLE.get_unchecked(offset as usize); // 5^offset + let b0 = m as u128 * (mul.0 - 1) as u128; + let b2 = m as u128 * mul.1 as u128; // 1/5^base2 * 5^offset = 1/5^(base2-offset) = 1/5^i + let delta = pow5bits(base2 as i32) - pow5bits(i as i32); + debug_assert!(base < POW5_INV_OFFSETS.len() as u32); + let shifted_sum = ((b0 >> delta) + (b2 << (64 - delta))) + + 1 + + ((*POW5_INV_OFFSETS.get_unchecked((i / 16) as usize) >> ((i % 16) << 1)) & 3) as u128; + (shifted_sum as u64, (shifted_sum >> 64) as u64) +} diff --git a/bitbox02-bt/vendor/ryu/src/digit_table.rs b/bitbox02-bt/vendor/ryu/src/digit_table.rs new file mode 100644 index 0000000..d871f03 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/digit_table.rs @@ -0,0 +1,28 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +// A table of all two-digit numbers. This is used to speed up decimal digit +// generation by copying pairs of digits into the final output. +pub static DIGIT_TABLE: [u8; 200] = *b"\ + 0001020304050607080910111213141516171819\ + 2021222324252627282930313233343536373839\ + 4041424344454647484950515253545556575859\ + 6061626364656667686970717273747576777879\ + 8081828384858687888990919293949596979899"; diff --git a/bitbox02-bt/vendor/ryu/src/f2s.rs b/bitbox02-bt/vendor/ryu/src/f2s.rs new file mode 100644 index 0000000..987fefb --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/f2s.rs @@ -0,0 +1,178 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +use crate::common::{log10_pow2, log10_pow5, pow5bits}; +use crate::f2s_intrinsics::{ + mul_pow5_div_pow2, mul_pow5_inv_div_pow2, multiple_of_power_of_2_32, multiple_of_power_of_5_32, +}; + +pub const FLOAT_MANTISSA_BITS: u32 = 23; +pub const FLOAT_EXPONENT_BITS: u32 = 8; +const FLOAT_BIAS: i32 = 127; +pub use crate::f2s_intrinsics::{FLOAT_POW5_BITCOUNT, FLOAT_POW5_INV_BITCOUNT}; + +// A floating decimal representing m * 10^e. +pub struct FloatingDecimal32 { + pub mantissa: u32, + // Decimal exponent's range is -45 to 38 + // inclusive, and can fit in i16 if needed. + pub exponent: i32, +} + +#[cfg_attr(feature = "no-panic", inline)] +pub fn f2d(ieee_mantissa: u32, ieee_exponent: u32) -> FloatingDecimal32 { + let (e2, m2) = if ieee_exponent == 0 { + ( + // We subtract 2 so that the bounds computation has 2 additional bits. + 1 - FLOAT_BIAS - FLOAT_MANTISSA_BITS as i32 - 2, + ieee_mantissa, + ) + } else { + ( + ieee_exponent as i32 - FLOAT_BIAS - FLOAT_MANTISSA_BITS as i32 - 2, + (1u32 << FLOAT_MANTISSA_BITS) | ieee_mantissa, + ) + }; + let even = (m2 & 1) == 0; + let accept_bounds = even; + + // Step 2: Determine the interval of valid decimal representations. + let mv = 4 * m2; + let mp = 4 * m2 + 2; + // Implicit bool -> int conversion. True is 1, false is 0. + let mm_shift = (ieee_mantissa != 0 || ieee_exponent <= 1) as u32; + let mm = 4 * m2 - 1 - mm_shift; + + // Step 3: Convert to a decimal power base using 64-bit arithmetic. + let mut vr: u32; + let mut vp: u32; + let mut vm: u32; + let e10: i32; + let mut vm_is_trailing_zeros = false; + let mut vr_is_trailing_zeros = false; + let mut last_removed_digit = 0u8; + if e2 >= 0 { + let q = log10_pow2(e2); + e10 = q as i32; + let k = FLOAT_POW5_INV_BITCOUNT + pow5bits(q as i32) - 1; + let i = -e2 + q as i32 + k; + vr = mul_pow5_inv_div_pow2(mv, q, i); + vp = mul_pow5_inv_div_pow2(mp, q, i); + vm = mul_pow5_inv_div_pow2(mm, q, i); + if q != 0 && (vp - 1) / 10 <= vm / 10 { + // We need to know one removed digit even if we are not going to loop below. We could use + // q = X - 1 above, except that would require 33 bits for the result, and we've found that + // 32-bit arithmetic is faster even on 64-bit machines. + let l = FLOAT_POW5_INV_BITCOUNT + pow5bits(q as i32 - 1) - 1; + last_removed_digit = + (mul_pow5_inv_div_pow2(mv, q - 1, -e2 + q as i32 - 1 + l) % 10) as u8; + } + if q <= 9 { + // The largest power of 5 that fits in 24 bits is 5^10, but q <= 9 seems to be safe as well. + // Only one of mp, mv, and mm can be a multiple of 5, if any. + if mv % 5 == 0 { + vr_is_trailing_zeros = multiple_of_power_of_5_32(mv, q); + } else if accept_bounds { + vm_is_trailing_zeros = multiple_of_power_of_5_32(mm, q); + } else { + vp -= multiple_of_power_of_5_32(mp, q) as u32; + } + } + } else { + let q = log10_pow5(-e2); + e10 = q as i32 + e2; + let i = -e2 - q as i32; + let k = pow5bits(i) - FLOAT_POW5_BITCOUNT; + let mut j = q as i32 - k; + vr = mul_pow5_div_pow2(mv, i as u32, j); + vp = mul_pow5_div_pow2(mp, i as u32, j); + vm = mul_pow5_div_pow2(mm, i as u32, j); + if q != 0 && (vp - 1) / 10 <= vm / 10 { + j = q as i32 - 1 - (pow5bits(i + 1) - FLOAT_POW5_BITCOUNT); + last_removed_digit = (mul_pow5_div_pow2(mv, (i + 1) as u32, j) % 10) as u8; + } + if q <= 1 { + // {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at least q trailing 0 bits. + // mv = 4 * m2, so it always has at least two trailing 0 bits. + vr_is_trailing_zeros = true; + if accept_bounds { + // mm = mv - 1 - mm_shift, so it has 1 trailing 0 bit iff mm_shift == 1. + vm_is_trailing_zeros = mm_shift == 1; + } else { + // mp = mv + 2, so it always has at least one trailing 0 bit. + vp -= 1; + } + } else if q < 31 { + // TODO(ulfjack): Use a tighter bound here. + vr_is_trailing_zeros = multiple_of_power_of_2_32(mv, q - 1); + } + } + + // Step 4: Find the shortest decimal representation in the interval of valid representations. + let mut removed = 0i32; + let output = if vm_is_trailing_zeros || vr_is_trailing_zeros { + // General case, which happens rarely (~4.0%). + while vp / 10 > vm / 10 { + vm_is_trailing_zeros &= vm - (vm / 10) * 10 == 0; + vr_is_trailing_zeros &= last_removed_digit == 0; + last_removed_digit = (vr % 10) as u8; + vr /= 10; + vp /= 10; + vm /= 10; + removed += 1; + } + if vm_is_trailing_zeros { + while vm % 10 == 0 { + vr_is_trailing_zeros &= last_removed_digit == 0; + last_removed_digit = (vr % 10) as u8; + vr /= 10; + vp /= 10; + vm /= 10; + removed += 1; + } + } + if vr_is_trailing_zeros && last_removed_digit == 5 && vr % 2 == 0 { + // Round even if the exact number is .....50..0. + last_removed_digit = 4; + } + // We need to take vr + 1 if vr is outside bounds or we need to round up. + vr + ((vr == vm && (!accept_bounds || !vm_is_trailing_zeros)) || last_removed_digit >= 5) + as u32 + } else { + // Specialized for the common case (~96.0%). Percentages below are relative to this. + // Loop iterations below (approximately): + // 0: 13.6%, 1: 70.7%, 2: 14.1%, 3: 1.39%, 4: 0.14%, 5+: 0.01% + while vp / 10 > vm / 10 { + last_removed_digit = (vr % 10) as u8; + vr /= 10; + vp /= 10; + vm /= 10; + removed += 1; + } + // We need to take vr + 1 if vr is outside bounds or we need to round up. + vr + (vr == vm || last_removed_digit >= 5) as u32 + }; + let exp = e10 + removed; + + FloatingDecimal32 { + exponent: exp, + mantissa: output, + } +} diff --git a/bitbox02-bt/vendor/ryu/src/f2s_intrinsics.rs b/bitbox02-bt/vendor/ryu/src/f2s_intrinsics.rs new file mode 100644 index 0000000..1a35218 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/f2s_intrinsics.rs @@ -0,0 +1,113 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +use crate::d2s; + +pub const FLOAT_POW5_INV_BITCOUNT: i32 = d2s::DOUBLE_POW5_INV_BITCOUNT - 64; +pub const FLOAT_POW5_BITCOUNT: i32 = d2s::DOUBLE_POW5_BITCOUNT - 64; + +#[cfg_attr(feature = "no-panic", inline)] +fn pow5factor_32(mut value: u32) -> u32 { + let mut count = 0u32; + loop { + debug_assert!(value != 0); + let q = value / 5; + let r = value % 5; + if r != 0 { + break; + } + value = q; + count += 1; + } + count +} + +// Returns true if value is divisible by 5^p. +#[cfg_attr(feature = "no-panic", inline)] +pub fn multiple_of_power_of_5_32(value: u32, p: u32) -> bool { + pow5factor_32(value) >= p +} + +// Returns true if value is divisible by 2^p. +#[cfg_attr(feature = "no-panic", inline)] +pub fn multiple_of_power_of_2_32(value: u32, p: u32) -> bool { + // __builtin_ctz doesn't appear to be faster here. + (value & ((1u32 << p) - 1)) == 0 +} + +// It seems to be slightly faster to avoid uint128_t here, although the +// generated code for uint128_t looks slightly nicer. +#[cfg_attr(feature = "no-panic", inline)] +fn mul_shift_32(m: u32, factor: u64, shift: i32) -> u32 { + debug_assert!(shift > 32); + + // The casts here help MSVC to avoid calls to the __allmul library + // function. + let factor_lo = factor as u32; + let factor_hi = (factor >> 32) as u32; + let bits0 = m as u64 * factor_lo as u64; + let bits1 = m as u64 * factor_hi as u64; + + let sum = (bits0 >> 32) + bits1; + let shifted_sum = sum >> (shift - 32); + debug_assert!(shifted_sum <= u32::max_value() as u64); + shifted_sum as u32 +} + +#[cfg_attr(feature = "no-panic", inline)] +pub fn mul_pow5_inv_div_pow2(m: u32, q: u32, j: i32) -> u32 { + #[cfg(feature = "small")] + { + // The inverse multipliers are defined as [2^x / 5^y] + 1; the upper 64 + // bits from the double lookup table are the correct bits for [2^x / + // 5^y], so we have to add 1 here. Note that we rely on the fact that + // the added 1 that's already stored in the table never overflows into + // the upper 64 bits. + let pow5 = unsafe { d2s::compute_inv_pow5(q) }; + mul_shift_32(m, pow5.1 + 1, j) + } + + #[cfg(not(feature = "small"))] + { + debug_assert!(q < d2s::DOUBLE_POW5_INV_SPLIT.len() as u32); + unsafe { + mul_shift_32( + m, + d2s::DOUBLE_POW5_INV_SPLIT.get_unchecked(q as usize).1 + 1, + j, + ) + } + } +} + +#[cfg_attr(feature = "no-panic", inline)] +pub fn mul_pow5_div_pow2(m: u32, i: u32, j: i32) -> u32 { + #[cfg(feature = "small")] + { + let pow5 = unsafe { d2s::compute_pow5(i) }; + mul_shift_32(m, pow5.1, j) + } + + #[cfg(not(feature = "small"))] + { + debug_assert!(i < d2s::DOUBLE_POW5_SPLIT.len() as u32); + unsafe { mul_shift_32(m, d2s::DOUBLE_POW5_SPLIT.get_unchecked(i as usize).1, j) } + } +} diff --git a/bitbox02-bt/vendor/ryu/src/lib.rs b/bitbox02-bt/vendor/ryu/src/lib.rs new file mode 100644 index 0000000..7b8b450 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/lib.rs @@ -0,0 +1,125 @@ +//! [![github]](https://github.com/dtolnay/ryu) [![crates-io]](https://crates.io/crates/ryu) [![docs-rs]](https://docs.rs/ryu) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs +//! +//!
+//! +//! Pure Rust implementation of Ryū, an algorithm to quickly convert floating +//! point numbers to decimal strings. +//! +//! The PLDI'18 paper [*Ryū: fast float-to-string conversion*][paper] by Ulf +//! Adams includes a complete correctness proof of the algorithm. The paper is +//! available under the creative commons CC-BY-SA license. +//! +//! This Rust implementation is a line-by-line port of Ulf Adams' implementation +//! in C, [https://github.com/ulfjack/ryu][upstream]. +//! +//! [paper]: https://dl.acm.org/citation.cfm?id=3192369 +//! [upstream]: https://github.com/ulfjack/ryu +//! +//! # Example +//! +//! ``` +//! fn main() { +//! let mut buffer = ryu::Buffer::new(); +//! let printed = buffer.format(1.234); +//! assert_eq!(printed, "1.234"); +//! } +//! ``` +//! +//! ## Performance (lower is better) +//! +//! ![performance](https://raw.githubusercontent.com/dtolnay/ryu/master/performance.png) +//! +//! You can run upstream's benchmarks with: +//! +//! ```console +//! $ git clone https://github.com/ulfjack/ryu c-ryu +//! $ cd c-ryu +//! $ bazel run -c opt //ryu/benchmark +//! ``` +//! +//! And the same benchmark against our implementation with: +//! +//! ```console +//! $ git clone https://github.com/dtolnay/ryu rust-ryu +//! $ cd rust-ryu +//! $ cargo run --example upstream_benchmark --release +//! ``` +//! +//! These benchmarks measure the average time to print a 32-bit float and average +//! time to print a 64-bit float, where the inputs are distributed as uniform random +//! bit patterns 32 and 64 bits wide. +//! +//! The upstream C code, the unsafe direct Rust port, and the safe pretty Rust API +//! all perform the same, taking around 21 nanoseconds to format a 32-bit float and +//! 31 nanoseconds to format a 64-bit float. +//! +//! There is also a Rust-specific benchmark comparing this implementation to the +//! standard library which you can run with: +//! +//! ```console +//! $ cargo bench +//! ``` +//! +//! The benchmark shows Ryū approximately 2-5x faster than the standard library +//! across a range of f32 and f64 inputs. Measurements are in nanoseconds per +//! iteration; smaller is better. +//! +//! ## Formatting +//! +//! This library tends to produce more human-readable output than the standard +//! library's to\_string, which never uses scientific notation. Here are two +//! examples: +//! +//! - *ryu:* 1.23e40, *std:* 12300000000000000000000000000000000000000 +//! - *ryu:* 1.23e-40, *std:* 0.000000000000000000000000000000000000000123 +//! +//! Both libraries print short decimals such as 0.0000123 without scientific +//! notation. + +#![no_std] +#![doc(html_root_url = "https://docs.rs/ryu/1.0.18")] +#![cfg_attr(not(check_cfg), allow(unexpected_cfgs))] +#![allow( + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::checked_conversions, + clippy::doc_markdown, + clippy::expl_impl_clone_on_copy, + clippy::if_not_else, + clippy::many_single_char_names, + clippy::missing_panics_doc, + clippy::module_name_repetitions, + clippy::must_use_candidate, + clippy::needless_doctest_main, + clippy::similar_names, + clippy::too_many_lines, + clippy::unreadable_literal, + clippy::unseparated_literal_suffix, + clippy::wildcard_imports +)] + +mod buffer; +mod common; +mod d2s; +#[cfg(not(feature = "small"))] +mod d2s_full_table; +mod d2s_intrinsics; +#[cfg(feature = "small")] +mod d2s_small_table; +mod digit_table; +mod f2s; +mod f2s_intrinsics; +mod pretty; + +pub use crate::buffer::{Buffer, Float}; + +/// Unsafe functions that mirror the API of the C implementation of Ryū. +pub mod raw { + pub use crate::pretty::{format32, format64}; +} diff --git a/bitbox02-bt/vendor/ryu/src/parse.rs b/bitbox02-bt/vendor/ryu/src/parse.rs new file mode 100644 index 0000000..00f7983 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/parse.rs @@ -0,0 +1,19 @@ +use core::fmt::{self, Display}; + +#[derive(Copy, Clone, Debug)] +pub enum Error { + InputTooShort, + InputTooLong, + MalformedInput, +} + +impl Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let msg = match self { + Error::InputTooShort => "input too short", + Error::InputTooLong => "input too long", + Error::MalformedInput => "malformed input", + }; + formatter.write_str(msg) + } +} diff --git a/bitbox02-bt/vendor/ryu/src/pretty/exponent.rs b/bitbox02-bt/vendor/ryu/src/pretty/exponent.rs new file mode 100644 index 0000000..529d92b --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/pretty/exponent.rs @@ -0,0 +1,48 @@ +use crate::digit_table::DIGIT_TABLE; +use core::ptr; + +#[cfg_attr(feature = "no-panic", inline)] +pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize { + let sign = k < 0; + if sign { + *result = b'-'; + result = result.offset(1); + k = -k; + } + + debug_assert!(k < 1000); + if k >= 100 { + *result = b'0' + (k / 100) as u8; + k %= 100; + let d = DIGIT_TABLE.as_ptr().offset(k * 2); + ptr::copy_nonoverlapping(d, result.offset(1), 2); + sign as usize + 3 + } else if k >= 10 { + let d = DIGIT_TABLE.as_ptr().offset(k * 2); + ptr::copy_nonoverlapping(d, result, 2); + sign as usize + 2 + } else { + *result = b'0' + k as u8; + sign as usize + 1 + } +} + +#[cfg_attr(feature = "no-panic", inline)] +pub unsafe fn write_exponent2(mut k: isize, mut result: *mut u8) -> usize { + let sign = k < 0; + if sign { + *result = b'-'; + result = result.offset(1); + k = -k; + } + + debug_assert!(k < 100); + if k >= 10 { + let d = DIGIT_TABLE.as_ptr().offset(k * 2); + ptr::copy_nonoverlapping(d, result, 2); + sign as usize + 2 + } else { + *result = b'0' + k as u8; + sign as usize + 1 + } +} diff --git a/bitbox02-bt/vendor/ryu/src/pretty/mantissa.rs b/bitbox02-bt/vendor/ryu/src/pretty/mantissa.rs new file mode 100644 index 0000000..552dfe3 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/pretty/mantissa.rs @@ -0,0 +1,82 @@ +use crate::digit_table::DIGIT_TABLE; +use core::ptr; + +#[cfg_attr(feature = "no-panic", inline)] +pub unsafe fn write_mantissa_long(mut output: u64, mut result: *mut u8) { + if (output >> 32) != 0 { + // One expensive 64-bit division. + let mut output2 = (output - 100_000_000 * (output / 100_000_000)) as u32; + output /= 100_000_000; + + let c = output2 % 10_000; + output2 /= 10_000; + let d = output2 % 10_000; + let c0 = (c % 100) << 1; + let c1 = (c / 100) << 1; + let d0 = (d % 100) << 1; + let d1 = (d / 100) << 1; + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(c0 as isize), + result.offset(-2), + 2, + ); + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(c1 as isize), + result.offset(-4), + 2, + ); + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(d0 as isize), + result.offset(-6), + 2, + ); + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(d1 as isize), + result.offset(-8), + 2, + ); + result = result.offset(-8); + } + write_mantissa(output as u32, result); +} + +#[cfg_attr(feature = "no-panic", inline)] +pub unsafe fn write_mantissa(mut output: u32, mut result: *mut u8) { + while output >= 10_000 { + let c = output - 10_000 * (output / 10_000); + output /= 10_000; + let c0 = (c % 100) << 1; + let c1 = (c / 100) << 1; + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(c0 as isize), + result.offset(-2), + 2, + ); + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(c1 as isize), + result.offset(-4), + 2, + ); + result = result.offset(-4); + } + if output >= 100 { + let c = (output % 100) << 1; + output /= 100; + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(c as isize), + result.offset(-2), + 2, + ); + result = result.offset(-2); + } + if output >= 10 { + let c = output << 1; + ptr::copy_nonoverlapping( + DIGIT_TABLE.as_ptr().offset(c as isize), + result.offset(-2), + 2, + ); + } else { + *result.offset(-1) = b'0' + output as u8; + } +} diff --git a/bitbox02-bt/vendor/ryu/src/pretty/mod.rs b/bitbox02-bt/vendor/ryu/src/pretty/mod.rs new file mode 100644 index 0000000..f901c5f --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/pretty/mod.rs @@ -0,0 +1,224 @@ +mod exponent; +mod mantissa; + +use self::exponent::{write_exponent2, write_exponent3}; +use self::mantissa::{write_mantissa, write_mantissa_long}; +use crate::common; +use crate::d2s::{self, d2d, DOUBLE_EXPONENT_BITS, DOUBLE_MANTISSA_BITS}; +use crate::f2s::{f2d, FLOAT_EXPONENT_BITS, FLOAT_MANTISSA_BITS}; +use core::ptr; +#[cfg(feature = "no-panic")] +use no_panic::no_panic; + +/// Print f64 to the given buffer and return number of bytes written. +/// +/// At most 24 bytes will be written. +/// +/// ## Special cases +/// +/// This function **does not** check for NaN or infinity. If the input +/// number is not a finite float, the printed representation will be some +/// correctly formatted but unspecified numerical value. +/// +/// Please check [`is_finite`] yourself before calling this function, or +/// check [`is_nan`] and [`is_infinite`] and handle those cases yourself. +/// +/// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite +/// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan +/// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite +/// +/// ## Safety +/// +/// The `result` pointer argument must point to sufficiently many writable bytes +/// to hold Ryū's representation of `f`. +/// +/// ## Example +/// +/// ``` +/// use std::{mem::MaybeUninit, slice, str}; +/// +/// let f = 1.234f64; +/// +/// unsafe { +/// let mut buffer = [MaybeUninit::::uninit(); 24]; +/// let len = ryu::raw::format64(f, buffer.as_mut_ptr() as *mut u8); +/// let slice = slice::from_raw_parts(buffer.as_ptr() as *const u8, len); +/// let print = str::from_utf8_unchecked(slice); +/// assert_eq!(print, "1.234"); +/// } +/// ``` +#[must_use] +#[cfg_attr(feature = "no-panic", no_panic)] +pub unsafe fn format64(f: f64, result: *mut u8) -> usize { + let bits = f.to_bits(); + let sign = ((bits >> (DOUBLE_MANTISSA_BITS + DOUBLE_EXPONENT_BITS)) & 1) != 0; + let ieee_mantissa = bits & ((1u64 << DOUBLE_MANTISSA_BITS) - 1); + let ieee_exponent = + (bits >> DOUBLE_MANTISSA_BITS) as u32 & ((1u32 << DOUBLE_EXPONENT_BITS) - 1); + + let mut index = 0isize; + if sign { + *result = b'-'; + index += 1; + } + + if ieee_exponent == 0 && ieee_mantissa == 0 { + ptr::copy_nonoverlapping(b"0.0".as_ptr(), result.offset(index), 3); + return sign as usize + 3; + } + + let v = d2d(ieee_mantissa, ieee_exponent); + + let length = d2s::decimal_length17(v.mantissa) as isize; + let k = v.exponent as isize; + let kk = length + k; // 10^(kk-1) <= v < 10^kk + debug_assert!(k >= -324); + + if 0 <= k && kk <= 16 { + // 1234e7 -> 12340000000.0 + write_mantissa_long(v.mantissa, result.offset(index + length)); + for i in length..kk { + *result.offset(index + i) = b'0'; + } + *result.offset(index + kk) = b'.'; + *result.offset(index + kk + 1) = b'0'; + index as usize + kk as usize + 2 + } else if 0 < kk && kk <= 16 { + // 1234e-2 -> 12.34 + write_mantissa_long(v.mantissa, result.offset(index + length + 1)); + ptr::copy(result.offset(index + 1), result.offset(index), kk as usize); + *result.offset(index + kk) = b'.'; + index as usize + length as usize + 1 + } else if -5 < kk && kk <= 0 { + // 1234e-6 -> 0.001234 + *result.offset(index) = b'0'; + *result.offset(index + 1) = b'.'; + let offset = 2 - kk; + for i in 2..offset { + *result.offset(index + i) = b'0'; + } + write_mantissa_long(v.mantissa, result.offset(index + length + offset)); + index as usize + length as usize + offset as usize + } else if length == 1 { + // 1e30 + *result.offset(index) = b'0' + v.mantissa as u8; + *result.offset(index + 1) = b'e'; + index as usize + 2 + write_exponent3(kk - 1, result.offset(index + 2)) + } else { + // 1234e30 -> 1.234e33 + write_mantissa_long(v.mantissa, result.offset(index + length + 1)); + *result.offset(index) = *result.offset(index + 1); + *result.offset(index + 1) = b'.'; + *result.offset(index + length + 1) = b'e'; + index as usize + + length as usize + + 2 + + write_exponent3(kk - 1, result.offset(index + length + 2)) + } +} + +/// Print f32 to the given buffer and return number of bytes written. +/// +/// At most 16 bytes will be written. +/// +/// ## Special cases +/// +/// This function **does not** check for NaN or infinity. If the input +/// number is not a finite float, the printed representation will be some +/// correctly formatted but unspecified numerical value. +/// +/// Please check [`is_finite`] yourself before calling this function, or +/// check [`is_nan`] and [`is_infinite`] and handle those cases yourself. +/// +/// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f32.html#method.is_finite +/// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f32.html#method.is_nan +/// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f32.html#method.is_infinite +/// +/// ## Safety +/// +/// The `result` pointer argument must point to sufficiently many writable bytes +/// to hold Ryū's representation of `f`. +/// +/// ## Example +/// +/// ``` +/// use std::{mem::MaybeUninit, slice, str}; +/// +/// let f = 1.234f32; +/// +/// unsafe { +/// let mut buffer = [MaybeUninit::::uninit(); 16]; +/// let len = ryu::raw::format32(f, buffer.as_mut_ptr() as *mut u8); +/// let slice = slice::from_raw_parts(buffer.as_ptr() as *const u8, len); +/// let print = str::from_utf8_unchecked(slice); +/// assert_eq!(print, "1.234"); +/// } +/// ``` +#[must_use] +#[cfg_attr(feature = "no-panic", no_panic)] +pub unsafe fn format32(f: f32, result: *mut u8) -> usize { + let bits = f.to_bits(); + let sign = ((bits >> (FLOAT_MANTISSA_BITS + FLOAT_EXPONENT_BITS)) & 1) != 0; + let ieee_mantissa = bits & ((1u32 << FLOAT_MANTISSA_BITS) - 1); + let ieee_exponent = (bits >> FLOAT_MANTISSA_BITS) & ((1u32 << FLOAT_EXPONENT_BITS) - 1); + + let mut index = 0isize; + if sign { + *result = b'-'; + index += 1; + } + + if ieee_exponent == 0 && ieee_mantissa == 0 { + ptr::copy_nonoverlapping(b"0.0".as_ptr(), result.offset(index), 3); + return sign as usize + 3; + } + + let v = f2d(ieee_mantissa, ieee_exponent); + + let length = common::decimal_length9(v.mantissa) as isize; + let k = v.exponent as isize; + let kk = length + k; // 10^(kk-1) <= v < 10^kk + debug_assert!(k >= -45); + + if 0 <= k && kk <= 13 { + // 1234e7 -> 12340000000.0 + write_mantissa(v.mantissa, result.offset(index + length)); + for i in length..kk { + *result.offset(index + i) = b'0'; + } + *result.offset(index + kk) = b'.'; + *result.offset(index + kk + 1) = b'0'; + index as usize + kk as usize + 2 + } else if 0 < kk && kk <= 13 { + // 1234e-2 -> 12.34 + write_mantissa(v.mantissa, result.offset(index + length + 1)); + ptr::copy(result.offset(index + 1), result.offset(index), kk as usize); + *result.offset(index + kk) = b'.'; + index as usize + length as usize + 1 + } else if -6 < kk && kk <= 0 { + // 1234e-6 -> 0.001234 + *result.offset(index) = b'0'; + *result.offset(index + 1) = b'.'; + let offset = 2 - kk; + for i in 2..offset { + *result.offset(index + i) = b'0'; + } + write_mantissa(v.mantissa, result.offset(index + length + offset)); + index as usize + length as usize + offset as usize + } else if length == 1 { + // 1e30 + *result.offset(index) = b'0' + v.mantissa as u8; + *result.offset(index + 1) = b'e'; + index as usize + 2 + write_exponent2(kk - 1, result.offset(index + 2)) + } else { + // 1234e30 -> 1.234e33 + write_mantissa(v.mantissa, result.offset(index + length + 1)); + *result.offset(index) = *result.offset(index + 1); + *result.offset(index + 1) = b'.'; + *result.offset(index + length + 1) = b'e'; + index as usize + + length as usize + + 2 + + write_exponent2(kk - 1, result.offset(index + length + 2)) + } +} diff --git a/bitbox02-bt/vendor/ryu/src/s2d.rs b/bitbox02-bt/vendor/ryu/src/s2d.rs new file mode 100644 index 0000000..c6b4fa4 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/s2d.rs @@ -0,0 +1,217 @@ +use crate::common::{ceil_log2_pow5, log2_pow5}; +use crate::d2s; +use crate::d2s_intrinsics::{mul_shift_64, multiple_of_power_of_2, multiple_of_power_of_5}; +use crate::parse::Error; +#[cfg(feature = "no-panic")] +use no_panic::no_panic; + +const DOUBLE_EXPONENT_BIAS: usize = 1023; + +fn floor_log2(value: u64) -> u32 { + 63_u32.wrapping_sub(value.leading_zeros()) +} + +#[cfg_attr(feature = "no-panic", no_panic)] +pub fn s2d(buffer: &[u8]) -> Result { + let len = buffer.len(); + if len == 0 { + return Err(Error::InputTooShort); + } + + let mut m10digits = 0; + let mut e10digits = 0; + let mut dot_index = len; + let mut e_index = len; + let mut m10 = 0u64; + let mut e10 = 0i32; + let mut signed_m = false; + let mut signed_e = false; + + let mut i = 0; + if unsafe { *buffer.get_unchecked(0) } == b'-' { + signed_m = true; + i += 1; + } + + while let Some(c) = buffer.get(i).copied() { + if c == b'.' { + if dot_index != len { + return Err(Error::MalformedInput); + } + dot_index = i; + i += 1; + continue; + } + if c < b'0' || c > b'9' { + break; + } + if m10digits >= 17 { + return Err(Error::InputTooLong); + } + m10 = 10 * m10 + (c - b'0') as u64; + if m10 != 0 { + m10digits += 1; + } + i += 1; + } + + if let Some(b'e') | Some(b'E') = buffer.get(i) { + e_index = i; + i += 1; + match buffer.get(i) { + Some(b'-') => { + signed_e = true; + i += 1; + } + Some(b'+') => i += 1, + _ => {} + } + while let Some(c) = buffer.get(i).copied() { + if c < b'0' || c > b'9' { + return Err(Error::MalformedInput); + } + if e10digits > 3 { + // TODO: Be more lenient. Return +/-Infinity or +/-0 instead. + return Err(Error::InputTooLong); + } + e10 = 10 * e10 + (c - b'0') as i32; + if e10 != 0 { + e10digits += 1; + } + i += 1; + } + } + + if i < len { + return Err(Error::MalformedInput); + } + if signed_e { + e10 = -e10; + } + e10 -= if dot_index < e_index { + (e_index - dot_index - 1) as i32 + } else { + 0 + }; + if m10 == 0 { + return Ok(if signed_m { -0.0 } else { 0.0 }); + } + + if m10digits + e10 <= -324 || m10 == 0 { + // Number is less than 1e-324, which should be rounded down to 0; return + // +/-0.0. + let ieee = (signed_m as u64) << (d2s::DOUBLE_EXPONENT_BITS + d2s::DOUBLE_MANTISSA_BITS); + return Ok(f64::from_bits(ieee)); + } + if m10digits + e10 >= 310 { + // Number is larger than 1e+309, which should be rounded to +/-Infinity. + let ieee = ((signed_m as u64) << (d2s::DOUBLE_EXPONENT_BITS + d2s::DOUBLE_MANTISSA_BITS)) + | (0x7ff_u64 << d2s::DOUBLE_MANTISSA_BITS); + return Ok(f64::from_bits(ieee)); + } + + // Convert to binary float m2 * 2^e2, while retaining information about + // whether the conversion was exact (trailing_zeros). + let e2: i32; + let m2: u64; + let mut trailing_zeros: bool; + if e10 >= 0 { + // The length of m * 10^e in bits is: + // log2(m10 * 10^e10) = log2(m10) + e10 log2(10) = log2(m10) + e10 + e10 * log2(5) + // + // We want to compute the DOUBLE_MANTISSA_BITS + 1 top-most bits (+1 for + // the implicit leading one in IEEE format). We therefore choose a + // binary output exponent of + // log2(m10 * 10^e10) - (DOUBLE_MANTISSA_BITS + 1). + // + // We use floor(log2(5^e10)) so that we get at least this many bits; + // better to have an additional bit than to not have enough bits. + e2 = floor_log2(m10) + .wrapping_add(e10 as u32) + .wrapping_add(log2_pow5(e10) as u32) + .wrapping_sub(d2s::DOUBLE_MANTISSA_BITS + 1) as i32; + + // We now compute [m10 * 10^e10 / 2^e2] = [m10 * 5^e10 / 2^(e2-e10)]. + // To that end, we use the DOUBLE_POW5_SPLIT table. + let j = e2 + .wrapping_sub(e10) + .wrapping_sub(ceil_log2_pow5(e10)) + .wrapping_add(d2s::DOUBLE_POW5_BITCOUNT); + debug_assert!(j >= 0); + debug_assert!(e10 < d2s::DOUBLE_POW5_SPLIT.len() as i32); + m2 = mul_shift_64( + m10, + unsafe { d2s::DOUBLE_POW5_SPLIT.get_unchecked(e10 as usize) }, + j as u32, + ); + + // We also compute if the result is exact, i.e., + // [m10 * 10^e10 / 2^e2] == m10 * 10^e10 / 2^e2. + // This can only be the case if 2^e2 divides m10 * 10^e10, which in turn + // requires that the largest power of 2 that divides m10 + e10 is + // greater than e2. If e2 is less than e10, then the result must be + // exact. Otherwise we use the existing multiple_of_power_of_2 function. + trailing_zeros = + e2 < e10 || e2 - e10 < 64 && multiple_of_power_of_2(m10, (e2 - e10) as u32); + } else { + e2 = floor_log2(m10) + .wrapping_add(e10 as u32) + .wrapping_sub(ceil_log2_pow5(-e10) as u32) + .wrapping_sub(d2s::DOUBLE_MANTISSA_BITS + 1) as i32; + let j = e2 + .wrapping_sub(e10) + .wrapping_add(ceil_log2_pow5(-e10)) + .wrapping_sub(1) + .wrapping_add(d2s::DOUBLE_POW5_INV_BITCOUNT); + debug_assert!(-e10 < d2s::DOUBLE_POW5_INV_SPLIT.len() as i32); + m2 = mul_shift_64( + m10, + unsafe { d2s::DOUBLE_POW5_INV_SPLIT.get_unchecked(-e10 as usize) }, + j as u32, + ); + trailing_zeros = multiple_of_power_of_5(m10, -e10 as u32); + } + + // Compute the final IEEE exponent. + let mut ieee_e2 = i32::max(0, e2 + DOUBLE_EXPONENT_BIAS as i32 + floor_log2(m2) as i32) as u32; + + if ieee_e2 > 0x7fe { + // Final IEEE exponent is larger than the maximum representable; return +/-Infinity. + let ieee = ((signed_m as u64) << (d2s::DOUBLE_EXPONENT_BITS + d2s::DOUBLE_MANTISSA_BITS)) + | (0x7ff_u64 << d2s::DOUBLE_MANTISSA_BITS); + return Ok(f64::from_bits(ieee)); + } + + // We need to figure out how much we need to shift m2. The tricky part is + // that we need to take the final IEEE exponent into account, so we need to + // reverse the bias and also special-case the value 0. + let shift = if ieee_e2 == 0 { 1 } else { ieee_e2 as i32 } + .wrapping_sub(e2) + .wrapping_sub(DOUBLE_EXPONENT_BIAS as i32) + .wrapping_sub(d2s::DOUBLE_MANTISSA_BITS as i32); + debug_assert!(shift >= 0); + + // We need to round up if the exact value is more than 0.5 above the value + // we computed. That's equivalent to checking if the last removed bit was 1 + // and either the value was not just trailing zeros or the result would + // otherwise be odd. + // + // We need to update trailing_zeros given that we have the exact output + // exponent ieee_e2 now. + trailing_zeros &= (m2 & ((1_u64 << (shift - 1)) - 1)) == 0; + let last_removed_bit = (m2 >> (shift - 1)) & 1; + let round_up = last_removed_bit != 0 && (!trailing_zeros || ((m2 >> shift) & 1) != 0); + + let mut ieee_m2 = (m2 >> shift).wrapping_add(round_up as u64); + debug_assert!(ieee_m2 <= 1_u64 << (d2s::DOUBLE_MANTISSA_BITS + 1)); + ieee_m2 &= (1_u64 << d2s::DOUBLE_MANTISSA_BITS) - 1; + if ieee_m2 == 0 && round_up { + // Due to how the IEEE represents +/-Infinity, we don't need to check + // for overflow here. + ieee_e2 += 1; + } + let ieee = ((((signed_m as u64) << d2s::DOUBLE_EXPONENT_BITS) | ieee_e2 as u64) + << d2s::DOUBLE_MANTISSA_BITS) + | ieee_m2; + Ok(f64::from_bits(ieee)) +} diff --git a/bitbox02-bt/vendor/ryu/src/s2f.rs b/bitbox02-bt/vendor/ryu/src/s2f.rs new file mode 100644 index 0000000..52a3235 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/src/s2f.rs @@ -0,0 +1,229 @@ +use crate::common::{ceil_log2_pow5, log2_pow5}; +use crate::f2s; +use crate::f2s_intrinsics::{ + mul_pow5_div_pow2, mul_pow5_inv_div_pow2, multiple_of_power_of_2_32, multiple_of_power_of_5_32, +}; +use crate::parse::Error; +#[cfg(feature = "no-panic")] +use no_panic::no_panic; + +const FLOAT_EXPONENT_BIAS: usize = 127; + +fn floor_log2(value: u32) -> u32 { + 31_u32.wrapping_sub(value.leading_zeros()) +} + +#[cfg_attr(feature = "no-panic", no_panic)] +pub fn s2f(buffer: &[u8]) -> Result { + let len = buffer.len(); + if len == 0 { + return Err(Error::InputTooShort); + } + + let mut m10digits = 0; + let mut e10digits = 0; + let mut dot_index = len; + let mut e_index = len; + let mut m10 = 0u32; + let mut e10 = 0i32; + let mut signed_m = false; + let mut signed_e = false; + + let mut i = 0; + if unsafe { *buffer.get_unchecked(0) } == b'-' { + signed_m = true; + i += 1; + } + + while let Some(c) = buffer.get(i).copied() { + if c == b'.' { + if dot_index != len { + return Err(Error::MalformedInput); + } + dot_index = i; + i += 1; + continue; + } + if c < b'0' || c > b'9' { + break; + } + if m10digits >= 9 { + return Err(Error::InputTooLong); + } + m10 = 10 * m10 + (c - b'0') as u32; + if m10 != 0 { + m10digits += 1; + } + i += 1; + } + + if let Some(b'e') | Some(b'E') = buffer.get(i) { + e_index = i; + i += 1; + match buffer.get(i) { + Some(b'-') => { + signed_e = true; + i += 1; + } + Some(b'+') => i += 1, + _ => {} + } + while let Some(c) = buffer.get(i).copied() { + if c < b'0' || c > b'9' { + return Err(Error::MalformedInput); + } + if e10digits > 3 { + // TODO: Be more lenient. Return +/-Infinity or +/-0 instead. + return Err(Error::InputTooLong); + } + e10 = 10 * e10 + (c - b'0') as i32; + if e10 != 0 { + e10digits += 1; + } + i += 1; + } + } + + if i < len { + return Err(Error::MalformedInput); + } + if signed_e { + e10 = -e10; + } + e10 -= if dot_index < e_index { + (e_index - dot_index - 1) as i32 + } else { + 0 + }; + if m10 == 0 { + return Ok(if signed_m { -0.0 } else { 0.0 }); + } + + if m10digits + e10 <= -46 || m10 == 0 { + // Number is less than 1e-46, which should be rounded down to 0; return + // +/-0.0. + let ieee = (signed_m as u32) << (f2s::FLOAT_EXPONENT_BITS + f2s::FLOAT_MANTISSA_BITS); + return Ok(f32::from_bits(ieee)); + } + if m10digits + e10 >= 40 { + // Number is larger than 1e+39, which should be rounded to +/-Infinity. + let ieee = ((signed_m as u32) << (f2s::FLOAT_EXPONENT_BITS + f2s::FLOAT_MANTISSA_BITS)) + | (0xff_u32 << f2s::FLOAT_MANTISSA_BITS); + return Ok(f32::from_bits(ieee)); + } + + // Convert to binary float m2 * 2^e2, while retaining information about + // whether the conversion was exact (trailing_zeros). + let e2: i32; + let m2: u32; + let mut trailing_zeros: bool; + if e10 >= 0 { + // The length of m * 10^e in bits is: + // log2(m10 * 10^e10) = log2(m10) + e10 log2(10) = log2(m10) + e10 + e10 * log2(5) + // + // We want to compute the FLOAT_MANTISSA_BITS + 1 top-most bits (+1 for + // the implicit leading one in IEEE format). We therefore choose a + // binary output exponent of + // log2(m10 * 10^e10) - (FLOAT_MANTISSA_BITS + 1). + // + // We use floor(log2(5^e10)) so that we get at least this many bits; better to + // have an additional bit than to not have enough bits. + e2 = floor_log2(m10) + .wrapping_add(e10 as u32) + .wrapping_add(log2_pow5(e10) as u32) + .wrapping_sub(f2s::FLOAT_MANTISSA_BITS + 1) as i32; + + // We now compute [m10 * 10^e10 / 2^e2] = [m10 * 5^e10 / 2^(e2-e10)]. + // To that end, we use the FLOAT_POW5_SPLIT table. + let j = e2 + .wrapping_sub(e10) + .wrapping_sub(ceil_log2_pow5(e10)) + .wrapping_add(f2s::FLOAT_POW5_BITCOUNT); + debug_assert!(j >= 0); + m2 = mul_pow5_div_pow2(m10, e10 as u32, j); + + // We also compute if the result is exact, i.e., + // [m10 * 10^e10 / 2^e2] == m10 * 10^e10 / 2^e2. + // This can only be the case if 2^e2 divides m10 * 10^e10, which in turn + // requires that the largest power of 2 that divides m10 + e10 is + // greater than e2. If e2 is less than e10, then the result must be + // exact. Otherwise we use the existing multiple_of_power_of_2 function. + trailing_zeros = + e2 < e10 || e2 - e10 < 32 && multiple_of_power_of_2_32(m10, (e2 - e10) as u32); + } else { + e2 = floor_log2(m10) + .wrapping_add(e10 as u32) + .wrapping_sub(ceil_log2_pow5(-e10) as u32) + .wrapping_sub(f2s::FLOAT_MANTISSA_BITS + 1) as i32; + + // We now compute [m10 * 10^e10 / 2^e2] = [m10 / (5^(-e10) 2^(e2-e10))]. + let j = e2 + .wrapping_sub(e10) + .wrapping_add(ceil_log2_pow5(-e10)) + .wrapping_sub(1) + .wrapping_add(f2s::FLOAT_POW5_INV_BITCOUNT); + m2 = mul_pow5_inv_div_pow2(m10, -e10 as u32, j); + + // We also compute if the result is exact, i.e., + // [m10 / (5^(-e10) 2^(e2-e10))] == m10 / (5^(-e10) 2^(e2-e10)) + // + // If e2-e10 >= 0, we need to check whether (5^(-e10) 2^(e2-e10)) + // divides m10, which is the case iff pow5(m10) >= -e10 AND pow2(m10) >= + // e2-e10. + // + // If e2-e10 < 0, we have actually computed [m10 * 2^(e10 e2) / + // 5^(-e10)] above, and we need to check whether 5^(-e10) divides (m10 * + // 2^(e10-e2)), which is the case iff pow5(m10 * 2^(e10-e2)) = pow5(m10) + // >= -e10. + trailing_zeros = (e2 < e10 + || (e2 - e10 < 32 && multiple_of_power_of_2_32(m10, (e2 - e10) as u32))) + && multiple_of_power_of_5_32(m10, -e10 as u32); + } + + // Compute the final IEEE exponent. + let mut ieee_e2 = i32::max(0, e2 + FLOAT_EXPONENT_BIAS as i32 + floor_log2(m2) as i32) as u32; + + if ieee_e2 > 0xfe { + // Final IEEE exponent is larger than the maximum representable; return + // +/-Infinity. + let ieee = ((signed_m as u32) << (f2s::FLOAT_EXPONENT_BITS + f2s::FLOAT_MANTISSA_BITS)) + | (0xff_u32 << f2s::FLOAT_MANTISSA_BITS); + return Ok(f32::from_bits(ieee)); + } + + // We need to figure out how much we need to shift m2. The tricky part is + // that we need to take the final IEEE exponent into account, so we need to + // reverse the bias and also special-case the value 0. + let shift = if ieee_e2 == 0 { 1 } else { ieee_e2 as i32 } + .wrapping_sub(e2) + .wrapping_sub(FLOAT_EXPONENT_BIAS as i32) + .wrapping_sub(f2s::FLOAT_MANTISSA_BITS as i32); + debug_assert!(shift >= 0); + + // We need to round up if the exact value is more than 0.5 above the value + // we computed. That's equivalent to checking if the last removed bit was 1 + // and either the value was not just trailing zeros or the result would + // otherwise be odd. + // + // We need to update trailing_zeros given that we have the exact output + // exponent ieee_e2 now. + trailing_zeros &= (m2 & ((1_u32 << (shift - 1)) - 1)) == 0; + let last_removed_bit = (m2 >> (shift - 1)) & 1; + let round_up = last_removed_bit != 0 && (!trailing_zeros || ((m2 >> shift) & 1) != 0); + + let mut ieee_m2 = (m2 >> shift).wrapping_add(round_up as u32); + debug_assert!(ieee_m2 <= 1_u32 << (f2s::FLOAT_MANTISSA_BITS + 1)); + ieee_m2 &= (1_u32 << f2s::FLOAT_MANTISSA_BITS) - 1; + if ieee_m2 == 0 && round_up { + // Rounding up may overflow the mantissa. + // In this case we move a trailing zero of the mantissa into the + // exponent. + // Due to how the IEEE represents +/-Infinity, we don't need to check + // for overflow here. + ieee_e2 += 1; + } + let ieee = ((((signed_m as u32) << f2s::FLOAT_EXPONENT_BITS) | ieee_e2) + << f2s::FLOAT_MANTISSA_BITS) + | ieee_m2; + Ok(f32::from_bits(ieee)) +} diff --git a/bitbox02-bt/vendor/ryu/tests/common_test.rs b/bitbox02-bt/vendor/ryu/tests/common_test.rs new file mode 100644 index 0000000..e2bc4e1 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/common_test.rs @@ -0,0 +1,91 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +#![allow(dead_code)] +#![allow( + clippy::approx_constant, + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::excessive_precision, + clippy::unreadable_literal, + clippy::wildcard_imports +)] + +#[path = "../src/common.rs"] +mod common; + +use common::{ceil_log2_pow5, decimal_length9, log10_pow2, log10_pow5}; + +#[test] +fn test_decimal_length9() { + assert_eq!(1, decimal_length9(0)); + assert_eq!(1, decimal_length9(1)); + assert_eq!(1, decimal_length9(9)); + assert_eq!(2, decimal_length9(10)); + assert_eq!(2, decimal_length9(99)); + assert_eq!(3, decimal_length9(100)); + assert_eq!(3, decimal_length9(999)); + assert_eq!(9, decimal_length9(999999999)); +} + +#[test] +fn test_ceil_log2_pow5() { + assert_eq!(1, ceil_log2_pow5(0)); + assert_eq!(3, ceil_log2_pow5(1)); + assert_eq!(5, ceil_log2_pow5(2)); + assert_eq!(7, ceil_log2_pow5(3)); + assert_eq!(10, ceil_log2_pow5(4)); + assert_eq!(8192, ceil_log2_pow5(3528)); +} + +#[test] +fn test_log10_pow2() { + assert_eq!(0, log10_pow2(0)); + assert_eq!(0, log10_pow2(1)); + assert_eq!(0, log10_pow2(2)); + assert_eq!(0, log10_pow2(3)); + assert_eq!(1, log10_pow2(4)); + assert_eq!(496, log10_pow2(1650)); +} + +#[test] +fn test_log10_pow5() { + assert_eq!(0, log10_pow5(0)); + assert_eq!(0, log10_pow5(1)); + assert_eq!(1, log10_pow5(2)); + assert_eq!(2, log10_pow5(3)); + assert_eq!(2, log10_pow5(4)); + assert_eq!(1831, log10_pow5(2620)); +} + +#[test] +fn test_float_to_bits() { + assert_eq!(0, 0.0_f32.to_bits()); + assert_eq!(0x40490fda, 3.1415926_f32.to_bits()); +} + +#[test] +fn test_double_to_bits() { + assert_eq!(0, 0.0_f64.to_bits()); + assert_eq!( + 0x400921FB54442D18, + 3.1415926535897932384626433_f64.to_bits(), + ); +} diff --git a/bitbox02-bt/vendor/ryu/tests/d2s_intrinsics_test.rs b/bitbox02-bt/vendor/ryu/tests/d2s_intrinsics_test.rs new file mode 100644 index 0000000..0ac80c9 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/d2s_intrinsics_test.rs @@ -0,0 +1,72 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +#![allow(dead_code)] +#![allow( + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::unreadable_literal +)] + +#[path = "../src/d2s_intrinsics.rs"] +mod d2s_intrinsics; + +use d2s_intrinsics::pow5_factor; + +#[test] +fn test_pow5_factor() { + assert_eq!(0, pow5_factor(1)); + assert_eq!(0, pow5_factor(2)); + assert_eq!(0, pow5_factor(3)); + assert_eq!(0, pow5_factor(4)); + assert_eq!(1, pow5_factor(5)); + assert_eq!(0, pow5_factor(6)); + assert_eq!(0, pow5_factor(7)); + assert_eq!(0, pow5_factor(8)); + assert_eq!(0, pow5_factor(9)); + assert_eq!(1, pow5_factor(10)); + + assert_eq!(0, pow5_factor(12)); + assert_eq!(0, pow5_factor(14)); + assert_eq!(0, pow5_factor(16)); + assert_eq!(0, pow5_factor(18)); + assert_eq!(1, pow5_factor(20)); + + assert_eq!(2, pow5_factor(5 * 5)); + assert_eq!(3, pow5_factor(5 * 5 * 5)); + assert_eq!(4, pow5_factor(5 * 5 * 5 * 5)); + assert_eq!(5, pow5_factor(5 * 5 * 5 * 5 * 5)); + assert_eq!(6, pow5_factor(5 * 5 * 5 * 5 * 5 * 5)); + assert_eq!(7, pow5_factor(5 * 5 * 5 * 5 * 5 * 5 * 5)); + assert_eq!(8, pow5_factor(5 * 5 * 5 * 5 * 5 * 5 * 5 * 5)); + assert_eq!(9, pow5_factor(5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5)); + assert_eq!(10, pow5_factor(5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5)); + + assert_eq!(0, pow5_factor(42)); + assert_eq!(1, pow5_factor(42 * 5)); + assert_eq!(2, pow5_factor(42 * 5 * 5)); + assert_eq!(3, pow5_factor(42 * 5 * 5 * 5)); + assert_eq!(4, pow5_factor(42 * 5 * 5 * 5 * 5)); + assert_eq!(5, pow5_factor(42 * 5 * 5 * 5 * 5 * 5)); + + assert_eq!(27, pow5_factor(7450580596923828125)); // 5^27, largest power of 5 < 2^64. + assert_eq!(1, pow5_factor(18446744073709551615)); // 2^64 - 1, largest multiple of 5 < 2^64. + assert_eq!(0, pow5_factor(18446744073709551614)); // 2^64 - 2, largest non-multiple of 5 < 2^64. +} diff --git a/bitbox02-bt/vendor/ryu/tests/d2s_table_test.rs b/bitbox02-bt/vendor/ryu/tests/d2s_table_test.rs new file mode 100644 index 0000000..13c4216 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/d2s_table_test.rs @@ -0,0 +1,59 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +#![allow(dead_code)] +#![allow( + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::unreadable_literal, + clippy::unseparated_literal_suffix, + clippy::wildcard_imports +)] + +#[path = "../src/common.rs"] +mod common; + +#[path = "../src/d2s_full_table.rs"] +mod d2s_full_table; + +#[path = "../src/d2s_intrinsics.rs"] +mod d2s_intrinsics; + +#[path = "../src/d2s_small_table.rs"] +mod d2s_small_table; + +use d2s_full_table::{DOUBLE_POW5_INV_SPLIT, DOUBLE_POW5_SPLIT}; +use d2s_small_table::{compute_inv_pow5, compute_pow5}; + +#[test] +fn test_compute_pow5() { + for (i, entry) in DOUBLE_POW5_SPLIT.iter().enumerate() { + assert_eq!(*entry, unsafe { compute_pow5(i as u32) }, "entry {}", i); + } +} + +#[test] +fn test_compute_inv_pow5() { + for (i, entry) in DOUBLE_POW5_INV_SPLIT[..292].iter().enumerate() { + assert_eq!(*entry, unsafe { compute_inv_pow5(i as u32) }, "entry {}", i); + } +} diff --git a/bitbox02-bt/vendor/ryu/tests/d2s_test.rs b/bitbox02-bt/vendor/ryu/tests/d2s_test.rs new file mode 100644 index 0000000..7e8eba6 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/d2s_test.rs @@ -0,0 +1,331 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +#![allow( + clippy::approx_constant, + clippy::cast_lossless, + clippy::float_cmp, + clippy::int_plus_one, + clippy::non_ascii_literal, + clippy::unreadable_literal, + clippy::unseparated_literal_suffix +)] + +#[macro_use] +mod macros; + +use std::f64; + +fn pretty(f: f64) -> String { + ryu::Buffer::new().format(f).to_owned() +} + +fn ieee_parts_to_double(sign: bool, ieee_exponent: u32, ieee_mantissa: u64) -> f64 { + assert!(ieee_exponent <= 2047); + assert!(ieee_mantissa <= (1u64 << 53) - 1); + f64::from_bits(((sign as u64) << 63) | ((ieee_exponent as u64) << 52) | ieee_mantissa) +} + +#[test] +fn test_ryu() { + check!(0.3); + check!(1234000000000000.0); + check!(1.234e16); + check!(2.71828); + check!(1.1e128); + check!(1.1e-64); + check!(2.718281828459045); + check!(5e-324); + check!(1.7976931348623157e308); +} + +#[test] +fn test_random() { + let n = if cfg!(miri) { 100 } else { 1000000 }; + let mut buffer = ryu::Buffer::new(); + for _ in 0..n { + let f: f64 = rand::random(); + assert_eq!(f, buffer.format_finite(f).parse().unwrap()); + } +} + +#[test] +#[cfg_attr(miri, ignore)] +fn test_non_finite() { + for i in 0u64..1 << 23 { + let f = f64::from_bits((((1 << 11) - 1) << 52) + (i << 29)); + assert!(!f.is_finite(), "f={}", f); + ryu::Buffer::new().format_finite(f); + } +} + +#[test] +fn test_basic() { + check!(0.0); + check!(-0.0); + check!(1.0); + check!(-1.0); + assert_eq!(pretty(f64::NAN.copysign(1.0)), "NaN"); + assert_eq!(pretty(f64::NAN.copysign(-1.0)), "NaN"); + assert_eq!(pretty(f64::INFINITY), "inf"); + assert_eq!(pretty(f64::NEG_INFINITY), "-inf"); +} + +#[test] +fn test_switch_to_subnormal() { + check!(2.2250738585072014e-308); +} + +#[test] +fn test_min_and_max() { + assert_eq!(f64::from_bits(0x7fefffffffffffff), 1.7976931348623157e308); + check!(1.7976931348623157e308); + assert_eq!(f64::from_bits(1), 5e-324); + check!(5e-324); +} + +#[test] +fn test_lots_of_trailing_zeros() { + check!(2.9802322387695312e-8); +} + +#[test] +fn test_regression() { + check!(-2.109808898695963e16); + check!(4.940656e-318); + check!(1.18575755e-316); + check!(2.989102097996e-312); + check!(9060801153433600.0); + check!(4.708356024711512e18); + check!(9.409340012568248e18); + check!(1.2345678); +} + +#[test] +fn test_looks_like_pow5() { + // These numbers have a mantissa that is a multiple of the largest power of + // 5 that fits, and an exponent that causes the computation for q to result + // in 22, which is a corner case for Ryū. + assert_eq!(f64::from_bits(0x4830F0CF064DD592), 5.764607523034235e39); + check!(5.764607523034235e39); + assert_eq!(f64::from_bits(0x4840F0CF064DD592), 1.152921504606847e40); + check!(1.152921504606847e40); + assert_eq!(f64::from_bits(0x4850F0CF064DD592), 2.305843009213694e40); + check!(2.305843009213694e40); +} + +#[test] +fn test_output_length() { + check!(1.0); // already tested in Basic + check!(1.2); + check!(1.23); + check!(1.234); + check!(1.2345); + check!(1.23456); + check!(1.234567); + check!(1.2345678); // already tested in Regression + check!(1.23456789); + check!(1.234567895); // 1.234567890 would be trimmed + check!(1.2345678901); + check!(1.23456789012); + check!(1.234567890123); + check!(1.2345678901234); + check!(1.23456789012345); + check!(1.234567890123456); + check!(1.2345678901234567); + + // Test 32-bit chunking + check!(4.294967294); // 2^32 - 2 + check!(4.294967295); // 2^32 - 1 + check!(4.294967296); // 2^32 + check!(4.294967297); // 2^32 + 1 + check!(4.294967298); // 2^32 + 2 +} + +// Test min, max shift values in shiftright128 +#[test] +fn test_min_max_shift() { + let max_mantissa = (1u64 << 53) - 1; + + // 32-bit opt-size=0: 49 <= dist <= 50 + // 32-bit opt-size=1: 30 <= dist <= 50 + // 64-bit opt-size=0: 50 <= dist <= 50 + // 64-bit opt-size=1: 30 <= dist <= 50 + assert_eq!(1.7800590868057611E-307, ieee_parts_to_double(false, 4, 0)); + check!(1.7800590868057611e-307); + // 32-bit opt-size=0: 49 <= dist <= 49 + // 32-bit opt-size=1: 28 <= dist <= 49 + // 64-bit opt-size=0: 50 <= dist <= 50 + // 64-bit opt-size=1: 28 <= dist <= 50 + assert_eq!( + 2.8480945388892175E-306, + ieee_parts_to_double(false, 6, max_mantissa) + ); + check!(2.8480945388892175e-306); + // 32-bit opt-size=0: 52 <= dist <= 53 + // 32-bit opt-size=1: 2 <= dist <= 53 + // 64-bit opt-size=0: 53 <= dist <= 53 + // 64-bit opt-size=1: 2 <= dist <= 53 + assert_eq!(2.446494580089078E-296, ieee_parts_to_double(false, 41, 0)); + check!(2.446494580089078e-296); + // 32-bit opt-size=0: 52 <= dist <= 52 + // 32-bit opt-size=1: 2 <= dist <= 52 + // 64-bit opt-size=0: 53 <= dist <= 53 + // 64-bit opt-size=1: 2 <= dist <= 53 + assert_eq!( + 4.8929891601781557E-296, + ieee_parts_to_double(false, 40, max_mantissa) + ); + check!(4.8929891601781557e-296); + + // 32-bit opt-size=0: 57 <= dist <= 58 + // 32-bit opt-size=1: 57 <= dist <= 58 + // 64-bit opt-size=0: 58 <= dist <= 58 + // 64-bit opt-size=1: 58 <= dist <= 58 + assert_eq!(1.8014398509481984E16, ieee_parts_to_double(false, 1077, 0)); + check!(1.8014398509481984e16); + // 32-bit opt-size=0: 57 <= dist <= 57 + // 32-bit opt-size=1: 57 <= dist <= 57 + // 64-bit opt-size=0: 58 <= dist <= 58 + // 64-bit opt-size=1: 58 <= dist <= 58 + assert_eq!( + 3.6028797018963964E16, + ieee_parts_to_double(false, 1076, max_mantissa) + ); + check!(3.6028797018963964e16); + // 32-bit opt-size=0: 51 <= dist <= 52 + // 32-bit opt-size=1: 51 <= dist <= 59 + // 64-bit opt-size=0: 52 <= dist <= 52 + // 64-bit opt-size=1: 52 <= dist <= 59 + assert_eq!(2.900835519859558E-216, ieee_parts_to_double(false, 307, 0)); + check!(2.900835519859558e-216); + // 32-bit opt-size=0: 51 <= dist <= 51 + // 32-bit opt-size=1: 51 <= dist <= 59 + // 64-bit opt-size=0: 52 <= dist <= 52 + // 64-bit opt-size=1: 52 <= dist <= 59 + assert_eq!( + 5.801671039719115E-216, + ieee_parts_to_double(false, 306, max_mantissa) + ); + check!(5.801671039719115e-216); + + // https://github.com/ulfjack/ryu/commit/19e44d16d80236f5de25800f56d82606d1be00b9#commitcomment-30146483 + // 32-bit opt-size=0: 49 <= dist <= 49 + // 32-bit opt-size=1: 44 <= dist <= 49 + // 64-bit opt-size=0: 50 <= dist <= 50 + // 64-bit opt-size=1: 44 <= dist <= 50 + assert_eq!( + 3.196104012172126E-27, + ieee_parts_to_double(false, 934, 0x000FA7161A4D6E0C) + ); + check!(3.196104012172126e-27); +} + +#[test] +fn test_small_integers() { + check!(9007199254740991.0); // 2^53-1 + check!(9007199254740992.0); // 2^53 + + check!(1.0); + check!(12.0); + check!(123.0); + check!(1234.0); + check!(12345.0); + check!(123456.0); + check!(1234567.0); + check!(12345678.0); + check!(123456789.0); + check!(1234567890.0); + check!(1234567895.0); + check!(12345678901.0); + check!(123456789012.0); + check!(1234567890123.0); + check!(12345678901234.0); + check!(123456789012345.0); + check!(1234567890123456.0); + + // 10^i + check!(1.0); + check!(10.0); + check!(100.0); + check!(1000.0); + check!(10000.0); + check!(100000.0); + check!(1000000.0); + check!(10000000.0); + check!(100000000.0); + check!(1000000000.0); + check!(10000000000.0); + check!(100000000000.0); + check!(1000000000000.0); + check!(10000000000000.0); + check!(100000000000000.0); + check!(1000000000000000.0); + + // 10^15 + 10^i + check!(1000000000000001.0); + check!(1000000000000010.0); + check!(1000000000000100.0); + check!(1000000000001000.0); + check!(1000000000010000.0); + check!(1000000000100000.0); + check!(1000000001000000.0); + check!(1000000010000000.0); + check!(1000000100000000.0); + check!(1000001000000000.0); + check!(1000010000000000.0); + check!(1000100000000000.0); + check!(1001000000000000.0); + check!(1010000000000000.0); + check!(1100000000000000.0); + + // Largest power of 2 <= 10^(i+1) + check!(8.0); + check!(64.0); + check!(512.0); + check!(8192.0); + check!(65536.0); + check!(524288.0); + check!(8388608.0); + check!(67108864.0); + check!(536870912.0); + check!(8589934592.0); + check!(68719476736.0); + check!(549755813888.0); + check!(8796093022208.0); + check!(70368744177664.0); + check!(562949953421312.0); + check!(9007199254740992.0); + + // 1000 * (Largest power of 2 <= 10^(i+1)) + check!(8000.0); + check!(64000.0); + check!(512000.0); + check!(8192000.0); + check!(65536000.0); + check!(524288000.0); + check!(8388608000.0); + check!(67108864000.0); + check!(536870912000.0); + check!(8589934592000.0); + check!(68719476736000.0); + check!(549755813888000.0); + check!(8796093022208000.0); +} diff --git a/bitbox02-bt/vendor/ryu/tests/exhaustive.rs b/bitbox02-bt/vendor/ryu/tests/exhaustive.rs new file mode 100644 index 0000000..569bcff --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/exhaustive.rs @@ -0,0 +1,52 @@ +#![cfg(exhaustive)] + +use std::str; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::thread; + +#[test] +fn test_exhaustive() { + const BATCH_SIZE: u32 = 1_000_000; + let counter = Arc::new(AtomicUsize::new(0)); + let finished = Arc::new(AtomicUsize::new(0)); + + let mut workers = Vec::new(); + for _ in 0..num_cpus::get() { + let counter = counter.clone(); + let finished = finished.clone(); + workers.push(thread::spawn(move || loop { + let batch = counter.fetch_add(1, Ordering::Relaxed) as u32; + if batch > u32::max_value() / BATCH_SIZE { + return; + } + + let min = batch * BATCH_SIZE; + let max = if batch == u32::max_value() / BATCH_SIZE { + u32::max_value() + } else { + min + BATCH_SIZE - 1 + }; + + let mut bytes = [0u8; 24]; + let mut buffer = ryu::Buffer::new(); + for u in min..=max { + let f = f32::from_bits(u); + if !f.is_finite() { + continue; + } + let n = unsafe { ryu::raw::format32(f, &mut bytes[0]) }; + assert_eq!(Ok(Ok(f)), str::from_utf8(&bytes[..n]).map(str::parse)); + assert_eq!(Ok(f), buffer.format_finite(f).parse()); + } + + let increment = (max - min + 1) as usize; + let update = finished.fetch_add(increment, Ordering::Relaxed); + println!("{}", update + increment); + })); + } + + for w in workers { + w.join().unwrap(); + } +} diff --git a/bitbox02-bt/vendor/ryu/tests/f2s_test.rs b/bitbox02-bt/vendor/ryu/tests/f2s_test.rs new file mode 100644 index 0000000..d6249a3 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/f2s_test.rs @@ -0,0 +1,181 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +#![allow( + clippy::approx_constant, + clippy::float_cmp, + clippy::non_ascii_literal, + clippy::unreadable_literal, + clippy::unseparated_literal_suffix +)] + +#[macro_use] +mod macros; + +use std::f32; + +fn pretty(f: f32) -> String { + ryu::Buffer::new().format(f).to_owned() +} + +#[test] +fn test_ryu() { + check!(0.3); + check!(1234000000000.0); + check!(1.234e13); + check!(2.71828); + check!(1.1e32); + check!(1.1e-32); + check!(2.7182817); + check!(1e-45); + check!(3.4028235e38); + check!(-0.001234); +} + +#[test] +fn test_random() { + let n = if cfg!(miri) { 100 } else { 1000000 }; + let mut buffer = ryu::Buffer::new(); + for _ in 0..n { + let f: f32 = rand::random(); + assert_eq!(f, buffer.format_finite(f).parse().unwrap()); + } +} + +#[test] +#[cfg_attr(miri, ignore)] +fn test_non_finite() { + for i in 0u32..1 << 23 { + let f = f32::from_bits((((1 << 8) - 1) << 23) + i); + assert!(!f.is_finite(), "f={}", f); + ryu::Buffer::new().format_finite(f); + } +} + +#[test] +fn test_basic() { + check!(0.0); + check!(-0.0); + check!(1.0); + check!(-1.0); + assert_eq!(pretty(f32::NAN.copysign(1.0)), "NaN"); + assert_eq!(pretty(f32::NAN.copysign(-1.0)), "NaN"); + assert_eq!(pretty(f32::INFINITY), "inf"); + assert_eq!(pretty(f32::NEG_INFINITY), "-inf"); +} + +#[test] +fn test_switch_to_subnormal() { + check!(1.1754944e-38); +} + +#[test] +fn test_min_and_max() { + assert_eq!(f32::from_bits(0x7f7fffff), 3.4028235e38); + check!(3.4028235e38); + assert_eq!(f32::from_bits(1), 1e-45); + check!(1e-45); +} + +// Check that we return the exact boundary if it is the shortest +// representation, but only if the original floating point number is even. +#[test] +fn test_boundary_round_even() { + check!(33554450.0); + check!(9000000000.0); + check!(34366720000.0); +} + +// If the exact value is exactly halfway between two shortest representations, +// then we round to even. It seems like this only makes a difference if the +// last two digits are ...2|5 or ...7|5, and we cut off the 5. +#[test] +fn test_exact_value_round_even() { + check!(305404.12); + check!(8099.0312); +} + +#[test] +fn test_lots_of_trailing_zeros() { + // Pattern for the first test: 00111001100000000000000000000000 + check!(0.00024414062); + check!(0.0024414062); + check!(0.0043945312); + check!(0.0063476562); +} + +#[test] +fn test_regression() { + check!(4.7223665e21); + check!(8388608.0); + check!(16777216.0); + check!(33554436.0); + check!(67131496.0); + check!(1.9310392e-38); + check!(-2.47e-43); + check!(1.993244e-38); + check!(4103.9004); + check!(5339999700.0); + check!(6.0898e-39); + check!(0.0010310042); + check!(2.882326e17); + check!(7.038531e-26); + check!(9.223404e17); + check!(67108870.0); + check!(1e-44); + check!(2.816025e14); + check!(9.223372e18); + check!(1.5846086e29); + check!(1.1811161e19); + check!(5.368709e18); + check!(4.6143166e18); + check!(0.007812537); + check!(1e-45); + check!(1.18697725e20); + check!(1.00014165e-36); + check!(200.0); + check!(33554432.0); +} + +#[test] +fn test_looks_like_pow5() { + // These numbers have a mantissa that is the largest power of 5 that fits, + // and an exponent that causes the computation for q to result in 10, which + // is a corner case for Ryū. + assert_eq!(f32::from_bits(0x5D1502F9), 6.7108864e17); + check!(6.7108864e17); + assert_eq!(f32::from_bits(0x5D9502F9), 1.3421773e18); + check!(1.3421773e18); + assert_eq!(f32::from_bits(0x5E1502F9), 2.6843546e18); + check!(2.6843546e18); +} + +#[test] +fn test_output_length() { + check!(1.0); // already tested in Basic + check!(1.2); + check!(1.23); + check!(1.234); + check!(1.2345); + check!(1.23456); + check!(1.234567); + check!(1.2345678); + check!(1.23456735e-36); +} diff --git a/bitbox02-bt/vendor/ryu/tests/macros/mod.rs b/bitbox02-bt/vendor/ryu/tests/macros/mod.rs new file mode 100644 index 0000000..de6fb46 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/macros/mod.rs @@ -0,0 +1,8 @@ +macro_rules! check { + ($f:tt) => { + assert_eq!(pretty($f), stringify!($f)); + }; + (-$f:tt) => { + assert_eq!(pretty(-$f), concat!("-", stringify!($f))); + }; +} diff --git a/bitbox02-bt/vendor/ryu/tests/s2d_test.rs b/bitbox02-bt/vendor/ryu/tests/s2d_test.rs new file mode 100644 index 0000000..7b42164 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/s2d_test.rs @@ -0,0 +1,167 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +#![cfg(not(feature = "small"))] +#![allow(dead_code)] +#![allow( + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::excessive_precision, + clippy::float_cmp, + clippy::manual_range_contains, + clippy::similar_names, + clippy::too_many_lines, + clippy::unreadable_literal, + clippy::unseparated_literal_suffix, + clippy::wildcard_imports +)] + +#[path = "../src/common.rs"] +mod common; + +#[cfg(not(feature = "small"))] +#[path = "../src/d2s_full_table.rs"] +mod d2s_full_table; + +#[path = "../src/d2s_intrinsics.rs"] +mod d2s_intrinsics; + +#[cfg(feature = "small")] +#[path = "../src/d2s_small_table.rs"] +mod d2s_small_table; + +#[path = "../src/d2s.rs"] +mod d2s; + +#[path = "../src/s2d.rs"] +mod s2d; + +#[path = "../src/parse.rs"] +mod parse; + +use crate::parse::Error; +use crate::s2d::s2d; + +impl PartialEq for Error { + fn eq(&self, other: &Self) -> bool { + *self as u8 == *other as u8 + } +} + +#[test] +fn test_bad_input() { + assert_eq!(Error::MalformedInput, s2d(b"x").unwrap_err()); + assert_eq!(Error::MalformedInput, s2d(b"1..1").unwrap_err()); + assert_eq!(Error::MalformedInput, s2d(b"..").unwrap_err()); + assert_eq!(Error::MalformedInput, s2d(b"1..1").unwrap_err()); + assert_eq!(Error::MalformedInput, s2d(b"1ee1").unwrap_err()); + assert_eq!(Error::MalformedInput, s2d(b"1e.1").unwrap_err()); + assert_eq!(Error::InputTooShort, s2d(b"").unwrap_err()); + assert_eq!(Error::InputTooLong, s2d(b"123456789012345678").unwrap_err()); + assert_eq!(Error::InputTooLong, s2d(b"1e12345").unwrap_err()); +} + +#[test] +fn test_basic() { + assert_eq!(0.0, s2d(b"0").unwrap()); + assert_eq!(-0.0, s2d(b"-0").unwrap()); + assert_eq!(1.0, s2d(b"1").unwrap()); + assert_eq!(2.0, s2d(b"2").unwrap()); + assert_eq!(123456789.0, s2d(b"123456789").unwrap()); + assert_eq!(123.456, s2d(b"123.456").unwrap()); + assert_eq!(123.456, s2d(b"123456e-3").unwrap()); + assert_eq!(123.456, s2d(b"1234.56e-1").unwrap()); + assert_eq!(1.453, s2d(b"1.453").unwrap()); + assert_eq!(1453.0, s2d(b"1.453e+3").unwrap()); + assert_eq!(0.0, s2d(b".0").unwrap()); + assert_eq!(1.0, s2d(b"1e0").unwrap()); + assert_eq!(1.0, s2d(b"1E0").unwrap()); + assert_eq!(1.0, s2d(b"000001.000000").unwrap()); + assert_eq!(0.2316419, s2d(b"0.2316419").unwrap()); +} + +#[test] +fn test_min_max() { + assert_eq!( + 1.7976931348623157e308, + s2d(b"1.7976931348623157e308").unwrap(), + ); + assert_eq!(5E-324, s2d(b"5E-324").unwrap()); +} + +#[test] +fn test_mantissa_rounding_overflow() { + // This results in binary mantissa that is all ones and requires rounding up + // because it is closer to 1 than to the next smaller float. This is a + // regression test that the mantissa overflow is handled correctly by + // increasing the exponent. + assert_eq!(1.0, s2d(b"0.99999999999999999").unwrap()); + // This number overflows the mantissa *and* the IEEE exponent. + assert_eq!(f64::INFINITY, s2d(b"1.7976931348623159e308").unwrap()); +} + +#[test] +fn test_underflow() { + assert_eq!(0.0, s2d(b"2.4e-324").unwrap()); + assert_eq!(0.0, s2d(b"1e-324").unwrap()); + assert_eq!(0.0, s2d(b"9.99999e-325").unwrap()); + // These are just about halfway between 0 and the smallest float. + // The first is just below the halfway point, the second just above. + assert_eq!(0.0, s2d(b"2.4703282292062327e-324").unwrap()); + assert_eq!(5e-324, s2d(b"2.4703282292062328e-324").unwrap()); +} + +#[test] +fn test_overflow() { + assert_eq!(f64::INFINITY, s2d(b"2e308").unwrap()); + assert_eq!(f64::INFINITY, s2d(b"1e309").unwrap()); +} + +#[test] +fn test_table_size_denormal() { + assert_eq!(5e-324, s2d(b"4.9406564584124654e-324").unwrap()); +} + +#[test] +fn test_issue157() { + assert_eq!( + 1.2999999999999999E+154, + s2d(b"1.2999999999999999E+154").unwrap(), + ); +} + +#[test] +fn test_issue173() { + // Denormal boundary + assert_eq!( + 2.2250738585072012e-308, + s2d(b"2.2250738585072012e-308").unwrap(), + ); + assert_eq!( + 2.2250738585072013e-308, + s2d(b"2.2250738585072013e-308").unwrap(), + ); + assert_eq!( + 2.2250738585072014e-308, + s2d(b"2.2250738585072014e-308").unwrap(), + ); +} diff --git a/bitbox02-bt/vendor/ryu/tests/s2f_test.rs b/bitbox02-bt/vendor/ryu/tests/s2f_test.rs new file mode 100644 index 0000000..5bae935 --- /dev/null +++ b/bitbox02-bt/vendor/ryu/tests/s2f_test.rs @@ -0,0 +1,110 @@ +// Translated from C to Rust. The original C code can be found at +// https://github.com/ulfjack/ryu and carries the following license: +// +// Copyright 2018 Ulf Adams +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE-Apache or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Alternatively, the contents of this file may be used under the terms of +// the Boost Software License, Version 1.0. +// (See accompanying file LICENSE-Boost or copy at +// https://www.boost.org/LICENSE_1_0.txt) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. + +#![allow(dead_code)] +#![allow( + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + clippy::checked_conversions, + clippy::float_cmp, + clippy::manual_range_contains, + clippy::similar_names, + clippy::too_many_lines, + clippy::unreadable_literal, + clippy::unseparated_literal_suffix, + clippy::wildcard_imports +)] + +#[path = "../src/common.rs"] +mod common; + +#[cfg(not(feature = "small"))] +#[path = "../src/d2s_full_table.rs"] +mod d2s_full_table; + +#[path = "../src/d2s_intrinsics.rs"] +mod d2s_intrinsics; + +#[cfg(feature = "small")] +#[path = "../src/d2s_small_table.rs"] +mod d2s_small_table; + +#[path = "../src/d2s.rs"] +mod d2s; + +#[path = "../src/f2s_intrinsics.rs"] +mod f2s_intrinsics; + +#[path = "../src/f2s.rs"] +mod f2s; + +#[path = "../src/s2f.rs"] +mod s2f; + +#[path = "../src/parse.rs"] +mod parse; + +use crate::parse::Error; +use crate::s2f::s2f; + +impl PartialEq for Error { + fn eq(&self, other: &Self) -> bool { + *self as u8 == *other as u8 + } +} + +#[test] +fn test_basic() { + assert_eq!(0.0, s2f(b"0").unwrap()); + assert_eq!(-0.0, s2f(b"-0").unwrap()); + assert_eq!(1.0, s2f(b"1").unwrap()); + assert_eq!(-1.0, s2f(b"-1").unwrap()); + assert_eq!(123456792.0, s2f(b"123456789").unwrap()); + assert_eq!(299792448.0, s2f(b"299792458").unwrap()); +} + +#[test] +fn test_min_max() { + assert_eq!(1e-45, s2f(b"1e-45").unwrap()); + assert_eq!(f32::MIN_POSITIVE, s2f(b"1.1754944e-38").unwrap()); + assert_eq!(f32::MAX, s2f(b"3.4028235e+38").unwrap()); +} + +#[test] +fn test_mantissa_rounding_overflow() { + assert_eq!(1.0, s2f(b"0.999999999").unwrap()); + assert_eq!(f32::INFINITY, s2f(b"3.4028236e+38").unwrap()); + assert_eq!(1.1754944e-38, s2f(b"1.17549430e-38").unwrap()); // FLT_MIN + assert_eq!(1.1754944e-38, s2f(b"1.17549431e-38").unwrap()); + assert_eq!(1.1754944e-38, s2f(b"1.17549432e-38").unwrap()); + assert_eq!(1.1754944e-38, s2f(b"1.17549433e-38").unwrap()); + assert_eq!(1.1754944e-38, s2f(b"1.17549434e-38").unwrap()); + assert_eq!(1.1754944e-38, s2f(b"1.17549435e-38").unwrap()); +} + +#[test] +fn test_trailing_zeros() { + assert_eq!(26843550.0, s2f(b"26843549.5").unwrap()); + assert_eq!(50000004.0, s2f(b"50000002.5").unwrap()); + assert_eq!(99999992.0, s2f(b"99999989.5").unwrap()); +} diff --git a/bitbox02-bt/vendor/semver-parser/.cargo-checksum.json b/bitbox02-bt/vendor/semver-parser/.cargo-checksum.json new file mode 100644 index 0000000..73575fe --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"67597114802114d2a7fdb457c1cf5f7e0c951b21e287c6a47b9a86b9028cf64d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"d38feaa4f9468cd1e0ece22e0ad2eadfe6195a9a0a3843b7c722d5c7d81804fb","src/common.rs":"dc42336abd34e19ca9f732f33657e106f98dcc8c10d4c2564bc4f160cb31926e","src/lib.rs":"3ac8ef5a280344a25cb18ac386034c0fee8d64060fa14af5e25ed49f0cb2fd9e","src/range.rs":"3596f048d466d43887aff1e8c8c834476672a4627631ed35379c35466b5f02ec","src/recognize.rs":"9f16eda9fcd7d8af7eee4c3b89c611bd648040273fde6b35778f8a50b004c8b1","src/version.rs":"dbd91a4e4fd92a0aa9eb4f858ecbc1ecd680aa60572cc2ad2085e5c5c30e5b77"},"package":"388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/semver-parser/Cargo.toml b/bitbox02-bt/vendor/semver-parser/Cargo.toml new file mode 100644 index 0000000..c2be878 --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "semver-parser" +version = "0.7.0" +authors = ["Steve Klabnik "] +license = "MIT/Apache-2.0" +repository = "https://github.com/steveklabnik/semver-parser" +homepage = "https://github.com/steveklabnik/semver-parser" +documentation = "https://docs.rs/semver-parser" +description = """ +Parsing of the semver spec. +""" diff --git a/bitbox02-bt/vendor/semver-parser/LICENSE-APACHE b/bitbox02-bt/vendor/semver-parser/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/semver-parser/LICENSE-MIT b/bitbox02-bt/vendor/semver-parser/LICENSE-MIT new file mode 100644 index 0000000..fb7494a --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Steve Klabnik + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/semver-parser/src/common.rs b/bitbox02-bt/vendor/semver-parser/src/common.rs new file mode 100644 index 0000000..267b4d9 --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/src/common.rs @@ -0,0 +1,66 @@ +use version::Identifier; +use recognize::{Recognize, Alt, OneOrMore, Inclusive, OneByte}; +use std::str::from_utf8; + +// by the time we get here, we know that it's all valid characters, so this doesn't need to return +// a result or anything +fn parse_meta(s: &str) -> Vec { + // Originally, I wanted to implement this method via calling parse, but parse is tolerant of + // leading zeroes, and we want anything with leading zeroes to be considered alphanumeric, not + // numeric. So the strategy is to check with a recognizer first, and then call parse once + // we've determined that it's a number without a leading zero. + s.split(".") + .map(|part| { + // another wrinkle: we made sure that any number starts with a + // non-zero. But there's a problem: an actual zero is a number, yet + // gets left out by this heuristic. So let's also check for the + // single, lone zero. + if is_alpha_numeric(part) { + Identifier::AlphaNumeric(part.to_string()) + } else { + // we can unwrap here because we know it is only digits due to the regex + Identifier::Numeric(part.parse().unwrap()) + } + }).collect() +} + +// parse optional metadata (preceded by the prefix character) +pub fn parse_optional_meta(s: &[u8], prefix_char: u8)-> Result<(Vec, usize), String> { + if let Some(len) = prefix_char.p(s) { + let start = len; + if let Some(len) = letters_numbers_dash_dot(&s[start..]) { + let end = start + len; + Ok((parse_meta(from_utf8(&s[start..end]).unwrap()), end)) + } else { + Err("Error parsing prerelease".to_string()) + } + } else { + Ok((Vec::new(), 0)) + } +} + +pub fn is_alpha_numeric(s: &str) -> bool { + if let Some((_val, len)) = numeric_identifier(s.as_bytes()) { + // Return true for number with leading zero + // Note: doing it this way also handily makes overflow fail over. + len != s.len() + } else { + true + } +} + +// Note: could plumb overflow error up to return value as Result +pub fn numeric_identifier(s: &[u8]) -> Option<(u64, usize)> { + if let Some(len) = Alt(b'0', OneOrMore(Inclusive(b'0'..b'9'))).p(s) { + from_utf8(&s[0..len]).unwrap().parse().ok().map(|val| (val, len)) + } else { + None + } +} + +pub fn letters_numbers_dash_dot(s: &[u8]) -> Option { + OneOrMore(OneByte(|c| c == b'-' || c == b'.' || + (b'0' <= c && c <= b'9') || + (b'a' <= c && c <= b'z') || + (b'A' <= c && c <= b'Z'))).p(s) +} diff --git a/bitbox02-bt/vendor/semver-parser/src/lib.rs b/bitbox02-bt/vendor/semver-parser/src/lib.rs new file mode 100644 index 0000000..3b0d8f0 --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/src/lib.rs @@ -0,0 +1,8 @@ +pub mod version; +pub mod range; + +// for private stuff the two share +mod common; + +// for recognizer combinators +mod recognize; diff --git a/bitbox02-bt/vendor/semver-parser/src/range.rs b/bitbox02-bt/vendor/semver-parser/src/range.rs new file mode 100644 index 0000000..858be9f --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/src/range.rs @@ -0,0 +1,696 @@ +use common::{self, numeric_identifier, letters_numbers_dash_dot}; +use version::Identifier; +use std::str::{FromStr, from_utf8}; +use recognize::*; + +#[derive(Debug)] +pub struct VersionReq { + pub predicates: Vec, +} + +#[derive(PartialEq,Debug)] +pub enum WildcardVersion { + Major, + Minor, + Patch, +} + +#[derive(PartialEq,Debug)] +pub enum Op { + Ex, // Exact + Gt, // Greater than + GtEq, // Greater than or equal to + Lt, // Less than + LtEq, // Less than or equal to + Tilde, // e.g. ~1.0.0 + Compatible, // compatible by definition of semver, indicated by ^ + Wildcard(WildcardVersion), // x.y.*, x.*, * +} + +impl FromStr for Op { + type Err = String; + + fn from_str(s: &str) -> Result { + match s { + "=" => Ok(Op::Ex), + ">" => Ok(Op::Gt), + ">=" => Ok(Op::GtEq), + "<" => Ok(Op::Lt), + "<=" => Ok(Op::LtEq), + "~" => Ok(Op::Tilde), + "^" => Ok(Op::Compatible), + _ => Err(String::from("Could not parse Op")), + } + } +} + +#[derive(PartialEq,Debug)] +pub struct Predicate { + pub op: Op, + pub major: u64, + pub minor: Option, + pub patch: Option, + pub pre: Vec, +} + +fn numeric_or_wild(s: &[u8]) -> Option<(Option, usize)> { + if let Some((val, len)) = numeric_identifier(s) { + Some((Some(val), len)) + } else if let Some(len) = OneOf(b"*xX").p(s) { + Some((None, len)) + } else { + None + } +} + +fn dot_numeric_or_wild(s: &[u8]) -> Option<(Option, usize)> { + b'.'.p(s).and_then(|len| + numeric_or_wild(&s[len..]).map(|(val, len2)| (val, len + len2)) + ) +} + +fn operation(s: &[u8]) -> Option<(Op, usize)> { + if let Some(len) = "=".p(s) { + Some((Op::Ex, len)) + } else if let Some(len) = ">=".p(s) { + Some((Op::GtEq, len)) + } else if let Some(len) = ">".p(s) { + Some((Op::Gt, len)) + } else if let Some(len) = "<=".p(s) { + Some((Op::LtEq, len)) + } else if let Some(len) = "<".p(s) { + Some((Op::Lt, len)) + } else if let Some(len) = "~".p(s) { + Some((Op::Tilde, len)) + } else if let Some(len) = "^".p(s) { + Some((Op::Compatible, len)) + } else { + None + } +} + +fn whitespace(s: &[u8]) -> Option { + ZeroOrMore(OneOf(b"\t\r\n ")).p(s) +} + +pub fn parse_predicate(range: &str) -> Result { + let s = range.trim().as_bytes(); + let mut i = 0; + let mut operation = if let Some((op, len)) = operation(&s[i..]) { + i += len; + op + } else { + // operations default to Compatible + Op::Compatible + }; + if let Some(len) = whitespace.p(&s[i..]) { + i += len; + } + let major = if let Some((major, len)) = numeric_identifier(&s[i..]) { + i += len; + major + } else { + return Err("Error parsing major version number: ".to_string()); + }; + let minor = if let Some((minor, len)) = dot_numeric_or_wild(&s[i..]) { + i += len; + if minor.is_none() { + operation = Op::Wildcard(WildcardVersion::Minor); + } + minor + } else { + None + }; + let patch = if let Some((patch, len)) = dot_numeric_or_wild(&s[i..]) { + i += len; + if patch.is_none() { + operation = Op::Wildcard(WildcardVersion::Patch); + } + patch + } else { + None + }; + let (pre, pre_len) = common::parse_optional_meta(&s[i..], b'-')?; + i += pre_len; + if let Some(len) = (b'+', letters_numbers_dash_dot).p(&s[i..]) { + i += len; + } + if i != s.len() { + return Err("Extra junk after valid predicate: ".to_string() + + from_utf8(&s[i..]).unwrap()); + } + Ok(Predicate { + op: operation, + major: major, + minor: minor, + patch: patch, + pre: pre, + }) +} + +pub fn parse(ranges: &str) -> Result { + // null is an error + if ranges == "\0" { + return Err(String::from("Null is not a valid VersionReq")); + } + + // an empty range is a major version wildcard + // so is a lone * or x of either capitalization + if (ranges == "") + || (ranges == "*") + || (ranges == "x") + || (ranges == "X") { + return Ok(VersionReq { + predicates: vec![Predicate { + op: Op::Wildcard(WildcardVersion::Major), + major: 0, + minor: None, + patch: None, + pre: Vec::new(), + }], + }); + } + + + let ranges = ranges.trim(); + + let predicates: Result, String> = ranges + .split(",") + .map(|range| { + parse_predicate(range) + }) + .collect(); + + let predicates = try!(predicates); + + if predicates.len() == 0 { + return Err(String::from("VersionReq did not parse properly")); + } + + Ok(VersionReq { + predicates: predicates, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use range; + use version::Identifier; + + #[test] + fn test_parsing_default() { + let r = range::parse("1.0.0").unwrap(); + + assert_eq!(Predicate { + op: Op::Compatible, + major: 1, + minor: Some(0), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_exact_01() { + let r = range::parse("=1.0.0").unwrap(); + + assert_eq!(Predicate { + op: Op::Ex, + major: 1, + minor: Some(0), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_exact_02() { + let r = range::parse("=0.9.0").unwrap(); + + assert_eq!(Predicate { + op: Op::Ex, + major: 0, + minor: Some(9), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_exact_03() { + let r = range::parse("=0.1.0-beta2.a").unwrap(); + + assert_eq!(Predicate { + op: Op::Ex, + major: 0, + minor: Some(1), + patch: Some(0), + pre: vec![Identifier::AlphaNumeric(String::from("beta2")), + Identifier::AlphaNumeric(String::from("a"))], + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_parsing_greater_than() { + let r = range::parse("> 1.0.0").unwrap(); + + assert_eq!(Predicate { + op: Op::Gt, + major: 1, + minor: Some(0), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_parsing_greater_than_01() { + let r = range::parse(">= 1.0.0").unwrap(); + + assert_eq!(Predicate { + op: Op::GtEq, + major: 1, + minor: Some(0), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_parsing_greater_than_02() { + let r = range::parse(">= 2.1.0-alpha2").unwrap(); + + assert_eq!(Predicate { + op: Op::GtEq, + major: 2, + minor: Some(1), + patch: Some(0), + pre: vec![Identifier::AlphaNumeric(String::from("alpha2"))], + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_parsing_less_than() { + let r = range::parse("< 1.0.0").unwrap(); + + assert_eq!(Predicate { + op: Op::Lt, + major: 1, + minor: Some(0), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_parsing_less_than_eq() { + let r = range::parse("<= 2.1.0-alpha2").unwrap(); + + assert_eq!(Predicate { + op: Op::LtEq, + major: 2, + minor: Some(1), + patch: Some(0), + pre: vec![Identifier::AlphaNumeric(String::from("alpha2"))], + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_parsing_tilde() { + let r = range::parse("~1").unwrap(); + + assert_eq!(Predicate { + op: Op::Tilde, + major: 1, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_parsing_compatible() { + let r = range::parse("^0").unwrap(); + + assert_eq!(Predicate { + op: Op::Compatible, + major: 0, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_blank() { + let r = range::parse("").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Major), + major: 0, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_wildcard() { + let r = range::parse("*").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Major), + major: 0, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_x() { + let r = range::parse("x").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Major), + major: 0, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_capital_x() { + let r = range::parse("X").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Major), + major: 0, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_minor_wildcard_star() { + let r = range::parse("1.*").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Minor), + major: 1, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_minor_wildcard_x() { + let r = range::parse("1.x").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Minor), + major: 1, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_minor_wildcard_capital_x() { + let r = range::parse("1.X").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Minor), + major: 1, + minor: None, + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_patch_wildcard_star() { + let r = range::parse("1.2.*").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Patch), + major: 1, + minor: Some(2), + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_patch_wildcard_x() { + let r = range::parse("1.2.x").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Patch), + major: 1, + minor: Some(2), + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + fn test_parsing_patch_wildcard_capital_x() { + let r = range::parse("1.2.X").unwrap(); + + assert_eq!(Predicate { + op: Op::Wildcard(WildcardVersion::Patch), + major: 1, + minor: Some(2), + patch: None, + pre: Vec::new(), + }, + r.predicates[0] + ); + } + + #[test] + pub fn test_multiple_01() { + let r = range::parse("> 0.0.9, <= 2.5.3").unwrap(); + + assert_eq!(Predicate { + op: Op::Gt, + major: 0, + minor: Some(0), + patch: Some(9), + pre: Vec::new(), + }, + r.predicates[0] + ); + + assert_eq!(Predicate { + op: Op::LtEq, + major: 2, + minor: Some(5), + patch: Some(3), + pre: Vec::new(), + }, + r.predicates[1] + ); + } + + #[test] + pub fn test_multiple_02() { + let r = range::parse("0.3.0, 0.4.0").unwrap(); + + assert_eq!(Predicate { + op: Op::Compatible, + major: 0, + minor: Some(3), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + + assert_eq!(Predicate { + op: Op::Compatible, + major: 0, + minor: Some(4), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[1] + ); + } + + #[test] + pub fn test_multiple_03() { + let r = range::parse("<= 0.2.0, >= 0.5.0").unwrap(); + + assert_eq!(Predicate { + op: Op::LtEq, + major: 0, + minor: Some(2), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + + assert_eq!(Predicate { + op: Op::GtEq, + major: 0, + minor: Some(5), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[1] + ); + } + + #[test] + pub fn test_multiple_04() { + let r = range::parse("0.1.0, 0.1.4, 0.1.6").unwrap(); + + assert_eq!(Predicate { + op: Op::Compatible, + major: 0, + minor: Some(1), + patch: Some(0), + pre: Vec::new(), + }, + r.predicates[0] + ); + + assert_eq!(Predicate { + op: Op::Compatible, + major: 0, + minor: Some(1), + patch: Some(4), + pre: Vec::new(), + }, + r.predicates[1] + ); + + assert_eq!(Predicate { + op: Op::Compatible, + major: 0, + minor: Some(1), + patch: Some(6), + pre: Vec::new(), + }, + r.predicates[2] + ); + } + + #[test] + pub fn test_multiple_05() { + let r = range::parse(">=0.5.1-alpha3, <0.6").unwrap(); + + assert_eq!(Predicate { + op: Op::GtEq, + major: 0, + minor: Some(5), + patch: Some(1), + pre: vec![Identifier::AlphaNumeric(String::from("alpha3"))], + }, + r.predicates[0] + ); + + assert_eq!(Predicate { + op: Op::Lt, + major: 0, + minor: Some(6), + patch: None, + pre: Vec::new(), + }, + r.predicates[1] + ); + } + + #[test] + fn test_parse_build_metadata_with_predicate() { + assert_eq!(range::parse("^1.2.3+meta").unwrap().predicates[0].op, + Op::Compatible); + assert_eq!(range::parse("~1.2.3+meta").unwrap().predicates[0].op, + Op::Tilde); + assert_eq!(range::parse("=1.2.3+meta").unwrap().predicates[0].op, + Op::Ex); + assert_eq!(range::parse("<=1.2.3+meta").unwrap().predicates[0].op, + Op::LtEq); + assert_eq!(range::parse(">=1.2.3+meta").unwrap().predicates[0].op, + Op::GtEq); + assert_eq!(range::parse("<1.2.3+meta").unwrap().predicates[0].op, + Op::Lt); + assert_eq!(range::parse(">1.2.3+meta").unwrap().predicates[0].op, + Op::Gt); + } + + #[test] + pub fn test_parse_errors() { + assert!(range::parse("\0").is_err()); + assert!(range::parse(">= >= 0.0.2").is_err()); + assert!(range::parse(">== 0.0.2").is_err()); + assert!(range::parse("a.0.0").is_err()); + assert!(range::parse("1.0.0-").is_err()); + assert!(range::parse(">=").is_err()); + assert!(range::parse("> 0.1.0,").is_err()); + assert!(range::parse("> 0.3.0, ,").is_err()); + } + + #[test] + pub fn test_large_major_version() { + assert!(range::parse("18446744073709551617.0.0").is_err()); + } + + #[test] + pub fn test_large_minor_version() { + assert!(range::parse("0.18446744073709551617.0").is_err()); + } + + #[test] + pub fn test_large_patch_version() { + assert!(range::parse("0.0.18446744073709551617").is_err()); + } +} diff --git a/bitbox02-bt/vendor/semver-parser/src/recognize.rs b/bitbox02-bt/vendor/semver-parser/src/recognize.rs new file mode 100644 index 0000000..c0dd771 --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/src/recognize.rs @@ -0,0 +1,154 @@ +// Copyright 2017 Google Inc. All rights reserved. +// +// Licensed under either of MIT or Apache License, Version 2.0, +// at your option. +// +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Simple recognizer combinators. + +// This version is similar to a similar one in the "lang" module of +// xi-editor, but is stripped down to only the needed combinators. + +use std::ops; + +pub trait Recognize { + fn p(&self, s: &[u8]) -> Option; +} + +impl Option> Recognize for F { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + self(s) + } +} + +pub struct OneByte(pub F); + +impl bool> Recognize for OneByte { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + if s.is_empty() || !self.0(s[0]) { + None + } else { + Some(1) + } + } +} + +impl Recognize for u8 { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + OneByte(|b| b == *self).p(s) + } +} + +/// Use Inclusive(a..b) to indicate an inclusive range. When a...b syntax becomes +/// stable, we can get rid of this and switch to that. +pub struct Inclusive(pub T); + +impl Recognize for Inclusive> { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + OneByte(|x| x >= self.0.start && x <= self.0.end).p(s) + } +} + +impl<'a> Recognize for &'a [u8] { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + let len = self.len(); + if s.len() >= len && &s[..len] == *self { + Some(len) + } else { + None + } + } +} + +impl<'a> Recognize for &'a str { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + self.as_bytes().p(s) + } +} + +impl Recognize for (P1, P2) { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + self.0.p(s).and_then(|len1| + self.1.p(&s[len1..]).map(|len2| + len1 + len2)) + } +} + +/// Choice from two heterogeneous alternatives. +pub struct Alt(pub P1, pub P2); + +impl Recognize for Alt { + #[inline(always)] + fn p(&self, s: &[u8]) -> Option { + self.0.p(s).or_else(|| self.1.p(s)) + } +} + +/// Choice from a homogenous slice of parsers. +pub struct OneOf<'a, P: 'a>(pub &'a [P]); + +impl<'a, P: Recognize> Recognize for OneOf<'a, P> { + #[inline] + fn p(&self, s: &[u8]) -> Option { + for ref p in self.0 { + if let Some(len) = p.p(s) { + return Some(len); + } + } + None + } +} + +pub struct OneOrMore

(pub P); + +impl Recognize for OneOrMore

{ + #[inline] + fn p(&self, s: &[u8]) -> Option { + let mut i = 0; + let mut count = 0; + while let Some(len) = self.0.p(&s[i..]) { + i += len; + count += 1; + } + if count >= 1 { + Some(i) + } else { + None + } + } +} + +pub struct ZeroOrMore

(pub P); + +impl Recognize for ZeroOrMore

{ + #[inline] + fn p(&self, s: &[u8]) -> Option { + let mut i = 0; + while let Some(len) = self.0.p(&s[i..]) { + i += len; + } + Some(i) + } +} diff --git a/bitbox02-bt/vendor/semver-parser/src/version.rs b/bitbox02-bt/vendor/semver-parser/src/version.rs new file mode 100644 index 0000000..570f947 --- /dev/null +++ b/bitbox02-bt/vendor/semver-parser/src/version.rs @@ -0,0 +1,365 @@ +use std::fmt; +use std::str::from_utf8; + +use recognize::*; + +use common::{self, numeric_identifier}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Version { + pub major: u64, + pub minor: u64, + pub patch: u64, + pub pre: Vec, + pub build: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Identifier { + /// An identifier that's solely numbers. + Numeric(u64), + /// An identifier with letters and numbers. + AlphaNumeric(String), +} + +pub fn parse(version: &str) -> Result { + let s = version.trim().as_bytes(); + let mut i = 0; + let major = if let Some((major, len)) = numeric_identifier(&s[i..]) { + i += len; + major + } else { + return Err("Error parsing major identifier".to_string()); + }; + if let Some(len) = b'.'.p(&s[i..]) { + i += len; + } else { + return Err("Expected dot".to_string()); + } + let minor = if let Some((minor, len)) = numeric_identifier(&s[i..]) { + i += len; + minor + } else { + return Err("Error parsing minor identifier".to_string()); + }; + if let Some(len) = b'.'.p(&s[i..]) { + i += len; + } else { + return Err("Expected dot".to_string()); + } + let patch = if let Some((patch, len)) = numeric_identifier(&s[i..]) { + i += len; + patch + } else { + return Err("Error parsing patch identifier".to_string()); + }; + let (pre, pre_len) = common::parse_optional_meta(&s[i..], b'-')?; + i += pre_len; + let (build, build_len) = common::parse_optional_meta(&s[i..], b'+')?; + i += build_len; + if i != s.len() { + return Err("Extra junk after valid version: ".to_string() + + from_utf8(&s[i..]).unwrap()); + } + Ok(Version { + major: major, + minor: minor, + patch: patch, + pre: pre, + build: build, + }) +} + +impl fmt::Display for Version { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)); + if !self.pre.is_empty() { + let strs: Vec<_> = + self.pre.iter().map(ToString::to_string).collect(); + try!(write!(f, "-{}", strs.join("."))); + } + if !self.build.is_empty() { + let strs: Vec<_> = + self.build.iter().map(ToString::to_string).collect(); + try!(write!(f, "+{}", strs.join("."))); + } + Ok(()) + } +} + +impl fmt::Display for Identifier { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Identifier::Numeric(ref id) => id.fmt(f), + Identifier::AlphaNumeric(ref id) => id.fmt(f), + } + } +} + +#[cfg(test)] +mod tests { + use version; + use super::*; + + #[test] + fn parse_empty() { + let version = ""; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "empty string incorrectly considered a valid parse"); + } + + #[test] + fn parse_blank() { + let version = " "; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "blank string incorrectly considered a valid parse"); + } + + #[test] + fn parse_no_minor_patch() { + let version = "1"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); + } + + #[test] + fn parse_no_patch() { + let version = "1.2"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); + } + + #[test] + fn parse_empty_pre() { + let version = "1.2.3-"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); + } + + #[test] + fn parse_letters() { + let version = "a.b.c"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); + } + + #[test] + fn parse_with_letters() { + let version = "1.2.3 a.b.c"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); + } + + #[test] + fn parse_basic_version() { + let version = "1.2.3"; + + let parsed = version::parse(version).unwrap(); + + assert_eq!(1, parsed.major); + assert_eq!(2, parsed.minor); + assert_eq!(3, parsed.patch); + } + + #[test] + fn parse_trims_input() { + let version = " 1.2.3 "; + + let parsed = version::parse(version).unwrap(); + + assert_eq!(1, parsed.major); + assert_eq!(2, parsed.minor); + assert_eq!(3, parsed.patch); + } + + #[test] + fn parse_no_major_leading_zeroes() { + let version = "01.0.0"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "01 incorrectly considered a valid major version"); + } + + #[test] + fn parse_no_minor_leading_zeroes() { + let version = "0.01.0"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "01 incorrectly considered a valid minor version"); + } + + #[test] + fn parse_no_patch_leading_zeroes() { + let version = "0.0.01"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "01 incorrectly considered a valid patch version"); + } + + #[test] + fn parse_no_major_overflow() { + let version = "98765432109876543210.0.0"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "98765432109876543210 incorrectly considered a valid major version"); + } + + #[test] + fn parse_no_minor_overflow() { + let version = "0.98765432109876543210.0"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "98765432109876543210 incorrectly considered a valid minor version"); + } + + #[test] + fn parse_no_patch_overflow() { + let version = "0.0.98765432109876543210"; + + let parsed = version::parse(version); + + assert!(parsed.is_err(), "98765432109876543210 incorrectly considered a valid patch version"); + } + + #[test] + fn parse_basic_prerelease() { + let version = "1.2.3-pre"; + + let parsed = version::parse(version).unwrap(); + + let expected_pre = vec![Identifier::AlphaNumeric(String::from("pre"))]; + assert_eq!(expected_pre, parsed.pre); + } + + #[test] + fn parse_prerelease_alphanumeric() { + let version = "1.2.3-alpha1"; + + let parsed = version::parse(version).unwrap(); + + let expected_pre = vec![Identifier::AlphaNumeric(String::from("alpha1"))]; + assert_eq!(expected_pre, parsed.pre); + } + + #[test] + fn parse_prerelease_zero() { + let version = "1.2.3-pre.0"; + + let parsed = version::parse(version).unwrap(); + + let expected_pre = vec![Identifier::AlphaNumeric(String::from("pre")), + Identifier::Numeric(0)]; + assert_eq!(expected_pre, parsed.pre); + } + + #[test] + fn parse_basic_build() { + let version = "1.2.3+build"; + + let parsed = version::parse(version).unwrap(); + + let expected_build = vec![Identifier::AlphaNumeric(String::from("build"))]; + assert_eq!(expected_build, parsed.build); + } + + #[test] + fn parse_build_alphanumeric() { + let version = "1.2.3+build5"; + + let parsed = version::parse(version).unwrap(); + + let expected_build = vec![Identifier::AlphaNumeric(String::from("build5"))]; + assert_eq!(expected_build, parsed.build); + } + + #[test] + fn parse_pre_and_build() { + let version = "1.2.3-alpha1+build5"; + + let parsed = version::parse(version).unwrap(); + + let expected_pre = vec![Identifier::AlphaNumeric(String::from("alpha1"))]; + assert_eq!(expected_pre, parsed.pre); + + let expected_build = vec![Identifier::AlphaNumeric(String::from("build5"))]; + assert_eq!(expected_build, parsed.build); + } + + #[test] + fn parse_complex_metadata_01() { + let version = "1.2.3-1.alpha1.9+build5.7.3aedf "; + + let parsed = version::parse(version).unwrap(); + + let expected_pre = vec![Identifier::Numeric(1), + Identifier::AlphaNumeric(String::from("alpha1")), + Identifier::Numeric(9)]; + assert_eq!(expected_pre, parsed.pre); + + let expected_build = vec![Identifier::AlphaNumeric(String::from("build5")), + Identifier::Numeric(7), + Identifier::AlphaNumeric(String::from("3aedf"))]; + assert_eq!(expected_build, parsed.build); + } + + #[test] + fn parse_complex_metadata_02() { + let version = "0.4.0-beta.1+0851523"; + + let parsed = version::parse(version).unwrap(); + + let expected_pre = vec![Identifier::AlphaNumeric(String::from("beta")), + Identifier::Numeric(1)]; + assert_eq!(expected_pre, parsed.pre); + + let expected_build = vec![Identifier::AlphaNumeric(String::from("0851523"))]; + assert_eq!(expected_build, parsed.build); + } + + #[test] + fn parse_metadata_overflow() { + let version = "0.4.0-beta.1+98765432109876543210"; + + let parsed = version::parse(version).unwrap(); + + let expected_pre = vec![Identifier::AlphaNumeric(String::from("beta")), + Identifier::Numeric(1)]; + assert_eq!(expected_pre, parsed.pre); + + let expected_build = vec![Identifier::AlphaNumeric(String::from("98765432109876543210"))]; + assert_eq!(expected_build, parsed.build); + } + + #[test] + fn parse_regression_01() { + let version = "0.0.0-WIP"; + + let parsed = version::parse(version).unwrap(); + + assert_eq!(0, parsed.major); + assert_eq!(0, parsed.minor); + assert_eq!(0, parsed.patch); + + let expected_pre = vec![Identifier::AlphaNumeric(String::from("WIP"))]; + assert_eq!(expected_pre, parsed.pre); + } +} diff --git a/bitbox02-bt/vendor/semver/.cargo-checksum.json b/bitbox02-bt/vendor/semver/.cargo-checksum.json new file mode 100644 index 0000000..2f9af6e --- /dev/null +++ b/bitbox02-bt/vendor/semver/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"a5b995796b5559de8975a6fee7166c9fda6c21b449ec90bef5f9baaeddd479a5","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"c780d8c3c802c5fe2c316127900385010c3e57f71c851eea9e8ed8495e2030dd","src/lib.rs":"cb1725a8bb90c1043f187c6ba504d0a9d07793e2f39f5205f926c58849311770","src/version.rs":"ffdf9c628597b889f149f3b2b1245b97c774eae1ce7030bd19235eabecaaede0","src/version_req.rs":"40d20720f5fdc0b3d9e398e64eb448a65987229bd322cab0fedf0cf1843f3bd8","tests/deprecation.rs":"b5ec79e19d61968d05b96b876c449e54d43cbd1762c6e63c23c3470f9db56292","tests/regression.rs":"180b699ad029b81e6135d42f0a8e6d782177bc29a41132f875ee6f8607a46b56","tests/serde.rs":"cdbbefc576ffcc814c30dad9598ab87a7fd9d14c5f42f1349e1db6afc72f8fed"},"package":"1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/semver/Cargo.toml b/bitbox02-bt/vendor/semver/Cargo.toml new file mode 100644 index 0000000..7749f76 --- /dev/null +++ b/bitbox02-bt/vendor/semver/Cargo.toml @@ -0,0 +1,45 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "semver" +version = "0.9.0" +authors = ["Steve Klabnik ", "The Rust Project Developers"] +description = "Semantic version parsing and comparison.\n" +homepage = "https://docs.rs/crate/semver/" +documentation = "https://docs.rs/crate/semver/" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/steveklabnik/semver" +[dependencies.semver-parser] +version = "0.7.0" + +[dependencies.serde] +version = "1.0" +optional = true +[dev-dependencies.crates-index] +version = "0.5.0" + +[dev-dependencies.serde_json] +version = "1.0" + +[dev-dependencies.serde_derive] +version = "1.0" + +[dev-dependencies.tempdir] +version = "0.3.4" + +[features] +default = [] +ci = ["serde"] +[badges.travis-ci] +repository = "steveklabnik/semver" diff --git a/bitbox02-bt/vendor/semver/LICENSE-APACHE b/bitbox02-bt/vendor/semver/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/semver/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/semver/LICENSE-MIT b/bitbox02-bt/vendor/semver/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/bitbox02-bt/vendor/semver/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/semver/README.md b/bitbox02-bt/vendor/semver/README.md new file mode 100644 index 0000000..2a5306d --- /dev/null +++ b/bitbox02-bt/vendor/semver/README.md @@ -0,0 +1,103 @@ +semver +====== + +Semantic version parsing and comparison. + +[![Build Status](https://api.travis-ci.org/steveklabnik/semver.svg?branch=master)](https://travis-ci.org/steveklabnik/semver) + +[Documentation](https://steveklabnik.github.io/semver) + +Semantic versioning (see http://semver.org/) is a set of rules for +assigning version numbers. + +## SemVer and the Rust ecosystem + +Rust itself follows the SemVer specification, as does its standard libraries. The two are +not tied together. + +[Cargo](https://crates.io), Rust's package manager, uses SemVer to determine which versions of +packages you need installed. + +## Installation + +To use `semver`, add this to your `[dependencies]` section: + +```toml +semver = "0.7.0" +``` + +And this to your crate root: + +```rust +extern crate semver; +``` + +## Versions + +At its simplest, the `semver` crate allows you to construct `Version` objects using the `parse` +method: + +```rust +use semver::Version; + +assert!(Version::parse("1.2.3") == Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec!(), + build: vec!(), +})); +``` + +If you have multiple `Version`s, you can use the usual comparison operators to compare them: + +```rust +use semver::Version; + +assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); +assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); +``` + +## Requirements + +The `semver` crate also provides the ability to compare requirements, which are more complex +comparisons. + +For example, creating a requirement that only matches versions greater than or +equal to 1.0.0: + +```rust +use semver::Version; +use semver::VersionReq; + +let r = VersionReq::parse(">= 1.0.0").unwrap(); +let v = Version::parse("1.0.0").unwrap(); + +assert!(r.to_string() == ">= 1.0.0".to_string()); +assert!(r.matches(&v)) +``` + +It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at +https://www.npmjs.org/doc/misc/semver.html + +**Tilde requirements** specify a minimal version with some updates: + +```notrust +~1.2.3 := >=1.2.3 <1.3.0 +~1.2 := >=1.2.0 <1.3.0 +~1 := >=1.0.0 <2.0.0 +``` + +**Caret requirements** allow SemVer compatible updates to a specified version, +`0.x` and `0.x+1` are not considered compatible, but `1.x` and `1.x+1` are. + +`0.0.x` is not considered compatible with any other version. +Missing minor and patch versions are desugared to `0` but allow flexibility for that value. + +```notrust +^1.2.3 := >=1.2.3 <2.0.0 +^0.2.3 := >=0.2.3 <0.3.0 +^0.0.3 := >=0.0.3 <0.0.4 +^0.0 := >=0.0.0 <0.1.0 +^0 := >=0.0.0 <1.0.0 +``` diff --git a/bitbox02-bt/vendor/semver/src/lib.rs b/bitbox02-bt/vendor/semver/src/lib.rs new file mode 100644 index 0000000..a38aae0 --- /dev/null +++ b/bitbox02-bt/vendor/semver/src/lib.rs @@ -0,0 +1,182 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Semantic version parsing and comparison. +//! +//! Semantic versioning (see http://semver.org/) is a set of rules for +//! assigning version numbers. +//! +//! ## SemVer overview +//! +//! Given a version number MAJOR.MINOR.PATCH, increment the: +//! +//! 1. MAJOR version when you make incompatible API changes, +//! 2. MINOR version when you add functionality in a backwards-compatible +//! manner, and +//! 3. PATCH version when you make backwards-compatible bug fixes. +//! +//! Additional labels for pre-release and build metadata are available as +//! extensions to the MAJOR.MINOR.PATCH format. +//! +//! Any references to 'the spec' in this documentation refer to [version 2.0 of +//! the SemVer spec](http://semver.org/spec/v2.0.0.html). +//! +//! ## SemVer and the Rust ecosystem +//! +//! Rust itself follows the SemVer specification, as does its standard +//! libraries. The two are not tied together. +//! +//! [Cargo](http://crates.io), Rust's package manager, uses SemVer to determine +//! which versions of packages you need installed. +//! +//! ## Versions +//! +//! At its simplest, the `semver` crate allows you to construct `Version` +//! objects using the `parse` method: +//! +//! ```{rust} +//! use semver::Version; +//! +//! assert!(Version::parse("1.2.3") == Ok(Version { +//! major: 1, +//! minor: 2, +//! patch: 3, +//! pre: vec!(), +//! build: vec!(), +//! })); +//! ``` +//! +//! If you have multiple `Version`s, you can use the usual comparison operators +//! to compare them: +//! +//! ```{rust} +//! use semver::Version; +//! +//! assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); +//! assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); +//! ``` +//! +//! If you explicitly need to modify a Version, SemVer also allows you to +//! increment the major, minor, and patch numbers in accordance with the spec. +//! +//! Please note that in order to do this, you must use a mutable Version: +//! +//! ```{rust} +//! use semver::Version; +//! +//! let mut bugfix_release = Version::parse("1.0.0").unwrap(); +//! bugfix_release.increment_patch(); +//! +//! assert_eq!(Ok(bugfix_release), Version::parse("1.0.1")); +//! ``` +//! +//! When incrementing the minor version number, the patch number resets to zero +//! (in accordance with section 7 of the spec) +//! +//! ```{rust} +//! use semver::Version; +//! +//! let mut feature_release = Version::parse("1.4.6").unwrap(); +//! feature_release.increment_minor(); +//! +//! assert_eq!(Ok(feature_release), Version::parse("1.5.0")); +//! ``` +//! +//! Similarly, when incrementing the major version number, the patch and minor +//! numbers reset to zero (in accordance with section 8 of the spec) +//! +//! ```{rust} +//! use semver::Version; +//! +//! let mut chrome_release = Version::parse("41.5.5377").unwrap(); +//! chrome_release.increment_major(); +//! +//! assert_eq!(Ok(chrome_release), Version::parse("42.0.0")); +//! ``` +//! +//! ## Requirements +//! +//! The `semver` crate also provides the ability to compare requirements, which +//! are more complex comparisons. +//! +//! For example, creating a requirement that only matches versions greater than +//! or equal to 1.0.0: +//! +//! ```{rust} +//! # #![allow(unstable)] +//! use semver::Version; +//! use semver::VersionReq; +//! +//! let r = VersionReq::parse(">= 1.0.0").unwrap(); +//! let v = Version::parse("1.0.0").unwrap(); +//! +//! assert!(r.to_string() == ">= 1.0.0".to_string()); +//! assert!(r.matches(&v)) +//! ``` +//! +//! It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at +//! https://www.npmjs.org/doc/misc/semver.html +//! +//! **Tilde requirements** specify a minimal version with some updates: +//! +//! ```notrust +//! ~1.2.3 := >=1.2.3 <1.3.0 +//! ~1.2 := >=1.2.0 <1.3.0 +//! ~1 := >=1.0.0 <2.0.0 +//! ``` +//! +//! **Caret requirements** allow SemVer compatible updates to a specified +//! verion, `0.x` and `0.x+1` are not considered compatible, but `1.x` and +//! `1.x+1` are. +//! +//! `0.0.x` is not considered compatible with any other version. +//! Missing minor and patch versions are desugared to `0` but allow flexibility +//! for that value. +//! +//! ```notrust +//! ^1.2.3 := >=1.2.3 <2.0.0 +//! ^0.2.3 := >=0.2.3 <0.3.0 +//! ^0.0.3 := >=0.0.3 <0.0.4 +//! ^0.0 := >=0.0.0 <0.1.0 +//! ^0 := >=0.0.0 <1.0.0 +//! ``` +//! +//! **Wildcard requirements** allows parsing of version requirements of the +//! formats `*`, `x.*` and `x.y.*`. +//! +//! ```notrust +//! * := >=0.0.0 +//! 1.* := >=1.0.0 <2.0.0 +//! 1.2.* := >=1.2.0 <1.3.0 +//! ``` + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico")] +#![deny(missing_docs)] +#![cfg_attr(test, deny(warnings))] + +extern crate semver_parser; + +// Serialization and deserialization support for version numbers +#[cfg(feature = "serde")] +extern crate serde; + +// We take the common approach of keeping our own module system private, and +// just re-exporting the interface that we want. + +pub use version::{Version, Identifier, SemVerError}; +pub use version::Identifier::{Numeric, AlphaNumeric}; +pub use version_req::{VersionReq, ReqParseError}; + +// SemVer-compliant versions. +mod version; + +// advanced version comparisons +mod version_req; diff --git a/bitbox02-bt/vendor/semver/src/version.rs b/bitbox02-bt/vendor/semver/src/version.rs new file mode 100644 index 0000000..38de133 --- /dev/null +++ b/bitbox02-bt/vendor/semver/src/version.rs @@ -0,0 +1,759 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The `version` module gives you tools to create and compare SemVer-compliant +//! versions. + +use std::cmp::{self, Ordering}; +use std::fmt; +use std::hash; +use std::error::Error; + +use std::result; +use std::str; + +use semver_parser; + +#[cfg(feature = "serde")] +use serde::ser::{Serialize, Serializer}; +#[cfg(feature = "serde")] +use serde::de::{self, Deserialize, Deserializer, Visitor}; + +/// An identifier in the pre-release or build metadata. +/// +/// See sections 9 and 10 of the spec for more about pre-release identifers and +/// build metadata. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub enum Identifier { + /// An identifier that's solely numbers. + Numeric(u64), + /// An identifier with letters and numbers. + AlphaNumeric(String), +} + +impl From for Identifier { + fn from(other: semver_parser::version::Identifier) -> Identifier { + match other { + semver_parser::version::Identifier::Numeric(n) => Identifier::Numeric(n), + semver_parser::version::Identifier::AlphaNumeric(s) => Identifier::AlphaNumeric(s), + } + } +} + +impl fmt::Display for Identifier { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Identifier::Numeric(ref n) => fmt::Display::fmt(n, f), + Identifier::AlphaNumeric(ref s) => fmt::Display::fmt(s, f), + } + } +} + +#[cfg(feature = "serde")] +impl Serialize for Identifier { + fn serialize(&self, serializer: S) -> result::Result + where S: Serializer + { + // Serialize Identifier as a number or string. + match *self { + Identifier::Numeric(n) => serializer.serialize_u64(n), + Identifier::AlphaNumeric(ref s) => serializer.serialize_str(s), + } + } +} + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for Identifier { + fn deserialize(deserializer: D) -> result::Result + where D: Deserializer<'de> + { + struct IdentifierVisitor; + + // Deserialize Identifier from a number or string. + impl<'de> Visitor<'de> for IdentifierVisitor { + type Value = Identifier; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a SemVer pre-release or build identifier") + } + + fn visit_u64(self, numeric: u64) -> result::Result + where E: de::Error + { + Ok(Identifier::Numeric(numeric)) + } + + fn visit_str(self, alphanumeric: &str) -> result::Result + where E: de::Error + { + Ok(Identifier::AlphaNumeric(alphanumeric.to_owned())) + } + } + + deserializer.deserialize_any(IdentifierVisitor) + } +} + +/// Represents a version number conforming to the semantic versioning scheme. +#[derive(Clone, Eq, Debug)] +pub struct Version { + /// The major version, to be incremented on incompatible changes. + pub major: u64, + /// The minor version, to be incremented when functionality is added in a + /// backwards-compatible manner. + pub minor: u64, + /// The patch version, to be incremented when backwards-compatible bug + /// fixes are made. + pub patch: u64, + /// The pre-release version identifier, if one exists. + pub pre: Vec, + /// The build metadata, ignored when determining version precedence. + pub build: Vec, +} + +impl From for Version { + fn from(other: semver_parser::version::Version) -> Version { + Version { + major: other.major, + minor: other.minor, + patch: other.patch, + pre: other.pre.into_iter().map(From::from).collect(), + build: other.build.into_iter().map(From::from).collect(), + } + } +} + +#[cfg(feature = "serde")] +impl Serialize for Version { + fn serialize(&self, serializer: S) -> result::Result + where S: Serializer + { + // Serialize Version as a string. + serializer.collect_str(self) + } +} + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for Version { + fn deserialize(deserializer: D) -> result::Result + where D: Deserializer<'de> + { + struct VersionVisitor; + + // Deserialize Version from a string. + impl<'de> Visitor<'de> for VersionVisitor { + type Value = Version; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a SemVer version as a string") + } + + fn visit_str(self, v: &str) -> result::Result + where E: de::Error + { + Version::parse(v).map_err(de::Error::custom) + } + } + + deserializer.deserialize_str(VersionVisitor) + } +} + +/// An error type for this crate +/// +/// Currently, just a generic error. Will make this nicer later. +#[derive(Clone,PartialEq,Debug,PartialOrd)] +pub enum SemVerError { + /// An error ocurred while parsing. + ParseError(String), +} + +impl fmt::Display for SemVerError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + &SemVerError::ParseError(ref m) => write!(f, "{}", m), + } + } +} + +impl Error for SemVerError { + fn description(&self) -> &str { + match self { + &SemVerError::ParseError(ref m) => m, + } + } +} + +/// A Result type for errors +pub type Result = result::Result; + +impl Version { + + /// Contructs the simple case without pre or build. + pub fn new(major: u64, minor: u64, patch: u64) -> Version { + Version { + major: major, + minor: minor, + patch: patch, + pre: Vec::new(), + build: Vec::new() + } + } + + /// Parse a string into a semver object. + pub fn parse(version: &str) -> Result { + let res = semver_parser::version::parse(version); + + match res { + // Convert plain String error into proper ParseError + Err(e) => Err(SemVerError::ParseError(e)), + Ok(v) => Ok(From::from(v)), + } + } + + /// Clears the build metadata + fn clear_metadata(&mut self) { + self.build = Vec::new(); + self.pre = Vec::new(); + } + + /// Increments the patch number for this Version (Must be mutable) + pub fn increment_patch(&mut self) { + self.patch += 1; + self.clear_metadata(); + } + + /// Increments the minor version number for this Version (Must be mutable) + /// + /// As instructed by section 7 of the spec, the patch number is reset to 0. + pub fn increment_minor(&mut self) { + self.minor += 1; + self.patch = 0; + self.clear_metadata(); + } + + /// Increments the major version number for this Version (Must be mutable) + /// + /// As instructed by section 8 of the spec, the minor and patch numbers are + /// reset to 0 + pub fn increment_major(&mut self) { + self.major += 1; + self.minor = 0; + self.patch = 0; + self.clear_metadata(); + } + + /// Checks to see if the current Version is in pre-release status + pub fn is_prerelease(&self) -> bool { + !self.pre.is_empty() + } +} + +impl str::FromStr for Version { + type Err = SemVerError; + + fn from_str(s: &str) -> Result { + Version::parse(s) + } +} + +impl fmt::Display for Version { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)); + if !self.pre.is_empty() { + try!(write!(f, "-")); + for (i, x) in self.pre.iter().enumerate() { + if i != 0 { + try!(write!(f, ".")) + } + try!(write!(f, "{}", x)); + } + } + if !self.build.is_empty() { + try!(write!(f, "+")); + for (i, x) in self.build.iter().enumerate() { + if i != 0 { + try!(write!(f, ".")) + } + try!(write!(f, "{}", x)); + } + } + Ok(()) + } +} + +impl cmp::PartialEq for Version { + #[inline] + fn eq(&self, other: &Version) -> bool { + // We should ignore build metadata here, otherwise versions v1 and v2 + // can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which + // violate strict total ordering rules. + self.major == other.major && self.minor == other.minor && self.patch == other.patch && + self.pre == other.pre + } +} + +impl cmp::PartialOrd for Version { + fn partial_cmp(&self, other: &Version) -> Option { + Some(self.cmp(other)) + } +} + +impl cmp::Ord for Version { + fn cmp(&self, other: &Version) -> Ordering { + match self.major.cmp(&other.major) { + Ordering::Equal => {} + r => return r, + } + + match self.minor.cmp(&other.minor) { + Ordering::Equal => {} + r => return r, + } + + match self.patch.cmp(&other.patch) { + Ordering::Equal => {} + r => return r, + } + + // NB: semver spec says 0.0.0-pre < 0.0.0 + // but the version of ord defined for vec + // says that [] < [pre] so we alter it here + match (self.pre.len(), other.pre.len()) { + (0, 0) => Ordering::Equal, + (0, _) => Ordering::Greater, + (_, 0) => Ordering::Less, + (_, _) => self.pre.cmp(&other.pre), + } + } +} + +impl hash::Hash for Version { + fn hash(&self, into: &mut H) { + self.major.hash(into); + self.minor.hash(into); + self.patch.hash(into); + self.pre.hash(into); + } +} + +impl From<(u64,u64,u64)> for Version { + fn from(tuple: (u64,u64,u64)) -> Version { + let (major, minor, patch) = tuple; + Version::new(major, minor, patch) + } +} + +#[cfg(test)] +mod tests { + use std::result; + use super::Version; + use super::Identifier; + use super::SemVerError; + + #[test] + fn test_parse() { + fn parse_error(e: &str) -> result::Result { + return Err(SemVerError::ParseError(e.to_string())); + } + + assert_eq!(Version::parse(""), + parse_error("Error parsing major identifier")); + assert_eq!(Version::parse(" "), + parse_error("Error parsing major identifier")); + assert_eq!(Version::parse("1"), + parse_error("Expected dot")); + assert_eq!(Version::parse("1.2"), + parse_error("Expected dot")); + assert_eq!(Version::parse("1.2.3-"), + parse_error("Error parsing prerelease")); + assert_eq!(Version::parse("a.b.c"), + parse_error("Error parsing major identifier")); + assert_eq!(Version::parse("1.2.3 abc"), + parse_error("Extra junk after valid version: abc")); + + assert_eq!(Version::parse("1.2.3"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + + assert_eq!(Version::parse("1.2.3"), + Ok(Version::new(1,2,3))); + + assert_eq!(Version::parse(" 1.2.3 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + assert_eq!(Version::parse("1.2.3-alpha1"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!(Version::parse(" 1.2.3-alpha1 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!(Version::parse("1.2.3+build5"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse(" 1.2.3+build5 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse("1.2.3-alpha1+build5"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse(" 1.2.3-alpha1+build5 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse("1.2.3-1.alpha1.9+build5.7.3aedf "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::Numeric(1), + Identifier::AlphaNumeric(String::from("alpha1")), + Identifier::Numeric(9), + ], + build: vec![Identifier::AlphaNumeric(String::from("build5")), + Identifier::Numeric(7), + Identifier::AlphaNumeric(String::from("3aedf")), + ], + })); + assert_eq!(Version::parse("0.4.0-beta.1+0851523"), + Ok(Version { + major: 0, + minor: 4, + patch: 0, + pre: vec![Identifier::AlphaNumeric(String::from("beta")), + Identifier::Numeric(1), + ], + build: vec![Identifier::AlphaNumeric(String::from("0851523"))], + })); + + } + + #[test] + fn test_increment_patch() { + let mut buggy_release = Version::parse("0.1.0").unwrap(); + buggy_release.increment_patch(); + assert_eq!(buggy_release, Version::parse("0.1.1").unwrap()); + } + + #[test] + fn test_increment_minor() { + let mut feature_release = Version::parse("1.4.6").unwrap(); + feature_release.increment_minor(); + assert_eq!(feature_release, Version::parse("1.5.0").unwrap()); + } + + #[test] + fn test_increment_major() { + let mut chrome_release = Version::parse("46.1.246773").unwrap(); + chrome_release.increment_major(); + assert_eq!(chrome_release, Version::parse("47.0.0").unwrap()); + } + + #[test] + fn test_increment_keep_prerelease() { + let mut release = Version::parse("1.0.0-alpha").unwrap(); + release.increment_patch(); + + assert_eq!(release, Version::parse("1.0.1").unwrap()); + + release.increment_minor(); + + assert_eq!(release, Version::parse("1.1.0").unwrap()); + + release.increment_major(); + + assert_eq!(release, Version::parse("2.0.0").unwrap()); + } + + + #[test] + fn test_increment_clear_metadata() { + let mut release = Version::parse("1.0.0+4442").unwrap(); + release.increment_patch(); + + assert_eq!(release, Version::parse("1.0.1").unwrap()); + release = Version::parse("1.0.1+hello").unwrap(); + + release.increment_minor(); + + assert_eq!(release, Version::parse("1.1.0").unwrap()); + release = Version::parse("1.1.3747+hello").unwrap(); + + release.increment_major(); + + assert_eq!(release, Version::parse("2.0.0").unwrap()); + } + + #[test] + fn test_eq() { + assert_eq!(Version::parse("1.2.3"), Version::parse("1.2.3")); + assert_eq!(Version::parse("1.2.3-alpha1"), + Version::parse("1.2.3-alpha1")); + assert_eq!(Version::parse("1.2.3+build.42"), + Version::parse("1.2.3+build.42")); + assert_eq!(Version::parse("1.2.3-alpha1+42"), + Version::parse("1.2.3-alpha1+42")); + assert_eq!(Version::parse("1.2.3+23"), Version::parse("1.2.3+42")); + } + + #[test] + fn test_ne() { + assert!(Version::parse("0.0.0") != Version::parse("0.0.1")); + assert!(Version::parse("0.0.0") != Version::parse("0.1.0")); + assert!(Version::parse("0.0.0") != Version::parse("1.0.0")); + assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); + } + + #[test] + fn test_show() { + assert_eq!(format!("{}", Version::parse("1.2.3").unwrap()), + "1.2.3".to_string()); + assert_eq!(format!("{}", Version::parse("1.2.3-alpha1").unwrap()), + "1.2.3-alpha1".to_string()); + assert_eq!(format!("{}", Version::parse("1.2.3+build.42").unwrap()), + "1.2.3+build.42".to_string()); + assert_eq!(format!("{}", Version::parse("1.2.3-alpha1+42").unwrap()), + "1.2.3-alpha1+42".to_string()); + } + + #[test] + fn test_to_string() { + assert_eq!(Version::parse("1.2.3").unwrap().to_string(), + "1.2.3".to_string()); + assert_eq!(Version::parse("1.2.3-alpha1").unwrap().to_string(), + "1.2.3-alpha1".to_string()); + assert_eq!(Version::parse("1.2.3+build.42").unwrap().to_string(), + "1.2.3+build.42".to_string()); + assert_eq!(Version::parse("1.2.3-alpha1+42").unwrap().to_string(), + "1.2.3-alpha1+42".to_string()); + } + + #[test] + fn test_lt() { + assert!(Version::parse("0.0.0") < Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.0.0") < Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.0") < Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3")); + assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3-alpha2")); + assert!(!(Version::parse("1.2.3-alpha2") < Version::parse("1.2.3-alpha2"))); + assert!(!(Version::parse("1.2.3+23") < Version::parse("1.2.3+42"))); + } + + #[test] + fn test_le() { + assert!(Version::parse("0.0.0") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.0.0") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.0") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3-alpha1") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3-alpha2") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3+23") <= Version::parse("1.2.3+42")); + } + + #[test] + fn test_gt() { + assert!(Version::parse("1.2.3-alpha2") > Version::parse("0.0.0")); + assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.0.0")); + assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); + assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha1")); + assert!(Version::parse("1.2.3") > Version::parse("1.2.3-alpha2")); + assert!(!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha2"))); + assert!(!(Version::parse("1.2.3+23") > Version::parse("1.2.3+42"))); + } + + #[test] + fn test_ge() { + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("0.0.0")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.0.0")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.0")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha1")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3+23") >= Version::parse("1.2.3+42")); + } + + #[test] + fn test_prerelease_check() { + assert!(Version::parse("1.0.0").unwrap().is_prerelease() == false); + assert!(Version::parse("0.0.1").unwrap().is_prerelease() == false); + assert!(Version::parse("4.1.4-alpha").unwrap().is_prerelease()); + assert!(Version::parse("1.0.0-beta294296").unwrap().is_prerelease()); + } + + #[test] + fn test_spec_order() { + let vs = ["1.0.0-alpha", + "1.0.0-alpha.1", + "1.0.0-alpha.beta", + "1.0.0-beta", + "1.0.0-beta.2", + "1.0.0-beta.11", + "1.0.0-rc.1", + "1.0.0"]; + let mut i = 1; + while i < vs.len() { + let a = Version::parse(vs[i - 1]); + let b = Version::parse(vs[i]); + assert!(a < b, "nope {:?} < {:?}", a, b); + i += 1; + } + } + + #[test] + fn test_from_str() { + assert_eq!("1.2.3".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + assert_eq!(" 1.2.3 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + assert_eq!("1.2.3-alpha1".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!(" 1.2.3-alpha1 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!("1.2.3+build5".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(" 1.2.3+build5 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!("1.2.3-alpha1+build5".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(" 1.2.3-alpha1+build5 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!("1.2.3-1.alpha1.9+build5.7.3aedf ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::Numeric(1), + Identifier::AlphaNumeric(String::from("alpha1")), + Identifier::Numeric(9), + ], + build: vec![Identifier::AlphaNumeric(String::from("build5")), + Identifier::Numeric(7), + Identifier::AlphaNumeric(String::from("3aedf")), + ], + })); + assert_eq!("0.4.0-beta.1+0851523".parse(), + Ok(Version { + major: 0, + minor: 4, + patch: 0, + pre: vec![Identifier::AlphaNumeric(String::from("beta")), + Identifier::Numeric(1), + ], + build: vec![Identifier::AlphaNumeric(String::from("0851523"))], + })); + + } + + #[test] + fn test_from_str_errors() { + fn parse_error(e: &str) -> result::Result { + return Err(SemVerError::ParseError(e.to_string())); + } + + assert_eq!("".parse(), parse_error("Error parsing major identifier")); + assert_eq!(" ".parse(), parse_error("Error parsing major identifier")); + assert_eq!("1".parse(), parse_error("Expected dot")); + assert_eq!("1.2".parse(), + parse_error("Expected dot")); + assert_eq!("1.2.3-".parse(), + parse_error("Error parsing prerelease")); + assert_eq!("a.b.c".parse(), + parse_error("Error parsing major identifier")); + assert_eq!("1.2.3 abc".parse(), + parse_error("Extra junk after valid version: abc")); + } +} diff --git a/bitbox02-bt/vendor/semver/src/version_req.rs b/bitbox02-bt/vendor/semver/src/version_req.rs new file mode 100644 index 0000000..6e6a542 --- /dev/null +++ b/bitbox02-bt/vendor/semver/src/version_req.rs @@ -0,0 +1,895 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::error::Error; +use std::fmt; +use std::result; +use std::str; + +use Version; +use version::Identifier; +use semver_parser; + +#[cfg(feature = "serde")] +use serde::ser::{Serialize, Serializer}; +#[cfg(feature = "serde")] +use serde::de::{self, Deserialize, Deserializer, Visitor}; + +use self::Op::{Ex, Gt, GtEq, Lt, LtEq, Tilde, Compatible, Wildcard}; +use self::WildcardVersion::{Major, Minor, Patch}; +use self::ReqParseError::*; + +/// A `VersionReq` is a struct containing a list of predicates that can apply to ranges of version +/// numbers. Matching operations can then be done with the `VersionReq` against a particular +/// version to see if it satisfies some or all of the constraints. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct VersionReq { + predicates: Vec, +} + +impl From for VersionReq { + fn from(other: semver_parser::range::VersionReq) -> VersionReq { + VersionReq { predicates: other.predicates.into_iter().map(From::from).collect() } + } +} + +#[cfg(feature = "serde")] +impl Serialize for VersionReq { + fn serialize(&self, serializer: S) -> result::Result + where S: Serializer + { + // Serialize VersionReq as a string. + serializer.collect_str(self) + } +} + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for VersionReq { + fn deserialize(deserializer: D) -> result::Result + where D: Deserializer<'de> + { + struct VersionReqVisitor; + + /// Deserialize `VersionReq` from a string. + impl<'de> Visitor<'de> for VersionReqVisitor { + type Value = VersionReq; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a SemVer version requirement as a string") + } + + fn visit_str(self, v: &str) -> result::Result + where E: de::Error + { + VersionReq::parse(v).map_err(de::Error::custom) + } + } + + deserializer.deserialize_str(VersionReqVisitor) + } +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +enum WildcardVersion { + Major, + Minor, + Patch, +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +enum Op { + Ex, // Exact + Gt, // Greater than + GtEq, // Greater than or equal to + Lt, // Less than + LtEq, // Less than or equal to + Tilde, // e.g. ~1.0.0 + Compatible, // compatible by definition of semver, indicated by ^ + Wildcard(WildcardVersion), // x.y.*, x.*, * +} + +impl From for Op { + fn from(other: semver_parser::range::Op) -> Op { + use semver_parser::range; + match other { + range::Op::Ex => Op::Ex, + range::Op::Gt => Op::Gt, + range::Op::GtEq => Op::GtEq, + range::Op::Lt => Op::Lt, + range::Op::LtEq => Op::LtEq, + range::Op::Tilde => Op::Tilde, + range::Op::Compatible => Op::Compatible, + range::Op::Wildcard(version) => { + match version { + range::WildcardVersion::Major => Op::Wildcard(WildcardVersion::Major), + range::WildcardVersion::Minor => Op::Wildcard(WildcardVersion::Minor), + range::WildcardVersion::Patch => Op::Wildcard(WildcardVersion::Patch), + } + } + } + } +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +struct Predicate { + op: Op, + major: u64, + minor: Option, + patch: Option, + pre: Vec, +} + +impl From for Predicate { + fn from(other: semver_parser::range::Predicate) -> Predicate { + Predicate { + op: From::from(other.op), + major: other.major, + minor: other.minor, + patch: other.patch, + pre: other.pre.into_iter().map(From::from).collect(), + } + } +} + +/// A `ReqParseError` is returned from methods which parse a string into a `VersionReq`. Each +/// enumeration is one of the possible errors that can occur. +#[derive(Clone, Debug, PartialEq)] +pub enum ReqParseError { + /// The given version requirement is invalid. + InvalidVersionRequirement, + /// You have already provided an operation, such as `=`, `~`, or `^`. Only use one. + OpAlreadySet, + /// The sigil you have written is not correct. + InvalidSigil, + /// All components of a version must be numeric. + VersionComponentsMustBeNumeric, + /// There was an error parsing an identifier. + InvalidIdentifier, + /// At least a major version is required. + MajorVersionRequired, + /// An unimplemented version requirement. + UnimplementedVersionRequirement, + /// This form of requirement is deprecated. + DeprecatedVersionRequirement(VersionReq), +} + +impl fmt::Display for ReqParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + +impl Error for ReqParseError { + fn description(&self) -> &str { + match self { + &InvalidVersionRequirement => "the given version requirement is invalid", + &OpAlreadySet => { + "you have already provided an operation, such as =, ~, or ^; only use one" + }, + &InvalidSigil => "the sigil you have written is not correct", + &VersionComponentsMustBeNumeric => "version components must be numeric", + &InvalidIdentifier => "invalid identifier", + &MajorVersionRequired => "at least a major version number is required", + &UnimplementedVersionRequirement => { + "the given version requirement is not implemented, yet" + }, + &DeprecatedVersionRequirement(_) => "This requirement is deprecated", + } + } +} + +impl From for ReqParseError { + fn from(other: String) -> ReqParseError { + match &*other { + "Null is not a valid VersionReq" => ReqParseError::InvalidVersionRequirement, + "VersionReq did not parse properly." => ReqParseError::OpAlreadySet, + _ => ReqParseError::InvalidVersionRequirement, + } + } +} + +impl VersionReq { + /// `any()` is a factory method which creates a `VersionReq` with no constraints. In other + /// words, any version will match against it. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// + /// let anything = VersionReq::any(); + /// ``` + pub fn any() -> VersionReq { + VersionReq { predicates: vec![] } + } + + /// `parse()` is the main constructor of a `VersionReq`. It takes a string like `"^1.2.3"` + /// and turns it into a `VersionReq` that matches that particular constraint. + /// + /// A `Result` is returned which contains a `ReqParseError` if there was a problem parsing the + /// `VersionReq`. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// + /// let version = VersionReq::parse("=1.2.3"); + /// let version = VersionReq::parse(">1.2.3"); + /// let version = VersionReq::parse("<1.2.3"); + /// let version = VersionReq::parse("~1.2.3"); + /// let version = VersionReq::parse("^1.2.3"); + /// let version = VersionReq::parse("1.2.3"); // synonym for ^1.2.3 + /// let version = VersionReq::parse("<=1.2.3"); + /// let version = VersionReq::parse(">=1.2.3"); + /// ``` + /// + /// This example demonstrates error handling, and will panic. + /// + /// ```should-panic + /// use semver::VersionReq; + /// + /// let version = match VersionReq::parse("not a version") { + /// Ok(version) => version, + /// Err(e) => panic!("There was a problem parsing: {}", e), + /// } + /// ``` + pub fn parse(input: &str) -> Result { + let res = semver_parser::range::parse(input); + + if let Ok(v) = res { + return Ok(From::from(v)); + } + + return match VersionReq::parse_deprecated(input) { + Some(v) => { + Err(ReqParseError::DeprecatedVersionRequirement(v)) + } + None => Err(From::from(res.err().unwrap())), + } + } + + fn parse_deprecated(version: &str) -> Option { + return match version { + ".*" => Some(VersionReq::any()), + "0.1.0." => Some(VersionReq::parse("0.1.0").unwrap()), + "0.3.1.3" => Some(VersionReq::parse("0.3.13").unwrap()), + "0.2*" => Some(VersionReq::parse("0.2.*").unwrap()), + "*.0" => Some(VersionReq::any()), + _ => None, + } + } + + /// `exact()` is a factory method which creates a `VersionReq` with one exact constraint. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// use semver::Version; + /// + /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; + /// let exact = VersionReq::exact(&version); + /// ``` + pub fn exact(version: &Version) -> VersionReq { + VersionReq { predicates: vec![Predicate::exact(version)] } + } + + /// `matches()` matches a given `Version` against this `VersionReq`. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// use semver::Version; + /// + /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; + /// let exact = VersionReq::exact(&version); + /// + /// assert!(exact.matches(&version)); + /// ``` + pub fn matches(&self, version: &Version) -> bool { + // no predicates means anything matches + if self.predicates.is_empty() { + return true; + } + + self.predicates.iter().all(|p| p.matches(version)) && + self.predicates.iter().any(|p| p.pre_tag_is_compatible(version)) + } +} + +impl str::FromStr for VersionReq { + type Err = ReqParseError; + + fn from_str(s: &str) -> Result { + VersionReq::parse(s) + } +} + +impl Predicate { + fn exact(version: &Version) -> Predicate { + Predicate { + op: Ex, + major: version.major, + minor: Some(version.minor), + patch: Some(version.patch), + pre: version.pre.clone(), + } + } + + /// `matches()` takes a `Version` and determines if it matches this particular `Predicate`. + pub fn matches(&self, ver: &Version) -> bool { + match self.op { + Ex => self.is_exact(ver), + Gt => self.is_greater(ver), + GtEq => self.is_exact(ver) || self.is_greater(ver), + Lt => !self.is_exact(ver) && !self.is_greater(ver), + LtEq => !self.is_greater(ver), + Tilde => self.matches_tilde(ver), + Compatible => self.is_compatible(ver), + Wildcard(_) => self.matches_wildcard(ver), + } + } + + fn is_exact(&self, ver: &Version) -> bool { + if self.major != ver.major { + return false; + } + + match self.minor { + Some(minor) => { + if minor != ver.minor { + return false; + } + } + None => return true, + } + + match self.patch { + Some(patch) => { + if patch != ver.patch { + return false; + } + } + None => return true, + } + + if self.pre != ver.pre { + return false; + } + + true + } + + // https://docs.npmjs.com/misc/semver#prerelease-tags + fn pre_tag_is_compatible(&self, ver: &Version) -> bool { + // If a version has a prerelease tag (for example, 1.2.3-alpha.3) then it will + // only be + // allowed to satisfy comparator sets if at least one comparator with the same + // [major, + // minor, patch] tuple also has a prerelease tag. + !ver.is_prerelease() || + (self.major == ver.major && self.minor == Some(ver.minor) && + self.patch == Some(ver.patch) && !self.pre.is_empty()) + } + + fn is_greater(&self, ver: &Version) -> bool { + if self.major != ver.major { + return ver.major > self.major; + } + + match self.minor { + Some(minor) => { + if minor != ver.minor { + return ver.minor > minor; + } + } + None => return false, + } + + match self.patch { + Some(patch) => { + if patch != ver.patch { + return ver.patch > patch; + } + } + None => return false, + } + + if !self.pre.is_empty() { + return ver.pre.is_empty() || ver.pre > self.pre; + } + + false + } + + // see https://www.npmjs.org/doc/misc/semver.html for behavior + fn matches_tilde(&self, ver: &Version) -> bool { + let minor = match self.minor { + Some(n) => n, + None => return self.major == ver.major, + }; + + match self.patch { + Some(patch) => { + self.major == ver.major && minor == ver.minor && + (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) + } + None => self.major == ver.major && minor == ver.minor, + } + } + + // see https://www.npmjs.org/doc/misc/semver.html for behavior + fn is_compatible(&self, ver: &Version) -> bool { + if self.major != ver.major { + return false; + } + + let minor = match self.minor { + Some(n) => n, + None => return self.major == ver.major, + }; + + match self.patch { + Some(patch) => { + if self.major == 0 { + if minor == 0 { + ver.minor == minor && ver.patch == patch && self.pre_is_compatible(ver) + } else { + ver.minor == minor && + (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) + } + } else { + ver.minor > minor || + (ver.minor == minor && + (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver)))) + } + } + None => { + if self.major == 0 { + ver.minor == minor + } else { + ver.minor >= minor + } + } + } + } + + fn pre_is_compatible(&self, ver: &Version) -> bool { + ver.pre.is_empty() || ver.pre >= self.pre + } + + // see https://www.npmjs.org/doc/misc/semver.html for behavior + fn matches_wildcard(&self, ver: &Version) -> bool { + match self.op { + Wildcard(Major) => true, + Wildcard(Minor) => self.major == ver.major, + Wildcard(Patch) => { + match self.minor { + Some(minor) => self.major == ver.major && minor == ver.minor, + None => { + // minor and patch version astericks mean match on major + self.major == ver.major + } + } + } + _ => false, // unreachable + } + } +} + +impl fmt::Display for VersionReq { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + if self.predicates.is_empty() { + try!(write!(fmt, "*")); + } else { + for (i, ref pred) in self.predicates.iter().enumerate() { + if i == 0 { + try!(write!(fmt, "{}", pred)); + } else { + try!(write!(fmt, ", {}", pred)); + } + } + } + + Ok(()) + } +} + +impl fmt::Display for Predicate { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match self.op { + Wildcard(Major) => try!(write!(fmt, "*")), + Wildcard(Minor) => try!(write!(fmt, "{}.*", self.major)), + Wildcard(Patch) => { + if let Some(minor) = self.minor { + try!(write!(fmt, "{}.{}.*", self.major, minor)) + } else { + try!(write!(fmt, "{}.*.*", self.major)) + } + } + _ => { + try!(write!(fmt, "{}{}", self.op, self.major)); + + match self.minor { + Some(v) => try!(write!(fmt, ".{}", v)), + None => (), + } + + match self.patch { + Some(v) => try!(write!(fmt, ".{}", v)), + None => (), + } + + if !self.pre.is_empty() { + try!(write!(fmt, "-")); + for (i, x) in self.pre.iter().enumerate() { + if i != 0 { + try!(write!(fmt, ".")) + } + try!(write!(fmt, "{}", x)); + } + } + } + } + + Ok(()) + } +} + +impl fmt::Display for Op { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match *self { + Ex => try!(write!(fmt, "= ")), + Gt => try!(write!(fmt, "> ")), + GtEq => try!(write!(fmt, ">= ")), + Lt => try!(write!(fmt, "< ")), + LtEq => try!(write!(fmt, "<= ")), + Tilde => try!(write!(fmt, "~")), + Compatible => try!(write!(fmt, "^")), + // gets handled specially in Predicate::fmt + Wildcard(_) => try!(write!(fmt, "")), + } + Ok(()) + } +} + +#[cfg(test)] +mod test { + use super::{VersionReq, Op}; + use super::super::version::Version; + use std::hash::{Hash, Hasher}; + + fn req(s: &str) -> VersionReq { + VersionReq::parse(s).unwrap() + } + + fn version(s: &str) -> Version { + match Version::parse(s) { + Ok(v) => v, + Err(e) => panic!("`{}` is not a valid version. Reason: {:?}", s, e), + } + } + + fn assert_match(req: &VersionReq, vers: &[&str]) { + for ver in vers.iter() { + assert!(req.matches(&version(*ver)), "did not match {}", ver); + } + } + + fn assert_not_match(req: &VersionReq, vers: &[&str]) { + for ver in vers.iter() { + assert!(!req.matches(&version(*ver)), "matched {}", ver); + } + } + + fn calculate_hash(t: T) -> u64 { + use std::collections::hash_map::DefaultHasher; + + let mut s = DefaultHasher::new(); + t.hash(&mut s); + s.finish() + } + + #[test] + fn test_parsing_default() { + let r = req("1.0.0"); + + assert_eq!(r.to_string(), "^1.0.0".to_string()); + + assert_match(&r, &["1.0.0", "1.0.1"]); + assert_not_match(&r, &["0.9.9", "0.10.0", "0.1.0"]); + } + + #[test] + fn test_parsing_exact() { + let r = req("=1.0.0"); + + assert!(r.to_string() == "= 1.0.0".to_string()); + assert_eq!(r.to_string(), "= 1.0.0".to_string()); + + assert_match(&r, &["1.0.0"]); + assert_not_match(&r, &["1.0.1", "0.9.9", "0.10.0", "0.1.0", "1.0.0-pre"]); + + let r = req("=0.9.0"); + + assert_eq!(r.to_string(), "= 0.9.0".to_string()); + + assert_match(&r, &["0.9.0"]); + assert_not_match(&r, &["0.9.1", "1.9.0", "0.0.9"]); + + let r = req("=0.1.0-beta2.a"); + + assert_eq!(r.to_string(), "= 0.1.0-beta2.a".to_string()); + + assert_match(&r, &["0.1.0-beta2.a"]); + assert_not_match(&r, &["0.9.1", "0.1.0", "0.1.1-beta2.a", "0.1.0-beta2"]); + } + + #[test] + fn test_parse_metadata_see_issue_88_see_issue_88() { + for op in &[Op::Compatible, Op::Ex, Op::Gt, Op::GtEq, Op::Lt, Op::LtEq, Op::Tilde] { + req(&format!("{} 1.2.3+meta", op)); + } + } + + #[test] + pub fn test_parsing_greater_than() { + let r = req(">= 1.0.0"); + + assert_eq!(r.to_string(), ">= 1.0.0".to_string()); + + assert_match(&r, &["1.0.0", "2.0.0"]); + assert_not_match(&r, &["0.1.0", "0.0.1", "1.0.0-pre", "2.0.0-pre"]); + + let r = req(">= 2.1.0-alpha2"); + + assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha3", "2.1.0", "3.0.0"]); + assert_not_match(&r, + &["2.0.0", "2.1.0-alpha1", "2.0.0-alpha2", "3.0.0-alpha2"]); + } + + #[test] + pub fn test_parsing_less_than() { + let r = req("< 1.0.0"); + + assert_eq!(r.to_string(), "< 1.0.0".to_string()); + + assert_match(&r, &["0.1.0", "0.0.1"]); + assert_not_match(&r, &["1.0.0", "1.0.0-beta", "1.0.1", "0.9.9-alpha"]); + + let r = req("<= 2.1.0-alpha2"); + + assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha1", "2.0.0", "1.0.0"]); + assert_not_match(&r, + &["2.1.0", "2.2.0-alpha1", "2.0.0-alpha2", "1.0.0-alpha2"]); + } + + #[test] + pub fn test_multiple() { + let r = req("> 0.0.9, <= 2.5.3"); + assert_eq!(r.to_string(), "> 0.0.9, <= 2.5.3".to_string()); + assert_match(&r, &["0.0.10", "1.0.0", "2.5.3"]); + assert_not_match(&r, &["0.0.8", "2.5.4"]); + + let r = req("0.3.0, 0.4.0"); + assert_eq!(r.to_string(), "^0.3.0, ^0.4.0".to_string()); + assert_not_match(&r, &["0.0.8", "0.3.0", "0.4.0"]); + + let r = req("<= 0.2.0, >= 0.5.0"); + assert_eq!(r.to_string(), "<= 0.2.0, >= 0.5.0".to_string()); + assert_not_match(&r, &["0.0.8", "0.3.0", "0.5.1"]); + + let r = req("0.1.0, 0.1.4, 0.1.6"); + assert_eq!(r.to_string(), "^0.1.0, ^0.1.4, ^0.1.6".to_string()); + assert_match(&r, &["0.1.6", "0.1.9"]); + assert_not_match(&r, &["0.1.0", "0.1.4", "0.2.0"]); + + assert!(VersionReq::parse("> 0.1.0,").is_err()); + assert!(VersionReq::parse("> 0.3.0, ,").is_err()); + + let r = req(">=0.5.1-alpha3, <0.6"); + assert_eq!(r.to_string(), ">= 0.5.1-alpha3, < 0.6".to_string()); + assert_match(&r, + &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); + assert_not_match(&r, + &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre"]); + assert_not_match(&r, &["0.6.0", "0.6.0-pre"]); + } + + #[test] + pub fn test_parsing_tilde() { + let r = req("~1"); + assert_match(&r, &["1.0.0", "1.0.1", "1.1.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "0.0.9"]); + + let r = req("~1.2"); + assert_match(&r, &["1.2.0", "1.2.1"]); + assert_not_match(&r, &["1.1.1", "1.3.0", "0.0.9"]); + + let r = req("~1.2.2"); + assert_match(&r, &["1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.2.1", "1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + + let r = req("~1.2.3-beta.2"); + assert_match(&r, &["1.2.3", "1.2.4", "1.2.3-beta.2", "1.2.3-beta.4"]); + assert_not_match(&r, &["1.3.3", "1.1.4", "1.2.3-beta.1", "1.2.4-beta.2"]); + } + + #[test] + pub fn test_parsing_compatible() { + let r = req("^1"); + assert_match(&r, &["1.1.2", "1.1.0", "1.2.1", "1.0.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "0.1.4"]); + assert_not_match(&r, &["1.0.0-beta1", "0.1.0-alpha", "1.0.1-pre"]); + + let r = req("^1.1"); + assert_match(&r, &["1.1.2", "1.1.0", "1.2.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.0.1", "0.1.4"]); + + let r = req("^1.1.2"); + assert_match(&r, &["1.1.2", "1.1.4", "1.2.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); + assert_not_match(&r, &["1.1.2-alpha1", "1.1.3-alpha1", "2.9.0-alpha1"]); + + let r = req("^0.1.2"); + assert_match(&r, &["0.1.2", "0.1.4"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); + assert_not_match(&r, &["0.1.2-beta", "0.1.3-alpha", "0.2.0-pre"]); + + let r = req("^0.5.1-alpha3"); + assert_match(&r, + &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); + assert_not_match(&r, + &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre", "0.6.0"]); + + let r = req("^0.0.2"); + assert_match(&r, &["0.0.2"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1", "0.1.4"]); + + let r = req("^0.0"); + assert_match(&r, &["0.0.2", "0.0.0"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.1.4"]); + + let r = req("^0"); + assert_match(&r, &["0.9.1", "0.0.2", "0.0.0"]); + assert_not_match(&r, &["2.9.0", "1.1.1"]); + + let r = req("^1.4.2-beta.5"); + assert_match(&r, + &["1.4.2", "1.4.3", "1.4.2-beta.5", "1.4.2-beta.6", "1.4.2-c"]); + assert_not_match(&r, + &["0.9.9", "2.0.0", "1.4.2-alpha", "1.4.2-beta.4", "1.4.3-beta.5"]); + } + + #[test] + pub fn test_parsing_wildcard() { + let r = req(""); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + let r = req("*"); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + let r = req("x"); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + let r = req("X"); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + + let r = req("1.*"); + assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); + assert_not_match(&r, &["0.0.9"]); + let r = req("1.x"); + assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); + assert_not_match(&r, &["0.0.9"]); + let r = req("1.X"); + assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); + assert_not_match(&r, &["0.0.9"]); + + let r = req("1.2.*"); + assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + let r = req("1.2.x"); + assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + let r = req("1.2.X"); + assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + } + + #[test] + pub fn test_any() { + let r = VersionReq::any(); + assert_match(&r, &["0.0.1", "0.1.0", "1.0.0"]); + } + + #[test] + pub fn test_pre() { + let r = req("=2.1.1-really.0"); + assert_match(&r, &["2.1.1-really.0"]); + } + + // #[test] + // pub fn test_parse_errors() { + // assert_eq!(Err(InvalidVersionRequirement), VersionReq::parse("\0")); + // assert_eq!(Err(OpAlreadySet), VersionReq::parse(">= >= 0.0.2")); + // assert_eq!(Err(InvalidSigil), VersionReq::parse(">== 0.0.2")); + // assert_eq!(Err(VersionComponentsMustBeNumeric), + // VersionReq::parse("a.0.0")); + // assert_eq!(Err(InvalidIdentifier), VersionReq::parse("1.0.0-")); + // assert_eq!(Err(MajorVersionRequired), VersionReq::parse(">=")); + // } + + #[test] + pub fn test_from_str() { + assert_eq!("1.0.0".parse::().unwrap().to_string(), + "^1.0.0".to_string()); + assert_eq!("=1.0.0".parse::().unwrap().to_string(), + "= 1.0.0".to_string()); + assert_eq!("~1".parse::().unwrap().to_string(), + "~1".to_string()); + assert_eq!("~1.2".parse::().unwrap().to_string(), + "~1.2".to_string()); + assert_eq!("^1".parse::().unwrap().to_string(), + "^1".to_string()); + assert_eq!("^1.1".parse::().unwrap().to_string(), + "^1.1".to_string()); + assert_eq!("*".parse::().unwrap().to_string(), + "*".to_string()); + assert_eq!("1.*".parse::().unwrap().to_string(), + "1.*".to_string()); + assert_eq!("< 1.0.0".parse::().unwrap().to_string(), + "< 1.0.0".to_string()); + } + + // #[test] + // pub fn test_from_str_errors() { + // assert_eq!(Err(InvalidVersionRequirement), "\0".parse::()); + // assert_eq!(Err(OpAlreadySet), ">= >= 0.0.2".parse::()); + // assert_eq!(Err(InvalidSigil), ">== 0.0.2".parse::()); + // assert_eq!(Err(VersionComponentsMustBeNumeric), + // "a.0.0".parse::()); + // assert_eq!(Err(InvalidIdentifier), "1.0.0-".parse::()); + // assert_eq!(Err(MajorVersionRequired), ">=".parse::()); + // } + + #[test] + fn test_cargo3202() { + let v = "0.*.*".parse::().unwrap(); + assert_eq!("0.*.*", format!("{}", v.predicates[0])); + + let v = "0.0.*".parse::().unwrap(); + assert_eq!("0.0.*", format!("{}", v.predicates[0])); + + let r = req("0.*.*"); + assert_match(&r, &["0.5.0"]); + } + + #[test] + fn test_eq_hash() { + assert!(req("^1") == req("^1")); + assert!(calculate_hash(req("^1")) == calculate_hash(req("^1"))); + assert!(req("^1") != req("^2")); + } + + #[test] + fn test_ordering() { + assert!(req("=1") < req("*")); + assert!(req(">1") < req("*")); + assert!(req(">=1") < req("*")); + assert!(req("<1") < req("*")); + assert!(req("<=1") < req("*")); + assert!(req("~1") < req("*")); + assert!(req("^1") < req("*")); + assert!(req("*") == req("*")); + } +} diff --git a/bitbox02-bt/vendor/semver/tests/deprecation.rs b/bitbox02-bt/vendor/semver/tests/deprecation.rs new file mode 100644 index 0000000..a5f533a --- /dev/null +++ b/bitbox02-bt/vendor/semver/tests/deprecation.rs @@ -0,0 +1,22 @@ +extern crate semver; + +#[test] +fn test_regressions() { + use semver::VersionReq; + use semver::ReqParseError; + + let versions = vec![ + (".*", VersionReq::any()), + ("0.1.0.", VersionReq::parse("0.1.0").unwrap()), + ("0.3.1.3", VersionReq::parse("0.3.13").unwrap()), + ("0.2*", VersionReq::parse("0.2.*").unwrap()), + ("*.0", VersionReq::any()), + ]; + + for (version, requirement) in versions.into_iter() { + let parsed = VersionReq::parse(version); + let error = parsed.err().unwrap(); + + assert_eq!(ReqParseError::DeprecatedVersionRequirement(requirement), error); + } +} diff --git a/bitbox02-bt/vendor/semver/tests/regression.rs b/bitbox02-bt/vendor/semver/tests/regression.rs new file mode 100644 index 0000000..ef568a7 --- /dev/null +++ b/bitbox02-bt/vendor/semver/tests/regression.rs @@ -0,0 +1,25 @@ +extern crate semver; +extern crate crates_index; +extern crate tempdir; + +// This test checks to see if every existing crate parses successfully. Important to not break the +// Rust universe! + +#[cfg(feature = "ci")] +#[test] +fn test_regressions() { + use tempdir::TempDir; + use crates_index::Index; + use semver::Version; + + let dir = TempDir::new("semver").unwrap(); + let index = Index::new(dir.into_path()); + index.clone().unwrap(); + + for krate in index.crates() { + for version in krate.versions() { + let v = version.version(); + assert!(Version::parse(v).is_ok(), "failed: {} ({})", version.name(), v); + } + } +} diff --git a/bitbox02-bt/vendor/semver/tests/serde.rs b/bitbox02-bt/vendor/semver/tests/serde.rs new file mode 100644 index 0000000..bcb9264 --- /dev/null +++ b/bitbox02-bt/vendor/semver/tests/serde.rs @@ -0,0 +1,90 @@ +#![cfg(feature = "serde")] + +#[macro_use] +extern crate serde_derive; + +extern crate semver; +extern crate serde_json; + +use semver::{Identifier, Version, VersionReq}; + +#[derive(Serialize, Deserialize, PartialEq, Debug)] +struct Identified { + name: String, + identifier: Identifier, +} + +#[derive(Serialize, Deserialize, PartialEq, Debug)] +struct Versioned { + name: String, + vers: Version, +} + +#[test] +fn serialize_identifier() { + let id = Identified { + name: "serde".to_owned(), + identifier: Identifier::Numeric(100), + }; + let j = serde_json::to_string(&id).unwrap(); + assert_eq!(j, r#"{"name":"serde","identifier":100}"#); + + let id = Identified { + name: "serde".to_owned(), + identifier: Identifier::AlphaNumeric("b100".to_owned()), + }; + let j = serde_json::to_string(&id).unwrap(); + assert_eq!(j, r#"{"name":"serde","identifier":"b100"}"#); +} + +#[test] +fn deserialize_identifier() { + let j = r#"{"name":"serde","identifier":100}"#; + let id = serde_json::from_str::(j).unwrap(); + let expected = Identified { + name: "serde".to_owned(), + identifier: Identifier::Numeric(100), + }; + assert_eq!(id, expected); + + let j = r#"{"name":"serde","identifier":"b100"}"#; + let id = serde_json::from_str::(j).unwrap(); + let expected = Identified { + name: "serde".to_owned(), + identifier: Identifier::AlphaNumeric("b100".to_owned()), + }; + assert_eq!(id, expected); +} + +#[test] +fn serialize_version() { + let v = Versioned { + name: "serde".to_owned(), + vers: Version::parse("1.0.0").unwrap(), + }; + let j = serde_json::to_string(&v).unwrap(); + assert_eq!(j, r#"{"name":"serde","vers":"1.0.0"}"#); +} + +#[test] +fn deserialize_version() { + let j = r#"{"name":"serde","vers":"1.0.0"}"#; + let v = serde_json::from_str::(j).unwrap(); + let expected = Versioned { + name: "serde".to_owned(), + vers: Version::parse("1.0.0").unwrap(), + }; + assert_eq!(v, expected); +} + +#[test] +fn serialize_versionreq() { + let v = VersionReq::exact(&Version::parse("1.0.0").unwrap()); + + assert_eq!(serde_json::to_string(&v).unwrap(), r#""= 1.0.0""#); +} + +#[test] +fn deserialize_versionreq() { + assert_eq!("1.0.0".parse::().unwrap(), serde_json::from_str(r#""1.0.0""#).unwrap()); +} diff --git a/bitbox02-bt/vendor/serde/.cargo-checksum.json b/bitbox02-bt/vendor/serde/.cargo-checksum.json new file mode 100644 index 0000000..77e49d8 --- /dev/null +++ b/bitbox02-bt/vendor/serde/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"6d6add51c2e5e089ce4597070f2a2770d3caaf07da77070b01afe7a2dec19592","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"731c044fc5f98b37a89e9049c9214267db98763309cb63146b45c029640f82a3","build.rs":"a98eaa82c783fdb4169d1646c06028ec5cb82937d39ee127ec8ed33651d2f238","crates-io.md":"407d92b2932923f8708aaf31db266fd7db32e2b0afa6c569d134b680b74a1920","src/de/ignored_any.rs":"6480f2b2a83dc4764d01b2eec7309729eef2492eede2e5ee98d23a60b05198eb","src/de/impls.rs":"18ed2d8221b04c7fe8f7a757445a04cd1d28c887f46f7a8717afff10eada146f","src/de/mod.rs":"b34735b2e5c9c93e9857540f24cba393f1b767a2ba33d469c2d28f15049e8f6c","src/de/seed.rs":"045d890712a04eb33ffc5a021e5d948a63c89402b8ffeea749df2171b7484f8f","src/de/size_hint.rs":"fff83dc39d30e75e8e611991f9c5399188a1aad23a6462dbca2c8b62655cfedb","src/de/value.rs":"0c485908b1f755e4750af0aefa2132460dadbcf30919c15c06ca795a92d96430","src/format.rs":"c85071b016df643b161859682d21ce34fa0ebf2a3bdbeeea69859da48f5d934f","src/integer128.rs":"29ef30b7d94507b34807090e68173767cdc7aff62edccd38affe69e75338dddc","src/lib.rs":"ff721a04872d840e4a9aabd0cbd98c1a60ae3eefd6237f5c6c1474b9549e4f04","src/macros.rs":"0d4b392ed6fe529fda2c5439c8547fe9717e64f528bfd01f633bb725f98b53cd","src/private/de.rs":"c12df7ee5ac43c9c30389e1f02d2bb5c206b1b850e598963dfedeb303e448f5a","src/private/doc.rs":"b222decb40321190155209e1b8a5a52e3adfaa470047e379e664b71e0320655a","src/private/mod.rs":"b8f0c348621d91dd9da3db83d8877e70bc61ad0a2dc2d6fb57c6fc2c2cbafa26","src/private/ser.rs":"4343ccbe0b345288dce0dbf1023c6082ef42ae7073c911b535e3d9e88c3aa472","src/ser/fmt.rs":"d1cfd9623605413e45a23ef778d97f0ac4da4adaed23739f1f9d7414b30e384b","src/ser/impls.rs":"00b58a84f7c07b2f575219d6d0745fd1258dae9b9c8ec5b9b299a712c482b1a3","src/ser/impossible.rs":"5c325da8e0370ab22abe1e15d8af1dc7a1707b127508f61e720cd7f0caa80593","src/ser/mod.rs":"9aab34f08defdd6be044383ad41aeb59acee3abe7cacb73ac5bc8c70f747a67e","src/std_error.rs":"25a07149e2e468747ffa5a58051c7f93d7b3c0fa0372f012a96c97ec8ab03b97"},"package":"c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/serde/Cargo.toml b/bitbox02-bt/vendor/serde/Cargo.toml new file mode 100644 index 0000000..e6d535d --- /dev/null +++ b/bitbox02-bt/vendor/serde/Cargo.toml @@ -0,0 +1,79 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.31" +name = "serde" +version = "1.0.210" +authors = [ + "Erick Tryzelaar ", + "David Tolnay ", +] +build = "build.rs" +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A generic serialization/deserialization framework" +homepage = "https://serde.rs" +documentation = "https://docs.rs/serde" +readme = "crates-io.md" +keywords = [ + "serde", + "serialization", + "no_std", +] +categories = [ + "encoding", + "no-std", + "no-std::no-alloc", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/serde-rs/serde" + +[package.metadata.docs.rs] +features = [ + "derive", + "rc", + "unstable", +] +rustdoc-args = ["--generate-link-to-definition"] +targets = ["x86_64-unknown-linux-gnu"] + +[package.metadata.playground] +features = [ + "derive", + "rc", +] + +[lib] +name = "serde" +path = "src/lib.rs" +doc-scrape-examples = false + +[dependencies.serde_derive] +version = "1" +optional = true + +[dev-dependencies.serde_derive] +version = "1" + +[features] +alloc = [] +default = ["std"] +derive = ["serde_derive"] +rc = [] +std = [] +unstable = [] + +[target."cfg(any())".dependencies.serde_derive] +version = "=1.0.210" diff --git a/bitbox02-bt/vendor/serde/LICENSE-APACHE b/bitbox02-bt/vendor/serde/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/serde/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/serde/LICENSE-MIT b/bitbox02-bt/vendor/serde/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/serde/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/serde/README.md b/bitbox02-bt/vendor/serde/README.md new file mode 100644 index 0000000..3129294 --- /dev/null +++ b/bitbox02-bt/vendor/serde/README.md @@ -0,0 +1,114 @@ +# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.31] [![serde_derive msrv]][Rust 1.56] + +[Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/serde/ci.yml?branch=master +[actions]: https://github.com/serde-rs/serde/actions?query=branch%3Amaster +[Latest Version]: https://img.shields.io/crates/v/serde.svg +[crates.io]: https://crates.io/crates/serde +[serde msrv]: https://img.shields.io/crates/msrv/serde.svg?label=serde%20msrv&color=lightgray +[serde_derive msrv]: https://img.shields.io/crates/msrv/serde_derive.svg?label=serde_derive%20msrv&color=lightgray +[Rust 1.31]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html +[Rust 1.56]: https://blog.rust-lang.org/2021/10/21/Rust-1.56.0.html + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.rs/serde) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + +

+ +Click to show Cargo.toml. +Run this code in the playground. + + +```toml +[dependencies] + +# The core APIs, including the Serialize and Deserialize traits. Always +# required when using Serde. The "derive" feature is only required when +# using #[derive(Serialize, Deserialize)] to make Serde work with structs +# and enums defined in your crate. +serde = { version = "1.0", features = ["derive"] } + +# Each data format lives in its own crate; the sample code below uses JSON +# but you may be using a different one. +serde_json = "1.0" +``` + +
+

+ +```rust +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde is one of the most widely used Rust libraries so any place that Rustaceans +congregate will be able to help you out. For chat, consider trying the +[#rust-questions] or [#rust-beginners] channels of the unofficial community +Discord (invite: ), the [#rust-usage] or +[#beginners] channels of the official Rust Project Discord (invite: +), or the [#general][zulip] stream in Zulip. For +asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the +[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust +[Discourse forum][discourse]. It's acceptable to file a support issue in this +repo but they tend not to get as many eyes as any of the above and may get +closed without a response after some time. + +[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513 +[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281 +[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848 +[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612 +[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general +[stackoverflow]: https://stackoverflow.com/questions/tagged/rust +[/r/rust]: https://www.reddit.com/r/rust +[discourse]: https://users.rust-lang.org + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/serde/build.rs b/bitbox02-bt/vendor/serde/build.rs new file mode 100644 index 0000000..8a4f725 --- /dev/null +++ b/bitbox02-bt/vendor/serde/build.rs @@ -0,0 +1,137 @@ +use std::env; +use std::process::Command; +use std::str::{self, FromStr}; + +// The rustc-cfg strings below are *not* public API. Please let us know by +// opening a GitHub issue if your build environment requires some way to enable +// these cfgs other than by executing our build script. +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + + let minor = match rustc_minor_version() { + Some(minor) => minor, + None => return, + }; + + if minor >= 77 { + println!("cargo:rustc-check-cfg=cfg(no_core_cstr)"); + println!("cargo:rustc-check-cfg=cfg(no_core_error)"); + println!("cargo:rustc-check-cfg=cfg(no_core_net)"); + println!("cargo:rustc-check-cfg=cfg(no_core_num_saturating)"); + println!("cargo:rustc-check-cfg=cfg(no_core_try_from)"); + println!("cargo:rustc-check-cfg=cfg(no_diagnostic_namespace)"); + println!("cargo:rustc-check-cfg=cfg(no_float_copysign)"); + println!("cargo:rustc-check-cfg=cfg(no_num_nonzero_signed)"); + println!("cargo:rustc-check-cfg=cfg(no_relaxed_trait_bounds)"); + println!("cargo:rustc-check-cfg=cfg(no_serde_derive)"); + println!("cargo:rustc-check-cfg=cfg(no_std_atomic)"); + println!("cargo:rustc-check-cfg=cfg(no_std_atomic64)"); + println!("cargo:rustc-check-cfg=cfg(no_systemtime_checked_add)"); + println!("cargo:rustc-check-cfg=cfg(no_target_has_atomic)"); + } + + let target = env::var("TARGET").unwrap(); + let emscripten = target == "asmjs-unknown-emscripten" || target == "wasm32-unknown-emscripten"; + + // TryFrom, Atomic types, non-zero signed integers, and SystemTime::checked_add + // stabilized in Rust 1.34: + // https://blog.rust-lang.org/2019/04/11/Rust-1.34.0.html#tryfrom-and-tryinto + // https://blog.rust-lang.org/2019/04/11/Rust-1.34.0.html#library-stabilizations + if minor < 34 { + println!("cargo:rustc-cfg=no_core_try_from"); + println!("cargo:rustc-cfg=no_num_nonzero_signed"); + println!("cargo:rustc-cfg=no_systemtime_checked_add"); + println!("cargo:rustc-cfg=no_relaxed_trait_bounds"); + } + + // f32::copysign and f64::copysign stabilized in Rust 1.35. + // https://blog.rust-lang.org/2019/05/23/Rust-1.35.0.html#copy-the-sign-of-a-floating-point-number-onto-another + if minor < 35 { + println!("cargo:rustc-cfg=no_float_copysign"); + } + + // Current minimum supported version of serde_derive crate is Rust 1.56. + if minor < 56 { + println!("cargo:rustc-cfg=no_serde_derive"); + } + + // Support for #[cfg(target_has_atomic = "...")] stabilized in Rust 1.60. + if minor < 60 { + println!("cargo:rustc-cfg=no_target_has_atomic"); + // Allowlist of archs that support std::sync::atomic module. This is + // based on rustc's compiler/rustc_target/src/spec/*.rs. + let has_atomic64 = target.starts_with("x86_64") + || target.starts_with("i686") + || target.starts_with("aarch64") + || target.starts_with("powerpc64") + || target.starts_with("sparc64") + || target.starts_with("mips64el") + || target.starts_with("riscv64"); + let has_atomic32 = has_atomic64 || emscripten; + if minor < 34 || !has_atomic64 { + println!("cargo:rustc-cfg=no_std_atomic64"); + } + if minor < 34 || !has_atomic32 { + println!("cargo:rustc-cfg=no_std_atomic"); + } + } + + // Support for core::ffi::CStr and alloc::ffi::CString stabilized in Rust 1.64. + // https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html#c-compatible-ffi-types-in-core-and-alloc + if minor < 64 { + println!("cargo:rustc-cfg=no_core_cstr"); + } + + // Support for core::num::Saturating and std::num::Saturating stabilized in Rust 1.74 + // https://blog.rust-lang.org/2023/11/16/Rust-1.74.0.html#stabilized-apis + if minor < 74 { + println!("cargo:rustc-cfg=no_core_num_saturating"); + } + + // Support for core::net stabilized in Rust 1.77. + // https://blog.rust-lang.org/2024/03/21/Rust-1.77.0.html + if minor < 77 { + println!("cargo:rustc-cfg=no_core_net"); + } + + // Support for the `#[diagnostic]` tool attribute namespace + // https://blog.rust-lang.org/2024/05/02/Rust-1.78.0.html#diagnostic-attributes + if minor < 78 { + println!("cargo:rustc-cfg=no_diagnostic_namespace"); + } + + // The Error trait became available in core in 1.81. + // https://blog.rust-lang.org/2024/09/05/Rust-1.81.0.html#coreerrorerror + if minor < 81 { + println!("cargo:rustc-cfg=no_core_error"); + } +} + +fn rustc_minor_version() -> Option { + let rustc = match env::var_os("RUSTC") { + Some(rustc) => rustc, + None => return None, + }; + + let output = match Command::new(rustc).arg("--version").output() { + Ok(output) => output, + Err(_) => return None, + }; + + let version = match str::from_utf8(&output.stdout) { + Ok(version) => version, + Err(_) => return None, + }; + + let mut pieces = version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + + let next = match pieces.next() { + Some(next) => next, + None => return None, + }; + + u32::from_str(next).ok() +} diff --git a/bitbox02-bt/vendor/serde/crates-io.md b/bitbox02-bt/vendor/serde/crates-io.md new file mode 100644 index 0000000..b49a548 --- /dev/null +++ b/bitbox02-bt/vendor/serde/crates-io.md @@ -0,0 +1,65 @@ + + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.rs/serde) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + +```rust +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde is one of the most widely used Rust libraries so any place that Rustaceans +congregate will be able to help you out. For chat, consider trying the +[#rust-questions] or [#rust-beginners] channels of the unofficial community +Discord (invite: ), the [#rust-usage] +or [#beginners] channels of the official Rust Project Discord (invite: +), or the [#general][zulip] stream in Zulip. For +asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the +[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust +[Discourse forum][discourse]. It's acceptable to file a support issue in this +repo but they tend not to get as many eyes as any of the above and may get +closed without a response after some time. + +[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513 +[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281 +[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848 +[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612 +[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general +[stackoverflow]: https://stackoverflow.com/questions/tagged/rust +[/r/rust]: https://www.reddit.com/r/rust +[discourse]: https://users.rust-lang.org diff --git a/bitbox02-bt/vendor/serde/src/de/ignored_any.rs b/bitbox02-bt/vendor/serde/src/de/ignored_any.rs new file mode 100644 index 0000000..2360a17 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/de/ignored_any.rs @@ -0,0 +1,238 @@ +use crate::lib::*; + +use crate::de::{ + Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor, +}; + +/// An efficient way of discarding data from a deserializer. +/// +/// Think of this like `serde_json::Value` in that it can be deserialized from +/// any type, except that it does not store any information about the data that +/// gets deserialized. +/// +/// ```edition2021 +/// use serde::de::{ +/// self, Deserialize, DeserializeSeed, Deserializer, IgnoredAny, SeqAccess, Visitor, +/// }; +/// use std::fmt; +/// use std::marker::PhantomData; +/// +/// /// A seed that can be used to deserialize only the `n`th element of a sequence +/// /// while efficiently discarding elements of any type before or after index `n`. +/// /// +/// /// For example to deserialize only the element at index 3: +/// /// +/// /// ``` +/// /// NthElement::new(3).deserialize(deserializer) +/// /// ``` +/// pub struct NthElement { +/// n: usize, +/// marker: PhantomData, +/// } +/// +/// impl NthElement { +/// pub fn new(n: usize) -> Self { +/// NthElement { +/// n: n, +/// marker: PhantomData, +/// } +/// } +/// } +/// +/// impl<'de, T> Visitor<'de> for NthElement +/// where +/// T: Deserialize<'de>, +/// { +/// type Value = T; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!( +/// formatter, +/// "a sequence in which we care about element {}", +/// self.n +/// ) +/// } +/// +/// fn visit_seq(self, mut seq: A) -> Result +/// where +/// A: SeqAccess<'de>, +/// { +/// // Skip over the first `n` elements. +/// for i in 0..self.n { +/// // It is an error if the sequence ends before we get to element `n`. +/// if seq.next_element::()?.is_none() { +/// return Err(de::Error::invalid_length(i, &self)); +/// } +/// } +/// +/// // Deserialize the one we care about. +/// let nth = match seq.next_element()? { +/// Some(nth) => nth, +/// None => { +/// return Err(de::Error::invalid_length(self.n, &self)); +/// } +/// }; +/// +/// // Skip over any remaining elements in the sequence after `n`. +/// while let Some(IgnoredAny) = seq.next_element()? { +/// // ignore +/// } +/// +/// Ok(nth) +/// } +/// } +/// +/// impl<'de, T> DeserializeSeed<'de> for NthElement +/// where +/// T: Deserialize<'de>, +/// { +/// type Value = T; +/// +/// fn deserialize(self, deserializer: D) -> Result +/// where +/// D: Deserializer<'de>, +/// { +/// deserializer.deserialize_seq(self) +/// } +/// } +/// +/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> +/// # where +/// # D: Deserializer<'de>, +/// # { +/// // Deserialize only the sequence element at index 3 from this deserializer. +/// // The element at index 3 is required to be a string. Elements before and +/// // after index 3 are allowed to be of any type. +/// let s: String = NthElement::new(3).deserialize(deserializer)?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Copy, Clone, Debug, Default, PartialEq)] +pub struct IgnoredAny; + +impl<'de> Visitor<'de> for IgnoredAny { + type Value = IgnoredAny; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("anything at all") + } + + #[inline] + fn visit_bool(self, x: bool) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_i64(self, x: i64) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_i128(self, x: i128) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_u64(self, x: u64) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_u128(self, x: u128) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_f64(self, x: f64) -> Result { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_str(self, s: &str) -> Result + where + E: Error, + { + let _ = s; + Ok(IgnoredAny) + } + + #[inline] + fn visit_none(self) -> Result { + Ok(IgnoredAny) + } + + #[inline] + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + IgnoredAny::deserialize(deserializer) + } + + #[inline] + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + IgnoredAny::deserialize(deserializer) + } + + #[inline] + fn visit_unit(self) -> Result { + Ok(IgnoredAny) + } + + #[inline] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + while let Some(IgnoredAny) = tri!(seq.next_element()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + while let Some((IgnoredAny, IgnoredAny)) = tri!(map.next_entry()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_bytes(self, bytes: &[u8]) -> Result + where + E: Error, + { + let _ = bytes; + Ok(IgnoredAny) + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + tri!(data.variant::()).1.newtype_variant() + } +} + +impl<'de> Deserialize<'de> for IgnoredAny { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_ignored_any(IgnoredAny) + } +} diff --git a/bitbox02-bt/vendor/serde/src/de/impls.rs b/bitbox02-bt/vendor/serde/src/de/impls.rs new file mode 100644 index 0000000..2d8c990 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/de/impls.rs @@ -0,0 +1,3183 @@ +use crate::lib::*; + +use crate::de::{ + Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, Unexpected, VariantAccess, + Visitor, +}; + +use crate::seed::InPlaceSeed; + +#[cfg(any(feature = "std", feature = "alloc"))] +use crate::de::size_hint; + +//////////////////////////////////////////////////////////////////////////////// + +struct UnitVisitor; + +impl<'de> Visitor<'de> for UnitVisitor { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + fn visit_unit(self) -> Result + where + E: Error, + { + Ok(()) + } +} + +impl<'de> Deserialize<'de> for () { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_unit(UnitVisitor) + } +} + +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +impl<'de> Deserialize<'de> for ! { + fn deserialize(_deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Err(Error::custom("cannot deserialize `!`")) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct BoolVisitor; + +impl<'de> Visitor<'de> for BoolVisitor { + type Value = bool; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a boolean") + } + + fn visit_bool(self, v: bool) -> Result + where + E: Error, + { + Ok(v) + } +} + +impl<'de> Deserialize<'de> for bool { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_bool(BoolVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! impl_deserialize_num { + ($primitive:ident, $nonzero:ident $(cfg($($cfg:tt)*))*, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => { + impl_deserialize_num!($primitive, $deserialize $($method!($($val : $visit)*);)*); + + $(#[cfg($($cfg)*)])* + impl<'de> Deserialize<'de> for num::$nonzero { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct NonZeroVisitor; + + impl<'de> Visitor<'de> for NonZeroVisitor { + type Value = num::$nonzero; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a nonzero ", stringify!($primitive))) + } + + $($($method!(nonzero $primitive $val : $visit);)*)* + } + + deserializer.$deserialize(NonZeroVisitor) + } + } + + #[cfg(not(no_core_num_saturating))] + impl<'de> Deserialize<'de> for Saturating<$primitive> { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct SaturatingVisitor; + + impl<'de> Visitor<'de> for SaturatingVisitor { + type Value = Saturating<$primitive>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("integer with support for saturating semantics") + } + + $($($method!(saturating $primitive $val : $visit);)*)* + } + + deserializer.$deserialize(SaturatingVisitor) + } + } + }; + + ($primitive:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => { + impl<'de> Deserialize<'de> for $primitive { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct PrimitiveVisitor; + + impl<'de> Visitor<'de> for PrimitiveVisitor { + type Value = $primitive; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(stringify!($primitive)) + } + + $($($method!($val : $visit);)*)* + } + + deserializer.$deserialize(PrimitiveVisitor) + } + } + }; +} + +macro_rules! num_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(v) + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if let Some(nonzero) = Self::Value::new(v) { + Ok(nonzero) + } else { + Err(Error::invalid_value(Unexpected::Unsigned(0), &self)) + } + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(Saturating(v)) + } + }; +} + +macro_rules! num_as_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(v as Self::Value) + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if let Some(nonzero) = Self::Value::new(v as $primitive) { + Ok(nonzero) + } else { + Err(Error::invalid_value(Unexpected::Unsigned(0), &self)) + } + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + Ok(Saturating(v as $primitive)) + } + }; +} + +macro_rules! num_as_copysign_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + #[cfg(any(no_float_copysign, not(feature = "std")))] + { + Ok(v as Self::Value) + } + + #[cfg(all(not(no_float_copysign), feature = "std"))] + { + // Preserve sign of NaN. The `as` produces a nondeterministic sign. + let sign = if v.is_sign_positive() { 1.0 } else { -1.0 }; + Ok((v as Self::Value).copysign(sign)) + } + } + }; +} + +macro_rules! int_to_int { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if Self::Value::min_value() as i64 <= v as i64 + && v as i64 <= Self::Value::max_value() as i64 + { + Ok(v as Self::Value) + } else { + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if $primitive::min_value() as i64 <= v as i64 + && v as i64 <= $primitive::max_value() as i64 + { + if let Some(nonzero) = Self::Value::new(v as $primitive) { + return Ok(nonzero); + } + } + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if (v as i64) < $primitive::MIN as i64 { + Ok(Saturating($primitive::MIN)) + } else if ($primitive::MAX as i64) < v as i64 { + Ok(Saturating($primitive::MAX)) + } else { + Ok(Saturating(v as $primitive)) + } + } + }; +} + +macro_rules! int_to_uint { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if 0 <= v && v as u64 <= Self::Value::max_value() as u64 { + Ok(v as Self::Value) + } else { + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if 0 < v && v as u64 <= $primitive::max_value() as u64 { + if let Some(nonzero) = Self::Value::new(v as $primitive) { + return Ok(nonzero); + } + } + Err(Error::invalid_value(Unexpected::Signed(v as i64), &self)) + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v < 0 { + Ok(Saturating(0)) + } else if ($primitive::MAX as u64) < v as u64 { + Ok(Saturating($primitive::MAX)) + } else { + Ok(Saturating(v as $primitive)) + } + } + }; +} + +macro_rules! uint_to_self { + ($ty:ident : $visit:ident) => { + #[inline] + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v as u64 <= Self::Value::max_value() as u64 { + Ok(v as Self::Value) + } else { + Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self)) + } + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v as u64 <= $primitive::max_value() as u64 { + if let Some(nonzero) = Self::Value::new(v as $primitive) { + return Ok(nonzero); + } + } + Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self)) + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v as u64 <= $primitive::MAX as u64 { + Ok(Saturating(v as $primitive)) + } else { + Ok(Saturating($primitive::MAX)) + } + } + }; +} + +impl_deserialize_num! { + i8, NonZeroI8 cfg(not(no_num_nonzero_signed)), deserialize_i8 + num_self!(i8:visit_i8); + int_to_int!(i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + i16, NonZeroI16 cfg(not(no_num_nonzero_signed)), deserialize_i16 + num_self!(i16:visit_i16); + num_as_self!(i8:visit_i8); + int_to_int!(i32:visit_i32 i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + i32, NonZeroI32 cfg(not(no_num_nonzero_signed)), deserialize_i32 + num_self!(i32:visit_i32); + num_as_self!(i8:visit_i8 i16:visit_i16); + int_to_int!(i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + i64, NonZeroI64 cfg(not(no_num_nonzero_signed)), deserialize_i64 + num_self!(i64:visit_i64); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + isize, NonZeroIsize cfg(not(no_num_nonzero_signed)), deserialize_i64 + num_as_self!(i8:visit_i8 i16:visit_i16); + int_to_int!(i32:visit_i32 i64:visit_i64); + uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + u8, NonZeroU8, deserialize_u8 + num_self!(u8:visit_u8); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + u16, NonZeroU16, deserialize_u16 + num_self!(u16:visit_u16); + num_as_self!(u8:visit_u8); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + u32, NonZeroU32, deserialize_u32 + num_self!(u32:visit_u32); + num_as_self!(u8:visit_u8 u16:visit_u16); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u64:visit_u64); +} + +impl_deserialize_num! { + u64, NonZeroU64, deserialize_u64 + num_self!(u64:visit_u64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); +} + +impl_deserialize_num! { + usize, NonZeroUsize, deserialize_u64 + num_as_self!(u8:visit_u8 u16:visit_u16); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + uint_to_self!(u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + f32, deserialize_f32 + num_self!(f32:visit_f32); + num_as_copysign_self!(f64:visit_f64); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +impl_deserialize_num! { + f64, deserialize_f64 + num_self!(f64:visit_f64); + num_as_copysign_self!(f32:visit_f32); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); +} + +macro_rules! num_128 { + ($ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v as i128 >= Self::Value::min_value() as i128 + && v as u128 <= Self::Value::max_value() as u128 + { + Ok(v as Self::Value) + } else { + Err(Error::invalid_value( + Unexpected::Other(stringify!($ty)), + &self, + )) + } + } + }; + + (nonzero $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if v as i128 >= $primitive::min_value() as i128 + && v as u128 <= $primitive::max_value() as u128 + { + if let Some(nonzero) = Self::Value::new(v as $primitive) { + Ok(nonzero) + } else { + Err(Error::invalid_value(Unexpected::Unsigned(0), &self)) + } + } else { + Err(Error::invalid_value( + Unexpected::Other(stringify!($ty)), + &self, + )) + } + } + }; + + (saturating $primitive:ident $ty:ident : $visit:ident) => { + fn $visit(self, v: $ty) -> Result + where + E: Error, + { + if (v as i128) < $primitive::MIN as i128 { + Ok(Saturating($primitive::MIN)) + } else if ($primitive::MAX as u128) < v as u128 { + Ok(Saturating($primitive::MAX)) + } else { + Ok(Saturating(v as $primitive)) + } + } + }; +} + +impl_deserialize_num! { + i128, NonZeroI128 cfg(not(no_num_nonzero_signed)), deserialize_i128 + num_self!(i128:visit_i128); + num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); + num_128!(u128:visit_u128); +} + +impl_deserialize_num! { + u128, NonZeroU128, deserialize_u128 + num_self!(u128:visit_u128); + num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64); + int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64); + num_128!(i128:visit_i128); +} + +//////////////////////////////////////////////////////////////////////////////// + +struct CharVisitor; + +impl<'de> Visitor<'de> for CharVisitor { + type Value = char; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a character") + } + + #[inline] + fn visit_char(self, v: char) -> Result + where + E: Error, + { + Ok(v) + } + + #[inline] + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + let mut iter = v.chars(); + match (iter.next(), iter.next()) { + (Some(c), None) => Ok(c), + _ => Err(Error::invalid_value(Unexpected::Str(v), &self)), + } + } +} + +impl<'de> Deserialize<'de> for char { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_char(CharVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +struct StringVisitor; +#[cfg(any(feature = "std", feature = "alloc"))] +struct StringInPlaceVisitor<'a>(&'a mut String); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de> Visitor<'de> for StringVisitor { + type Value = String; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Ok(v.to_owned()) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + Ok(v) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => Ok(s.to_owned()), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => Ok(s), + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + self.0.clear(); + self.0.push_str(v); + Ok(()) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + *self.0 = v; + Ok(()) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => { + self.0.clear(); + self.0.push_str(s); + Ok(()) + } + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => { + *self.0 = s; + Ok(()) + } + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de> Deserialize<'de> for String { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(StringVisitor) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(StringInPlaceVisitor(place)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct StrVisitor; + +impl<'a> Visitor<'a> for StrVisitor { + type Value = &'a str; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed string") + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(v) // so easy + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } +} + +impl<'de: 'a, 'a> Deserialize<'de> for &'a str { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(StrVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct BytesVisitor; + +impl<'a> Visitor<'a> for BytesVisitor { + type Value = &'a [u8]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed byte array") + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + Ok(v) + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(v.as_bytes()) + } +} + +impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_bytes(BytesVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +struct CStringVisitor; + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +impl<'de> Visitor<'de> for CStringVisitor { + type Value = CString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("byte array") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let capacity = size_hint::cautious::(seq.size_hint()); + let mut values = Vec::::with_capacity(capacity); + + while let Some(value) = tri!(seq.next_element()) { + values.push(value); + } + + CString::new(values).map_err(Error::custom) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } +} + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de> Deserialize<'de> for CString { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_byte_buf(CStringVisitor) + } +} + +macro_rules! forwarded_impl { + ( + $(#[$attr:meta])* + ($($id:ident),*), $ty:ty, $func:expr + ) => { + $(#[$attr])* + impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map($func) + } + } + } +} + +forwarded_impl! { + #[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (), Box, CString::into_boxed_c_str +} + +forwarded_impl! { + (T), Reverse, Reverse +} + +//////////////////////////////////////////////////////////////////////////////// + +struct OptionVisitor { + marker: PhantomData, +} + +impl<'de, T> Visitor<'de> for OptionVisitor +where + T: Deserialize<'de>, +{ + type Value = Option; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("option") + } + + #[inline] + fn visit_unit(self) -> Result + where + E: Error, + { + Ok(None) + } + + #[inline] + fn visit_none(self) -> Result + where + E: Error, + { + Ok(None) + } + + #[inline] + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize(deserializer).map(Some) + } + + fn __private_visit_untagged_option(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Ok(T::deserialize(deserializer).ok()) + } +} + +impl<'de, T> Deserialize<'de> for Option +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_option(OptionVisitor { + marker: PhantomData, + }) + } + + // The Some variant's repr is opaque, so we can't play cute tricks with its + // tag to have deserialize_in_place build the content in place unconditionally. + // + // FIXME: investigate whether branching on the old value being Some to + // deserialize_in_place the value is profitable (probably data-dependent?) +} + +//////////////////////////////////////////////////////////////////////////////// + +struct PhantomDataVisitor { + marker: PhantomData, +} + +impl<'de, T> Visitor<'de> for PhantomDataVisitor +where + T: ?Sized, +{ + type Value = PhantomData; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + #[inline] + fn visit_unit(self) -> Result + where + E: Error, + { + Ok(PhantomData) + } +} + +impl<'de, T> Deserialize<'de> for PhantomData +where + T: ?Sized, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let visitor = PhantomDataVisitor { + marker: PhantomData, + }; + deserializer.deserialize_unit_struct("PhantomData", visitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! seq_impl { + ( + $(#[$attr:meta])* + $ty:ident , + $access:ident, + $clear:expr, + $with_capacity:expr, + $reserve:expr, + $insert:expr + ) => { + $(#[$attr])* + impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct SeqVisitor { + marker: PhantomData<$ty>, + } + + impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[inline] + fn visit_seq(self, mut $access: A) -> Result + where + A: SeqAccess<'de>, + { + let mut values = $with_capacity; + + while let Some(value) = tri!($access.next_element()) { + $insert(&mut values, value); + } + + Ok(values) + } + } + + let visitor = SeqVisitor { marker: PhantomData }; + deserializer.deserialize_seq(visitor) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty); + + impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*> + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[inline] + fn visit_seq(mut self, mut $access: A) -> Result + where + A: SeqAccess<'de>, + { + $clear(&mut self.0); + $reserve(&mut self.0, size_hint::cautious::($access.size_hint())); + + // FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList) + while let Some(value) = tri!($access.next_element()) { + $insert(&mut self.0, value); + } + + Ok(()) + } + } + + deserializer.deserialize_seq(SeqInPlaceVisitor(place)) + } + } + } +} + +// Dummy impl of reserve +#[cfg(any(feature = "std", feature = "alloc"))] +fn nop_reserve(_seq: T, _n: usize) {} + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BinaryHeap, + seq, + BinaryHeap::clear, + BinaryHeap::with_capacity(size_hint::cautious::(seq.size_hint())), + BinaryHeap::reserve, + BinaryHeap::push +); + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeSet, + seq, + BTreeSet::clear, + BTreeSet::new(), + nop_reserve, + BTreeSet::insert +); + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + LinkedList, + seq, + LinkedList::clear, + LinkedList::new(), + nop_reserve, + LinkedList::push_back +); + +seq_impl!( + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashSet, + seq, + HashSet::clear, + HashSet::with_capacity_and_hasher(size_hint::cautious::(seq.size_hint()), S::default()), + HashSet::reserve, + HashSet::insert +); + +seq_impl!( + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + VecDeque, + seq, + VecDeque::clear, + VecDeque::with_capacity(size_hint::cautious::(seq.size_hint())), + VecDeque::reserve, + VecDeque::push_back +); + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, T> Deserialize<'de> for Vec +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct VecVisitor { + marker: PhantomData, + } + + impl<'de, T> Visitor<'de> for VecVisitor + where + T: Deserialize<'de>, + { + type Value = Vec; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let capacity = size_hint::cautious::(seq.size_hint()); + let mut values = Vec::::with_capacity(capacity); + + while let Some(value) = tri!(seq.next_element()) { + values.push(value); + } + + Ok(values) + } + } + + let visitor = VecVisitor { + marker: PhantomData, + }; + deserializer.deserialize_seq(visitor) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct VecInPlaceVisitor<'a, T: 'a>(&'a mut Vec); + + impl<'a, 'de, T> Visitor<'de> for VecInPlaceVisitor<'a, T> + where + T: Deserialize<'de>, + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let hint = size_hint::cautious::(seq.size_hint()); + if let Some(additional) = hint.checked_sub(self.0.len()) { + self.0.reserve(additional); + } + + for i in 0..self.0.len() { + let next = { + let next_place = InPlaceSeed(&mut self.0[i]); + tri!(seq.next_element_seed(next_place)) + }; + if next.is_none() { + self.0.truncate(i); + return Ok(()); + } + } + + while let Some(value) = tri!(seq.next_element()) { + self.0.push(value); + } + + Ok(()) + } + } + + deserializer.deserialize_seq(VecInPlaceVisitor(place)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct ArrayVisitor { + marker: PhantomData, +} +struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A); + +impl ArrayVisitor { + fn new() -> Self { + ArrayVisitor { + marker: PhantomData, + } + } +} + +impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> { + type Value = [T; 0]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("an empty array") + } + + #[inline] + fn visit_seq(self, _: A) -> Result + where + A: SeqAccess<'de>, + { + Ok([]) + } +} + +// Does not require T: Deserialize<'de>. +impl<'de, T> Deserialize<'de> for [T; 0] { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new()) + } +} + +macro_rules! array_impls { + ($($len:expr => ($($n:tt)+))+) => { + $( + impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]> + where + T: Deserialize<'de>, + { + type Value = [T; $len]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("an array of length ", $len)) + } + + #[inline] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + Ok([$( + match tri!(seq.next_element()) { + Some(val) => val, + None => return Err(Error::invalid_length($n, &self)), + } + ),+]) + } + } + + impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]> + where + T: Deserialize<'de>, + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("an array of length ", $len)) + } + + #[inline] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let mut fail_idx = None; + for (idx, dest) in self.0[..].iter_mut().enumerate() { + if tri!(seq.next_element_seed(InPlaceSeed(dest))).is_none() { + fail_idx = Some(idx); + break; + } + } + if let Some(idx) = fail_idx { + return Err(Error::invalid_length(idx, &self)); + } + Ok(()) + } + } + + impl<'de, T> Deserialize<'de> for [T; $len] + where + T: Deserialize<'de>, + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new()) + } + + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place)) + } + } + )+ + } +} + +array_impls! { + 1 => (0) + 2 => (0 1) + 3 => (0 1 2) + 4 => (0 1 2 3) + 5 => (0 1 2 3 4) + 6 => (0 1 2 3 4 5) + 7 => (0 1 2 3 4 5 6) + 8 => (0 1 2 3 4 5 6 7) + 9 => (0 1 2 3 4 5 6 7 8) + 10 => (0 1 2 3 4 5 6 7 8 9) + 11 => (0 1 2 3 4 5 6 7 8 9 10) + 12 => (0 1 2 3 4 5 6 7 8 9 10 11) + 13 => (0 1 2 3 4 5 6 7 8 9 10 11 12) + 14 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13) + 15 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14) + 16 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) + 17 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16) + 18 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17) + 19 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18) + 20 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) + 21 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20) + 22 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21) + 23 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22) + 24 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23) + 25 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24) + 26 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25) + 27 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26) + 28 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27) + 29 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28) + 30 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29) + 31 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30) + 32 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31) +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($($len:tt => ($($n:tt $name:ident)+))+) => { + $( + #[cfg_attr(docsrs, doc(hidden))] + impl<'de, $($name),+> Deserialize<'de> for ($($name,)+) + where + $($name: Deserialize<'de>,)+ + { + tuple_impl_body!($len => ($($n $name)+)); + } + )+ + }; +} + +macro_rules! tuple_impl_body { + ($len:tt => ($($n:tt $name:ident)+)) => { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct TupleVisitor<$($name,)+> { + marker: PhantomData<($($name,)+)>, + } + + impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> { + type Value = ($($name,)+); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a tuple of size ", $len)) + } + + #[inline] + #[allow(non_snake_case)] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + $( + let $name = match tri!(seq.next_element()) { + Some(value) => value, + None => return Err(Error::invalid_length($n, &self)), + }; + )+ + + Ok(($($name,)+)) + } + } + + deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData }) + } + + #[inline] + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+)); + + impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a tuple of size ", $len)) + } + + #[inline] + #[allow(non_snake_case)] + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + $( + if tri!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() { + return Err(Error::invalid_length($n, &self)); + } + )+ + + Ok(()) + } + } + + deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place)) + } + }; +} + +#[cfg_attr(docsrs, doc(fake_variadic))] +#[cfg_attr( + docsrs, + doc = "This trait is implemented for tuples up to 16 items long." +)] +impl<'de, T> Deserialize<'de> for (T,) +where + T: Deserialize<'de>, +{ + tuple_impl_body!(1 => (0 T)); +} + +tuple_impls! { + 2 => (0 T0 1 T1) + 3 => (0 T0 1 T1 2 T2) + 4 => (0 T0 1 T1 2 T2 3 T3) + 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) + 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) + 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) + 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) + 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) + 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) + 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) + 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) + 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) + 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) + 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) + 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! map_impl { + ( + $(#[$attr:meta])* + $ty:ident , + $access:ident, + $with_capacity:expr, + ) => { + $(#[$attr])* + impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty + where + K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, + V: Deserialize<'de>, + $($typaram: $bound1 $(+ $bound2)*),* + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct MapVisitor { + marker: PhantomData<$ty>, + } + + impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor + where + K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, + V: Deserialize<'de>, + $($typaram: $bound1 $(+ $bound2)*),* + { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map") + } + + #[inline] + fn visit_map(self, mut $access: A) -> Result + where + A: MapAccess<'de>, + { + let mut values = $with_capacity; + + while let Some((key, value)) = tri!($access.next_entry()) { + values.insert(key, value); + } + + Ok(values) + } + } + + let visitor = MapVisitor { marker: PhantomData }; + deserializer.deserialize_map(visitor) + } + } + } +} + +map_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeMap, + map, + BTreeMap::new(), +} + +map_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashMap, + map, + HashMap::with_capacity_and_hasher(size_hint::cautious::<(K, V)>(map.size_hint()), S::default()), +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! parse_ip_impl { + ($ty:ty, $expecting:expr, $size:tt) => { + impl<'de> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new($expecting)) + } else { + <[u8; $size]>::deserialize(deserializer).map(<$ty>::from) + } + } + } + }; +} + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! variant_identifier { + ( + $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) + $expecting_message:expr, + $variants_name:ident + ) => { + enum $name_kind { + $($variant),* + } + + static $variants_name: &[&str] = &[$(stringify!($variant)),*]; + + impl<'de> Deserialize<'de> for $name_kind { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct KindVisitor; + + impl<'de> Visitor<'de> for KindVisitor { + type Value = $name_kind; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str($expecting_message) + } + + fn visit_u64(self, value: u64) -> Result + where + E: Error, + { + match value { + $( + $index => Ok($name_kind :: $variant), + )* + _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self),), + } + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + $( + stringify!($variant) => Ok($name_kind :: $variant), + )* + _ => Err(Error::unknown_variant(value, $variants_name)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + $( + $bytes => Ok($name_kind :: $variant), + )* + _ => { + match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, $variants_name)), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)), + } + } + } + } + } + + deserializer.deserialize_identifier(KindVisitor) + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! deserialize_enum { + ( + $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) + $expecting_message:expr, + $deserializer:expr + ) => { + variant_identifier! { + $name_kind ($($variant; $bytes; $index),*) + $expecting_message, + VARIANTS + } + + struct EnumVisitor; + impl<'de> Visitor<'de> for EnumVisitor { + type Value = $name; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a ", stringify!($name))) + } + + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + match tri!(data.variant()) { + $( + ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant), + )* + } + } + } + $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor) + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl<'de> Deserialize<'de> for net::IpAddr { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new("IP address")) + } else { + use crate::lib::net::IpAddr; + deserialize_enum! { + IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) + "`V4` or `V6`", + deserializer + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_ip_impl!(net::Ipv4Addr, "IPv4 address", 4); + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_ip_impl!(net::Ipv6Addr, "IPv6 address", 16); + +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! parse_socket_impl { + ( + $ty:ty, $expecting:tt, + $new:expr, + ) => { + impl<'de> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new($expecting)) + } else { + <(_, u16)>::deserialize(deserializer).map($new) + } + } + } + }; +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl<'de> Deserialize<'de> for net::SocketAddr { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + deserializer.deserialize_str(FromStrVisitor::new("socket address")) + } else { + use crate::lib::net::SocketAddr; + deserialize_enum! { + SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) + "`V4` or `V6`", + deserializer + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_socket_impl! { + net::SocketAddrV4, "IPv4 socket address", + |(ip, port)| net::SocketAddrV4::new(ip, port), +} + +#[cfg(any(feature = "std", not(no_core_net)))] +parse_socket_impl! { + net::SocketAddrV6, "IPv6 socket address", + |(ip, port)| net::SocketAddrV6::new(ip, port, 0, 0), +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +struct PathVisitor; + +#[cfg(feature = "std")] +impl<'a> Visitor<'a> for PathVisitor { + type Value = &'a Path; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed path") + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(v.as_ref()) + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + str::from_utf8(v) + .map(AsRef::as_ref) + .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de: 'a, 'a> Deserialize<'de> for &'a Path { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(PathVisitor) + } +} + +#[cfg(feature = "std")] +struct PathBufVisitor; + +#[cfg(feature = "std")] +impl<'de> Visitor<'de> for PathBufVisitor { + type Value = PathBuf; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("path string") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Ok(From::from(v)) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + Ok(From::from(v)) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + str::from_utf8(v) + .map(From::from) + .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + String::from_utf8(v) + .map(From::from) + .map_err(|e| Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de> Deserialize<'de> for PathBuf { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(PathBufVisitor) + } +} + +forwarded_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + (), Box, PathBuf::into_boxed_path +} + +//////////////////////////////////////////////////////////////////////////////// + +// If this were outside of the serde crate, it would just use: +// +// #[derive(Deserialize)] +// #[serde(variant_identifier)] +#[cfg(all(feature = "std", any(unix, windows)))] +variant_identifier! { + OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1) + "`Unix` or `Windows`", + OSSTR_VARIANTS +} + +#[cfg(all(feature = "std", any(unix, windows)))] +struct OsStringVisitor; + +#[cfg(all(feature = "std", any(unix, windows)))] +impl<'de> Visitor<'de> for OsStringVisitor { + type Value = OsString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("os string") + } + + #[cfg(unix)] + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + use std::os::unix::ffi::OsStringExt; + + match tri!(data.variant()) { + (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec), + (OsStringKind::Windows, _) => Err(Error::custom( + "cannot deserialize Windows OS string on Unix", + )), + } + } + + #[cfg(windows)] + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + use std::os::windows::ffi::OsStringExt; + + match tri!(data.variant()) { + (OsStringKind::Windows, v) => v + .newtype_variant::>() + .map(|vec| OsString::from_wide(&vec)), + (OsStringKind::Unix, _) => Err(Error::custom( + "cannot deserialize Unix OS string on Windows", + )), + } + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] +impl<'de> Deserialize<'de> for OsString { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +forwarded_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (T), Box, Box::new +} + +forwarded_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (T), Box<[T]>, Vec::into_boxed_slice +} + +forwarded_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + (), Box, String::into_boxed_str +} + +forwarded_impl! { + #[cfg(all(feature = "std", any(unix, windows)))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] + (), Box, OsString::into_boxed_os_str +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, 'a, T> Deserialize<'de> for Cow<'a, T> +where + T: ?Sized + ToOwned, + T::Owned: Deserialize<'de>, +{ + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::Owned::deserialize(deserializer).map(Cow::Owned) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting +/// `Weak` has a reference count of 0 and cannot be upgraded. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl<'de, T> Deserialize<'de> for RcWeak +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + tri!(Option::::deserialize(deserializer)); + Ok(RcWeak::new()) + } +} + +/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting +/// `Weak` has a reference count of 0 and cannot be upgraded. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl<'de, T> Deserialize<'de> for ArcWeak +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + tri!(Option::::deserialize(deserializer)); + Ok(ArcWeak::new()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! box_forwarded_impl { + ( + $(#[$attr:meta])* + $t:ident + ) => { + $(#[$attr])* + impl<'de, T> Deserialize<'de> for $t + where + T: ?Sized, + Box: Deserialize<'de>, + { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Box::deserialize(deserializer).map(Into::into) + } + } + }; +} + +box_forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Rc` will not attempt to + /// deduplicate `Rc` references to the same data. Every deserialized `Rc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Rc +} + +box_forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Arc` will not attempt to + /// deduplicate `Arc` references to the same data. Every deserialized `Arc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Arc +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T> Deserialize<'de> for Cell +where + T: Deserialize<'de> + Copy, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize(deserializer).map(Cell::new) + } +} + +forwarded_impl! { + (T), RefCell, RefCell::new +} + +forwarded_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + (T), Mutex, Mutex::new +} + +forwarded_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + (T), RwLock, RwLock::new +} + +//////////////////////////////////////////////////////////////////////////////// + +// This is a cleaned-up version of the impl generated by: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Duration { +// secs: u64, +// nanos: u32, +// } +impl<'de> Deserialize<'de> for Duration { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Secs, + Nanos, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`secs` or `nanos`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "secs" => Ok(Field::Secs), + "nanos" => Ok(Field::Nanos), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"secs" => Ok(Field::Secs), + b"nanos" => Ok(Field::Nanos), + _ => { + let value = crate::__private::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + fn check_overflow(secs: u64, nanos: u32) -> Result<(), E> + where + E: Error, + { + static NANOS_PER_SEC: u32 = 1_000_000_000; + match secs.checked_add((nanos / NANOS_PER_SEC) as u64) { + Some(_) => Ok(()), + None => Err(E::custom("overflow deserializing Duration")), + } + } + + struct DurationVisitor; + + impl<'de> Visitor<'de> for DurationVisitor { + type Value = Duration; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Duration") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let secs: u64 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let nanos: u32 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut secs: Option = None; + let mut nanos: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Secs => { + if secs.is_some() { + return Err(::duplicate_field("secs")); + } + secs = Some(tri!(map.next_value())); + } + Field::Nanos => { + if nanos.is_some() { + return Err(::duplicate_field("nanos")); + } + nanos = Some(tri!(map.next_value())); + } + } + } + let secs = match secs { + Some(secs) => secs, + None => return Err(::missing_field("secs")), + }; + let nanos = match nanos { + Some(nanos) => nanos, + None => return Err(::missing_field("nanos")), + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + } + + const FIELDS: &[&str] = &["secs", "nanos"]; + deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de> Deserialize<'de> for SystemTime { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // Reuse duration + enum Field { + Secs, + Nanos, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "secs_since_epoch" => Ok(Field::Secs), + "nanos_since_epoch" => Ok(Field::Nanos), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"secs_since_epoch" => Ok(Field::Secs), + b"nanos_since_epoch" => Ok(Field::Nanos), + _ => { + let value = String::from_utf8_lossy(value); + Err(Error::unknown_field(&value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + fn check_overflow(secs: u64, nanos: u32) -> Result<(), E> + where + E: Error, + { + static NANOS_PER_SEC: u32 = 1_000_000_000; + match secs.checked_add((nanos / NANOS_PER_SEC) as u64) { + Some(_) => Ok(()), + None => Err(E::custom("overflow deserializing SystemTime epoch offset")), + } + } + + struct DurationVisitor; + + impl<'de> Visitor<'de> for DurationVisitor { + type Value = Duration; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct SystemTime") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let secs: u64 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let nanos: u32 = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut secs: Option = None; + let mut nanos: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Secs => { + if secs.is_some() { + return Err(::duplicate_field( + "secs_since_epoch", + )); + } + secs = Some(tri!(map.next_value())); + } + Field::Nanos => { + if nanos.is_some() { + return Err(::duplicate_field( + "nanos_since_epoch", + )); + } + nanos = Some(tri!(map.next_value())); + } + } + } + let secs = match secs { + Some(secs) => secs, + None => return Err(::missing_field("secs_since_epoch")), + }; + let nanos = match nanos { + Some(nanos) => nanos, + None => return Err(::missing_field("nanos_since_epoch")), + }; + tri!(check_overflow(secs, nanos)); + Ok(Duration::new(secs, nanos)) + } + } + + const FIELDS: &[&str] = &["secs_since_epoch", "nanos_since_epoch"]; + let duration = tri!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor)); + #[cfg(not(no_systemtime_checked_add))] + let ret = UNIX_EPOCH + .checked_add(duration) + .ok_or_else(|| D::Error::custom("overflow deserializing SystemTime")); + #[cfg(no_systemtime_checked_add)] + let ret = Ok(UNIX_EPOCH + duration); + ret + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Range { +// start: Idx, +// end: Idx, +// } +impl<'de, Idx> Deserialize<'de> for Range +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let (start, end) = tri!(deserializer.deserialize_struct( + "Range", + range::FIELDS, + range::RangeVisitor { + expecting: "struct Range", + phantom: PhantomData, + }, + )); + Ok(start..end) + } +} + +impl<'de, Idx> Deserialize<'de> for RangeInclusive +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let (start, end) = tri!(deserializer.deserialize_struct( + "RangeInclusive", + range::FIELDS, + range::RangeVisitor { + expecting: "struct RangeInclusive", + phantom: PhantomData, + }, + )); + Ok(RangeInclusive::new(start, end)) + } +} + +mod range { + use crate::lib::*; + + use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + + pub const FIELDS: &[&str] = &["start", "end"]; + + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Start, + End, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`start` or `end`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "start" => Ok(Field::Start), + "end" => Ok(Field::End), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"start" => Ok(Field::Start), + b"end" => Ok(Field::End), + _ => { + let value = crate::__private::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + pub struct RangeVisitor { + pub expecting: &'static str, + pub phantom: PhantomData, + } + + impl<'de, Idx> Visitor<'de> for RangeVisitor + where + Idx: Deserialize<'de>, + { + type Value = (Idx, Idx); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let start: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let end: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + Ok((start, end)) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut start: Option = None; + let mut end: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Start => { + if start.is_some() { + return Err(::duplicate_field("start")); + } + start = Some(tri!(map.next_value())); + } + Field::End => { + if end.is_some() { + return Err(::duplicate_field("end")); + } + end = Some(tri!(map.next_value())); + } + } + } + let start = match start { + Some(start) => start, + None => return Err(::missing_field("start")), + }; + let end = match end { + Some(end) => end, + None => return Err(::missing_field("end")), + }; + Ok((start, end)) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct RangeFrom { +// start: Idx, +// } +impl<'de, Idx> Deserialize<'de> for RangeFrom +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let start = tri!(deserializer.deserialize_struct( + "RangeFrom", + range_from::FIELDS, + range_from::RangeFromVisitor { + expecting: "struct RangeFrom", + phantom: PhantomData, + }, + )); + Ok(start..) + } +} + +mod range_from { + use crate::lib::*; + + use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + + pub const FIELDS: &[&str] = &["start"]; + + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Start, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`start`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "start" => Ok(Field::Start), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"start" => Ok(Field::Start), + _ => { + let value = crate::__private::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + pub struct RangeFromVisitor { + pub expecting: &'static str, + pub phantom: PhantomData, + } + + impl<'de, Idx> Visitor<'de> for RangeFromVisitor + where + Idx: Deserialize<'de>, + { + type Value = Idx; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let start: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + Ok(start) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut start: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::Start => { + if start.is_some() { + return Err(::duplicate_field("start")); + } + start = Some(tri!(map.next_value())); + } + } + } + let start = match start { + Some(start) => start, + None => return Err(::missing_field("start")), + }; + Ok(start) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct RangeTo { +// end: Idx, +// } +impl<'de, Idx> Deserialize<'de> for RangeTo +where + Idx: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let end = tri!(deserializer.deserialize_struct( + "RangeTo", + range_to::FIELDS, + range_to::RangeToVisitor { + expecting: "struct RangeTo", + phantom: PhantomData, + }, + )); + Ok(..end) + } +} + +mod range_to { + use crate::lib::*; + + use crate::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + + pub const FIELDS: &[&str] = &["end"]; + + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + End, + } + + impl<'de> Deserialize<'de> for Field { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`end`") + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "end" => Ok(Field::End), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"end" => Ok(Field::End), + _ => { + let value = crate::__private::from_utf8_lossy(value); + Err(Error::unknown_field(&*value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + pub struct RangeToVisitor { + pub expecting: &'static str, + pub phantom: PhantomData, + } + + impl<'de, Idx> Visitor<'de> for RangeToVisitor + where + Idx: Deserialize<'de>, + { + type Value = Idx; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let end: Idx = match tri!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + Ok(end) + } + + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut end: Option = None; + while let Some(key) = tri!(map.next_key()) { + match key { + Field::End => { + if end.is_some() { + return Err(::duplicate_field("end")); + } + end = Some(tri!(map.next_value())); + } + } + } + let end = match end { + Some(end) => end, + None => return Err(::missing_field("end")), + }; + Ok(end) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T> Deserialize<'de> for Bound +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + enum Field { + Unbounded, + Included, + Excluded, + } + + impl<'de> Deserialize<'de> for Field { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`Unbounded`, `Included` or `Excluded`") + } + + fn visit_u64(self, value: u64) -> Result + where + E: Error, + { + match value { + 0 => Ok(Field::Unbounded), + 1 => Ok(Field::Included), + 2 => Ok(Field::Excluded), + _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)), + } + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "Unbounded" => Ok(Field::Unbounded), + "Included" => Ok(Field::Included), + "Excluded" => Ok(Field::Excluded), + _ => Err(Error::unknown_variant(value, VARIANTS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"Unbounded" => Ok(Field::Unbounded), + b"Included" => Ok(Field::Included), + b"Excluded" => Ok(Field::Excluded), + _ => match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, VARIANTS)), + Err(_) => { + Err(Error::invalid_value(Unexpected::Bytes(value), &self)) + } + }, + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct BoundVisitor(PhantomData>); + + impl<'de, T> Visitor<'de> for BoundVisitor + where + T: Deserialize<'de>, + { + type Value = Bound; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("enum Bound") + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + match tri!(data.variant()) { + (Field::Unbounded, v) => v.unit_variant().map(|()| Bound::Unbounded), + (Field::Included, v) => v.newtype_variant().map(Bound::Included), + (Field::Excluded, v) => v.newtype_variant().map(Bound::Excluded), + } + } + } + + const VARIANTS: &[&str] = &["Unbounded", "Included", "Excluded"]; + + deserializer.deserialize_enum("Bound", VARIANTS, BoundVisitor(PhantomData)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T, E> Deserialize<'de> for Result +where + T: Deserialize<'de>, + E: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(variant_identifier)] + enum Field { + Ok, + Err, + } + + impl<'de> Deserialize<'de> for Field { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`Ok` or `Err`") + } + + fn visit_u64(self, value: u64) -> Result + where + E: Error, + { + match value { + 0 => Ok(Field::Ok), + 1 => Ok(Field::Err), + _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self)), + } + } + + fn visit_str(self, value: &str) -> Result + where + E: Error, + { + match value { + "Ok" => Ok(Field::Ok), + "Err" => Ok(Field::Err), + _ => Err(Error::unknown_variant(value, VARIANTS)), + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + E: Error, + { + match value { + b"Ok" => Ok(Field::Ok), + b"Err" => Ok(Field::Err), + _ => match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, VARIANTS)), + Err(_) => { + Err(Error::invalid_value(Unexpected::Bytes(value), &self)) + } + }, + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct ResultVisitor(PhantomData>); + + impl<'de, T, E> Visitor<'de> for ResultVisitor + where + T: Deserialize<'de>, + E: Deserialize<'de>, + { + type Value = Result; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("enum Result") + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + match tri!(data.variant()) { + (Field::Ok, v) => v.newtype_variant().map(Ok), + (Field::Err, v) => v.newtype_variant().map(Err), + } + } + } + + const VARIANTS: &[&str] = &["Ok", "Err"]; + + deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T> Deserialize<'de> for Wrapping +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(Wrapping) + } +} + +#[cfg(all(feature = "std", not(no_std_atomic)))] +macro_rules! atomic_impl { + ($($ty:ident $size:expr)*) => { + $( + #[cfg(any(no_target_has_atomic, target_has_atomic = $size))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "std", target_has_atomic = $size))))] + impl<'de> Deserialize<'de> for $ty { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(Self::new) + } + } + )* + }; +} + +#[cfg(all(feature = "std", not(no_std_atomic)))] +atomic_impl! { + AtomicBool "8" + AtomicI8 "8" + AtomicI16 "16" + AtomicI32 "32" + AtomicIsize "ptr" + AtomicU8 "8" + AtomicU16 "16" + AtomicU32 "32" + AtomicUsize "ptr" +} + +#[cfg(all(feature = "std", not(no_std_atomic64)))] +atomic_impl! { + AtomicI64 "64" + AtomicU64 "64" +} + +#[cfg(any(feature = "std", not(no_core_net)))] +struct FromStrVisitor { + expecting: &'static str, + ty: PhantomData, +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl FromStrVisitor { + fn new(expecting: &'static str) -> Self { + FromStrVisitor { + expecting, + ty: PhantomData, + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl<'de, T> Visitor<'de> for FromStrVisitor +where + T: str::FromStr, + T::Err: fmt::Display, +{ + type Value = T; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.expecting) + } + + fn visit_str(self, s: &str) -> Result + where + E: Error, + { + s.parse().map_err(Error::custom) + } +} diff --git a/bitbox02-bt/vendor/serde/src/de/mod.rs b/bitbox02-bt/vendor/serde/src/de/mod.rs new file mode 100644 index 0000000..21cfd04 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/de/mod.rs @@ -0,0 +1,2335 @@ +//! Generic data structure deserialization framework. +//! +//! The two most important traits in this module are [`Deserialize`] and +//! [`Deserializer`]. +//! +//! - **A type that implements `Deserialize` is a data structure** that can be +//! deserialized from any data format supported by Serde, and conversely +//! - **A type that implements `Deserializer` is a data format** that can +//! deserialize any data structure supported by Serde. +//! +//! # The Deserialize trait +//! +//! Serde provides [`Deserialize`] implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! deserialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called [`serde_derive`] to +//! automatically generate [`Deserialize`] implementations for structs and enums +//! in your program. See the [derive section of the manual] for how to use this. +//! +//! In rare cases it may be necessary to implement [`Deserialize`] manually for +//! some type in your program. See the [Implementing `Deserialize`] section of +//! the manual for more about this. +//! +//! Third-party crates may provide [`Deserialize`] implementations for types +//! that they expose. For example the [`linked-hash-map`] crate provides a +//! [`LinkedHashMap`] type that is deserializable by Serde because the +//! crate provides an implementation of [`Deserialize`] for it. +//! +//! # The Deserializer trait +//! +//! [`Deserializer`] implementations are provided by third-party crates, for +//! example [`serde_json`], [`serde_yaml`] and [`postcard`]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data formats]. +//! +//! # Implementations of Deserialize provided by Serde +//! +//! This is a slightly different set of types than what is supported for +//! serialization. Some types can be serialized by Serde but not deserialized. +//! One example is `OsStr`. +//! +//! - **Primitive types**: +//! - bool +//! - i8, i16, i32, i64, i128, isize +//! - u8, u16, u32, u64, u128, usize +//! - f32, f64 +//! - char +//! - **Compound types**: +//! - \[T; 0\] through \[T; 32\] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\ +//! - Result\ +//! - PhantomData\ +//! - **Wrapper types**: +//! - Box\ +//! - Box\<\[T\]\> +//! - Box\ +//! - Cow\<'a, T\> +//! - Cell\ +//! - RefCell\ +//! - Mutex\ +//! - RwLock\ +//! - Rc\ *(if* features = \["rc"\] *is enabled)* +//! - Arc\ *(if* features = \["rc"\] *is enabled)* +//! - **Collection types**: +//! - BTreeMap\ +//! - BTreeSet\ +//! - BinaryHeap\ +//! - HashMap\ +//! - HashSet\ +//! - LinkedList\ +//! - VecDeque\ +//! - Vec\ +//! - **Zero-copy types**: +//! - &str +//! - &\[u8\] +//! - **FFI types**: +//! - CString +//! - Box\ +//! - OsString +//! - **Miscellaneous standard library types**: +//! - Duration +//! - SystemTime +//! - Path +//! - PathBuf +//! - Range\ +//! - RangeInclusive\ +//! - Bound\ +//! - num::NonZero* +//! - `!` *(unstable)* +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html +//! [`Deserialize`]: ../trait.Deserialize.html +//! [`Deserializer`]: ../trait.Deserializer.html +//! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +//! [`postcard`]: https://github.com/jamesmunns/postcard +//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +//! [`serde_derive`]: https://crates.io/crates/serde_derive +//! [`serde_json`]: https://github.com/serde-rs/json +//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml +//! [derive section of the manual]: https://serde.rs/derive.html +//! [data formats]: https://serde.rs/#data-formats + +use crate::lib::*; + +//////////////////////////////////////////////////////////////////////////////// + +pub mod value; + +mod ignored_any; +mod impls; +pub(crate) mod size_hint; + +pub use self::ignored_any::IgnoredAny; + +#[cfg(all(not(feature = "std"), no_core_error))] +#[doc(no_inline)] +pub use crate::std_error::Error as StdError; +#[cfg(not(any(feature = "std", no_core_error)))] +#[doc(no_inline)] +pub use core::error::Error as StdError; +#[cfg(feature = "std")] +#[doc(no_inline)] +pub use std::error::Error as StdError; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! declare_error_trait { + (Error: Sized $(+ $($supertrait:ident)::+)*) => { + /// The `Error` trait allows `Deserialize` implementations to create descriptive + /// error messages belonging to the `Deserializer` against which they are + /// currently running. + /// + /// Every `Deserializer` declares an `Error` type that encompasses both + /// general-purpose deserialization errors as well as errors specific to the + /// particular deserialization format. For example the `Error` type of + /// `serde_json` can represent errors like an invalid JSON escape sequence or an + /// unterminated string literal, in addition to the error cases that are part of + /// this trait. + /// + /// Most deserializers should only need to provide the `Error::custom` method + /// and inherit the default behavior for the other methods. + /// + /// # Example implementation + /// + /// The [example data format] presented on the website shows an error + /// type appropriate for a basic JSON data format. + /// + /// [example data format]: https://serde.rs/data-format.html + pub trait Error: Sized $(+ $($supertrait)::+)* { + /// Raised when there is general error when deserializing a type. + /// + /// The message should not be capitalized and should not end with a period. + /// + /// ```edition2021 + /// # use std::str::FromStr; + /// # + /// # struct IpAddr; + /// # + /// # impl FromStr for IpAddr { + /// # type Err = String; + /// # + /// # fn from_str(_: &str) -> Result { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::de::{self, Deserialize, Deserializer}; + /// + /// impl<'de> Deserialize<'de> for IpAddr { + /// fn deserialize(deserializer: D) -> Result + /// where + /// D: Deserializer<'de>, + /// { + /// let s = String::deserialize(deserializer)?; + /// s.parse().map_err(de::Error::custom) + /// } + /// } + /// ``` + fn custom(msg: T) -> Self + where + T: Display; + + /// Raised when a `Deserialize` receives a type different from what it was + /// expecting. + /// + /// The `unexp` argument provides information about what type was received. + /// This is the type that was present in the input file or other source data + /// of the Deserializer. + /// + /// The `exp` argument provides information about what type was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of a JSON file + /// containing an integer, the unexpected type is the integer and the + /// expected type is the string. + #[cold] + fn invalid_type(unexp: Unexpected, exp: &Expected) -> Self { + Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) + } + + /// Raised when a `Deserialize` receives a value of the right type but that + /// is wrong for some other reason. + /// + /// The `unexp` argument provides information about what value was received. + /// This is the value that was present in the input file or other source + /// data of the Deserializer. + /// + /// The `exp` argument provides information about what value was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of some binary data + /// that is not valid UTF-8, the unexpected value is the bytes and the + /// expected value is a string. + #[cold] + fn invalid_value(unexp: Unexpected, exp: &Expected) -> Self { + Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp)) + } + + /// Raised when deserializing a sequence or map and the input data contains + /// too many or too few elements. + /// + /// The `len` argument is the number of elements encountered. The sequence + /// or map may have expected more arguments or fewer arguments. + /// + /// The `exp` argument provides information about what data was being + /// expected. For example `exp` might say that a tuple of size 6 was + /// expected. + #[cold] + fn invalid_length(len: usize, exp: &Expected) -> Self { + Error::custom(format_args!("invalid length {}, expected {}", len, exp)) + } + + /// Raised when a `Deserialize` enum type received a variant with an + /// unrecognized name. + #[cold] + fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!( + "unknown variant `{}`, there are no variants", + variant + )) + } else { + Error::custom(format_args!( + "unknown variant `{}`, expected {}", + variant, + OneOf { names: expected } + )) + } + } + + /// Raised when a `Deserialize` struct type received a field with an + /// unrecognized name. + #[cold] + fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!( + "unknown field `{}`, there are no fields", + field + )) + } else { + Error::custom(format_args!( + "unknown field `{}`, expected {}", + field, + OneOf { names: expected } + )) + } + } + + /// Raised when a `Deserialize` struct type expected to receive a required + /// field with a particular name but that field was not present in the + /// input. + #[cold] + fn missing_field(field: &'static str) -> Self { + Error::custom(format_args!("missing field `{}`", field)) + } + + /// Raised when a `Deserialize` struct type received more than one of the + /// same field. + #[cold] + fn duplicate_field(field: &'static str) -> Self { + Error::custom(format_args!("duplicate field `{}`", field)) + } + } + } +} + +#[cfg(feature = "std")] +declare_error_trait!(Error: Sized + StdError); + +#[cfg(not(feature = "std"))] +declare_error_trait!(Error: Sized + Debug + Display); + +/// `Unexpected` represents an unexpected invocation of any one of the `Visitor` +/// trait methods. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. +/// +/// ```edition2021 +/// # use std::fmt; +/// # +/// # use serde::de::{self, Unexpected, Visitor}; +/// # +/// # struct Example; +/// # +/// # impl<'de> Visitor<'de> for Example { +/// # type Value = (); +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # +/// fn visit_bool(self, v: bool) -> Result +/// where +/// E: de::Error, +/// { +/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # } +/// ``` +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum Unexpected<'a> { + /// The input contained a boolean value that was not expected. + Bool(bool), + + /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that + /// was not expected. + Unsigned(u64), + + /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that + /// was not expected. + Signed(i64), + + /// The input contained a floating point `f32` or `f64` that was not + /// expected. + Float(f64), + + /// The input contained a `char` that was not expected. + Char(char), + + /// The input contained a `&str` or `String` that was not expected. + Str(&'a str), + + /// The input contained a `&[u8]` or `Vec` that was not expected. + Bytes(&'a [u8]), + + /// The input contained a unit `()` that was not expected. + Unit, + + /// The input contained an `Option` that was not expected. + Option, + + /// The input contained a newtype struct that was not expected. + NewtypeStruct, + + /// The input contained a sequence that was not expected. + Seq, + + /// The input contained a map that was not expected. + Map, + + /// The input contained an enum that was not expected. + Enum, + + /// The input contained a unit variant that was not expected. + UnitVariant, + + /// The input contained a newtype variant that was not expected. + NewtypeVariant, + + /// The input contained a tuple variant that was not expected. + TupleVariant, + + /// The input contained a struct variant that was not expected. + StructVariant, + + /// A message stating what uncategorized thing the input contained that was + /// not expected. + /// + /// The message should be a noun or noun phrase, not capitalized and without + /// a period. An example message is "unoriginal superhero". + Other(&'a str), +} + +impl<'a> fmt::Display for Unexpected<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + use self::Unexpected::*; + match *self { + Bool(b) => write!(formatter, "boolean `{}`", b), + Unsigned(i) => write!(formatter, "integer `{}`", i), + Signed(i) => write!(formatter, "integer `{}`", i), + Float(f) => write!(formatter, "floating point `{}`", WithDecimalPoint(f)), + Char(c) => write!(formatter, "character `{}`", c), + Str(s) => write!(formatter, "string {:?}", s), + Bytes(_) => formatter.write_str("byte array"), + Unit => formatter.write_str("unit value"), + Option => formatter.write_str("Option value"), + NewtypeStruct => formatter.write_str("newtype struct"), + Seq => formatter.write_str("sequence"), + Map => formatter.write_str("map"), + Enum => formatter.write_str("enum"), + UnitVariant => formatter.write_str("unit variant"), + NewtypeVariant => formatter.write_str("newtype variant"), + TupleVariant => formatter.write_str("tuple variant"), + StructVariant => formatter.write_str("struct variant"), + Other(other) => formatter.write_str(other), + } + } +} + +/// `Expected` represents an explanation of what data a `Visitor` was expecting +/// to receive. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. The +/// message should be a noun or noun phrase that completes the sentence "This +/// Visitor expects to receive ...", for example the message could be "an +/// integer between 0 and 64". The message should not be capitalized and should +/// not end with a period. +/// +/// Within the context of a `Visitor` implementation, the `Visitor` itself +/// (`&self`) is an implementation of this trait. +/// +/// ```edition2021 +/// # use serde::de::{self, Unexpected, Visitor}; +/// # use std::fmt; +/// # +/// # struct Example; +/// # +/// # impl<'de> Visitor<'de> for Example { +/// # type Value = (); +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # +/// fn visit_bool(self, v: bool) -> Result +/// where +/// E: de::Error, +/// { +/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # } +/// ``` +/// +/// Outside of a `Visitor`, `&"..."` can be used. +/// +/// ```edition2021 +/// # use serde::de::{self, Unexpected}; +/// # +/// # fn example() -> Result<(), E> +/// # where +/// # E: de::Error, +/// # { +/// # let v = true; +/// return Err(de::Error::invalid_type( +/// Unexpected::Bool(v), +/// &"a negative integer", +/// )); +/// # } +/// ``` +pub trait Expected { + /// Format an explanation of what data was being expected. Same signature as + /// the `Display` and `Debug` traits. + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result; +} + +impl<'de, T> Expected for T +where + T: Visitor<'de>, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.expecting(formatter) + } +} + +impl<'a> Expected for &'a str { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self) + } +} + +impl<'a> Display for Expected + 'a { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Expected::fmt(self, formatter) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be deserialized from any data format supported +/// by Serde. +/// +/// Serde provides `Deserialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][crate::de]. All of these +/// can be deserialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called `serde_derive` to +/// automatically generate `Deserialize` implementations for structs and enums +/// in your program. See the [derive section of the manual][derive] for how to +/// use this. +/// +/// In rare cases it may be necessary to implement `Deserialize` manually for +/// some type in your program. See the [Implementing +/// `Deserialize`][impl-deserialize] section of the manual for more about this. +/// +/// Third-party crates may provide `Deserialize` implementations for types that +/// they expose. For example the `linked-hash-map` crate provides a +/// `LinkedHashMap` type that is deserializable by Serde because the crate +/// provides an implementation of `Deserialize` for it. +/// +/// [derive]: https://serde.rs/derive.html +/// [impl-deserialize]: https://serde.rs/impl-deserialize.html +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by `Self` when deserialized. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + note = "for local types consider adding `#[derive(serde::Deserialize)]` to your `{Self}` type", + note = "for types from other crates check whether the crate offers a `serde` feature flag", + ) +)] +pub trait Deserialize<'de>: Sized { + /// Deserialize this value from the given Serde deserializer. + /// + /// See the [Implementing `Deserialize`][impl-deserialize] section of the + /// manual for more information about how to implement this method. + /// + /// [impl-deserialize]: https://serde.rs/impl-deserialize.html + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>; + + /// Deserializes a value into `self` from the given Deserializer. + /// + /// The purpose of this method is to allow the deserializer to reuse + /// resources and avoid copies. As such, if this method returns an error, + /// `self` will be in an indeterminate state where some parts of the struct + /// have been overwritten. Although whatever state that is will be + /// memory-safe. + /// + /// This is generally useful when repeatedly deserializing values that + /// are processed one at a time, where the value of `self` doesn't matter + /// when the next deserialization occurs. + /// + /// If you manually implement this, your recursive deserializations should + /// use `deserialize_in_place`. + /// + /// This method is stable and an official public API, but hidden from the + /// documentation because it is almost never what newbies are looking for. + /// Showing it in rustdoc would cause it to be featured more prominently + /// than it deserves. + #[doc(hidden)] + fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + // Default implementation just delegates to `deserialize` impl. + *place = tri!(Deserialize::deserialize(deserializer)); + Ok(()) + } +} + +/// A data structure that can be deserialized without borrowing any data from +/// the deserializer. +/// +/// This is primarily useful for trait bounds on functions. For example a +/// `from_str` function may be able to deserialize a data structure that borrows +/// from the input string, but a `from_reader` function may only deserialize +/// owned data. +/// +/// ```edition2021 +/// # use serde::de::{Deserialize, DeserializeOwned}; +/// # use std::io::{Read, Result}; +/// # +/// # trait Ignore { +/// fn from_str<'a, T>(s: &'a str) -> Result +/// where +/// T: Deserialize<'a>; +/// +/// fn from_reader(rdr: R) -> Result +/// where +/// R: Read, +/// T: DeserializeOwned; +/// # } +/// ``` +/// +/// # Lifetime +/// +/// The relationship between `Deserialize` and `DeserializeOwned` in trait +/// bounds is explained in more detail on the page [Understanding deserializer +/// lifetimes]. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +pub trait DeserializeOwned: for<'de> Deserialize<'de> {} +impl DeserializeOwned for T where T: for<'de> Deserialize<'de> {} + +/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you +/// ever find yourself looking for a way to pass data into a `Deserialize` impl, +/// this trait is the way to do it. +/// +/// As one example of stateful deserialization consider deserializing a JSON +/// array into an existing buffer. Using the `Deserialize` trait we could +/// deserialize a JSON array into a `Vec` but it would be a freshly allocated +/// `Vec`; there is no way for `Deserialize` to reuse a previously allocated +/// buffer. Using `DeserializeSeed` instead makes this possible as in the +/// example code below. +/// +/// The canonical API for stateless deserialization looks like this: +/// +/// ```edition2021 +/// # use serde::Deserialize; +/// # +/// # enum Error {} +/// # +/// fn func<'de, T: Deserialize<'de>>() -> Result +/// # { +/// # unimplemented!() +/// # } +/// ``` +/// +/// Adjusting an API like this to support stateful deserialization is a matter +/// of accepting a seed as input: +/// +/// ```edition2021 +/// # use serde::de::DeserializeSeed; +/// # +/// # enum Error {} +/// # +/// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result +/// # { +/// # let _ = seed; +/// # unimplemented!() +/// # } +/// ``` +/// +/// In practice the majority of deserialization is stateless. An API expecting a +/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the +/// case of stateless deserialization. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by `Self::Value` when deserialized. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example +/// +/// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need +/// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`. +/// Allocating a brand new `Vec` for each subarray would be slow. Instead we +/// would like to allocate a single `Vec` and then deserialize each subarray +/// into it. This requires stateful deserialization using the `DeserializeSeed` +/// trait. +/// +/// ```edition2021 +/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor}; +/// use std::fmt; +/// use std::marker::PhantomData; +/// +/// // A DeserializeSeed implementation that uses stateful deserialization to +/// // append array elements onto the end of an existing vector. The preexisting +/// // state ("seed") in this case is the Vec. The `deserialize` method of +/// // `ExtendVec` will be traversing the inner arrays of the JSON input and +/// // appending each integer into the existing Vec. +/// struct ExtendVec<'a, T: 'a>(&'a mut Vec); +/// +/// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T> +/// where +/// T: Deserialize<'de>, +/// { +/// // The return type of the `deserialize` method. This implementation +/// // appends onto an existing vector but does not create any new data +/// // structure, so the return type is (). +/// type Value = (); +/// +/// fn deserialize(self, deserializer: D) -> Result +/// where +/// D: Deserializer<'de>, +/// { +/// // Visitor implementation that will walk an inner array of the JSON +/// // input. +/// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec); +/// +/// impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T> +/// where +/// T: Deserialize<'de>, +/// { +/// type Value = (); +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "an array of integers") +/// } +/// +/// fn visit_seq(self, mut seq: A) -> Result<(), A::Error> +/// where +/// A: SeqAccess<'de>, +/// { +/// // Decrease the number of reallocations if there are many elements +/// if let Some(size_hint) = seq.size_hint() { +/// self.0.reserve(size_hint); +/// } +/// +/// // Visit each element in the inner array and push it onto +/// // the existing vector. +/// while let Some(elem) = seq.next_element()? { +/// self.0.push(elem); +/// } +/// Ok(()) +/// } +/// } +/// +/// deserializer.deserialize_seq(ExtendVecVisitor(self.0)) +/// } +/// } +/// +/// // Visitor implementation that will walk the outer array of the JSON input. +/// struct FlattenedVecVisitor(PhantomData); +/// +/// impl<'de, T> Visitor<'de> for FlattenedVecVisitor +/// where +/// T: Deserialize<'de>, +/// { +/// // This Visitor constructs a single Vec to hold the flattened +/// // contents of the inner arrays. +/// type Value = Vec; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "an array of arrays") +/// } +/// +/// fn visit_seq(self, mut seq: A) -> Result, A::Error> +/// where +/// A: SeqAccess<'de>, +/// { +/// // Create a single Vec to hold the flattened contents. +/// let mut vec = Vec::new(); +/// +/// // Each iteration through this loop is one inner array. +/// while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? { +/// // Nothing to do; inner array has been appended into `vec`. +/// } +/// +/// // Return the finished vec. +/// Ok(vec) +/// } +/// } +/// +/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> +/// # where +/// # D: Deserializer<'de>, +/// # { +/// let visitor = FlattenedVecVisitor(PhantomData); +/// let flattened: Vec = deserializer.deserialize_seq(visitor)?; +/// # Ok(()) +/// # } +/// ``` +pub trait DeserializeSeed<'de>: Sized { + /// The type produced by using this seed. + type Value; + + /// Equivalent to the more common `Deserialize::deserialize` method, except + /// with some initial piece of data (the seed) passed in. + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>; +} + +impl<'de, T> DeserializeSeed<'de> for PhantomData +where + T: Deserialize<'de>, +{ + type Value = T; + + #[inline] + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize(deserializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can deserialize any data structure supported by +/// Serde. +/// +/// The role of this trait is to define the deserialization half of the [Serde +/// data model], which is a way to categorize every Rust data type into one of +/// 29 possible types. Each method of the `Deserializer` trait corresponds to one +/// of the types of the data model. +/// +/// Implementations of `Deserialize` map themselves into this data model by +/// passing to the `Deserializer` a `Visitor` implementation that can receive +/// these various types. +/// +/// The types that make up the Serde data model are: +/// +/// - **14 primitive types** +/// - bool +/// - i8, i16, i32, i64, i128 +/// - u8, u16, u32, u64, u128 +/// - f32, f64 +/// - char +/// - **string** +/// - UTF-8 bytes with a length and no null terminator. +/// - When serializing, all strings are handled equally. When deserializing, +/// there are three flavors of strings: transient, owned, and borrowed. +/// - **byte array** - \[u8\] +/// - Similar to strings, during deserialization byte arrays can be +/// transient, owned, or borrowed. +/// - **option** +/// - Either none or some value. +/// - **unit** +/// - The type of `()` in Rust. It represents an anonymous value containing +/// no data. +/// - **unit_struct** +/// - For example `struct Unit` or `PhantomData`. It represents a named +/// value containing no data. +/// - **unit_variant** +/// - For example the `E::A` and `E::B` in `enum E { A, B }`. +/// - **newtype_struct** +/// - For example `struct Millimeters(u8)`. +/// - **newtype_variant** +/// - For example the `E::N` in `enum E { N(u8) }`. +/// - **seq** +/// - A variably sized heterogeneous sequence of values, for example `Vec` +/// or `HashSet`. When serializing, the length may or may not be known +/// before iterating through all the data. When deserializing, the length +/// is determined by looking at the serialized data. +/// - **tuple** +/// - A statically sized heterogeneous sequence of values for which the +/// length will be known at deserialization time without looking at the +/// serialized data, for example `(u8,)` or `(String, u64, Vec)` or +/// `[u64; 10]`. +/// - **tuple_struct** +/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. +/// - **tuple_variant** +/// - For example the `E::T` in `enum E { T(u8, u8) }`. +/// - **map** +/// - A heterogeneous key-value pairing, for example `BTreeMap`. +/// - **struct** +/// - A heterogeneous key-value pairing in which the keys are strings and +/// will be known at deserialization time without looking at the serialized +/// data, for example `struct S { r: u8, g: u8, b: u8 }`. +/// - **struct_variant** +/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. +/// +/// The `Deserializer` trait supports two entry point styles which enables +/// different kinds of deserialization. +/// +/// 1. The `deserialize_any` method. Self-describing data formats like JSON are +/// able to look at the serialized data and tell what it represents. For +/// example the JSON deserializer may see an opening curly brace (`{`) and +/// know that it is seeing a map. If the data format supports +/// `Deserializer::deserialize_any`, it will drive the Visitor using whatever +/// type it sees in the input. JSON uses this approach when deserializing +/// `serde_json::Value` which is an enum that can represent any JSON +/// document. Without knowing what is in a JSON document, we can deserialize +/// it to `serde_json::Value` by going through +/// `Deserializer::deserialize_any`. +/// +/// 2. The various `deserialize_*` methods. Non-self-describing formats like +/// Postcard need to be told what is in the input in order to deserialize it. +/// The `deserialize_*` methods are hints to the deserializer for how to +/// interpret the next piece of input. Non-self-describing formats are not +/// able to deserialize something like `serde_json::Value` which relies on +/// `Deserializer::deserialize_any`. +/// +/// When implementing `Deserialize`, you should avoid relying on +/// `Deserializer::deserialize_any` unless you need to be told by the +/// Deserializer what type is in the input. Know that relying on +/// `Deserializer::deserialize_any` means your data type will be able to +/// deserialize from self-describing formats only, ruling out Postcard and many +/// others. +/// +/// [Serde data model]: https://serde.rs/data-model.html +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed from the input when deserializing. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website contains example code for +/// a basic JSON `Deserializer`. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait Deserializer<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// Require the `Deserializer` to figure out how to drive the visitor based + /// on what data type is in the input. + /// + /// When implementing `Deserialize`, you should avoid relying on + /// `Deserializer::deserialize_any` unless you need to be told by the + /// Deserializer what type is in the input. Know that relying on + /// `Deserializer::deserialize_any` means your data type will be able to + /// deserialize from self-describing formats only, ruling out Postcard and + /// many others. + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `bool` value. + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i8` value. + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i16` value. + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i32` value. + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i64` value. + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i128` value. + /// + /// The default behavior unconditionally returns an error. + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let _ = visitor; + Err(Error::custom("i128 is not supported")) + } + + /// Hint that the `Deserialize` type is expecting a `u8` value. + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u16` value. + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u32` value. + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u64` value. + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `u128` value. + /// + /// The default behavior unconditionally returns an error. + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let _ = visitor; + Err(Error::custom("u128 is not supported")) + } + + /// Hint that the `Deserialize` type is expecting a `f32` value. + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `f64` value. + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `char` value. + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a string value and does + /// not benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `String` data, + /// indicate this to the `Deserializer` by using `deserialize_string` + /// instead. + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a string value and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `String` + /// data, indicate that to the `Deserializer` by using `deserialize_str` + /// instead. + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a byte array and does not + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `Vec` data, + /// indicate this to the `Deserializer` by using `deserialize_byte_buf` + /// instead. + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a byte array and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `Vec` + /// data, indicate that to the `Deserializer` by using `deserialize_bytes` + /// instead. + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an optional value. + /// + /// This allows deserializers that encode an optional value as a nullable + /// value to convert the null value into `None` and a regular value into + /// `Some(value)`. + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a unit value. + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a unit struct with a + /// particular name. + fn deserialize_unit_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a newtype struct with a + /// particular name. + fn deserialize_newtype_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a sequence of values. + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a sequence of values and + /// knows how many values there are without looking at the serialized data. + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a tuple struct with a + /// particular name and number of fields. + fn deserialize_tuple_struct( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a map of key-value pairs. + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a struct with a particular + /// name and fields. + fn deserialize_struct( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an enum value with a + /// particular name and possible variants. + fn deserialize_enum( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting the name of a struct + /// field or the discriminant of an enum variant. + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type needs to deserialize a value whose type + /// doesn't matter because it is ignored. + /// + /// Deserializers for non-self-describing formats may not support this mode. + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Determine whether `Deserialize` implementations should expect to + /// deserialize their human-readable form. + /// + /// Some types have a human-readable form that may be somewhat expensive to + /// construct, as well as a binary form that is compact and efficient. + /// Generally text-based formats like JSON and YAML will prefer to use the + /// human-readable one and binary formats like Postcard will prefer the + /// compact one. + /// + /// ```edition2021 + /// # use std::ops::Add; + /// # use std::str::FromStr; + /// # + /// # struct Timestamp; + /// # + /// # impl Timestamp { + /// # const EPOCH: Timestamp = Timestamp; + /// # } + /// # + /// # impl FromStr for Timestamp { + /// # type Err = String; + /// # fn from_str(_: &str) -> Result { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # struct Duration; + /// # + /// # impl Duration { + /// # fn seconds(_: u64) -> Self { unimplemented!() } + /// # } + /// # + /// # impl Add for Timestamp { + /// # type Output = Timestamp; + /// # fn add(self, _: Duration) -> Self::Output { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::de::{self, Deserialize, Deserializer}; + /// + /// impl<'de> Deserialize<'de> for Timestamp { + /// fn deserialize(deserializer: D) -> Result + /// where + /// D: Deserializer<'de>, + /// { + /// if deserializer.is_human_readable() { + /// // Deserialize from a human-readable string like "2015-05-15T17:01:00Z". + /// let s = String::deserialize(deserializer)?; + /// Timestamp::from_str(&s).map_err(de::Error::custom) + /// } else { + /// // Deserialize from a compact binary representation, seconds since + /// // the Unix epoch. + /// let n = u64::deserialize(deserializer)?; + /// Ok(Timestamp::EPOCH + Duration::seconds(n)) + /// } + /// } + /// } + /// ``` + /// + /// The default implementation of this method returns `true`. Data formats + /// may override this to `false` to request a compact form for types that + /// support one. Note that modifying this method to change a format from + /// human-readable to compact or vice versa should be regarded as a breaking + /// change, as a value serialized in human-readable mode is not required to + /// deserialize from the same data in compact mode. + #[inline] + fn is_human_readable(&self) -> bool { + true + } + + // Not public API. + #[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] + #[doc(hidden)] + fn __deserialize_content( + self, + _: crate::actually_private::T, + visitor: V, + ) -> Result, Self::Error> + where + V: Visitor<'de, Value = crate::__private::de::Content<'de>>, + { + self.deserialize_any(visitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// This trait represents a visitor that walks through a deserializer. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the requirement for lifetime of data +/// that may be borrowed by `Self::Value`. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example +/// +/// ```edition2021 +/// # use serde::de::{self, Unexpected, Visitor}; +/// # use std::fmt; +/// # +/// /// A visitor that deserializes a long string - a string containing at least +/// /// some minimum number of bytes. +/// struct LongString { +/// min: usize, +/// } +/// +/// impl<'de> Visitor<'de> for LongString { +/// type Value = String; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "a string containing at least {} bytes", self.min) +/// } +/// +/// fn visit_str(self, s: &str) -> Result +/// where +/// E: de::Error, +/// { +/// if s.len() >= self.min { +/// Ok(s.to_owned()) +/// } else { +/// Err(de::Error::invalid_value(Unexpected::Str(s), &self)) +/// } +/// } +/// } +/// ``` +pub trait Visitor<'de>: Sized { + /// The value produced by this visitor. + type Value; + + /// Format a message stating what data this Visitor expects to receive. + /// + /// This is used in error messages. The message should complete the sentence + /// "This Visitor expects to receive ...", for example the message could be + /// "an integer between 0 and 64". The message should not be capitalized and + /// should not end with a period. + /// + /// ```edition2021 + /// # use std::fmt; + /// # + /// # struct S { + /// # max: usize, + /// # } + /// # + /// # impl<'de> serde::de::Visitor<'de> for S { + /// # type Value = (); + /// # + /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + /// write!(formatter, "an integer between 0 and {}", self.max) + /// } + /// # } + /// ``` + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result; + + /// The input contains a boolean. + /// + /// The default implementation fails with a type error. + fn visit_bool(self, v: bool) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Bool(v), &self)) + } + + /// The input contains an `i8`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i8(self, v: i8) -> Result + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i16`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i16(self, v: i16) -> Result + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i32`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i32(self, v: i32) -> Result + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i64`. + /// + /// The default implementation fails with a type error. + fn visit_i64(self, v: i64) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Signed(v), &self)) + } + + /// The input contains a `i128`. + /// + /// The default implementation fails with a type error. + fn visit_i128(self, v: i128) -> Result + where + E: Error, + { + let mut buf = [0u8; 58]; + let mut writer = crate::format::Buf::new(&mut buf); + fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap(); + Err(Error::invalid_type( + Unexpected::Other(writer.as_str()), + &self, + )) + } + + /// The input contains a `u8`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u8(self, v: u8) -> Result + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u16`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u16(self, v: u16) -> Result + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u32`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u32(self, v: u32) -> Result + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u64`. + /// + /// The default implementation fails with a type error. + fn visit_u64(self, v: u64) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Unsigned(v), &self)) + } + + /// The input contains a `u128`. + /// + /// The default implementation fails with a type error. + fn visit_u128(self, v: u128) -> Result + where + E: Error, + { + let mut buf = [0u8; 57]; + let mut writer = crate::format::Buf::new(&mut buf); + fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap(); + Err(Error::invalid_type( + Unexpected::Other(writer.as_str()), + &self, + )) + } + + /// The input contains an `f32`. + /// + /// The default implementation forwards to [`visit_f64`]. + /// + /// [`visit_f64`]: #method.visit_f64 + fn visit_f32(self, v: f32) -> Result + where + E: Error, + { + self.visit_f64(v as f64) + } + + /// The input contains an `f64`. + /// + /// The default implementation fails with a type error. + fn visit_f64(self, v: f64) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Float(v), &self)) + } + + /// The input contains a `char`. + /// + /// The default implementation forwards to [`visit_str`] as a one-character + /// string. + /// + /// [`visit_str`]: #method.visit_str + #[inline] + fn visit_char(self, v: char) -> Result + where + E: Error, + { + self.visit_str(v.encode_utf8(&mut [0u8; 4])) + } + + /// The input contains a string. The lifetime of the string is ephemeral and + /// it may be destroyed after this method returns. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_str` rather than + /// `Deserializer::deserialize_string`. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Str(v), &self)) + } + + /// The input contains a string that lives at least as long as the + /// `Deserializer`. + /// + /// This enables zero-copy deserialization of strings in some formats. For + /// example JSON input containing the JSON string `"borrowed"` can be + /// deserialized with zero copying into a `&'a str` as long as the input + /// data outlives `'a`. + /// + /// The default implementation forwards to `visit_str`. + #[inline] + fn visit_borrowed_str(self, v: &'de str) -> Result + where + E: Error, + { + self.visit_str(v) + } + + /// The input contains a string and ownership of the string is being given + /// to the `Visitor`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a string created by the `Deserializer`. `Deserialize` implementations + /// that benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_string` rather + /// than `Deserializer::deserialize_str`, although not every deserializer + /// will honor such a request. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + /// + /// The default implementation forwards to `visit_str` and then drops the + /// `String`. + #[inline] + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + fn visit_string(self, v: String) -> Result + where + E: Error, + { + self.visit_str(&v) + } + + /// The input contains a byte array. The lifetime of the byte array is + /// ephemeral and it may be destroyed after this method returns. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `Vec` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_bytes` rather + /// than `Deserializer::deserialize_byte_buf`. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Bytes(v), &self)) + } + + /// The input contains a byte array that lives at least as long as the + /// `Deserializer`. + /// + /// This enables zero-copy deserialization of bytes in some formats. For + /// example Postcard data containing bytes can be deserialized with zero + /// copying into a `&'a [u8]` as long as the input data outlives `'a`. + /// + /// The default implementation forwards to `visit_bytes`. + #[inline] + fn visit_borrowed_bytes(self, v: &'de [u8]) -> Result + where + E: Error, + { + self.visit_bytes(v) + } + + /// The input contains a byte array and ownership of the byte array is being + /// given to the `Visitor`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a byte buffer created by the `Deserializer`. `Deserialize` + /// implementations that benefit from taking ownership of `Vec` data + /// should indicate that to the deserializer by using + /// `Deserializer::deserialize_byte_buf` rather than + /// `Deserializer::deserialize_bytes`, although not every deserializer will + /// honor such a request. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + /// + /// The default implementation forwards to `visit_bytes` and then drops the + /// `Vec`. + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + self.visit_bytes(&v) + } + + /// The input contains an optional that is absent. + /// + /// The default implementation fails with a type error. + fn visit_none(self) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// The input contains an optional that is present. + /// + /// The default implementation fails with a type error. + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// The input contains a unit `()`. + /// + /// The default implementation fails with a type error. + fn visit_unit(self) -> Result + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Unit, &self)) + } + + /// The input contains a newtype struct. + /// + /// The content of the newtype struct may be read from the given + /// `Deserializer`. + /// + /// The default implementation fails with a type error. + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::NewtypeStruct, &self)) + } + + /// The input contains a sequence of elements. + /// + /// The default implementation fails with a type error. + fn visit_seq(self, seq: A) -> Result + where + A: SeqAccess<'de>, + { + let _ = seq; + Err(Error::invalid_type(Unexpected::Seq, &self)) + } + + /// The input contains a key-value map. + /// + /// The default implementation fails with a type error. + fn visit_map(self, map: A) -> Result + where + A: MapAccess<'de>, + { + let _ = map; + Err(Error::invalid_type(Unexpected::Map, &self)) + } + + /// The input contains an enum. + /// + /// The default implementation fails with a type error. + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + let _ = data; + Err(Error::invalid_type(Unexpected::Enum, &self)) + } + + // Used when deserializing a flattened Option field. Not public API. + #[doc(hidden)] + fn __private_visit_untagged_option(self, _: D) -> Result + where + D: Deserializer<'de>, + { + Err(()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to each element of a sequence in the input. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation, +/// which deserializes each item in a sequence. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by deserialized sequence elements. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SeqAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SeqAccess<'de> { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// `Deserialize` implementations should typically use + /// `SeqAccess::next_element` instead. + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `SeqAccess` implementations should not override the default behavior. + #[inline] + fn next_element(&mut self) -> Result, Self::Error> + where + T: Deserialize<'de>, + { + self.next_element_seed(PhantomData) + } + + /// Returns the number of elements remaining in the sequence, if known. + #[inline] + fn size_hint(&self) -> Option { + None + } +} + +impl<'de, 'a, A> SeqAccess<'de> for &'a mut A +where + A: ?Sized + SeqAccess<'de>, +{ + type Error = A::Error; + + #[inline] + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + (**self).next_element_seed(seed) + } + + #[inline] + fn next_element(&mut self) -> Result, Self::Error> + where + T: Deserialize<'de>, + { + (**self).next_element() + } + + #[inline] + fn size_hint(&self) -> Option { + (**self).size_hint() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to each entry of a map in the input. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by deserialized map entries. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `MapAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait MapAccess<'de> { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_key` or `MapAccess::next_entry` instead. + fn next_key_seed(&mut self, seed: K) -> Result, Self::Error> + where + K: DeserializeSeed<'de>; + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_value` instead. + /// + /// # Panics + /// + /// Calling `next_value_seed` before `next_key_seed` is incorrect and is + /// allowed to panic or return bogus results. + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>; + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// `MapAccess` implementations should override the default behavior if a + /// more efficient implementation is possible. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_entry` instead. + #[inline] + fn next_entry_seed( + &mut self, + kseed: K, + vseed: V, + ) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + V: DeserializeSeed<'de>, + { + match tri!(self.next_key_seed(kseed)) { + Some(key) => { + let value = tri!(self.next_value_seed(vseed)); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + #[inline] + fn next_key(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + { + self.next_key_seed(PhantomData) + } + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + /// + /// # Panics + /// + /// Calling `next_value` before `next_key` is incorrect and is allowed to + /// panic or return bogus results. + #[inline] + fn next_value(&mut self) -> Result + where + V: Deserialize<'de>, + { + self.next_value_seed(PhantomData) + } + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + #[inline] + fn next_entry(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + V: Deserialize<'de>, + { + self.next_entry_seed(PhantomData, PhantomData) + } + + /// Returns the number of entries remaining in the map, if known. + #[inline] + fn size_hint(&self) -> Option { + None + } +} + +impl<'de, 'a, A> MapAccess<'de> for &'a mut A +where + A: ?Sized + MapAccess<'de>, +{ + type Error = A::Error; + + #[inline] + fn next_key_seed(&mut self, seed: K) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + { + (**self).next_key_seed(seed) + } + + #[inline] + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>, + { + (**self).next_value_seed(seed) + } + + #[inline] + fn next_entry_seed( + &mut self, + kseed: K, + vseed: V, + ) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + V: DeserializeSeed<'de>, + { + (**self).next_entry_seed(kseed, vseed) + } + + #[inline] + fn next_entry(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + V: Deserialize<'de>, + { + (**self).next_entry() + } + + #[inline] + fn next_key(&mut self) -> Result, Self::Error> + where + K: Deserialize<'de>, + { + (**self).next_key() + } + + #[inline] + fn next_value(&mut self) -> Result + where + V: Deserialize<'de>, + { + (**self).next_value() + } + + #[inline] + fn size_hint(&self) -> Option { + (**self).size_hint() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to the data of an enum in the input. +/// +/// `EnumAccess` is created by the `Deserializer` and passed to the +/// `Visitor` in order to identify which variant of an enum to deserialize. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by the deserialized enum variant. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `EnumAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait EnumAccess<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + /// The `Visitor` that will be used to deserialize the content of the enum + /// variant. + type Variant: VariantAccess<'de, Error = Self::Error>; + + /// `variant` is called to identify which variant to deserialize. + /// + /// `Deserialize` implementations should typically use `EnumAccess::variant` + /// instead. + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: DeserializeSeed<'de>; + + /// `variant` is called to identify which variant to deserialize. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `EnumAccess` implementations should not override the default behavior. + #[inline] + fn variant(self) -> Result<(V, Self::Variant), Self::Error> + where + V: Deserialize<'de>, + { + self.variant_seed(PhantomData) + } +} + +/// `VariantAccess` is a visitor that is created by the `Deserializer` and +/// passed to the `Deserialize` to deserialize the content of a particular enum +/// variant. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed by the deserialized enum variant. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `VariantAccess` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait VariantAccess<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. Must match the error type of our `EnumAccess`. + type Error: Error; + + /// Called when deserializing a variant with no values. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// fn unit_variant(self) -> Result<(), Self::Error> { + /// // What the data actually contained; suppose it is a tuple variant. + /// let unexp = Unexpected::TupleVariant; + /// Err(de::Error::invalid_type(unexp, &"unit variant")) + /// } + /// # + /// # fn newtype_variant_seed(self, _: T) -> Result + /// # where + /// # T: DeserializeSeed<'de>, + /// # { unimplemented!() } + /// # + /// # fn tuple_variant(self, _: usize, _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # + /// # fn struct_variant(self, _: &[&str], _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # } + /// ``` + fn unit_variant(self) -> Result<(), Self::Error>; + + /// Called when deserializing a variant with a single value. + /// + /// `Deserialize` implementations should typically use + /// `VariantAccess::newtype_variant` instead. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// fn newtype_variant_seed(self, _seed: T) -> Result + /// where + /// T: DeserializeSeed<'de>, + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"newtype variant")) + /// } + /// # + /// # fn tuple_variant(self, _: usize, _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # + /// # fn struct_variant(self, _: &[&str], _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # } + /// ``` + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>; + + /// Called when deserializing a variant with a single value. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `VariantAccess` implementations should not override the default + /// behavior. + #[inline] + fn newtype_variant(self) -> Result + where + T: Deserialize<'de>, + { + self.newtype_variant_seed(PhantomData) + } + + /// Called when deserializing a tuple-like variant. + /// + /// The `len` is the number of fields expected in the tuple variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// # fn newtype_variant_seed(self, _: T) -> Result + /// # where + /// # T: DeserializeSeed<'de>, + /// # { unimplemented!() } + /// # + /// fn tuple_variant(self, _len: usize, _visitor: V) -> Result + /// where + /// V: Visitor<'de>, + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"tuple variant")) + /// } + /// # + /// # fn struct_variant(self, _: &[&str], _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # } + /// ``` + fn tuple_variant(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>; + + /// Called when deserializing a struct-like variant. + /// + /// The `fields` are the names of the fields of the struct variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```edition2021 + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// # fn newtype_variant_seed(self, _: T) -> Result + /// # where + /// # T: DeserializeSeed<'de>, + /// # { unimplemented!() } + /// # + /// # fn tuple_variant(self, _: usize, _: V) -> Result + /// # where + /// # V: Visitor<'de>, + /// # { unimplemented!() } + /// # + /// fn struct_variant( + /// self, + /// _fields: &'static [&'static str], + /// _visitor: V, + /// ) -> Result + /// where + /// V: Visitor<'de>, + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"struct variant")) + /// } + /// # } + /// ``` + fn struct_variant( + self, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Converts an existing value into a `Deserializer` from which other values can +/// be deserialized. +/// +/// # Lifetime +/// +/// The `'de` lifetime of this trait is the lifetime of data that may be +/// borrowed from the resulting `Deserializer`. See the page [Understanding +/// deserializer lifetimes] for a more detailed explanation of these lifetimes. +/// +/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html +/// +/// # Example +/// +/// ```edition2021 +/// use serde::de::{value, Deserialize, IntoDeserializer}; +/// use serde_derive::Deserialize; +/// use std::str::FromStr; +/// +/// #[derive(Deserialize)] +/// enum Setting { +/// On, +/// Off, +/// } +/// +/// impl FromStr for Setting { +/// type Err = value::Error; +/// +/// fn from_str(s: &str) -> Result { +/// Self::deserialize(s.into_deserializer()) +/// } +/// } +/// ``` +pub trait IntoDeserializer<'de, E: Error = value::Error> { + /// The type of the deserializer being converted into. + type Deserializer: Deserializer<'de, Error = E>; + + /// Convert this value into a deserializer. + fn into_deserializer(self) -> Self::Deserializer; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Used in error messages. +/// +/// - expected `a` +/// - expected `a` or `b` +/// - expected one of `a`, `b`, `c` +/// +/// The slice of names must not be empty. +struct OneOf { + names: &'static [&'static str], +} + +impl Display for OneOf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.names.len() { + 0 => panic!(), // special case elsewhere + 1 => write!(formatter, "`{}`", self.names[0]), + 2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]), + _ => { + tri!(formatter.write_str("one of ")); + for (i, alt) in self.names.iter().enumerate() { + if i > 0 { + tri!(formatter.write_str(", ")); + } + tri!(write!(formatter, "`{}`", alt)); + } + Ok(()) + } + } + } +} + +struct WithDecimalPoint(f64); + +impl Display for WithDecimalPoint { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + struct LookForDecimalPoint<'f, 'a> { + formatter: &'f mut fmt::Formatter<'a>, + has_decimal_point: bool, + } + + impl<'f, 'a> fmt::Write for LookForDecimalPoint<'f, 'a> { + fn write_str(&mut self, fragment: &str) -> fmt::Result { + self.has_decimal_point |= fragment.contains('.'); + self.formatter.write_str(fragment) + } + + fn write_char(&mut self, ch: char) -> fmt::Result { + self.has_decimal_point |= ch == '.'; + self.formatter.write_char(ch) + } + } + + if self.0.is_finite() { + let mut writer = LookForDecimalPoint { + formatter, + has_decimal_point: false, + }; + tri!(write!(writer, "{}", self.0)); + if !writer.has_decimal_point { + tri!(formatter.write_str(".0")); + } + } else { + tri!(write!(formatter, "{}", self.0)); + } + Ok(()) + } +} diff --git a/bitbox02-bt/vendor/serde/src/de/seed.rs b/bitbox02-bt/vendor/serde/src/de/seed.rs new file mode 100644 index 0000000..52fb89d --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/de/seed.rs @@ -0,0 +1,19 @@ +use crate::de::{Deserialize, DeserializeSeed, Deserializer}; + +/// A DeserializeSeed helper for implementing deserialize_in_place Visitors. +/// +/// Wraps a mutable reference and calls deserialize_in_place on it. +pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T); + +impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T> +where + T: Deserialize<'de>, +{ + type Value = (); + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + T::deserialize_in_place(deserializer, self.0) + } +} diff --git a/bitbox02-bt/vendor/serde/src/de/size_hint.rs b/bitbox02-bt/vendor/serde/src/de/size_hint.rs new file mode 100644 index 0000000..4a4fe25 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/de/size_hint.rs @@ -0,0 +1,29 @@ +use crate::lib::*; + +pub fn from_bounds(iter: &I) -> Option +where + I: Iterator, +{ + helper(iter.size_hint()) +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub fn cautious(hint: Option) -> usize { + const MAX_PREALLOC_BYTES: usize = 1024 * 1024; + + if mem::size_of::() == 0 { + 0 + } else { + cmp::min( + hint.unwrap_or(0), + MAX_PREALLOC_BYTES / mem::size_of::(), + ) + } +} + +fn helper(bounds: (usize, Option)) -> Option { + match bounds { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } +} diff --git a/bitbox02-bt/vendor/serde/src/de/value.rs b/bitbox02-bt/vendor/serde/src/de/value.rs new file mode 100644 index 0000000..1ec9477 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/de/value.rs @@ -0,0 +1,1720 @@ +//! Building blocks for deserializing basic values using the `IntoDeserializer` +//! trait. +//! +//! ```edition2021 +//! use serde::de::{value, Deserialize, IntoDeserializer}; +//! use serde_derive::Deserialize; +//! use std::str::FromStr; +//! +//! #[derive(Deserialize)] +//! enum Setting { +//! On, +//! Off, +//! } +//! +//! impl FromStr for Setting { +//! type Err = value::Error; +//! +//! fn from_str(s: &str) -> Result { +//! Self::deserialize(s.into_deserializer()) +//! } +//! } +//! ``` + +use crate::lib::*; + +use self::private::{First, Second}; +use crate::de::{self, size_hint, Deserializer, Expected, IntoDeserializer, SeqAccess, Visitor}; +use crate::ser; + +//////////////////////////////////////////////////////////////////////////////// + +// For structs that contain a PhantomData. We do not want the trait +// bound `E: Clone` inferred by derive(Clone). +macro_rules! impl_copy_clone { + ($ty:ident $(<$lifetime:tt>)*) => { + impl<$($lifetime,)* E> Copy for $ty<$($lifetime,)* E> {} + + impl<$($lifetime,)* E> Clone for $ty<$($lifetime,)* E> { + fn clone(&self) -> Self { + *self + } + } + }; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A minimal representation of all possible errors that can occur using the +/// `IntoDeserializer` trait. +#[derive(Clone, PartialEq)] +pub struct Error { + err: ErrorImpl, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +type ErrorImpl = Box; +#[cfg(not(any(feature = "std", feature = "alloc")))] +type ErrorImpl = (); + +impl de::Error for Error { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cold] + fn custom(msg: T) -> Self + where + T: Display, + { + Error { + err: msg.to_string().into_boxed_str(), + } + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + #[cold] + fn custom(msg: T) -> Self + where + T: Display, + { + let _ = msg; + Error { err: () } + } +} + +impl ser::Error for Error { + #[cold] + fn custom(msg: T) -> Self + where + T: Display, + { + de::Error::custom(msg) + } +} + +impl Display for Error { + #[cfg(any(feature = "std", feature = "alloc"))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(&self.err) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Serde deserialization error") + } +} + +impl Debug for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut debug = formatter.debug_tuple("Error"); + #[cfg(any(feature = "std", feature = "alloc"))] + debug.field(&self.err); + debug.finish() + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl error::Error for Error { + fn description(&self) -> &str { + &self.err + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, E> IntoDeserializer<'de, E> for () +where + E: de::Error, +{ + type Deserializer = UnitDeserializer; + + fn into_deserializer(self) -> UnitDeserializer { + UnitDeserializer::new() + } +} + +/// A deserializer holding a `()`. +pub struct UnitDeserializer { + marker: PhantomData, +} + +impl_copy_clone!(UnitDeserializer); + +impl UnitDeserializer { + #[allow(missing_docs)] + pub fn new() -> Self { + UnitDeserializer { + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for UnitDeserializer +where + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_unit() + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_none() + } +} + +impl Debug for UnitDeserializer { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.debug_struct("UnitDeserializer").finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that cannot be instantiated. +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +pub struct NeverDeserializer { + never: !, + marker: PhantomData, +} + +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +impl<'de, E> IntoDeserializer<'de, E> for ! +where + E: de::Error, +{ + type Deserializer = NeverDeserializer; + + fn into_deserializer(self) -> Self::Deserializer { + self + } +} + +#[cfg(feature = "unstable")] +impl<'de, E> de::Deserializer<'de> for NeverDeserializer +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, _visitor: V) -> Result + where + V: de::Visitor<'de>, + { + self.never + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! primitive_deserializer { + ($ty:ty, $doc:tt, $name:ident, $method:ident $($cast:tt)*) => { + #[doc = "A deserializer holding"] + #[doc = $doc] + pub struct $name { + value: $ty, + marker: PhantomData + } + + impl_copy_clone!($name); + + impl<'de, E> IntoDeserializer<'de, E> for $ty + where + E: de::Error, + { + type Deserializer = $name; + + fn into_deserializer(self) -> $name { + $name::new(self) + } + } + + impl $name { + #[allow(missing_docs)] + pub fn new(value: $ty) -> Self { + $name { + value, + marker: PhantomData, + } + } + } + + impl<'de, E> de::Deserializer<'de> for $name + where + E: de::Error, + { + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str + string bytes byte_buf option unit unit_struct newtype_struct seq + tuple tuple_struct map struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.$method(self.value $($cast)*) + } + } + + impl Debug for $name { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct(stringify!($name)) + .field("value", &self.value) + .finish() + } + } + } +} + +primitive_deserializer!(bool, "a `bool`.", BoolDeserializer, visit_bool); +primitive_deserializer!(i8, "an `i8`.", I8Deserializer, visit_i8); +primitive_deserializer!(i16, "an `i16`.", I16Deserializer, visit_i16); +primitive_deserializer!(i32, "an `i32`.", I32Deserializer, visit_i32); +primitive_deserializer!(i64, "an `i64`.", I64Deserializer, visit_i64); +primitive_deserializer!(i128, "an `i128`.", I128Deserializer, visit_i128); +primitive_deserializer!(isize, "an `isize`.", IsizeDeserializer, visit_i64 as i64); +primitive_deserializer!(u8, "a `u8`.", U8Deserializer, visit_u8); +primitive_deserializer!(u16, "a `u16`.", U16Deserializer, visit_u16); +primitive_deserializer!(u64, "a `u64`.", U64Deserializer, visit_u64); +primitive_deserializer!(u128, "a `u128`.", U128Deserializer, visit_u128); +primitive_deserializer!(usize, "a `usize`.", UsizeDeserializer, visit_u64 as u64); +primitive_deserializer!(f32, "an `f32`.", F32Deserializer, visit_f32); +primitive_deserializer!(f64, "an `f64`.", F64Deserializer, visit_f64); +primitive_deserializer!(char, "a `char`.", CharDeserializer, visit_char); + +/// A deserializer holding a `u32`. +pub struct U32Deserializer { + value: u32, + marker: PhantomData, +} + +impl_copy_clone!(U32Deserializer); + +impl<'de, E> IntoDeserializer<'de, E> for u32 +where + E: de::Error, +{ + type Deserializer = U32Deserializer; + + fn into_deserializer(self) -> U32Deserializer { + U32Deserializer::new(self) + } +} + +impl U32Deserializer { + #[allow(missing_docs)] + pub fn new(value: u32) -> Self { + U32Deserializer { + value, + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for U32Deserializer +where + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_u32(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } +} + +impl<'de, E> de::EnumAccess<'de> for U32Deserializer +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +impl Debug for U32Deserializer { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("U32Deserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&str`. +pub struct StrDeserializer<'a, E> { + value: &'a str, + marker: PhantomData, +} + +impl_copy_clone!(StrDeserializer<'de>); + +impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a str +where + E: de::Error, +{ + type Deserializer = StrDeserializer<'a, E>; + + fn into_deserializer(self) -> StrDeserializer<'a, E> { + StrDeserializer::new(self) + } +} + +impl<'a, E> StrDeserializer<'a, E> { + #[allow(missing_docs)] + pub fn new(value: &'a str) -> Self { + StrDeserializer { + value, + marker: PhantomData, + } + } +} + +impl<'de, 'a, E> de::Deserializer<'de> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_str(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +impl<'de, 'a, E> de::EnumAccess<'de> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +impl<'a, E> Debug for StrDeserializer<'a, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("StrDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&str` with a lifetime tied to another +/// deserializer. +pub struct BorrowedStrDeserializer<'de, E> { + value: &'de str, + marker: PhantomData, +} + +impl_copy_clone!(BorrowedStrDeserializer<'de>); + +impl<'de, E> BorrowedStrDeserializer<'de, E> { + /// Create a new borrowed deserializer from the given string. + pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> { + BorrowedStrDeserializer { + value, + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_borrowed_str(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +impl<'de, E> de::EnumAccess<'de> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +impl<'de, E> Debug for BorrowedStrDeserializer<'de, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("BorrowedStrDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `String`. +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +pub struct StringDeserializer { + value: String, + marker: PhantomData, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl Clone for StringDeserializer { + fn clone(&self) -> Self { + StringDeserializer { + value: self.value.clone(), + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, E> IntoDeserializer<'de, E> for String +where + E: de::Error, +{ + type Deserializer = StringDeserializer; + + fn into_deserializer(self) -> StringDeserializer { + StringDeserializer::new(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl StringDeserializer { + #[allow(missing_docs)] + pub fn new(value: String) -> Self { + StringDeserializer { + value, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> de::Deserializer<'de> for StringDeserializer +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_string(self.value) + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> de::EnumAccess<'de> for StringDeserializer +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl Debug for StringDeserializer { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("StringDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `Cow`. +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +pub struct CowStrDeserializer<'a, E> { + value: Cow<'a, str>, + marker: PhantomData, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, E> Clone for CowStrDeserializer<'a, E> { + fn clone(&self) -> Self { + CowStrDeserializer { + value: self.value.clone(), + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str> +where + E: de::Error, +{ + type Deserializer = CowStrDeserializer<'a, E>; + + fn into_deserializer(self) -> CowStrDeserializer<'a, E> { + CowStrDeserializer::new(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, E> CowStrDeserializer<'a, E> { + #[allow(missing_docs)] + pub fn new(value: Cow<'a, str>) -> Self { + CowStrDeserializer { + value, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> de::Deserializer<'de> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + match self.value { + Cow::Borrowed(string) => visitor.visit_str(string), + Cow::Owned(string) => visitor.visit_string(string), + } + } + + fn deserialize_enum( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly; + + fn variant_seed(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, E> Debug for CowStrDeserializer<'a, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("CowStrDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&[u8]`. Always calls [`Visitor::visit_bytes`]. +pub struct BytesDeserializer<'a, E> { + value: &'a [u8], + marker: PhantomData, +} + +impl<'a, E> BytesDeserializer<'a, E> { + /// Create a new deserializer from the given bytes. + pub fn new(value: &'a [u8]) -> Self { + BytesDeserializer { + value, + marker: PhantomData, + } + } +} + +impl_copy_clone!(BytesDeserializer<'a>); + +impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a [u8] +where + E: de::Error, +{ + type Deserializer = BytesDeserializer<'a, E>; + + fn into_deserializer(self) -> BytesDeserializer<'a, E> { + BytesDeserializer::new(self) + } +} + +impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_bytes(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'a, E> Debug for BytesDeserializer<'a, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("BytesDeserializer") + .field("value", &self.value) + .finish() + } +} + +/// A deserializer holding a `&[u8]` with a lifetime tied to another +/// deserializer. Always calls [`Visitor::visit_borrowed_bytes`]. +pub struct BorrowedBytesDeserializer<'de, E> { + value: &'de [u8], + marker: PhantomData, +} + +impl<'de, E> BorrowedBytesDeserializer<'de, E> { + /// Create a new borrowed deserializer from the given borrowed bytes. + pub fn new(value: &'de [u8]) -> Self { + BorrowedBytesDeserializer { + value, + marker: PhantomData, + } + } +} + +impl_copy_clone!(BorrowedBytesDeserializer<'de>); + +impl<'de, E> Deserializer<'de> for BorrowedBytesDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_borrowed_bytes(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, E> Debug for BorrowedBytesDeserializer<'de, E> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("BorrowedBytesDeserializer") + .field("value", &self.value) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that iterates over a sequence. +#[derive(Clone)] +pub struct SeqDeserializer { + iter: iter::Fuse, + count: usize, + marker: PhantomData, +} + +impl SeqDeserializer +where + I: Iterator, +{ + /// Construct a new `SeqDeserializer`. + pub fn new(iter: I) -> Self { + SeqDeserializer { + iter: iter.fuse(), + count: 0, + marker: PhantomData, + } + } +} + +impl SeqDeserializer +where + I: Iterator, + E: de::Error, +{ + /// Check for remaining elements after passing a `SeqDeserializer` to + /// `Visitor::visit_seq`. + pub fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInSeq(self.count), + )) + } + } +} + +impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer +where + I: Iterator, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn deserialize_any(mut self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let v = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(v) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, I, T, E> de::SeqAccess<'de> for SeqDeserializer +where + I: Iterator, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed(&mut self, seed: V) -> Result, Self::Error> + where + V: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => { + self.count += 1; + seed.deserialize(value.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } +} + +struct ExpectedInSeq(usize); + +impl Expected for ExpectedInSeq { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + formatter.write_str("1 element in sequence") + } else { + write!(formatter, "{} elements in sequence", self.0) + } + } +} + +impl Debug for SeqDeserializer +where + I: Debug, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("SeqDeserializer") + .field("iter", &self.iter) + .field("count", &self.count) + .finish() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, T, E> IntoDeserializer<'de, E> for Vec +where + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = SeqDeserializer<::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet +where + T: IntoDeserializer<'de, E> + Eq + Ord, + E: de::Error, +{ + type Deserializer = SeqDeserializer<::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de, T, S, E> IntoDeserializer<'de, E> for HashSet +where + T: IntoDeserializer<'de, E> + Eq + Hash, + S: BuildHasher, + E: de::Error, +{ + type Deserializer = SeqDeserializer<::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `SeqAccess`. +#[derive(Clone, Debug)] +pub struct SeqAccessDeserializer { + seq: A, +} + +impl SeqAccessDeserializer { + /// Construct a new `SeqAccessDeserializer`. + pub fn new(seq: A) -> Self { + SeqAccessDeserializer { seq } + } +} + +impl<'de, A> de::Deserializer<'de> for SeqAccessDeserializer +where + A: de::SeqAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_seq(self.seq) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that iterates over a map. +pub struct MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + iter: iter::Fuse, + value: Option>, + count: usize, + lifetime: PhantomData<&'de ()>, + error: PhantomData, +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + /// Construct a new `MapDeserializer`. + pub fn new(iter: I) -> Self { + MapDeserializer { + iter: iter.fuse(), + value: None, + count: 0, + lifetime: PhantomData, + error: PhantomData, + } + } +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + E: de::Error, +{ + /// Check for remaining elements after passing a `MapDeserializer` to + /// `Visitor::visit_map`. + pub fn end(self) -> Result<(), E> { + let remaining = self.iter.count(); + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInMap(self.count), + )) + } + } +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + fn next_pair(&mut self) -> Option<(First, Second)> { + match self.iter.next() { + Some(kv) => { + self.count += 1; + Some(private::Pair::split(kv)) + } + None => None, + } + } +} + +impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn deserialize_any(mut self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let value = tri!(visitor.visit_map(&mut self)); + tri!(self.end()); + Ok(value) + } + + fn deserialize_seq(mut self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let value = tri!(visitor.visit_seq(&mut self)); + tri!(self.end()); + Ok(value) + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let _ = len; + self.deserialize_seq(visitor) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any + } +} + +impl<'de, I, E> de::MapAccess<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(key.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: de::DeserializeSeed<'de>, + { + let value = self.value.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let value = value.expect("MapAccess::next_value called before next_key"); + seed.deserialize(value.into_deserializer()) + } + + fn next_entry_seed( + &mut self, + kseed: TK, + vseed: TV, + ) -> Result, Self::Error> + where + TK: de::DeserializeSeed<'de>, + TV: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + let key = tri!(kseed.deserialize(key.into_deserializer())); + let value = tri!(vseed.deserialize(value.into_deserializer())); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } +} + +impl<'de, I, E> de::SeqAccess<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First: IntoDeserializer<'de, E>, + Second: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((k, v)) => { + let de = PairDeserializer(k, v, PhantomData); + seed.deserialize(de).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + size_hint::from_bounds(&self.iter) + } +} + +// Cannot #[derive(Clone)] because of the bound `Second: Clone`. +impl<'de, I, E> Clone for MapDeserializer<'de, I, E> +where + I: Iterator + Clone, + I::Item: private::Pair, + Second: Clone, +{ + fn clone(&self) -> Self { + MapDeserializer { + iter: self.iter.clone(), + value: self.value.clone(), + count: self.count, + lifetime: self.lifetime, + error: self.error, + } + } +} + +impl<'de, I, E> Debug for MapDeserializer<'de, I, E> +where + I: Iterator + Debug, + I::Item: private::Pair, + Second: Debug, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("MapDeserializer") + .field("iter", &self.iter) + .field("value", &self.value) + .field("count", &self.count) + .finish() + } +} + +// Used in the `impl SeqAccess for MapDeserializer` to visit the map as a +// sequence of pairs. +struct PairDeserializer(A, B, PhantomData); + +impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer +where + A: IntoDeserializer<'de, E>, + B: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct tuple_struct map + struct enum identifier ignored_any + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData); + let pair = tri!(visitor.visit_seq(&mut pair_visitor)); + if pair_visitor.1.is_none() { + Ok(pair) + } else { + let remaining = pair_visitor.size_hint().unwrap(); + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining))) + } + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + if len == 2 { + self.deserialize_seq(visitor) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(len))) + } + } +} + +struct PairVisitor(Option, Option, PhantomData); + +impl<'de, A, B, E> de::SeqAccess<'de> for PairVisitor +where + A: IntoDeserializer<'de, E>, + B: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + if let Some(k) = self.0.take() { + seed.deserialize(k.into_deserializer()).map(Some) + } else if let Some(v) = self.1.take() { + seed.deserialize(v.into_deserializer()).map(Some) + } else { + Ok(None) + } + } + + fn size_hint(&self) -> Option { + if self.0.is_some() { + Some(2) + } else if self.1.is_some() { + Some(1) + } else { + Some(0) + } + } +} + +struct ExpectedInMap(usize); + +impl Expected for ExpectedInMap { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + formatter.write_str("1 element in map") + } else { + write!(formatter, "{} elements in map", self.0) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap +where + K: IntoDeserializer<'de, E> + Eq + Ord, + V: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = MapDeserializer<'de, ::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl<'de, K, V, S, E> IntoDeserializer<'de, E> for HashMap +where + K: IntoDeserializer<'de, E> + Eq + Hash, + V: IntoDeserializer<'de, E>, + S: BuildHasher, + E: de::Error, +{ + type Deserializer = MapDeserializer<'de, ::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `MapAccess`. +#[derive(Clone, Debug)] +pub struct MapAccessDeserializer { + map: A, +} + +impl MapAccessDeserializer { + /// Construct a new `MapAccessDeserializer`. + pub fn new(map: A) -> Self { + MapAccessDeserializer { map } + } +} + +impl<'de, A> de::Deserializer<'de> for MapAccessDeserializer +where + A: de::MapAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_map(self.map) + } + + fn deserialize_enum( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +impl<'de, A> de::EnumAccess<'de> for MapAccessDeserializer +where + A: de::MapAccess<'de>, +{ + type Error = A::Error; + type Variant = private::MapAsEnum; + + fn variant_seed(mut self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match tri!(self.map.next_key_seed(seed)) { + Some(key) => Ok((key, private::map_as_enum(self.map))), + None => Err(de::Error::invalid_type(de::Unexpected::Map, &"enum")), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding an `EnumAccess`. +#[derive(Clone, Debug)] +pub struct EnumAccessDeserializer { + access: A, +} + +impl EnumAccessDeserializer { + /// Construct a new `EnumAccessDeserializer`. + pub fn new(access: A) -> Self { + EnumAccessDeserializer { access } + } +} + +impl<'de, A> de::Deserializer<'de> for EnumAccessDeserializer +where + A: de::EnumAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + visitor.visit_enum(self.access) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +//////////////////////////////////////////////////////////////////////////////// + +mod private { + use crate::lib::*; + + use crate::de::{ + self, DeserializeSeed, Deserializer, MapAccess, Unexpected, VariantAccess, Visitor, + }; + + pub struct UnitOnly { + marker: PhantomData, + } + + pub fn unit_only(t: T) -> (T, UnitOnly) { + ( + t, + UnitOnly { + marker: PhantomData, + }, + ) + } + + impl<'de, E> de::VariantAccess<'de> for UnitOnly + where + E: de::Error, + { + type Error = E; + + fn unit_variant(self) -> Result<(), Self::Error> { + Ok(()) + } + + fn newtype_variant_seed(self, _seed: T) -> Result + where + T: de::DeserializeSeed<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"newtype variant", + )) + } + + fn tuple_variant(self, _len: usize, _visitor: V) -> Result + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"tuple variant", + )) + } + + fn struct_variant( + self, + _fields: &'static [&'static str], + _visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"struct variant", + )) + } + } + + pub struct MapAsEnum { + map: A, + } + + pub fn map_as_enum(map: A) -> MapAsEnum { + MapAsEnum { map } + } + + impl<'de, A> VariantAccess<'de> for MapAsEnum + where + A: MapAccess<'de>, + { + type Error = A::Error; + + fn unit_variant(mut self) -> Result<(), Self::Error> { + self.map.next_value() + } + + fn newtype_variant_seed(mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + self.map.next_value_seed(seed) + } + + fn tuple_variant(mut self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.map.next_value_seed(SeedTupleVariant { len, visitor }) + } + + fn struct_variant( + mut self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.map.next_value_seed(SeedStructVariant { visitor }) + } + } + + struct SeedTupleVariant { + len: usize, + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for SeedTupleVariant + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple(self.len, self.visitor) + } + } + + struct SeedStructVariant { + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for SeedStructVariant + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_map(self.visitor) + } + } + + /// Avoid having to restate the generic types on `MapDeserializer`. The + /// `Iterator::Item` contains enough information to figure out K and V. + pub trait Pair { + type First; + type Second; + fn split(self) -> (Self::First, Self::Second); + } + + impl Pair for (A, B) { + type First = A; + type Second = B; + fn split(self) -> (A, B) { + self + } + } + + pub type First = ::First; + pub type Second = ::Second; +} diff --git a/bitbox02-bt/vendor/serde/src/format.rs b/bitbox02-bt/vendor/serde/src/format.rs new file mode 100644 index 0000000..9053cc0 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/format.rs @@ -0,0 +1,30 @@ +use crate::lib::fmt::{self, Write}; +use crate::lib::str; + +pub(super) struct Buf<'a> { + bytes: &'a mut [u8], + offset: usize, +} + +impl<'a> Buf<'a> { + pub fn new(bytes: &'a mut [u8]) -> Self { + Buf { bytes, offset: 0 } + } + + pub fn as_str(&self) -> &str { + let slice = &self.bytes[..self.offset]; + unsafe { str::from_utf8_unchecked(slice) } + } +} + +impl<'a> Write for Buf<'a> { + fn write_str(&mut self, s: &str) -> fmt::Result { + if self.offset + s.len() > self.bytes.len() { + Err(fmt::Error) + } else { + self.bytes[self.offset..self.offset + s.len()].copy_from_slice(s.as_bytes()); + self.offset += s.len(); + Ok(()) + } + } +} diff --git a/bitbox02-bt/vendor/serde/src/integer128.rs b/bitbox02-bt/vendor/serde/src/integer128.rs new file mode 100644 index 0000000..2f94a64 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/integer128.rs @@ -0,0 +1,9 @@ +// No longer used. Old versions of serde used this macro for supporting targets +// that did not yet have 128-bit integer support. +#[macro_export] +#[doc(hidden)] +macro_rules! serde_if_integer128 { + ($($tt:tt)*) => { + $($tt)* + }; +} diff --git a/bitbox02-bt/vendor/serde/src/lib.rs b/bitbox02-bt/vendor/serde/src/lib.rs new file mode 100644 index 0000000..15710d8 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/lib.rs @@ -0,0 +1,347 @@ +//! # Serde +//! +//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data +//! structures efficiently and generically. +//! +//! The Serde ecosystem consists of data structures that know how to serialize +//! and deserialize themselves along with data formats that know how to +//! serialize and deserialize other things. Serde provides the layer by which +//! these two groups interact with each other, allowing any supported data +//! structure to be serialized and deserialized using any supported data format. +//! +//! See the Serde website for additional documentation and +//! usage examples. +//! +//! ## Design +//! +//! Where many other languages rely on runtime reflection for serializing data, +//! Serde is instead built on Rust's powerful trait system. A data structure +//! that knows how to serialize and deserialize itself is one that implements +//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's derive +//! attribute to automatically generate implementations at compile time). This +//! avoids any overhead of reflection or runtime type information. In fact in +//! many situations the interaction between data structure and data format can +//! be completely optimized away by the Rust compiler, leaving Serde +//! serialization to perform the same speed as a handwritten serializer for the +//! specific selection of data structure and data format. +//! +//! ## Data formats +//! +//! The following is a partial list of data formats that have been implemented +//! for Serde by the community. +//! +//! - [JSON], the ubiquitous JavaScript Object Notation used by many HTTP APIs. +//! - [Postcard], a no\_std and embedded-systems friendly compact binary format. +//! - [CBOR], a Concise Binary Object Representation designed for small message +//! size without the need for version negotiation. +//! - [YAML], a self-proclaimed human-friendly configuration language that ain't +//! markup language. +//! - [MessagePack], an efficient binary format that resembles a compact JSON. +//! - [TOML], a minimal configuration format used by [Cargo]. +//! - [Pickle], a format common in the Python world. +//! - [RON], a Rusty Object Notation. +//! - [BSON], the data storage and network transfer format used by MongoDB. +//! - [Avro], a binary format used within Apache Hadoop, with support for schema +//! definition. +//! - [JSON5], a superset of JSON including some productions from ES5. +//! - [URL] query strings, in the x-www-form-urlencoded format. +//! - [Starlark], the format used for describing build targets by the Bazel and +//! Buck build systems. *(serialization only)* +//! - [Envy], a way to deserialize environment variables into Rust structs. +//! *(deserialization only)* +//! - [Envy Store], a way to deserialize [AWS Parameter Store] parameters into +//! Rust structs. *(deserialization only)* +//! - [S-expressions], the textual representation of code and data used by the +//! Lisp language family. +//! - [D-Bus]'s binary wire format. +//! - [FlexBuffers], the schemaless cousin of Google's FlatBuffers zero-copy +//! serialization format. +//! - [Bencode], a simple binary format used in the BitTorrent protocol. +//! - [Token streams], for processing Rust procedural macro input. +//! *(deserialization only)* +//! - [DynamoDB Items], the format used by [rusoto_dynamodb] to transfer data to +//! and from DynamoDB. +//! - [Hjson], a syntax extension to JSON designed around human reading and +//! editing. *(deserialization only)* +//! - [CSV], Comma-separated values is a tabular text file format. +//! +//! [JSON]: https://github.com/serde-rs/json +//! [Postcard]: https://github.com/jamesmunns/postcard +//! [CBOR]: https://github.com/enarx/ciborium +//! [YAML]: https://github.com/dtolnay/serde-yaml +//! [MessagePack]: https://github.com/3Hren/msgpack-rust +//! [TOML]: https://docs.rs/toml +//! [Pickle]: https://github.com/birkenfeld/serde-pickle +//! [RON]: https://github.com/ron-rs/ron +//! [BSON]: https://github.com/mongodb/bson-rust +//! [Avro]: https://docs.rs/apache-avro +//! [JSON5]: https://github.com/callum-oakley/json5-rs +//! [URL]: https://docs.rs/serde_qs +//! [Starlark]: https://github.com/dtolnay/serde-starlark +//! [Envy]: https://github.com/softprops/envy +//! [Envy Store]: https://github.com/softprops/envy-store +//! [Cargo]: https://doc.rust-lang.org/cargo/reference/manifest.html +//! [AWS Parameter Store]: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html +//! [S-expressions]: https://github.com/rotty/lexpr-rs +//! [D-Bus]: https://docs.rs/zvariant +//! [FlexBuffers]: https://github.com/google/flatbuffers/tree/master/rust/flexbuffers +//! [Bencode]: https://github.com/P3KI/bendy +//! [Token streams]: https://github.com/oxidecomputer/serde_tokenstream +//! [DynamoDB Items]: https://docs.rs/serde_dynamo +//! [rusoto_dynamodb]: https://docs.rs/rusoto_dynamodb +//! [Hjson]: https://github.com/Canop/deser-hjson +//! [CSV]: https://docs.rs/csv + +//////////////////////////////////////////////////////////////////////////////// + +// Serde types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/serde/1.0.210")] +// Support using Serde without the standard library! +#![cfg_attr(not(feature = "std"), no_std)] +// Show which crate feature enables conditionally compiled APIs in documentation. +#![cfg_attr(docsrs, feature(doc_cfg, rustdoc_internals))] +#![cfg_attr(docsrs, allow(internal_features))] +// Unstable functionality only if the user asks for it. For tracking and +// discussion of these features please refer to this issue: +// +// https://github.com/serde-rs/serde/issues/812 +#![cfg_attr(feature = "unstable", feature(never_type))] +#![allow(unknown_lints, bare_trait_objects, deprecated)] +// Ignored clippy and clippy_pedantic lints +#![allow( + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704 + clippy::unnested_or_patterns, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7768 + clippy::semicolon_if_nothing_returned, + // not available in our oldest supported compiler + clippy::empty_enum, + clippy::type_repetition_in_bounds, // https://github.com/rust-lang/rust-clippy/issues/8772 + // integer and float ser/de requires these sorts of casts + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_precision_loss, + clippy::cast_sign_loss, + // things are often more readable this way + clippy::cast_lossless, + clippy::module_name_repetitions, + clippy::single_match_else, + clippy::type_complexity, + clippy::use_self, + clippy::zero_prefixed_literal, + // correctly used + clippy::derive_partial_eq_without_eq, + clippy::enum_glob_use, + clippy::explicit_auto_deref, + clippy::incompatible_msrv, + clippy::let_underscore_untyped, + clippy::map_err_ignore, + clippy::new_without_default, + clippy::result_unit_err, + clippy::wildcard_imports, + // not practical + clippy::needless_pass_by_value, + clippy::similar_names, + clippy::too_many_lines, + // preference + clippy::doc_markdown, + clippy::unseparated_literal_suffix, + // false positive + clippy::needless_doctest_main, + // noisy + clippy::missing_errors_doc, + clippy::must_use_candidate, +)] +// Restrictions +#![deny(clippy::question_mark_used)] +// Rustc lints. +#![deny(missing_docs, unused_imports)] + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "alloc")] +extern crate alloc; + +/// A facade around all the types we need from the `std`, `core`, and `alloc` +/// crates. This avoids elaborate import wrangling having to happen in every +/// module. +mod lib { + mod core { + #[cfg(not(feature = "std"))] + pub use core::*; + #[cfg(feature = "std")] + pub use std::*; + } + + pub use self::core::{f32, f64}; + pub use self::core::{i16, i32, i64, i8, isize}; + pub use self::core::{iter, num, ptr, str}; + pub use self::core::{u16, u32, u64, u8, usize}; + + #[cfg(any(feature = "std", feature = "alloc"))] + pub use self::core::{cmp, mem, slice}; + + pub use self::core::cell::{Cell, RefCell}; + pub use self::core::clone; + pub use self::core::cmp::Reverse; + pub use self::core::convert; + pub use self::core::default; + pub use self::core::fmt::{self, Debug, Display, Write as FmtWrite}; + pub use self::core::marker::{self, PhantomData}; + pub use self::core::num::Wrapping; + pub use self::core::ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo}; + pub use self::core::option; + pub use self::core::result; + pub use self::core::time::Duration; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::borrow::{Cow, ToOwned}; + #[cfg(feature = "std")] + pub use std::borrow::{Cow, ToOwned}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::string::{String, ToString}; + #[cfg(feature = "std")] + pub use std::string::{String, ToString}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::vec::Vec; + #[cfg(feature = "std")] + pub use std::vec::Vec; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::boxed::Box; + #[cfg(feature = "std")] + pub use std::boxed::Box; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::rc::{Rc, Weak as RcWeak}; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::rc::{Rc, Weak as RcWeak}; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::sync::{Arc, Weak as ArcWeak}; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::sync::{Arc, Weak as ArcWeak}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + #[cfg(feature = "std")] + pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + + #[cfg(all(not(no_core_cstr), not(feature = "std")))] + pub use self::core::ffi::CStr; + #[cfg(feature = "std")] + pub use std::ffi::CStr; + + #[cfg(all(not(no_core_cstr), feature = "alloc", not(feature = "std")))] + pub use alloc::ffi::CString; + #[cfg(feature = "std")] + pub use std::ffi::CString; + + #[cfg(all(not(no_core_net), not(feature = "std")))] + pub use self::core::net; + #[cfg(feature = "std")] + pub use std::net; + + #[cfg(feature = "std")] + pub use std::error; + + #[cfg(feature = "std")] + pub use std::collections::{HashMap, HashSet}; + #[cfg(feature = "std")] + pub use std::ffi::{OsStr, OsString}; + #[cfg(feature = "std")] + pub use std::hash::{BuildHasher, Hash}; + #[cfg(feature = "std")] + pub use std::io::Write; + #[cfg(feature = "std")] + pub use std::path::{Path, PathBuf}; + #[cfg(feature = "std")] + pub use std::sync::{Mutex, RwLock}; + #[cfg(feature = "std")] + pub use std::time::{SystemTime, UNIX_EPOCH}; + + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic)))] + pub use std::sync::atomic::{ + AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU8, + AtomicUsize, Ordering, + }; + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic64)))] + pub use std::sync::atomic::{AtomicI64, AtomicU64}; + + #[cfg(all(feature = "std", not(no_target_has_atomic)))] + pub use std::sync::atomic::Ordering; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "8"))] + pub use std::sync::atomic::{AtomicBool, AtomicI8, AtomicU8}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "16"))] + pub use std::sync::atomic::{AtomicI16, AtomicU16}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "32"))] + pub use std::sync::atomic::{AtomicI32, AtomicU32}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "64"))] + pub use std::sync::atomic::{AtomicI64, AtomicU64}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))] + pub use std::sync::atomic::{AtomicIsize, AtomicUsize}; + + #[cfg(not(no_core_num_saturating))] + pub use self::core::num::Saturating; +} + +// None of this crate's error handling needs the `From::from` error conversion +// performed implicitly by the `?` operator or the standard library's `try!` +// macro. This simplified macro gives a 5.5% improvement in compile time +// compared to standard `try!`, and 9% improvement compared to `?`. +macro_rules! tri { + ($expr:expr) => { + match $expr { + Ok(val) => val, + Err(err) => return Err(err), + } + }; +} + +//////////////////////////////////////////////////////////////////////////////// + +#[macro_use] +mod macros; + +#[macro_use] +mod integer128; + +pub mod de; +pub mod ser; + +mod format; + +#[doc(inline)] +pub use crate::de::{Deserialize, Deserializer}; +#[doc(inline)] +pub use crate::ser::{Serialize, Serializer}; + +// Used by generated code and doc tests. Not public API. +#[doc(hidden)] +#[path = "private/mod.rs"] +pub mod __private; + +#[path = "de/seed.rs"] +mod seed; + +#[cfg(all(not(feature = "std"), no_core_error))] +mod std_error; + +// Re-export #[derive(Serialize, Deserialize)]. +// +// The reason re-exporting is not enabled by default is that disabling it would +// be annoying for crates that provide handwritten impls or data formats. They +// would need to disable default features and then explicitly re-enable std. +#[cfg(feature = "serde_derive")] +extern crate serde_derive; + +/// Derive macro available if serde is built with `features = ["derive"]`. +#[cfg(feature = "serde_derive")] +#[cfg_attr(docsrs, doc(cfg(feature = "derive")))] +pub use serde_derive::{Deserialize, Serialize}; + +#[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))] +mod actually_private { + pub struct T; +} diff --git a/bitbox02-bt/vendor/serde/src/macros.rs b/bitbox02-bt/vendor/serde/src/macros.rs new file mode 100644 index 0000000..9646cb3 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/macros.rs @@ -0,0 +1,231 @@ +// Super explicit first paragraph because this shows up at the top level and +// trips up people who are just looking for basic Serialize / Deserialize +// documentation. +// +/// Helper macro when implementing the `Deserializer` part of a new data format +/// for Serde. +/// +/// Some [`Deserializer`] implementations for self-describing formats do not +/// care what hint the [`Visitor`] gives them, they just want to blindly call +/// the [`Visitor`] method corresponding to the data they can tell is in the +/// input. This requires repetitive implementations of all the [`Deserializer`] +/// trait methods. +/// +/// ```edition2021 +/// # use serde::forward_to_deserialize_any; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # +/// # struct MyDeserializer; +/// # +/// # impl<'de> Deserializer<'de> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// # fn deserialize_any(self, _: V) -> Result +/// # where +/// # V: Visitor<'de>, +/// # { +/// # unimplemented!() +/// # } +/// # +/// #[inline] +/// fn deserialize_bool(self, visitor: V) -> Result +/// where +/// V: Visitor<'de>, +/// { +/// self.deserialize_any(visitor) +/// } +/// # +/// # forward_to_deserialize_any! { +/// # i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string +/// # bytes byte_buf option unit unit_struct newtype_struct seq tuple +/// # tuple_struct map struct enum identifier ignored_any +/// # } +/// # } +/// ``` +/// +/// The `forward_to_deserialize_any!` macro implements these simple forwarding +/// methods so that they forward directly to [`Deserializer::deserialize_any`]. +/// You can choose which methods to forward. +/// +/// ```edition2021 +/// # use serde::forward_to_deserialize_any; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # +/// # struct MyDeserializer; +/// # +/// impl<'de> Deserializer<'de> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// fn deserialize_any(self, visitor: V) -> Result +/// where +/// V: Visitor<'de>, +/// { +/// /* ... */ +/// # let _ = visitor; +/// # unimplemented!() +/// } +/// +/// forward_to_deserialize_any! { +/// bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string +/// bytes byte_buf option unit unit_struct newtype_struct seq tuple +/// tuple_struct map struct enum identifier ignored_any +/// } +/// } +/// ``` +/// +/// The macro assumes the convention that your `Deserializer` lifetime parameter +/// is called `'de` and that the `Visitor` type parameters on each method are +/// called `V`. A different type parameter and a different lifetime can be +/// specified explicitly if necessary. +/// +/// ```edition2021 +/// # use serde::forward_to_deserialize_any; +/// # use serde::de::{value, Deserializer, Visitor}; +/// # use std::marker::PhantomData; +/// # +/// # struct MyDeserializer(PhantomData); +/// # +/// # impl<'q, V> Deserializer<'q> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// # fn deserialize_any(self, visitor: W) -> Result +/// # where +/// # W: Visitor<'q>, +/// # { +/// # unimplemented!() +/// # } +/// # +/// forward_to_deserialize_any! { +/// > +/// bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string +/// bytes byte_buf option unit unit_struct newtype_struct seq tuple +/// tuple_struct map struct enum identifier ignored_any +/// } +/// # } +/// ``` +/// +/// [`Deserializer`]: trait.Deserializer.html +/// [`Visitor`]: de/trait.Visitor.html +/// [`Deserializer::deserialize_any`]: trait.Deserializer.html#tymethod.deserialize_any +#[macro_export(local_inner_macros)] +macro_rules! forward_to_deserialize_any { + (<$visitor:ident: Visitor<$lifetime:tt>> $($func:ident)*) => { + $(forward_to_deserialize_any_helper!{$func<$lifetime, $visitor>})* + }; + // This case must be after the previous one. + ($($func:ident)*) => { + $(forward_to_deserialize_any_helper!{$func<'de, V>})* + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! forward_to_deserialize_any_method { + ($func:ident<$l:tt, $v:ident>($($arg:ident : $ty:ty),*)) => { + #[inline] + fn $func<$v>(self, $($arg: $ty,)* visitor: $v) -> $crate::__private::Result<$v::Value, >::Error> + where + $v: $crate::de::Visitor<$l>, + { + $( + let _ = $arg; + )* + self.deserialize_any(visitor) + } + }; +} + +#[doc(hidden)] +#[macro_export(local_inner_macros)] +macro_rules! forward_to_deserialize_any_helper { + (bool<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_bool<$l, $v>()} + }; + (i8<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i8<$l, $v>()} + }; + (i16<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i16<$l, $v>()} + }; + (i32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i32<$l, $v>()} + }; + (i64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i64<$l, $v>()} + }; + (i128<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i128<$l, $v>()} + }; + (u8<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u8<$l, $v>()} + }; + (u16<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u16<$l, $v>()} + }; + (u32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u32<$l, $v>()} + }; + (u64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u64<$l, $v>()} + }; + (u128<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u128<$l, $v>()} + }; + (f32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_f32<$l, $v>()} + }; + (f64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_f64<$l, $v>()} + }; + (char<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_char<$l, $v>()} + }; + (str<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_str<$l, $v>()} + }; + (string<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_string<$l, $v>()} + }; + (bytes<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_bytes<$l, $v>()} + }; + (byte_buf<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_byte_buf<$l, $v>()} + }; + (option<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_option<$l, $v>()} + }; + (unit<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_unit<$l, $v>()} + }; + (unit_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_unit_struct<$l, $v>(name: &'static str)} + }; + (newtype_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_newtype_struct<$l, $v>(name: &'static str)} + }; + (seq<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_seq<$l, $v>()} + }; + (tuple<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_tuple<$l, $v>(len: usize)} + }; + (tuple_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_tuple_struct<$l, $v>(name: &'static str, len: usize)} + }; + (map<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_map<$l, $v>()} + }; + (struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_struct<$l, $v>(name: &'static str, fields: &'static [&'static str])} + }; + (enum<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_enum<$l, $v>(name: &'static str, variants: &'static [&'static str])} + }; + (identifier<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_identifier<$l, $v>()} + }; + (ignored_any<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_ignored_any<$l, $v>()} + }; +} diff --git a/bitbox02-bt/vendor/serde/src/private/de.rs b/bitbox02-bt/vendor/serde/src/private/de.rs new file mode 100644 index 0000000..f0eca71 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/private/de.rs @@ -0,0 +1,2795 @@ +use crate::lib::*; + +use crate::de::value::{BorrowedBytesDeserializer, BytesDeserializer}; +use crate::de::{ + Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error, IntoDeserializer, VariantAccess, + Visitor, +}; + +#[cfg(any(feature = "std", feature = "alloc"))] +use crate::de::{MapAccess, Unexpected}; + +#[cfg(any(feature = "std", feature = "alloc"))] +pub use self::content::{ + Content, ContentDeserializer, ContentRefDeserializer, EnumDeserializer, + InternallyTaggedUnitVisitor, TagContentOtherField, TagContentOtherFieldVisitor, + TagOrContentField, TagOrContentFieldVisitor, TaggedContentVisitor, UntaggedUnitVisitor, +}; + +pub use crate::seed::InPlaceSeed; + +/// If the missing field is of type `Option` then treat is as `None`, +/// otherwise it is an error. +pub fn missing_field<'de, V, E>(field: &'static str) -> Result +where + V: Deserialize<'de>, + E: Error, +{ + struct MissingFieldDeserializer(&'static str, PhantomData); + + impl<'de, E> Deserializer<'de> for MissingFieldDeserializer + where + E: Error, + { + type Error = E; + + fn deserialize_any(self, _visitor: V) -> Result + where + V: Visitor<'de>, + { + Err(Error::missing_field(self.0)) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_none() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } + } + + let deserializer = MissingFieldDeserializer(field, PhantomData); + Deserialize::deserialize(deserializer) +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub fn borrow_cow_str<'de: 'a, 'a, D, R>(deserializer: D) -> Result +where + D: Deserializer<'de>, + R: From>, +{ + struct CowStrVisitor; + + impl<'a> Visitor<'a> for CowStrVisitor { + type Value = Cow<'a, str>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Ok(Cow::Owned(v.to_owned())) + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(Cow::Borrowed(v)) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + Ok(Cow::Owned(v)) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => Ok(Cow::Owned(s.to_owned())), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => Ok(Cow::Borrowed(s)), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => Ok(Cow::Owned(s)), + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } + } + + deserializer.deserialize_str(CowStrVisitor).map(From::from) +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub fn borrow_cow_bytes<'de: 'a, 'a, D, R>(deserializer: D) -> Result +where + D: Deserializer<'de>, + R: From>, +{ + struct CowBytesVisitor; + + impl<'a> Visitor<'a> for CowBytesVisitor { + type Value = Cow<'a, [u8]>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a byte array") + } + + fn visit_str(self, v: &str) -> Result + where + E: Error, + { + Ok(Cow::Owned(v.as_bytes().to_vec())) + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where + E: Error, + { + Ok(Cow::Borrowed(v.as_bytes())) + } + + fn visit_string(self, v: String) -> Result + where + E: Error, + { + Ok(Cow::Owned(v.into_bytes())) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: Error, + { + Ok(Cow::Owned(v.to_vec())) + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where + E: Error, + { + Ok(Cow::Borrowed(v)) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: Error, + { + Ok(Cow::Owned(v)) + } + } + + deserializer + .deserialize_bytes(CowBytesVisitor) + .map(From::from) +} + +#[cfg(any(feature = "std", feature = "alloc"))] +mod content { + // This module is private and nothing here should be used outside of + // generated code. + // + // We will iterate on the implementation for a few releases and only have to + // worry about backward compatibility for the `untagged` and `tag` attributes + // rather than for this entire mechanism. + // + // This issue is tracking making some of this stuff public: + // https://github.com/serde-rs/serde/issues/741 + + use crate::lib::*; + + use crate::actually_private; + use crate::de::value::{MapDeserializer, SeqDeserializer}; + use crate::de::{ + self, size_hint, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected, + IgnoredAny, MapAccess, SeqAccess, Unexpected, Visitor, + }; + + /// Used from generated code to buffer the contents of the Deserializer when + /// deserializing untagged enums and internally tagged enums. + /// + /// Not public API. Use serde-value instead. + #[derive(Debug, Clone)] + pub enum Content<'de> { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Str(&'de str), + ByteBuf(Vec), + Bytes(&'de [u8]), + + None, + Some(Box>), + + Unit, + Newtype(Box>), + Seq(Vec>), + Map(Vec<(Content<'de>, Content<'de>)>), + } + + impl<'de> Content<'de> { + pub fn as_str(&self) -> Option<&str> { + match *self { + Content::Str(x) => Some(x), + Content::String(ref x) => Some(x), + Content::Bytes(x) => str::from_utf8(x).ok(), + Content::ByteBuf(ref x) => str::from_utf8(x).ok(), + _ => None, + } + } + + #[cold] + fn unexpected(&self) -> Unexpected { + match *self { + Content::Bool(b) => Unexpected::Bool(b), + Content::U8(n) => Unexpected::Unsigned(n as u64), + Content::U16(n) => Unexpected::Unsigned(n as u64), + Content::U32(n) => Unexpected::Unsigned(n as u64), + Content::U64(n) => Unexpected::Unsigned(n), + Content::I8(n) => Unexpected::Signed(n as i64), + Content::I16(n) => Unexpected::Signed(n as i64), + Content::I32(n) => Unexpected::Signed(n as i64), + Content::I64(n) => Unexpected::Signed(n), + Content::F32(f) => Unexpected::Float(f as f64), + Content::F64(f) => Unexpected::Float(f), + Content::Char(c) => Unexpected::Char(c), + Content::String(ref s) => Unexpected::Str(s), + Content::Str(s) => Unexpected::Str(s), + Content::ByteBuf(ref b) => Unexpected::Bytes(b), + Content::Bytes(b) => Unexpected::Bytes(b), + Content::None | Content::Some(_) => Unexpected::Option, + Content::Unit => Unexpected::Unit, + Content::Newtype(_) => Unexpected::NewtypeStruct, + Content::Seq(_) => Unexpected::Seq, + Content::Map(_) => Unexpected::Map, + } + } + } + + impl<'de> Deserialize<'de> for Content<'de> { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // Untagged and internally tagged enums are only supported in + // self-describing formats. + let visitor = ContentVisitor { value: PhantomData }; + deserializer.__deserialize_content(actually_private::T, visitor) + } + } + + impl<'de, E> de::IntoDeserializer<'de, E> for Content<'de> + where + E: de::Error, + { + type Deserializer = ContentDeserializer<'de, E>; + + fn into_deserializer(self) -> Self::Deserializer { + ContentDeserializer::new(self) + } + } + + /// Used to capture data in [`Content`] from other deserializers. + /// Cannot capture externally tagged enums, `i128` and `u128`. + struct ContentVisitor<'de> { + value: PhantomData>, + } + + impl<'de> ContentVisitor<'de> { + fn new() -> Self { + ContentVisitor { value: PhantomData } + } + } + + impl<'de> Visitor<'de> for ContentVisitor<'de> { + type Value = Content<'de>; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str("any value") + } + + fn visit_bool(self, value: bool) -> Result + where + F: de::Error, + { + Ok(Content::Bool(value)) + } + + fn visit_i8(self, value: i8) -> Result + where + F: de::Error, + { + Ok(Content::I8(value)) + } + + fn visit_i16(self, value: i16) -> Result + where + F: de::Error, + { + Ok(Content::I16(value)) + } + + fn visit_i32(self, value: i32) -> Result + where + F: de::Error, + { + Ok(Content::I32(value)) + } + + fn visit_i64(self, value: i64) -> Result + where + F: de::Error, + { + Ok(Content::I64(value)) + } + + fn visit_u8(self, value: u8) -> Result + where + F: de::Error, + { + Ok(Content::U8(value)) + } + + fn visit_u16(self, value: u16) -> Result + where + F: de::Error, + { + Ok(Content::U16(value)) + } + + fn visit_u32(self, value: u32) -> Result + where + F: de::Error, + { + Ok(Content::U32(value)) + } + + fn visit_u64(self, value: u64) -> Result + where + F: de::Error, + { + Ok(Content::U64(value)) + } + + fn visit_f32(self, value: f32) -> Result + where + F: de::Error, + { + Ok(Content::F32(value)) + } + + fn visit_f64(self, value: f64) -> Result + where + F: de::Error, + { + Ok(Content::F64(value)) + } + + fn visit_char(self, value: char) -> Result + where + F: de::Error, + { + Ok(Content::Char(value)) + } + + fn visit_str(self, value: &str) -> Result + where + F: de::Error, + { + Ok(Content::String(value.into())) + } + + fn visit_borrowed_str(self, value: &'de str) -> Result + where + F: de::Error, + { + Ok(Content::Str(value)) + } + + fn visit_string(self, value: String) -> Result + where + F: de::Error, + { + Ok(Content::String(value)) + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + F: de::Error, + { + Ok(Content::ByteBuf(value.into())) + } + + fn visit_borrowed_bytes(self, value: &'de [u8]) -> Result + where + F: de::Error, + { + Ok(Content::Bytes(value)) + } + + fn visit_byte_buf(self, value: Vec) -> Result + where + F: de::Error, + { + Ok(Content::ByteBuf(value)) + } + + fn visit_unit(self) -> Result + where + F: de::Error, + { + Ok(Content::Unit) + } + + fn visit_none(self) -> Result + where + F: de::Error, + { + Ok(Content::None) + } + + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v))) + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v))) + } + + fn visit_seq(self, mut visitor: V) -> Result + where + V: SeqAccess<'de>, + { + let mut vec = + Vec::::with_capacity(size_hint::cautious::(visitor.size_hint())); + while let Some(e) = tri!(visitor.next_element()) { + vec.push(e); + } + Ok(Content::Seq(vec)) + } + + fn visit_map(self, mut visitor: V) -> Result + where + V: MapAccess<'de>, + { + let mut vec = + Vec::<(Content, Content)>::with_capacity( + size_hint::cautious::<(Content, Content)>(visitor.size_hint()), + ); + while let Some(kv) = tri!(visitor.next_entry()) { + vec.push(kv); + } + Ok(Content::Map(vec)) + } + + fn visit_enum(self, _visitor: V) -> Result + where + V: EnumAccess<'de>, + { + Err(de::Error::custom( + "untagged and internally tagged enums do not support enum input", + )) + } + } + + /// This is the type of the map keys in an internally tagged enum. + /// + /// Not public API. + pub enum TagOrContent<'de> { + Tag, + Content(Content<'de>), + } + + /// Serves as a seed for deserializing a key of internally tagged enum. + /// Cannot capture externally tagged enums, `i128` and `u128`. + struct TagOrContentVisitor<'de> { + name: &'static str, + value: PhantomData>, + } + + impl<'de> TagOrContentVisitor<'de> { + fn new(name: &'static str) -> Self { + TagOrContentVisitor { + name, + value: PhantomData, + } + } + } + + impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> { + type Value = TagOrContent<'de>; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // Internally tagged enums are only supported in self-describing + // formats. + deserializer.deserialize_any(self) + } + } + + impl<'de> Visitor<'de> for TagOrContentVisitor<'de> { + type Value = TagOrContent<'de>; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "a type tag `{}` or any other value", self.name) + } + + fn visit_bool(self, value: bool) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_bool(value) + .map(TagOrContent::Content) + } + + fn visit_i8(self, value: i8) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_i8(value) + .map(TagOrContent::Content) + } + + fn visit_i16(self, value: i16) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_i16(value) + .map(TagOrContent::Content) + } + + fn visit_i32(self, value: i32) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_i32(value) + .map(TagOrContent::Content) + } + + fn visit_i64(self, value: i64) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_i64(value) + .map(TagOrContent::Content) + } + + fn visit_u8(self, value: u8) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_u8(value) + .map(TagOrContent::Content) + } + + fn visit_u16(self, value: u16) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_u16(value) + .map(TagOrContent::Content) + } + + fn visit_u32(self, value: u32) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_u32(value) + .map(TagOrContent::Content) + } + + fn visit_u64(self, value: u64) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_u64(value) + .map(TagOrContent::Content) + } + + fn visit_f32(self, value: f32) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_f32(value) + .map(TagOrContent::Content) + } + + fn visit_f64(self, value: f64) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_f64(value) + .map(TagOrContent::Content) + } + + fn visit_char(self, value: char) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_char(value) + .map(TagOrContent::Content) + } + + fn visit_str(self, value: &str) -> Result + where + F: de::Error, + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_str(value) + .map(TagOrContent::Content) + } + } + + fn visit_borrowed_str(self, value: &'de str) -> Result + where + F: de::Error, + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_borrowed_str(value) + .map(TagOrContent::Content) + } + } + + fn visit_string(self, value: String) -> Result + where + F: de::Error, + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_string(value) + .map(TagOrContent::Content) + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where + F: de::Error, + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_bytes(value) + .map(TagOrContent::Content) + } + } + + fn visit_borrowed_bytes(self, value: &'de [u8]) -> Result + where + F: de::Error, + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_borrowed_bytes(value) + .map(TagOrContent::Content) + } + } + + fn visit_byte_buf(self, value: Vec) -> Result + where + F: de::Error, + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_byte_buf(value) + .map(TagOrContent::Content) + } + } + + fn visit_unit(self) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_unit() + .map(TagOrContent::Content) + } + + fn visit_none(self) -> Result + where + F: de::Error, + { + ContentVisitor::new() + .visit_none() + .map(TagOrContent::Content) + } + + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + ContentVisitor::new() + .visit_some(deserializer) + .map(TagOrContent::Content) + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + ContentVisitor::new() + .visit_newtype_struct(deserializer) + .map(TagOrContent::Content) + } + + fn visit_seq(self, visitor: V) -> Result + where + V: SeqAccess<'de>, + { + ContentVisitor::new() + .visit_seq(visitor) + .map(TagOrContent::Content) + } + + fn visit_map(self, visitor: V) -> Result + where + V: MapAccess<'de>, + { + ContentVisitor::new() + .visit_map(visitor) + .map(TagOrContent::Content) + } + + fn visit_enum(self, visitor: V) -> Result + where + V: EnumAccess<'de>, + { + ContentVisitor::new() + .visit_enum(visitor) + .map(TagOrContent::Content) + } + } + + /// Used by generated code to deserialize an internally tagged enum. + /// + /// Captures map or sequence from the original deserializer and searches + /// a tag in it (in case of sequence, tag is the first element of sequence). + /// + /// Not public API. + pub struct TaggedContentVisitor { + tag_name: &'static str, + expecting: &'static str, + value: PhantomData, + } + + impl TaggedContentVisitor { + /// Visitor for the content of an internally tagged enum with the given + /// tag name. + pub fn new(name: &'static str, expecting: &'static str) -> Self { + TaggedContentVisitor { + tag_name: name, + expecting, + value: PhantomData, + } + } + } + + impl<'de, T> Visitor<'de> for TaggedContentVisitor + where + T: Deserialize<'de>, + { + type Value = (T, Content<'de>); + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str(self.expecting) + } + + fn visit_seq(self, mut seq: S) -> Result + where + S: SeqAccess<'de>, + { + let tag = match tri!(seq.next_element()) { + Some(tag) => tag, + None => { + return Err(de::Error::missing_field(self.tag_name)); + } + }; + let rest = de::value::SeqAccessDeserializer::new(seq); + Ok((tag, tri!(Content::deserialize(rest)))) + } + + fn visit_map(self, mut map: M) -> Result + where + M: MapAccess<'de>, + { + let mut tag = None; + let mut vec = Vec::<(Content, Content)>::with_capacity(size_hint::cautious::<( + Content, + Content, + )>(map.size_hint())); + while let Some(k) = tri!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) { + match k { + TagOrContent::Tag => { + if tag.is_some() { + return Err(de::Error::duplicate_field(self.tag_name)); + } + tag = Some(tri!(map.next_value())); + } + TagOrContent::Content(k) => { + let v = tri!(map.next_value()); + vec.push((k, v)); + } + } + } + match tag { + None => Err(de::Error::missing_field(self.tag_name)), + Some(tag) => Ok((tag, Content::Map(vec))), + } + } + } + + /// Used by generated code to deserialize an adjacently tagged enum. + /// + /// Not public API. + pub enum TagOrContentField { + Tag, + Content, + } + + /// Not public API. + pub struct TagOrContentFieldVisitor { + /// Name of the tag field of the adjacently tagged enum + pub tag: &'static str, + /// Name of the content field of the adjacently tagged enum + pub content: &'static str, + } + + impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_identifier(self) + } + } + + impl<'de> Visitor<'de> for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "{:?} or {:?}", self.tag, self.content) + } + + fn visit_u64(self, field_index: u64) -> Result + where + E: de::Error, + { + match field_index { + 0 => Ok(TagOrContentField::Tag), + 1 => Ok(TagOrContentField::Content), + _ => Err(de::Error::invalid_value( + Unexpected::Unsigned(field_index), + &self, + )), + } + } + + fn visit_str(self, field: &str) -> Result + where + E: de::Error, + { + if field == self.tag { + Ok(TagOrContentField::Tag) + } else if field == self.content { + Ok(TagOrContentField::Content) + } else { + Err(de::Error::invalid_value(Unexpected::Str(field), &self)) + } + } + + fn visit_bytes(self, field: &[u8]) -> Result + where + E: de::Error, + { + if field == self.tag.as_bytes() { + Ok(TagOrContentField::Tag) + } else if field == self.content.as_bytes() { + Ok(TagOrContentField::Content) + } else { + Err(de::Error::invalid_value(Unexpected::Bytes(field), &self)) + } + } + } + + /// Used by generated code to deserialize an adjacently tagged enum when + /// ignoring unrelated fields is allowed. + /// + /// Not public API. + pub enum TagContentOtherField { + Tag, + Content, + Other, + } + + /// Not public API. + pub struct TagContentOtherFieldVisitor { + /// Name of the tag field of the adjacently tagged enum + pub tag: &'static str, + /// Name of the content field of the adjacently tagged enum + pub content: &'static str, + } + + impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor { + type Value = TagContentOtherField; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_identifier(self) + } + } + + impl<'de> Visitor<'de> for TagContentOtherFieldVisitor { + type Value = TagContentOtherField; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "{:?}, {:?}, or other ignored fields", + self.tag, self.content + ) + } + + fn visit_u64(self, field_index: u64) -> Result + where + E: de::Error, + { + match field_index { + 0 => Ok(TagContentOtherField::Tag), + 1 => Ok(TagContentOtherField::Content), + _ => Ok(TagContentOtherField::Other), + } + } + + fn visit_str(self, field: &str) -> Result + where + E: de::Error, + { + self.visit_bytes(field.as_bytes()) + } + + fn visit_bytes(self, field: &[u8]) -> Result + where + E: de::Error, + { + if field == self.tag.as_bytes() { + Ok(TagContentOtherField::Tag) + } else if field == self.content.as_bytes() { + Ok(TagContentOtherField::Content) + } else { + Ok(TagContentOtherField::Other) + } + } + } + + /// Not public API + pub struct ContentDeserializer<'de, E> { + content: Content<'de>, + err: PhantomData, + } + + impl<'de, E> ContentDeserializer<'de, E> + where + E: de::Error, + { + #[cold] + fn invalid_type(self, exp: &Expected) -> E { + de::Error::invalid_type(self.content.unexpected(), exp) + } + + fn deserialize_integer(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_float(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + _ => Err(self.invalid_type(&visitor)), + } + } + } + + fn visit_content_seq<'de, V, E>(content: Vec>, visitor: V) -> Result + where + V: Visitor<'de>, + E: de::Error, + { + let seq = content.into_iter().map(ContentDeserializer::new); + let mut seq_visitor = SeqDeserializer::new(seq); + let value = tri!(visitor.visit_seq(&mut seq_visitor)); + tri!(seq_visitor.end()); + Ok(value) + } + + fn visit_content_map<'de, V, E>( + content: Vec<(Content<'de>, Content<'de>)>, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + E: de::Error, + { + let map = content + .into_iter() + .map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v))); + let mut map_visitor = MapDeserializer::new(map); + let value = tri!(visitor.visit_map(&mut map_visitor)); + tri!(map_visitor.end()); + Ok(value) + } + + /// Used when deserializing an internally tagged enum because the content + /// will be used exactly once. + impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(v) => visitor.visit_string(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(v) => visitor.visit_byte_buf(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)), + Content::Seq(v) => visit_content_seq(v, visitor), + Content::Map(v) => visit_content_map(v, visitor), + } + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Bool(v) => visitor.visit_bool(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_float(visitor) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_float(visitor) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Char(v) => visitor.visit_char(v), + Content::String(v) => visitor.visit_string(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(visitor) + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::String(v) => visitor.visit_string(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(v) => visitor.visit_byte_buf(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_byte_buf(visitor) + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::String(v) => visitor.visit_string(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(v) => visitor.visit_byte_buf(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::Seq(v) => visit_content_seq(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Unit => visitor.visit_unit(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Unit => visitor.visit_unit(), + + // Allow deserializing newtype variant containing unit. + // + // #[derive(Deserialize)] + // #[serde(tag = "result")] + // enum Response { + // Success(T), + // } + // + // We want {"result":"Success"} to deserialize into Response<()>. + Content::Map(ref v) if v.is_empty() => visitor.visit_unit(), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_unit_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + match self.content { + // As a special case, allow deserializing untagged newtype + // variant containing unit struct. + // + // #[derive(Deserialize)] + // struct Info; + // + // #[derive(Deserialize)] + // #[serde(tag = "topic")] + // enum Message { + // Info(Info), + // } + // + // We want {"topic":"Info"} to deserialize even though + // ordinarily unit structs do not deserialize from empty map/seq. + Content::Map(ref v) if v.is_empty() => visitor.visit_unit(), + Content::Seq(ref v) if v.is_empty() => visitor.visit_unit(), + _ => self.deserialize_any(visitor), + } + } + + fn deserialize_newtype_struct( + self, + _name: &str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)), + _ => visitor.visit_newtype_struct(self), + } + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Seq(v) => visit_content_seq(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_tuple(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Map(v) => visit_content_map(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_struct( + self, + _name: &'static str, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::Seq(v) => visit_content_seq(v, visitor), + Content::Map(v) => visit_content_map(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_enum( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let (variant, value) = match self.content { + Content::Map(value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + (variant, Some(value)) + } + s @ Content::String(_) | s @ Content::Str(_) => (s, None), + other => { + return Err(de::Error::invalid_type( + other.unexpected(), + &"string or map", + )); + } + }; + + visitor.visit_enum(EnumDeserializer::new(variant, value)) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.content { + Content::String(v) => visitor.visit_string(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(v) => visitor.visit_byte_buf(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U64(v) => visitor.visit_u64(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + drop(self); + visitor.visit_unit() + } + + fn __deserialize_content( + self, + _: actually_private::T, + visitor: V, + ) -> Result, Self::Error> + where + V: Visitor<'de, Value = Content<'de>>, + { + let _ = visitor; + Ok(self.content) + } + } + + impl<'de, E> ContentDeserializer<'de, E> { + /// private API, don't use + pub fn new(content: Content<'de>) -> Self { + ContentDeserializer { + content, + err: PhantomData, + } + } + } + + pub struct EnumDeserializer<'de, E> + where + E: de::Error, + { + variant: Content<'de>, + value: Option>, + err: PhantomData, + } + + impl<'de, E> EnumDeserializer<'de, E> + where + E: de::Error, + { + pub fn new(variant: Content<'de>, value: Option>) -> EnumDeserializer<'de, E> { + EnumDeserializer { + variant, + value, + err: PhantomData, + } + } + } + + impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + type Variant = VariantDeserializer<'de, Self::Error>; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), E> + where + V: de::DeserializeSeed<'de>, + { + let visitor = VariantDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentDeserializer::new(self.variant)) + .map(|v| (v, visitor)) + } + } + + pub struct VariantDeserializer<'de, E> + where + E: de::Error, + { + value: Option>, + err: PhantomData, + } + + impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn unit_variant(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)), + None => Ok(()), + } + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: de::DeserializeSeed<'de>, + { + match self.value { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"newtype variant", + )), + } + } + + fn tuple_variant(self, _len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + match self.value { + Some(Content::Seq(v)) => { + de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor) + } + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"tuple variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"tuple variant", + )), + } + } + + fn struct_variant( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + match self.value { + Some(Content::Map(v)) => { + de::Deserializer::deserialize_any(MapDeserializer::new(v.into_iter()), visitor) + } + Some(Content::Seq(v)) => { + de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor) + } + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"struct variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"struct variant", + )), + } + } + } + + /// Not public API. + pub struct ContentRefDeserializer<'a, 'de: 'a, E> { + content: &'a Content<'de>, + err: PhantomData, + } + + impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + #[cold] + fn invalid_type(self, exp: &Expected) -> E { + de::Error::invalid_type(self.content.unexpected(), exp) + } + + fn deserialize_integer(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_float(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + _ => Err(self.invalid_type(&visitor)), + } + } + } + + fn visit_content_seq_ref<'a, 'de, V, E>( + content: &'a [Content<'de>], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + E: de::Error, + { + let seq = content.iter().map(ContentRefDeserializer::new); + let mut seq_visitor = SeqDeserializer::new(seq); + let value = tri!(visitor.visit_seq(&mut seq_visitor)); + tri!(seq_visitor.end()); + Ok(value) + } + + fn visit_content_map_ref<'a, 'de, V, E>( + content: &'a [(Content<'de>, Content<'de>)], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + E: de::Error, + { + let map = content.iter().map(|(k, v)| { + ( + ContentRefDeserializer::new(k), + ContentRefDeserializer::new(v), + ) + }); + let mut map_visitor = MapDeserializer::new(map); + let value = tri!(visitor.visit_map(&mut map_visitor)); + tri!(map_visitor.end()); + Ok(value) + } + + /// Used when deserializing an untagged enum because the content may need + /// to be used more than once. + impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(ref v) => visitor.visit_str(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(ref v) => visitor.visit_bytes(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Newtype(ref v) => { + visitor.visit_newtype_struct(ContentRefDeserializer::new(v)) + } + Content::Seq(ref v) => visit_content_seq_ref(v, visitor), + Content::Map(ref v) => visit_content_map_ref(v, visitor), + } + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::Bool(v) => visitor.visit_bool(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_integer(visitor) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_float(visitor) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_float(visitor) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::Char(v) => visitor.visit_char(v), + Content::String(ref v) => visitor.visit_str(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::String(ref v) => visitor.visit_str(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(ref v) => visitor.visit_bytes(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_str(visitor) + } + + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::String(ref v) => visitor.visit_str(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(ref v) => visitor.visit_bytes(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::Seq(ref v) => visit_content_seq_ref(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_bytes(visitor) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + // Covered by tests/test_enum_untagged.rs + // with_optional_field::* + match *self.content { + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Unit => visitor.visit_unit(), + // This case is to support data formats which do not encode an + // indication whether a value is optional. An example of such a + // format is JSON, and a counterexample is RON. When requesting + // `deserialize_any` in JSON, the data format never performs + // `Visitor::visit_some` but we still must be able to + // deserialize the resulting Content into data structures with + // optional fields. + _ => visitor.visit_some(self), + } + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::Unit => visitor.visit_unit(), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_unit_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_unit(visitor) + } + + fn deserialize_newtype_struct(self, _name: &str, visitor: V) -> Result + where + V: Visitor<'de>, + { + // Covered by tests/test_enum_untagged.rs + // newtype_struct + match *self.content { + Content::Newtype(ref v) => { + visitor.visit_newtype_struct(ContentRefDeserializer::new(v)) + } + // This case is to support data formats that encode newtype + // structs and their underlying data the same, with no + // indication whether a newtype wrapper was present. For example + // JSON does this, while RON does not. In RON a newtype's name + // is included in the serialized representation and it knows to + // call `Visitor::visit_newtype_struct` from `deserialize_any`. + // JSON's `deserialize_any` never calls `visit_newtype_struct` + // but in this code we still must be able to deserialize the + // resulting Content into newtypes. + _ => visitor.visit_newtype_struct(self), + } + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::Seq(ref v) => visit_content_seq_ref(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_tuple(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::Map(ref v) => visit_content_map_ref(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_struct( + self, + _name: &'static str, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::Seq(ref v) => visit_content_seq_ref(v, visitor), + Content::Map(ref v) => visit_content_map_ref(v, visitor), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_enum( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let (variant, value) = match *self.content { + Content::Map(ref value) => { + let mut iter = value.iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + (variant, Some(value)) + } + ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None), + ref other => { + return Err(de::Error::invalid_type( + other.unexpected(), + &"string or map", + )); + } + }; + + visitor.visit_enum(EnumRefDeserializer { + variant, + value, + err: PhantomData, + }) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match *self.content { + Content::String(ref v) => visitor.visit_str(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(ref v) => visitor.visit_bytes(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U64(v) => visitor.visit_u64(v), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + + fn __deserialize_content( + self, + _: actually_private::T, + visitor: V, + ) -> Result, Self::Error> + where + V: Visitor<'de, Value = Content<'de>>, + { + let _ = visitor; + Ok(self.content.clone()) + } + } + + impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> { + /// private API, don't use + pub fn new(content: &'a Content<'de>) -> Self { + ContentRefDeserializer { + content, + err: PhantomData, + } + } + } + + impl<'a, 'de: 'a, E> Copy for ContentRefDeserializer<'a, 'de, E> {} + + impl<'a, 'de: 'a, E> Clone for ContentRefDeserializer<'a, 'de, E> { + fn clone(&self) -> Self { + *self + } + } + + struct EnumRefDeserializer<'a, 'de: 'a, E> + where + E: de::Error, + { + variant: &'a Content<'de>, + value: Option<&'a Content<'de>>, + err: PhantomData, + } + + impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + type Variant = VariantRefDeserializer<'a, 'de, Self::Error>; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: de::DeserializeSeed<'de>, + { + let visitor = VariantRefDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentRefDeserializer::new(self.variant)) + .map(|v| (v, visitor)) + } + } + + struct VariantRefDeserializer<'a, 'de: 'a, E> + where + E: de::Error, + { + value: Option<&'a Content<'de>>, + err: PhantomData, + } + + impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + fn unit_variant(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), + // Covered by tests/test_annotations.rs + // test_partially_untagged_adjacently_tagged_enum + // Covered by tests/test_enum_untagged.rs + // newtype_enum::unit + None => Ok(()), + } + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: de::DeserializeSeed<'de>, + { + match self.value { + // Covered by tests/test_annotations.rs + // test_partially_untagged_enum_desugared + // test_partially_untagged_enum_generic + // Covered by tests/test_enum_untagged.rs + // newtype_enum::newtype + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"newtype variant", + )), + } + } + + fn tuple_variant(self, _len: usize, visitor: V) -> Result + where + V: de::Visitor<'de>, + { + match self.value { + // Covered by tests/test_annotations.rs + // test_partially_untagged_enum + // test_partially_untagged_enum_desugared + // Covered by tests/test_enum_untagged.rs + // newtype_enum::tuple0 + // newtype_enum::tuple2 + Some(Content::Seq(v)) => visit_content_seq_ref(v, visitor), + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"tuple variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"tuple variant", + )), + } + } + + fn struct_variant( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, + { + match self.value { + // Covered by tests/test_enum_untagged.rs + // newtype_enum::struct_from_map + Some(Content::Map(v)) => visit_content_map_ref(v, visitor), + // Covered by tests/test_enum_untagged.rs + // newtype_enum::struct_from_seq + // newtype_enum::empty_struct_from_seq + Some(Content::Seq(v)) => visit_content_seq_ref(v, visitor), + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"struct variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"struct variant", + )), + } + } + } + + impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E> + where + E: de::Error, + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + + impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + + /// Visitor for deserializing an internally tagged unit variant. + /// + /// Not public API. + pub struct InternallyTaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, + } + + impl<'a> InternallyTaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + InternallyTaggedUnitVisitor { + type_name, + variant_name, + } + } + } + + impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "unit variant {}::{}", + self.type_name, self.variant_name + ) + } + + fn visit_seq(self, _: S) -> Result<(), S::Error> + where + S: SeqAccess<'de>, + { + Ok(()) + } + + fn visit_map(self, mut access: M) -> Result<(), M::Error> + where + M: MapAccess<'de>, + { + while tri!(access.next_entry::()).is_some() {} + Ok(()) + } + } + + /// Visitor for deserializing an untagged unit variant. + /// + /// Not public API. + pub struct UntaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, + } + + impl<'a> UntaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + UntaggedUnitVisitor { + type_name, + variant_name, + } + } + } + + impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "unit variant {}::{}", + self.type_name, self.variant_name + ) + } + + fn visit_unit(self) -> Result<(), E> + where + E: de::Error, + { + Ok(()) + } + + fn visit_none(self) -> Result<(), E> + where + E: de::Error, + { + Ok(()) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Like `IntoDeserializer` but also implemented for `&[u8]`. This is used for +// the newtype fallthrough case of `field_identifier`. +// +// #[derive(Deserialize)] +// #[serde(field_identifier)] +// enum F { +// A, +// B, +// Other(String), // deserialized using IdentifierDeserializer +// } +pub trait IdentifierDeserializer<'de, E: Error> { + type Deserializer: Deserializer<'de, Error = E>; + + fn from(self) -> Self::Deserializer; +} + +pub struct Borrowed<'de, T: 'de + ?Sized>(pub &'de T); + +impl<'de, E> IdentifierDeserializer<'de, E> for u64 +where + E: Error, +{ + type Deserializer = >::Deserializer; + + fn from(self) -> Self::Deserializer { + self.into_deserializer() + } +} + +pub struct StrDeserializer<'a, E> { + value: &'a str, + marker: PhantomData, +} + +impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E> +where + E: Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_str(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +pub struct BorrowedStrDeserializer<'de, E> { + value: &'de str, + marker: PhantomData, +} + +impl<'de, E> Deserializer<'de> for BorrowedStrDeserializer<'de, E> +where + E: Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_borrowed_str(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'a, E> IdentifierDeserializer<'a, E> for &'a str +where + E: Error, +{ + type Deserializer = StrDeserializer<'a, E>; + + fn from(self) -> Self::Deserializer { + StrDeserializer { + value: self, + marker: PhantomData, + } + } +} + +impl<'de, E> IdentifierDeserializer<'de, E> for Borrowed<'de, str> +where + E: Error, +{ + type Deserializer = BorrowedStrDeserializer<'de, E>; + + fn from(self) -> Self::Deserializer { + BorrowedStrDeserializer { + value: self.0, + marker: PhantomData, + } + } +} + +impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8] +where + E: Error, +{ + type Deserializer = BytesDeserializer<'a, E>; + + fn from(self) -> Self::Deserializer { + BytesDeserializer::new(self) + } +} + +impl<'de, E> IdentifierDeserializer<'de, E> for Borrowed<'de, [u8]> +where + E: Error, +{ + type Deserializer = BorrowedBytesDeserializer<'de, E>; + + fn from(self) -> Self::Deserializer { + BorrowedBytesDeserializer::new(self.0) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapDeserializer<'a, 'de: 'a, E>( + pub &'a mut Vec, Content<'de>)>>, + pub PhantomData, +); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de, E> FlatMapDeserializer<'a, 'de, E> +where + E: Error, +{ + fn deserialize_other() -> Result { + Err(Error::custom("can only flatten structs and maps")) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +macro_rules! forward_to_deserialize_other { + ($($func:ident ($($arg:ty),*))*) => { + $( + fn $func(self, $(_: $arg,)* _visitor: V) -> Result + where + V: Visitor<'de>, + { + Self::deserialize_other() + } + )* + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E> +where + E: Error, +{ + type Error = E; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_map(visitor) + } + + fn deserialize_enum( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + for entry in self.0 { + if let Some((key, value)) = flat_map_take_entry(entry, variants) { + return visitor.visit_enum(EnumDeserializer::new(key, Some(value))); + } + } + + Err(Error::custom(format_args!( + "no variant of enum {} found in flattened data", + name + ))) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_map(FlatMapAccess { + iter: self.0.iter(), + pending_content: None, + _marker: PhantomData, + }) + } + + fn deserialize_struct( + self, + _: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_map(FlatStructAccess { + iter: self.0.iter_mut(), + pending_content: None, + fields, + _marker: PhantomData, + }) + } + + fn deserialize_newtype_struct(self, _name: &str, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match visitor.__private_visit_untagged_option(self) { + Ok(value) => Ok(value), + Err(()) => Self::deserialize_other(), + } + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + + fn deserialize_unit_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + + forward_to_deserialize_other! { + deserialize_bool() + deserialize_i8() + deserialize_i16() + deserialize_i32() + deserialize_i64() + deserialize_u8() + deserialize_u16() + deserialize_u32() + deserialize_u64() + deserialize_f32() + deserialize_f64() + deserialize_char() + deserialize_str() + deserialize_string() + deserialize_bytes() + deserialize_byte_buf() + deserialize_seq() + deserialize_tuple(usize) + deserialize_tuple_struct(&'static str, usize) + deserialize_identifier() + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +struct FlatMapAccess<'a, 'de: 'a, E> { + iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>, + pending_content: Option<&'a Content<'de>>, + _marker: PhantomData, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E> +where + E: Error, +{ + type Error = E; + + fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + for item in &mut self.iter { + // Items in the vector are nulled out when used by a struct. + if let Some((ref key, ref content)) = *item { + // Do not take(), instead borrow this entry. The internally tagged + // enum does its own buffering so we can't tell whether this entry + // is going to be consumed. Borrowing here leaves the entry + // available for later flattened fields. + self.pending_content = Some(content); + return seed.deserialize(ContentRefDeserializer::new(key)).map(Some); + } + } + Ok(None) + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + match self.pending_content.take() { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(Error::custom("value is missing")), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +struct FlatStructAccess<'a, 'de: 'a, E> { + iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>, + pending_content: Option>, + fields: &'static [&'static str], + _marker: PhantomData, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de, E> MapAccess<'de> for FlatStructAccess<'a, 'de, E> +where + E: Error, +{ + type Error = E; + + fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + for entry in self.iter.by_ref() { + if let Some((key, content)) = flat_map_take_entry(entry, self.fields) { + self.pending_content = Some(content); + return seed.deserialize(ContentDeserializer::new(key)).map(Some); + } + } + Ok(None) + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + match self.pending_content.take() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(Error::custom("value is missing")), + } + } +} + +/// Claims one key-value pair from a FlatMapDeserializer's field buffer if the +/// field name matches any of the recognized ones. +#[cfg(any(feature = "std", feature = "alloc"))] +fn flat_map_take_entry<'de>( + entry: &mut Option<(Content<'de>, Content<'de>)>, + recognized: &[&str], +) -> Option<(Content<'de>, Content<'de>)> { + // Entries in the FlatMapDeserializer buffer are nulled out as they get + // claimed for deserialization. We only use an entry if it is still present + // and if the field is one recognized by the current data structure. + let is_recognized = match entry { + None => false, + Some((k, _v)) => k.as_str().map_or(false, |name| recognized.contains(&name)), + }; + + if is_recognized { + entry.take() + } else { + None + } +} + +pub struct AdjacentlyTaggedEnumVariantSeed { + pub enum_name: &'static str, + pub variants: &'static [&'static str], + pub fields_enum: PhantomData, +} + +pub struct AdjacentlyTaggedEnumVariantVisitor { + enum_name: &'static str, + fields_enum: PhantomData, +} + +impl<'de, F> Visitor<'de> for AdjacentlyTaggedEnumVariantVisitor +where + F: Deserialize<'de>, +{ + type Value = F; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "variant of enum {}", self.enum_name) + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + let (variant, variant_access) = tri!(data.variant()); + tri!(variant_access.unit_variant()); + Ok(variant) + } +} + +impl<'de, F> DeserializeSeed<'de> for AdjacentlyTaggedEnumVariantSeed +where + F: Deserialize<'de>, +{ + type Value = F; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_enum( + self.enum_name, + self.variants, + AdjacentlyTaggedEnumVariantVisitor { + enum_name: self.enum_name, + fields_enum: PhantomData, + }, + ) + } +} diff --git a/bitbox02-bt/vendor/serde/src/private/doc.rs b/bitbox02-bt/vendor/serde/src/private/doc.rs new file mode 100644 index 0000000..1f17c8d --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/private/doc.rs @@ -0,0 +1,162 @@ +// Used only by Serde doc tests. Not public API. + +use crate::lib::*; + +use crate::ser; + +#[doc(hidden)] +#[derive(Debug)] +pub struct Error; + +impl ser::Error for Error { + fn custom(_: T) -> Self + where + T: Display, + { + unimplemented!() + } +} + +#[cfg(feature = "std")] +impl error::Error for Error { + fn description(&self) -> &str { + unimplemented!() + } +} + +impl Display for Error { + fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __private_serialize { + () => { + trait Serialize { + fn serialize(&self, serializer: S) -> Result + where + S: $crate::Serializer; + } + }; +} + +#[doc(hidden)] +#[macro_export(local_inner_macros)] +macro_rules! __serialize_unimplemented { + ($($func:ident)*) => { + $( + __serialize_unimplemented_helper!($func); + )* + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented_method { + ($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => { + fn $func $(<$t>)* (self $(, _: $arg)*) -> $crate::__private::Result + where + $($t: ?Sized + $crate::Serialize,)* + { + unimplemented!() + } + }; +} + +#[doc(hidden)] +#[macro_export(local_inner_macros)] +macro_rules! __serialize_unimplemented_helper { + (bool) => { + __serialize_unimplemented_method!(serialize_bool(bool) -> Ok); + }; + (i8) => { + __serialize_unimplemented_method!(serialize_i8(i8) -> Ok); + }; + (i16) => { + __serialize_unimplemented_method!(serialize_i16(i16) -> Ok); + }; + (i32) => { + __serialize_unimplemented_method!(serialize_i32(i32) -> Ok); + }; + (i64) => { + __serialize_unimplemented_method!(serialize_i64(i64) -> Ok); + }; + (u8) => { + __serialize_unimplemented_method!(serialize_u8(u8) -> Ok); + }; + (u16) => { + __serialize_unimplemented_method!(serialize_u16(u16) -> Ok); + }; + (u32) => { + __serialize_unimplemented_method!(serialize_u32(u32) -> Ok); + }; + (u64) => { + __serialize_unimplemented_method!(serialize_u64(u64) -> Ok); + }; + (f32) => { + __serialize_unimplemented_method!(serialize_f32(f32) -> Ok); + }; + (f64) => { + __serialize_unimplemented_method!(serialize_f64(f64) -> Ok); + }; + (char) => { + __serialize_unimplemented_method!(serialize_char(char) -> Ok); + }; + (str) => { + __serialize_unimplemented_method!(serialize_str(&str) -> Ok); + }; + (bytes) => { + __serialize_unimplemented_method!(serialize_bytes(&[u8]) -> Ok); + }; + (none) => { + __serialize_unimplemented_method!(serialize_none() -> Ok); + }; + (some) => { + __serialize_unimplemented_method!(serialize_some(&T) -> Ok); + }; + (unit) => { + __serialize_unimplemented_method!(serialize_unit() -> Ok); + }; + (unit_struct) => { + __serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok); + }; + (unit_variant) => { + __serialize_unimplemented_method!(serialize_unit_variant(&str, u32, &str) -> Ok); + }; + (newtype_struct) => { + __serialize_unimplemented_method!(serialize_newtype_struct(&str, &T) -> Ok); + }; + (newtype_variant) => { + __serialize_unimplemented_method!(serialize_newtype_variant(&str, u32, &str, &T) -> Ok); + }; + (seq) => { + type SerializeSeq = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_seq(Option) -> SerializeSeq); + }; + (tuple) => { + type SerializeTuple = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple); + }; + (tuple_struct) => { + type SerializeTupleStruct = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple_struct(&str, usize) -> SerializeTupleStruct); + }; + (tuple_variant) => { + type SerializeTupleVariant = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple_variant(&str, u32, &str, usize) -> SerializeTupleVariant); + }; + (map) => { + type SerializeMap = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_map(Option) -> SerializeMap); + }; + (struct) => { + type SerializeStruct = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_struct(&str, usize) -> SerializeStruct); + }; + (struct_variant) => { + type SerializeStructVariant = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_struct_variant(&str, u32, &str, usize) -> SerializeStructVariant); + }; +} diff --git a/bitbox02-bt/vendor/serde/src/private/mod.rs b/bitbox02-bt/vendor/serde/src/private/mod.rs new file mode 100644 index 0000000..177f850 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/private/mod.rs @@ -0,0 +1,48 @@ +#[cfg(not(no_serde_derive))] +pub mod de; +#[cfg(not(no_serde_derive))] +pub mod ser; + +// FIXME: #[cfg(doctest)] once https://github.com/rust-lang/rust/issues/67295 is fixed. +pub mod doc; + +pub use crate::lib::clone::Clone; +pub use crate::lib::convert::{From, Into}; +pub use crate::lib::default::Default; +pub use crate::lib::fmt::{self, Formatter}; +pub use crate::lib::marker::PhantomData; +pub use crate::lib::option::Option::{self, None, Some}; +pub use crate::lib::ptr; +pub use crate::lib::result::Result::{self, Err, Ok}; + +pub use self::string::from_utf8_lossy; + +#[cfg(any(feature = "alloc", feature = "std"))] +pub use crate::lib::{ToString, Vec}; + +#[cfg(not(no_core_try_from))] +pub use crate::lib::convert::TryFrom; + +mod string { + use crate::lib::*; + + #[cfg(any(feature = "std", feature = "alloc"))] + pub fn from_utf8_lossy(bytes: &[u8]) -> Cow { + String::from_utf8_lossy(bytes) + } + + // The generated code calls this like: + // + // let value = &_serde::__private::from_utf8_lossy(bytes); + // Err(_serde::de::Error::unknown_variant(value, VARIANTS)) + // + // so it is okay for the return type to be different from the std case as long + // as the above works. + #[cfg(not(any(feature = "std", feature = "alloc")))] + pub fn from_utf8_lossy(bytes: &[u8]) -> &str { + // Three unicode replacement characters if it fails. They look like a + // white-on-black question mark. The user will recognize it as invalid + // UTF-8. + str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}") + } +} diff --git a/bitbox02-bt/vendor/serde/src/private/ser.rs b/bitbox02-bt/vendor/serde/src/private/ser.rs new file mode 100644 index 0000000..ebfeba9 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/private/ser.rs @@ -0,0 +1,1360 @@ +use crate::lib::*; + +use crate::ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer}; + +#[cfg(any(feature = "std", feature = "alloc"))] +use self::content::{ + Content, ContentSerializer, SerializeStructVariantAsMapValue, SerializeTupleVariantAsMapValue, +}; + +/// Used to check that serde(getter) attributes return the expected type. +/// Not public API. +pub fn constrain(t: &T) -> &T { + t +} + +/// Not public API. +pub fn serialize_tagged_newtype( + serializer: S, + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + value: &T, +) -> Result +where + S: Serializer, + T: Serialize, +{ + value.serialize(TaggedSerializer { + type_ident, + variant_ident, + tag, + variant_name, + delegate: serializer, + }) +} + +struct TaggedSerializer { + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + delegate: S, +} + +enum Unsupported { + Boolean, + Integer, + Float, + Char, + String, + ByteArray, + Optional, + Sequence, + Tuple, + TupleStruct, + Enum, +} + +impl Display for Unsupported { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match *self { + Unsupported::Boolean => formatter.write_str("a boolean"), + Unsupported::Integer => formatter.write_str("an integer"), + Unsupported::Float => formatter.write_str("a float"), + Unsupported::Char => formatter.write_str("a char"), + Unsupported::String => formatter.write_str("a string"), + Unsupported::ByteArray => formatter.write_str("a byte array"), + Unsupported::Optional => formatter.write_str("an optional"), + Unsupported::Sequence => formatter.write_str("a sequence"), + Unsupported::Tuple => formatter.write_str("a tuple"), + Unsupported::TupleStruct => formatter.write_str("a tuple struct"), + Unsupported::Enum => formatter.write_str("an enum"), + } + } +} + +impl TaggedSerializer +where + S: Serializer, +{ + fn bad_type(self, what: Unsupported) -> S::Error { + ser::Error::custom(format_args!( + "cannot serialize tagged newtype variant {}::{} containing {}", + self.type_ident, self.variant_ident, what + )) + } +} + +impl Serializer for TaggedSerializer +where + S: Serializer, +{ + type Ok = S::Ok; + type Error = S::Error; + + type SerializeSeq = Impossible; + type SerializeTuple = Impossible; + type SerializeTupleStruct = Impossible; + type SerializeMap = S::SerializeMap; + type SerializeStruct = S::SerializeStruct; + + #[cfg(not(any(feature = "std", feature = "alloc")))] + type SerializeTupleVariant = Impossible; + #[cfg(any(feature = "std", feature = "alloc"))] + type SerializeTupleVariant = SerializeTupleVariantAsMapValue; + + #[cfg(not(any(feature = "std", feature = "alloc")))] + type SerializeStructVariant = Impossible; + #[cfg(any(feature = "std", feature = "alloc"))] + type SerializeStructVariant = SerializeStructVariantAsMapValue; + + fn serialize_bool(self, _: bool) -> Result { + Err(self.bad_type(Unsupported::Boolean)) + } + + fn serialize_i8(self, _: i8) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i16(self, _: i16) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i32(self, _: i32) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i64(self, _: i64) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u8(self, _: u8) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u16(self, _: u16) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u32(self, _: u32) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u64(self, _: u64) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_f32(self, _: f32) -> Result { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_f64(self, _: f64) -> Result { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_char(self, _: char) -> Result { + Err(self.bad_type(Unsupported::Char)) + } + + fn serialize_str(self, _: &str) -> Result { + Err(self.bad_type(Unsupported::String)) + } + + fn serialize_bytes(self, _: &[u8]) -> Result { + Err(self.bad_type(Unsupported::ByteArray)) + } + + fn serialize_none(self) -> Result { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_some(self, _: &T) -> Result + where + T: ?Sized + Serialize, + { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_unit(self) -> Result { + let mut map = tri!(self.delegate.serialize_map(Some(1))); + tri!(map.serialize_entry(self.tag, self.variant_name)); + map.end() + } + + fn serialize_unit_struct(self, _: &'static str) -> Result { + let mut map = tri!(self.delegate.serialize_map(Some(1))); + tri!(map.serialize_entry(self.tag, self.variant_name)); + map.end() + } + + fn serialize_unit_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + ) -> Result { + let mut map = tri!(self.delegate.serialize_map(Some(2))); + tri!(map.serialize_entry(self.tag, self.variant_name)); + tri!(map.serialize_entry(inner_variant, &())); + map.end() + } + + fn serialize_newtype_struct( + self, + _: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + inner_value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + let mut map = tri!(self.delegate.serialize_map(Some(2))); + tri!(map.serialize_entry(self.tag, self.variant_name)); + tri!(map.serialize_entry(inner_variant, inner_value)); + map.end() + } + + fn serialize_seq(self, _: Option) -> Result { + Err(self.bad_type(Unsupported::Sequence)) + } + + fn serialize_tuple(self, _: usize) -> Result { + Err(self.bad_type(Unsupported::Tuple)) + } + + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result { + Err(self.bad_type(Unsupported::TupleStruct)) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + // Lack of push-based serialization means we need to buffer the content + // of the tuple variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "alloc"))] + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + len: usize, + ) -> Result { + let mut map = tri!(self.delegate.serialize_map(Some(2))); + tri!(map.serialize_entry(self.tag, self.variant_name)); + tri!(map.serialize_key(inner_variant)); + Ok(SerializeTupleVariantAsMapValue::new( + map, + inner_variant, + len, + )) + } + + fn serialize_map(self, len: Option) -> Result { + let mut map = tri!(self.delegate.serialize_map(len.map(|len| len + 1))); + tri!(map.serialize_entry(self.tag, self.variant_name)); + Ok(map) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + let mut state = tri!(self.delegate.serialize_struct(name, len + 1)); + tri!(state.serialize_field(self.tag, self.variant_name)); + Ok(state) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + // Lack of push-based serialization means we need to buffer the content + // of the struct variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "alloc"))] + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + len: usize, + ) -> Result { + let mut map = tri!(self.delegate.serialize_map(Some(2))); + tri!(map.serialize_entry(self.tag, self.variant_name)); + tri!(map.serialize_key(inner_variant)); + Ok(SerializeStructVariantAsMapValue::new( + map, + inner_variant, + len, + )) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn collect_str(self, _: &T) -> Result + where + T: ?Sized + Display, + { + Err(self.bad_type(Unsupported::String)) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +mod content { + use crate::lib::*; + + use crate::ser::{self, Serialize, Serializer}; + + pub struct SerializeTupleVariantAsMapValue { + map: M, + name: &'static str, + fields: Vec, + } + + impl SerializeTupleVariantAsMapValue { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeTupleVariantAsMapValue { + map, + name, + fields: Vec::with_capacity(len), + } + } + } + + impl ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue + where + M: ser::SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), M::Error> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push(value); + Ok(()) + } + + fn end(mut self) -> Result { + tri!(self + .map + .serialize_value(&Content::TupleStruct(self.name, self.fields))); + self.map.end() + } + } + + pub struct SerializeStructVariantAsMapValue { + map: M, + name: &'static str, + fields: Vec<(&'static str, Content)>, + } + + impl SerializeStructVariantAsMapValue { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeStructVariantAsMapValue { + map, + name, + fields: Vec::with_capacity(len), + } + } + } + + impl ser::SerializeStructVariant for SerializeStructVariantAsMapValue + where + M: ser::SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), M::Error> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(mut self) -> Result { + tri!(self + .map + .serialize_value(&Content::Struct(self.name, self.fields))); + self.map.end() + } + } + + pub enum Content { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Bytes(Vec), + + None, + Some(Box), + + Unit, + UnitStruct(&'static str), + UnitVariant(&'static str, u32, &'static str), + NewtypeStruct(&'static str, Box), + NewtypeVariant(&'static str, u32, &'static str, Box), + + Seq(Vec), + Tuple(Vec), + TupleStruct(&'static str, Vec), + TupleVariant(&'static str, u32, &'static str, Vec), + Map(Vec<(Content, Content)>), + Struct(&'static str, Vec<(&'static str, Content)>), + StructVariant( + &'static str, + u32, + &'static str, + Vec<(&'static str, Content)>, + ), + } + + impl Serialize for Content { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Content::Bool(b) => serializer.serialize_bool(b), + Content::U8(u) => serializer.serialize_u8(u), + Content::U16(u) => serializer.serialize_u16(u), + Content::U32(u) => serializer.serialize_u32(u), + Content::U64(u) => serializer.serialize_u64(u), + Content::I8(i) => serializer.serialize_i8(i), + Content::I16(i) => serializer.serialize_i16(i), + Content::I32(i) => serializer.serialize_i32(i), + Content::I64(i) => serializer.serialize_i64(i), + Content::F32(f) => serializer.serialize_f32(f), + Content::F64(f) => serializer.serialize_f64(f), + Content::Char(c) => serializer.serialize_char(c), + Content::String(ref s) => serializer.serialize_str(s), + Content::Bytes(ref b) => serializer.serialize_bytes(b), + Content::None => serializer.serialize_none(), + Content::Some(ref c) => serializer.serialize_some(&**c), + Content::Unit => serializer.serialize_unit(), + Content::UnitStruct(n) => serializer.serialize_unit_struct(n), + Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v), + Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c), + Content::NewtypeVariant(n, i, v, ref c) => { + serializer.serialize_newtype_variant(n, i, v, &**c) + } + Content::Seq(ref elements) => elements.serialize(serializer), + Content::Tuple(ref elements) => { + use crate::ser::SerializeTuple; + let mut tuple = tri!(serializer.serialize_tuple(elements.len())); + for e in elements { + tri!(tuple.serialize_element(e)); + } + tuple.end() + } + Content::TupleStruct(n, ref fields) => { + use crate::ser::SerializeTupleStruct; + let mut ts = tri!(serializer.serialize_tuple_struct(n, fields.len())); + for f in fields { + tri!(ts.serialize_field(f)); + } + ts.end() + } + Content::TupleVariant(n, i, v, ref fields) => { + use crate::ser::SerializeTupleVariant; + let mut tv = tri!(serializer.serialize_tuple_variant(n, i, v, fields.len())); + for f in fields { + tri!(tv.serialize_field(f)); + } + tv.end() + } + Content::Map(ref entries) => { + use crate::ser::SerializeMap; + let mut map = tri!(serializer.serialize_map(Some(entries.len()))); + for (k, v) in entries { + tri!(map.serialize_entry(k, v)); + } + map.end() + } + Content::Struct(n, ref fields) => { + use crate::ser::SerializeStruct; + let mut s = tri!(serializer.serialize_struct(n, fields.len())); + for &(k, ref v) in fields { + tri!(s.serialize_field(k, v)); + } + s.end() + } + Content::StructVariant(n, i, v, ref fields) => { + use crate::ser::SerializeStructVariant; + let mut sv = tri!(serializer.serialize_struct_variant(n, i, v, fields.len())); + for &(k, ref v) in fields { + tri!(sv.serialize_field(k, v)); + } + sv.end() + } + } + } + } + + pub struct ContentSerializer { + error: PhantomData, + } + + impl ContentSerializer { + pub fn new() -> Self { + ContentSerializer { error: PhantomData } + } + } + + impl Serializer for ContentSerializer + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + type SerializeSeq = SerializeSeq; + type SerializeTuple = SerializeTuple; + type SerializeTupleStruct = SerializeTupleStruct; + type SerializeTupleVariant = SerializeTupleVariant; + type SerializeMap = SerializeMap; + type SerializeStruct = SerializeStruct; + type SerializeStructVariant = SerializeStructVariant; + + fn serialize_bool(self, v: bool) -> Result { + Ok(Content::Bool(v)) + } + + fn serialize_i8(self, v: i8) -> Result { + Ok(Content::I8(v)) + } + + fn serialize_i16(self, v: i16) -> Result { + Ok(Content::I16(v)) + } + + fn serialize_i32(self, v: i32) -> Result { + Ok(Content::I32(v)) + } + + fn serialize_i64(self, v: i64) -> Result { + Ok(Content::I64(v)) + } + + fn serialize_u8(self, v: u8) -> Result { + Ok(Content::U8(v)) + } + + fn serialize_u16(self, v: u16) -> Result { + Ok(Content::U16(v)) + } + + fn serialize_u32(self, v: u32) -> Result { + Ok(Content::U32(v)) + } + + fn serialize_u64(self, v: u64) -> Result { + Ok(Content::U64(v)) + } + + fn serialize_f32(self, v: f32) -> Result { + Ok(Content::F32(v)) + } + + fn serialize_f64(self, v: f64) -> Result { + Ok(Content::F64(v)) + } + + fn serialize_char(self, v: char) -> Result { + Ok(Content::Char(v)) + } + + fn serialize_str(self, value: &str) -> Result { + Ok(Content::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result { + Ok(Content::Bytes(value.to_owned())) + } + + fn serialize_none(self) -> Result { + Ok(Content::None) + } + + fn serialize_some(self, value: &T) -> Result + where + T: ?Sized + Serialize, + { + Ok(Content::Some(Box::new(tri!(value.serialize(self))))) + } + + fn serialize_unit(self) -> Result { + Ok(Content::Unit) + } + + fn serialize_unit_struct(self, name: &'static str) -> Result { + Ok(Content::UnitStruct(name)) + } + + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result { + Ok(Content::UnitVariant(name, variant_index, variant)) + } + + fn serialize_newtype_struct(self, name: &'static str, value: &T) -> Result + where + T: ?Sized + Serialize, + { + Ok(Content::NewtypeStruct( + name, + Box::new(tri!(value.serialize(self))), + )) + } + + fn serialize_newtype_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + Ok(Content::NewtypeVariant( + name, + variant_index, + variant, + Box::new(tri!(value.serialize(self))), + )) + } + + fn serialize_seq(self, len: Option) -> Result { + Ok(SerializeSeq { + elements: Vec::with_capacity(len.unwrap_or(0)), + error: PhantomData, + }) + } + + fn serialize_tuple(self, len: usize) -> Result { + Ok(SerializeTuple { + elements: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(SerializeTupleStruct { + name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + Ok(SerializeTupleVariant { + name, + variant_index, + variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_map(self, len: Option) -> Result { + Ok(SerializeMap { + entries: Vec::with_capacity(len.unwrap_or(0)), + key: None, + error: PhantomData, + }) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(SerializeStruct { + name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_struct_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + Ok(SerializeStructVariant { + name, + variant_index, + variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + } + + pub struct SerializeSeq { + elements: Vec, + error: PhantomData, + } + + impl ser::SerializeSeq for SerializeSeq + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_element(&mut self, value: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::Seq(self.elements)) + } + } + + pub struct SerializeTuple { + elements: Vec, + error: PhantomData, + } + + impl ser::SerializeTuple for SerializeTuple + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_element(&mut self, value: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::Tuple(self.elements)) + } + } + + pub struct SerializeTupleStruct { + name: &'static str, + fields: Vec, + error: PhantomData, + } + + impl ser::SerializeTupleStruct for SerializeTupleStruct + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, value: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::TupleStruct(self.name, self.fields)) + } + } + + pub struct SerializeTupleVariant { + name: &'static str, + variant_index: u32, + variant: &'static str, + fields: Vec, + error: PhantomData, + } + + impl ser::SerializeTupleVariant for SerializeTupleVariant + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, value: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::TupleVariant( + self.name, + self.variant_index, + self.variant, + self.fields, + )) + } + } + + pub struct SerializeMap { + entries: Vec<(Content, Content)>, + key: Option, + error: PhantomData, + } + + impl ser::SerializeMap for SerializeMap + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_key(&mut self, key: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let key = tri!(key.serialize(ContentSerializer::::new())); + self.key = Some(key); + Ok(()) + } + + fn serialize_value(&mut self, value: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let key = self + .key + .take() + .expect("serialize_value called before serialize_key"); + let value = tri!(value.serialize(ContentSerializer::::new())); + self.entries.push((key, value)); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::Map(self.entries)) + } + + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), E> + where + K: ?Sized + Serialize, + V: ?Sized + Serialize, + { + let key = tri!(key.serialize(ContentSerializer::::new())); + let value = tri!(value.serialize(ContentSerializer::::new())); + self.entries.push((key, value)); + Ok(()) + } + } + + pub struct SerializeStruct { + name: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData, + } + + impl ser::SerializeStruct for SerializeStruct + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::Struct(self.name, self.fields)) + } + } + + pub struct SerializeStructVariant { + name: &'static str, + variant_index: u32, + variant: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData, + } + + impl ser::SerializeStructVariant for SerializeStructVariant + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), E> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::StructVariant( + self.name, + self.variant_index, + self.variant, + self.fields, + )) + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializer<'a, M: 'a>(pub &'a mut M); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> FlatMapSerializer<'a, M> +where + M: SerializeMap + 'a, +{ + fn bad_type(what: Unsupported) -> M::Error { + ser::Error::custom(format_args!( + "can only flatten structs and maps (got {})", + what + )) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> Serializer for FlatMapSerializer<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + type SerializeSeq = Impossible; + type SerializeTuple = Impossible; + type SerializeTupleStruct = Impossible; + type SerializeMap = FlatMapSerializeMap<'a, M>; + type SerializeStruct = FlatMapSerializeStruct<'a, M>; + type SerializeTupleVariant = FlatMapSerializeTupleVariantAsMapValue<'a, M>; + type SerializeStructVariant = FlatMapSerializeStructVariantAsMapValue<'a, M>; + + fn serialize_bool(self, _: bool) -> Result { + Err(Self::bad_type(Unsupported::Boolean)) + } + + fn serialize_i8(self, _: i8) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_i16(self, _: i16) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_i32(self, _: i32) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_i64(self, _: i64) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_u8(self, _: u8) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_u16(self, _: u16) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_u32(self, _: u32) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_u64(self, _: u64) -> Result { + Err(Self::bad_type(Unsupported::Integer)) + } + + fn serialize_f32(self, _: f32) -> Result { + Err(Self::bad_type(Unsupported::Float)) + } + + fn serialize_f64(self, _: f64) -> Result { + Err(Self::bad_type(Unsupported::Float)) + } + + fn serialize_char(self, _: char) -> Result { + Err(Self::bad_type(Unsupported::Char)) + } + + fn serialize_str(self, _: &str) -> Result { + Err(Self::bad_type(Unsupported::String)) + } + + fn serialize_bytes(self, _: &[u8]) -> Result { + Err(Self::bad_type(Unsupported::ByteArray)) + } + + fn serialize_none(self) -> Result { + Ok(()) + } + + fn serialize_some(self, value: &T) -> Result + where + T: ?Sized + Serialize, + { + value.serialize(self) + } + + fn serialize_unit(self) -> Result { + Ok(()) + } + + fn serialize_unit_struct(self, _: &'static str) -> Result { + Ok(()) + } + + fn serialize_unit_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + ) -> Result { + Err(Self::bad_type(Unsupported::Enum)) + } + + fn serialize_newtype_struct( + self, + _: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + self.0.serialize_entry(variant, value) + } + + fn serialize_seq(self, _: Option) -> Result { + Err(Self::bad_type(Unsupported::Sequence)) + } + + fn serialize_tuple(self, _: usize) -> Result { + Err(Self::bad_type(Unsupported::Tuple)) + } + + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result { + Err(Self::bad_type(Unsupported::TupleStruct)) + } + + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + variant: &'static str, + _: usize, + ) -> Result { + tri!(self.0.serialize_key(variant)); + Ok(FlatMapSerializeTupleVariantAsMapValue::new(self.0)) + } + + fn serialize_map(self, _: Option) -> Result { + Ok(FlatMapSerializeMap(self.0)) + } + + fn serialize_struct( + self, + _: &'static str, + _: usize, + ) -> Result { + Ok(FlatMapSerializeStruct(self.0)) + } + + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + _: usize, + ) -> Result { + tri!(self.0.serialize_key(inner_variant)); + Ok(FlatMapSerializeStructVariantAsMapValue::new( + self.0, + inner_variant, + )) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializeMap<'a, M: 'a>(&'a mut M); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> ser::SerializeMap for FlatMapSerializeMap<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + self.0.serialize_key(key) + } + + fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + self.0.serialize_value(value) + } + + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), Self::Error> + where + K: ?Sized + Serialize, + V: ?Sized + Serialize, + { + self.0.serialize_entry(key, value) + } + + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializeStruct<'a, M: 'a>(&'a mut M); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> ser::SerializeStruct for FlatMapSerializeStruct<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + self.0.serialize_entry(key, value) + } + + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializeTupleVariantAsMapValue<'a, M: 'a> { + map: &'a mut M, + fields: Vec, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> FlatMapSerializeTupleVariantAsMapValue<'a, M> +where + M: SerializeMap + 'a, +{ + fn new(map: &'a mut M) -> Self { + FlatMapSerializeTupleVariantAsMapValue { + map, + fields: Vec::new(), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> ser::SerializeTupleVariant for FlatMapSerializeTupleVariantAsMapValue<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result<(), Self::Error> { + tri!(self.map.serialize_value(&Content::Seq(self.fields))); + Ok(()) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializeStructVariantAsMapValue<'a, M: 'a> { + map: &'a mut M, + name: &'static str, + fields: Vec<(&'static str, Content)>, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> FlatMapSerializeStructVariantAsMapValue<'a, M> +where + M: SerializeMap + 'a, +{ + fn new(map: &'a mut M, name: &'static str) -> FlatMapSerializeStructVariantAsMapValue<'a, M> { + FlatMapSerializeStructVariantAsMapValue { + map, + name, + fields: Vec::new(), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> ser::SerializeStructVariant for FlatMapSerializeStructVariantAsMapValue<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + let value = tri!(value.serialize(ContentSerializer::::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<(), Self::Error> { + tri!(self + .map + .serialize_value(&Content::Struct(self.name, self.fields))); + Ok(()) + } +} + +pub struct AdjacentlyTaggedEnumVariant { + pub enum_name: &'static str, + pub variant_index: u32, + pub variant_name: &'static str, +} + +impl Serialize for AdjacentlyTaggedEnumVariant { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant(self.enum_name, self.variant_index, self.variant_name) + } +} + +// Error when Serialize for a non_exhaustive remote enum encounters a variant +// that is not recognized. +pub struct CannotSerializeVariant(pub T); + +impl Display for CannotSerializeVariant +where + T: Debug, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "enum variant cannot be serialized: {:?}", self.0) + } +} diff --git a/bitbox02-bt/vendor/serde/src/ser/fmt.rs b/bitbox02-bt/vendor/serde/src/ser/fmt.rs new file mode 100644 index 0000000..04684ad --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/ser/fmt.rs @@ -0,0 +1,170 @@ +use crate::lib::*; +use crate::ser::{Error, Impossible, Serialize, Serializer}; + +impl Error for fmt::Error { + fn custom(_msg: T) -> Self { + fmt::Error + } +} + +macro_rules! fmt_primitives { + ($($f:ident: $t:ty,)*) => { + $( + fn $f(self, v: $t) -> fmt::Result { + Display::fmt(&v, self) + } + )* + }; +} + +/// ```edition2021 +/// use serde::ser::Serialize; +/// use serde_derive::Serialize; +/// use std::fmt::{self, Display}; +/// +/// #[derive(Serialize)] +/// #[serde(rename_all = "kebab-case")] +/// pub enum MessageType { +/// StartRequest, +/// EndRequest, +/// } +/// +/// impl Display for MessageType { +/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +/// self.serialize(f) +/// } +/// } +/// ``` +impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> { + type Ok = (); + type Error = fmt::Error; + type SerializeSeq = Impossible<(), fmt::Error>; + type SerializeTuple = Impossible<(), fmt::Error>; + type SerializeTupleStruct = Impossible<(), fmt::Error>; + type SerializeTupleVariant = Impossible<(), fmt::Error>; + type SerializeMap = Impossible<(), fmt::Error>; + type SerializeStruct = Impossible<(), fmt::Error>; + type SerializeStructVariant = Impossible<(), fmt::Error>; + + fmt_primitives! { + serialize_bool: bool, + serialize_i8: i8, + serialize_i16: i16, + serialize_i32: i32, + serialize_i64: i64, + serialize_i128: i128, + serialize_u8: u8, + serialize_u16: u16, + serialize_u32: u32, + serialize_u64: u64, + serialize_u128: u128, + serialize_f32: f32, + serialize_f64: f64, + serialize_char: char, + serialize_str: &str, + serialize_unit_struct: &'static str, + } + + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> fmt::Result { + Display::fmt(variant, self) + } + + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> fmt::Result + where + T: ?Sized + Serialize, + { + Serialize::serialize(value, self) + } + + fn serialize_bytes(self, _v: &[u8]) -> fmt::Result { + Err(fmt::Error) + } + + fn serialize_none(self) -> fmt::Result { + Err(fmt::Error) + } + + fn serialize_some(self, _value: &T) -> fmt::Result + where + T: ?Sized + Serialize, + { + Err(fmt::Error) + } + + fn serialize_unit(self) -> fmt::Result { + Err(fmt::Error) + } + + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> fmt::Result + where + T: ?Sized + Serialize, + { + Err(fmt::Error) + } + + fn serialize_seq(self, _len: Option) -> Result { + Err(fmt::Error) + } + + fn serialize_tuple(self, _len: usize) -> Result { + Err(fmt::Error) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn serialize_map(self, _len: Option) -> Result { + Err(fmt::Error) + } + + fn serialize_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + Err(fmt::Error) + } + + fn collect_str(self, value: &T) -> fmt::Result + where + T: ?Sized + Display, + { + Display::fmt(value, self) + } +} diff --git a/bitbox02-bt/vendor/serde/src/ser/impls.rs b/bitbox02-bt/vendor/serde/src/ser/impls.rs new file mode 100644 index 0000000..fb574ea --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/ser/impls.rs @@ -0,0 +1,1096 @@ +use crate::lib::*; + +use crate::ser::{Error, Serialize, SerializeTuple, Serializer}; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! primitive_impl { + ($ty:ident, $method:ident $($cast:tt)*) => { + impl Serialize for $ty { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.$method(*self $($cast)*) + } + } + } +} + +primitive_impl!(bool, serialize_bool); +primitive_impl!(isize, serialize_i64 as i64); +primitive_impl!(i8, serialize_i8); +primitive_impl!(i16, serialize_i16); +primitive_impl!(i32, serialize_i32); +primitive_impl!(i64, serialize_i64); +primitive_impl!(i128, serialize_i128); +primitive_impl!(usize, serialize_u64 as u64); +primitive_impl!(u8, serialize_u8); +primitive_impl!(u16, serialize_u16); +primitive_impl!(u32, serialize_u32); +primitive_impl!(u64, serialize_u64); +primitive_impl!(u128, serialize_u128); +primitive_impl!(f32, serialize_f32); +primitive_impl!(f64, serialize_f64); +primitive_impl!(char, serialize_char); + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for str { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl Serialize for String { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(self) + } +} + +impl<'a> Serialize for fmt::Arguments<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_str(self) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", not(no_core_cstr)))] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for CStr { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +impl Serialize for CString { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Option +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Some(ref value) => serializer.serialize_some(value), + None => serializer.serialize_none(), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for PhantomData +where + T: ?Sized, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_struct("PhantomData") + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Does not require T: Serialize. +impl Serialize for [T; 0] { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + tri!(serializer.serialize_tuple(0)).end() + } +} + +macro_rules! array_impls { + ($($len:tt)+) => { + $( + impl Serialize for [T; $len] + where + T: Serialize, + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = tri!(serializer.serialize_tuple($len)); + for e in self { + tri!(seq.serialize_element(e)); + } + seq.end() + } + } + )+ + } +} + +array_impls! { + 01 02 03 04 05 06 07 08 09 10 + 11 12 13 14 15 16 17 18 19 20 + 21 22 23 24 25 26 27 28 29 30 + 31 32 +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for [T] +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_seq(self) + } +} + +#[cfg(not(no_relaxed_trait_bounds))] +macro_rules! seq_impl { + ( + $(#[$attr:meta])* + $ty:ident + ) => { + $(#[$attr])* + impl Serialize for $ty + where + T: Serialize, + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_seq(self) + } + } + } +} + +#[cfg(no_relaxed_trait_bounds)] +macro_rules! seq_impl { + ( + $(#[$attr:meta])* + $ty:ident + ) => { + $(#[$attr])* + impl Serialize for $ty + where + T: Serialize $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound,)* + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_seq(self) + } + } + } +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BinaryHeap +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeSet +} + +seq_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashSet +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + LinkedList +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + Vec +} + +seq_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + VecDeque +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Range +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("Range", 2)); + tri!(state.serialize_field("start", &self.start)); + tri!(state.serialize_field("end", &self.end)); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for RangeFrom +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("RangeFrom", 1)); + tri!(state.serialize_field("start", &self.start)); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for RangeInclusive +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("RangeInclusive", 2)); + tri!(state.serialize_field("start", &self.start())); + tri!(state.serialize_field("end", &self.end())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for RangeTo +where + Idx: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("RangeTo", 1)); + tri!(state.serialize_field("end", &self.end)); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Bound +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Bound::Unbounded => serializer.serialize_unit_variant("Bound", 0, "Unbounded"), + Bound::Included(ref value) => { + serializer.serialize_newtype_variant("Bound", 1, "Included", value) + } + Bound::Excluded(ref value) => { + serializer.serialize_newtype_variant("Bound", 2, "Excluded", value) + } + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for () { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit() + } +} + +#[cfg(feature = "unstable")] +#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] +impl Serialize for ! { + fn serialize(&self, _serializer: S) -> Result + where + S: Serializer, + { + *self + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($($len:expr => ($($n:tt $name:ident)+))+) => { + $( + #[cfg_attr(docsrs, doc(hidden))] + impl<$($name),+> Serialize for ($($name,)+) + where + $($name: Serialize,)+ + { + tuple_impl_body!($len => ($($n)+)); + } + )+ + }; +} + +macro_rules! tuple_impl_body { + ($len:expr => ($($n:tt)+)) => { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut tuple = tri!(serializer.serialize_tuple($len)); + $( + tri!(tuple.serialize_element(&self.$n)); + )+ + tuple.end() + } + }; +} + +#[cfg_attr(docsrs, doc(fake_variadic))] +#[cfg_attr( + docsrs, + doc = "This trait is implemented for tuples up to 16 items long." +)] +impl Serialize for (T,) +where + T: Serialize, +{ + tuple_impl_body!(1 => (0)); +} + +tuple_impls! { + 2 => (0 T0 1 T1) + 3 => (0 T0 1 T1 2 T2) + 4 => (0 T0 1 T1 2 T2 3 T3) + 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) + 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) + 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) + 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) + 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) + 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) + 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) + 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) + 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) + 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) + 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) + 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(not(no_relaxed_trait_bounds))] +macro_rules! map_impl { + ( + $(#[$attr:meta])* + $ty:ident + ) => { + $(#[$attr])* + impl Serialize for $ty + where + K: Serialize, + V: Serialize, + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_map(self) + } + } + } +} + +#[cfg(no_relaxed_trait_bounds)] +macro_rules! map_impl { + ( + $(#[$attr:meta])* + $ty:ident + ) => { + $(#[$attr])* + impl Serialize for $ty + where + K: Serialize $(+ $kbound1 $(+ $kbound2)*)*, + V: Serialize, + $($typaram: $bound,)* + { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_map(self) + } + } + } +} + +map_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + BTreeMap +} + +map_impl! { + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + HashMap +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! deref_impl { + ( + $(#[$attr:meta])* + <$($desc:tt)+ + ) => { + $(#[$attr])* + impl <$($desc)+ { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + (**self).serialize(serializer) + } + } + }; +} + +deref_impl! { + <'a, T> Serialize for &'a T where T: ?Sized + Serialize +} + +deref_impl! { + <'a, T> Serialize for &'a mut T where T: ?Sized + Serialize +} + +deref_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + Serialize for Box where T: ?Sized + Serialize +} + +deref_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Serializing a data structure containing `Rc` will serialize a copy of + /// the contents of the `Rc` each time the `Rc` is referenced within the + /// data structure. Serialization will not attempt to deduplicate these + /// repeated data. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Serialize for Rc where T: ?Sized + Serialize +} + +deref_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Serializing a data structure containing `Arc` will serialize a copy of + /// the contents of the `Arc` each time the `Arc` is referenced within the + /// data structure. Serialization will not attempt to deduplicate these + /// repeated data. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))] + Serialize for Arc where T: ?Sized + Serialize +} + +deref_impl! { + #[cfg(any(feature = "std", feature = "alloc"))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] + <'a, T> Serialize for Cow<'a, T> where T: ?Sized + Serialize + ToOwned +} + +//////////////////////////////////////////////////////////////////////////////// + +/// This impl requires the [`"rc"`] Cargo feature of Serde. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl Serialize for RcWeak +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.upgrade().serialize(serializer) + } +} + +/// This impl requires the [`"rc"`] Cargo feature of Serde. +/// +/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +#[cfg_attr( + docsrs, + doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))) +)] +impl Serialize for ArcWeak +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.upgrade().serialize(serializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! nonzero_integers { + ($($T:ident,)+) => { + $( + impl Serialize for num::$T { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.get().serialize(serializer) + } + } + )+ + } +} + +nonzero_integers! { + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + NonZeroU128, + NonZeroUsize, +} + +#[cfg(not(no_num_nonzero_signed))] +nonzero_integers! { + NonZeroI8, + NonZeroI16, + NonZeroI32, + NonZeroI64, + NonZeroI128, + NonZeroIsize, +} + +impl Serialize for Cell +where + T: Serialize + Copy, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.get().serialize(serializer) + } +} + +impl Serialize for RefCell +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.try_borrow() { + Ok(value) => value.serialize(serializer), + Err(_) => Err(S::Error::custom("already mutably borrowed")), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for Mutex +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.lock() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for RwLock +where + T: ?Sized + Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.read() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Result +where + T: Serialize, + E: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value), + Result::Err(ref value) => { + serializer.serialize_newtype_variant("Result", 1, "Err", value) + } + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Duration { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = tri!(serializer.serialize_struct("Duration", 2)); + tri!(state.serialize_field("secs", &self.as_secs())); + tri!(state.serialize_field("nanos", &self.subsec_nanos())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for SystemTime { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use super::SerializeStruct; + let duration_since_epoch = match self.duration_since(UNIX_EPOCH) { + Ok(duration_since_epoch) => duration_since_epoch, + Err(_) => return Err(S::Error::custom("SystemTime must be later than UNIX_EPOCH")), + }; + let mut state = tri!(serializer.serialize_struct("SystemTime", 2)); + tri!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs())); + tri!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Serialize a value that implements `Display` as a string, when that string is +/// statically known to never have more than a constant `MAX_LEN` bytes. +/// +/// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes. +#[cfg(any(feature = "std", not(no_core_net)))] +macro_rules! serialize_display_bounded_length { + ($value:expr, $max:expr, $serializer:expr) => {{ + let mut buffer = [0u8; $max]; + let mut writer = crate::format::Buf::new(&mut buffer); + write!(&mut writer, "{}", $value).unwrap(); + $serializer.serialize_str(writer.as_str()) + }}; +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::IpAddr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + match *self { + net::IpAddr::V4(ref a) => a.serialize(serializer), + net::IpAddr::V6(ref a) => a.serialize(serializer), + } + } else { + match *self { + net::IpAddr::V4(ref a) => { + serializer.serialize_newtype_variant("IpAddr", 0, "V4", a) + } + net::IpAddr::V6(ref a) => { + serializer.serialize_newtype_variant("IpAddr", 1, "V6", a) + } + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +const DEC_DIGITS_LUT: &[u8] = b"\ + 0001020304050607080910111213141516171819\ + 2021222324252627282930313233343536373839\ + 4041424344454647484950515253545556575859\ + 6061626364656667686970717273747576777879\ + 8081828384858687888990919293949596979899"; + +#[cfg(any(feature = "std", not(no_core_net)))] +#[inline] +fn format_u8(mut n: u8, out: &mut [u8]) -> usize { + if n >= 100 { + let d1 = ((n % 100) << 1) as usize; + n /= 100; + out[0] = b'0' + n; + out[1] = DEC_DIGITS_LUT[d1]; + out[2] = DEC_DIGITS_LUT[d1 + 1]; + 3 + } else if n >= 10 { + let d1 = (n << 1) as usize; + out[0] = DEC_DIGITS_LUT[d1]; + out[1] = DEC_DIGITS_LUT[d1 + 1]; + 2 + } else { + out[0] = b'0' + n; + 1 + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +#[test] +fn test_format_u8() { + let mut i = 0u8; + + loop { + let mut buf = [0u8; 3]; + let written = format_u8(i, &mut buf); + assert_eq!(i.to_string().as_bytes(), &buf[..written]); + + match i.checked_add(1) { + Some(next) => i = next, + None => break, + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::Ipv4Addr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 15; + debug_assert_eq!(MAX_LEN, "101.102.103.104".len()); + let mut buf = [b'.'; MAX_LEN]; + let mut written = format_u8(self.octets()[0], &mut buf); + for oct in &self.octets()[1..] { + // Skip over delimiters that we initialized buf with + written += format_u8(*oct, &mut buf[written + 1..]) + 1; + } + // Safety: We've only written ASCII bytes to the buffer, so it is valid UTF-8 + let buf = unsafe { str::from_utf8_unchecked(&buf[..written]) }; + serializer.serialize_str(buf) + } else { + self.octets().serialize(serializer) + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::Ipv6Addr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 39; + debug_assert_eq!(MAX_LEN, "1001:1002:1003:1004:1005:1006:1007:1008".len()); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + self.octets().serialize(serializer) + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::SocketAddr { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + match *self { + net::SocketAddr::V4(ref addr) => addr.serialize(serializer), + net::SocketAddr::V6(ref addr) => addr.serialize(serializer), + } + } else { + match *self { + net::SocketAddr::V4(ref addr) => { + serializer.serialize_newtype_variant("SocketAddr", 0, "V4", addr) + } + net::SocketAddr::V6(ref addr) => { + serializer.serialize_newtype_variant("SocketAddr", 1, "V6", addr) + } + } + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::SocketAddrV4 { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 21; + debug_assert_eq!(MAX_LEN, "101.102.103.104:65000".len()); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + (self.ip(), self.port()).serialize(serializer) + } + } +} + +#[cfg(any(feature = "std", not(no_core_net)))] +impl Serialize for net::SocketAddrV6 { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 58; + debug_assert_eq!( + MAX_LEN, + "[1001:1002:1003:1004:1005:1006:1007:1008%4294967295]:65000".len() + ); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + (self.ip(), self.port()).serialize(serializer) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for Path { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.to_str() { + Some(s) => s.serialize(serializer), + None => Err(Error::custom("path contains invalid UTF-8 characters")), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Serialize for PathBuf { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.as_path().serialize(serializer) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] +impl Serialize for OsStr { + #[cfg(unix)] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use std::os::unix::ffi::OsStrExt; + serializer.serialize_newtype_variant("OsString", 0, "Unix", self.as_bytes()) + } + + #[cfg(windows)] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + use std::os::windows::ffi::OsStrExt; + let val = self.encode_wide().collect::>(); + serializer.serialize_newtype_variant("OsString", 1, "Windows", &val) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))] +impl Serialize for OsString { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.as_os_str().serialize(serializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for Wrapping +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } +} + +#[cfg(not(no_core_num_saturating))] +impl Serialize for Saturating +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } +} + +impl Serialize for Reverse +where + T: Serialize, +{ + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(all(feature = "std", not(no_std_atomic)))] +macro_rules! atomic_impl { + ($($ty:ident $size:expr)*) => { + $( + #[cfg(any(no_target_has_atomic, target_has_atomic = $size))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "std", target_has_atomic = $size))))] + impl Serialize for $ty { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + // Matches the atomic ordering used in libcore for the Debug impl + self.load(Ordering::Relaxed).serialize(serializer) + } + } + )* + } +} + +#[cfg(all(feature = "std", not(no_std_atomic)))] +atomic_impl! { + AtomicBool "8" + AtomicI8 "8" + AtomicI16 "16" + AtomicI32 "32" + AtomicIsize "ptr" + AtomicU8 "8" + AtomicU16 "16" + AtomicU32 "32" + AtomicUsize "ptr" +} + +#[cfg(all(feature = "std", not(no_std_atomic64)))] +atomic_impl! { + AtomicI64 "64" + AtomicU64 "64" +} diff --git a/bitbox02-bt/vendor/serde/src/ser/impossible.rs b/bitbox02-bt/vendor/serde/src/ser/impossible.rs new file mode 100644 index 0000000..6432d57 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/ser/impossible.rs @@ -0,0 +1,216 @@ +//! This module contains `Impossible` serializer and its implementations. + +use crate::lib::*; + +use crate::ser::{ + self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, + SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, +}; + +/// Helper type for implementing a `Serializer` that does not support +/// serializing one of the compound types. +/// +/// This type cannot be instantiated, but implements every one of the traits +/// corresponding to the [`Serializer`] compound types: [`SerializeSeq`], +/// [`SerializeTuple`], [`SerializeTupleStruct`], [`SerializeTupleVariant`], +/// [`SerializeMap`], [`SerializeStruct`], and [`SerializeStructVariant`]. +/// +/// ```edition2021 +/// # use serde::ser::{Serializer, Impossible}; +/// # use serde::__private::doc::Error; +/// # +/// # struct MySerializer; +/// # +/// impl Serializer for MySerializer { +/// type Ok = (); +/// type Error = Error; +/// +/// type SerializeSeq = Impossible<(), Error>; +/// /* other associated types */ +/// +/// /// This data format does not support serializing sequences. +/// fn serialize_seq(self, +/// len: Option) +/// -> Result { +/// // Given Impossible cannot be instantiated, the only +/// // thing we can do here is to return an error. +/// # stringify! { +/// Err(...) +/// # }; +/// # unimplemented!() +/// } +/// +/// /* other Serializer methods */ +/// # serde::__serialize_unimplemented! { +/// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some +/// # unit unit_struct unit_variant newtype_struct newtype_variant +/// # tuple tuple_struct tuple_variant map struct struct_variant +/// # } +/// } +/// ``` +/// +/// [`Serializer`]: trait.Serializer.html +/// [`SerializeSeq`]: trait.SerializeSeq.html +/// [`SerializeTuple`]: trait.SerializeTuple.html +/// [`SerializeTupleStruct`]: trait.SerializeTupleStruct.html +/// [`SerializeTupleVariant`]: trait.SerializeTupleVariant.html +/// [`SerializeMap`]: trait.SerializeMap.html +/// [`SerializeStruct`]: trait.SerializeStruct.html +/// [`SerializeStructVariant`]: trait.SerializeStructVariant.html +pub struct Impossible { + void: Void, + ok: PhantomData, + error: PhantomData, +} + +enum Void {} + +impl SerializeSeq for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_element(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeTuple for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_element(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeTupleStruct for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeTupleVariant for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeMap for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_key(&mut self, key: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = key; + match self.void {} + } + + fn serialize_value(&mut self, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeStruct for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = key; + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} + +impl SerializeStructVariant for Impossible +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: ?Sized + Serialize, + { + let _ = key; + let _ = value; + match self.void {} + } + + fn end(self) -> Result { + match self.void {} + } +} diff --git a/bitbox02-bt/vendor/serde/src/ser/mod.rs b/bitbox02-bt/vendor/serde/src/ser/mod.rs new file mode 100644 index 0000000..fb0033e --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/ser/mod.rs @@ -0,0 +1,1954 @@ +//! Generic data structure serialization framework. +//! +//! The two most important traits in this module are [`Serialize`] and +//! [`Serializer`]. +//! +//! - **A type that implements `Serialize` is a data structure** that can be +//! serialized to any data format supported by Serde, and conversely +//! - **A type that implements `Serializer` is a data format** that can +//! serialize any data structure supported by Serde. +//! +//! # The Serialize trait +//! +//! Serde provides [`Serialize`] implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! serialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called [`serde_derive`] to +//! automatically generate [`Serialize`] implementations for structs and enums +//! in your program. See the [derive section of the manual] for how to use this. +//! +//! In rare cases it may be necessary to implement [`Serialize`] manually for +//! some type in your program. See the [Implementing `Serialize`] section of the +//! manual for more about this. +//! +//! Third-party crates may provide [`Serialize`] implementations for types that +//! they expose. For example the [`linked-hash-map`] crate provides a +//! [`LinkedHashMap`] type that is serializable by Serde because the crate +//! provides an implementation of [`Serialize`] for it. +//! +//! # The Serializer trait +//! +//! [`Serializer`] implementations are provided by third-party crates, for +//! example [`serde_json`], [`serde_yaml`] and [`postcard`]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data formats]. +//! +//! # Implementations of Serialize provided by Serde +//! +//! - **Primitive types**: +//! - bool +//! - i8, i16, i32, i64, i128, isize +//! - u8, u16, u32, u64, u128, usize +//! - f32, f64 +//! - char +//! - str +//! - &T and &mut T +//! - **Compound types**: +//! - \[T\] +//! - \[T; 0\] through \[T; 32\] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\ +//! - Result\ +//! - PhantomData\ +//! - **Wrapper types**: +//! - Box\ +//! - Cow\<'a, T\> +//! - Cell\ +//! - RefCell\ +//! - Mutex\ +//! - RwLock\ +//! - Rc\ *(if* features = \["rc"\] *is enabled)* +//! - Arc\ *(if* features = \["rc"\] *is enabled)* +//! - **Collection types**: +//! - BTreeMap\ +//! - BTreeSet\ +//! - BinaryHeap\ +//! - HashMap\ +//! - HashSet\ +//! - LinkedList\ +//! - VecDeque\ +//! - Vec\ +//! - **FFI types**: +//! - CStr +//! - CString +//! - OsStr +//! - OsString +//! - **Miscellaneous standard library types**: +//! - Duration +//! - SystemTime +//! - Path +//! - PathBuf +//! - Range\ +//! - RangeInclusive\ +//! - Bound\ +//! - num::NonZero* +//! - `!` *(unstable)* +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html +//! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +//! [`Serialize`]: ../trait.Serialize.html +//! [`Serializer`]: ../trait.Serializer.html +//! [`postcard`]: https://github.com/jamesmunns/postcard +//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +//! [`serde_derive`]: https://crates.io/crates/serde_derive +//! [`serde_json`]: https://github.com/serde-rs/json +//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml +//! [derive section of the manual]: https://serde.rs/derive.html +//! [data formats]: https://serde.rs/#data-formats + +use crate::lib::*; + +mod fmt; +mod impls; +mod impossible; + +pub use self::impossible::Impossible; + +#[cfg(all(not(feature = "std"), no_core_error))] +#[doc(no_inline)] +pub use crate::std_error::Error as StdError; +#[cfg(not(any(feature = "std", no_core_error)))] +#[doc(no_inline)] +pub use core::error::Error as StdError; +#[cfg(feature = "std")] +#[doc(no_inline)] +pub use std::error::Error as StdError; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! declare_error_trait { + (Error: Sized $(+ $($supertrait:ident)::+)*) => { + /// Trait used by `Serialize` implementations to generically construct + /// errors belonging to the `Serializer` against which they are + /// currently running. + /// + /// # Example implementation + /// + /// The [example data format] presented on the website shows an error + /// type appropriate for a basic JSON data format. + /// + /// [example data format]: https://serde.rs/data-format.html + pub trait Error: Sized $(+ $($supertrait)::+)* { + /// Used when a [`Serialize`] implementation encounters any error + /// while serializing a type. + /// + /// The message should not be capitalized and should not end with a + /// period. + /// + /// For example, a filesystem [`Path`] may refuse to serialize + /// itself if it contains invalid UTF-8 data. + /// + /// ```edition2021 + /// # struct Path; + /// # + /// # impl Path { + /// # fn to_str(&self) -> Option<&str> { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{self, Serialize, Serializer}; + /// + /// impl Serialize for Path { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match self.to_str() { + /// Some(s) => serializer.serialize_str(s), + /// None => Err(ser::Error::custom("path contains invalid UTF-8 characters")), + /// } + /// } + /// } + /// ``` + /// + /// [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html + /// [`Serialize`]: ../trait.Serialize.html + fn custom(msg: T) -> Self + where + T: Display; + } + } +} + +#[cfg(feature = "std")] +declare_error_trait!(Error: Sized + StdError); + +#[cfg(not(feature = "std"))] +declare_error_trait!(Error: Sized + Debug + Display); + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be serialized into any data format supported +/// by Serde. +/// +/// Serde provides `Serialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][crate::ser]. All of +/// these can be serialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called [`serde_derive`] to +/// automatically generate `Serialize` implementations for structs and enums in +/// your program. See the [derive section of the manual] for how to use this. +/// +/// In rare cases it may be necessary to implement `Serialize` manually for some +/// type in your program. See the [Implementing `Serialize`] section of the +/// manual for more about this. +/// +/// Third-party crates may provide `Serialize` implementations for types that +/// they expose. For example the [`linked-hash-map`] crate provides a +/// [`LinkedHashMap`] type that is serializable by Serde because the crate +/// provides an implementation of `Serialize` for it. +/// +/// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html +/// [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +/// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +/// [`serde_derive`]: https://crates.io/crates/serde_derive +/// [derive section of the manual]: https://serde.rs/derive.html +#[cfg_attr( + not(no_diagnostic_namespace), + diagnostic::on_unimplemented( + note = "for local types consider adding `#[derive(serde::Serialize)]` to your `{Self}` type", + note = "for types from other crates check whether the crate offers a `serde` feature flag", + ) +)] +pub trait Serialize { + /// Serialize this value into the given Serde serializer. + /// + /// See the [Implementing `Serialize`] section of the manual for more + /// information about how to implement this method. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeStruct, Serializer}; + /// + /// struct Person { + /// name: String, + /// age: u8, + /// phones: Vec, + /// } + /// + /// // This is what #[derive(Serialize)] would generate. + /// impl Serialize for Person { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut s = serializer.serialize_struct("Person", 3)?; + /// s.serialize_field("name", &self.name)?; + /// s.serialize_field("age", &self.age)?; + /// s.serialize_field("phones", &self.phones)?; + /// s.end() + /// } + /// } + /// ``` + /// + /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html + fn serialize(&self, serializer: S) -> Result + where + S: Serializer; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can serialize any data structure supported by Serde. +/// +/// The role of this trait is to define the serialization half of the [Serde +/// data model], which is a way to categorize every Rust data structure into one +/// of 29 possible types. Each method of the `Serializer` trait corresponds to +/// one of the types of the data model. +/// +/// Implementations of `Serialize` map themselves into this data model by +/// invoking exactly one of the `Serializer` methods. +/// +/// The types that make up the Serde data model are: +/// +/// - **14 primitive types** +/// - bool +/// - i8, i16, i32, i64, i128 +/// - u8, u16, u32, u64, u128 +/// - f32, f64 +/// - char +/// - **string** +/// - UTF-8 bytes with a length and no null terminator. +/// - When serializing, all strings are handled equally. When deserializing, +/// there are three flavors of strings: transient, owned, and borrowed. +/// - **byte array** - \[u8\] +/// - Similar to strings, during deserialization byte arrays can be +/// transient, owned, or borrowed. +/// - **option** +/// - Either none or some value. +/// - **unit** +/// - The type of `()` in Rust. It represents an anonymous value containing +/// no data. +/// - **unit_struct** +/// - For example `struct Unit` or `PhantomData`. It represents a named +/// value containing no data. +/// - **unit_variant** +/// - For example the `E::A` and `E::B` in `enum E { A, B }`. +/// - **newtype_struct** +/// - For example `struct Millimeters(u8)`. +/// - **newtype_variant** +/// - For example the `E::N` in `enum E { N(u8) }`. +/// - **seq** +/// - A variably sized heterogeneous sequence of values, for example +/// `Vec` or `HashSet`. When serializing, the length may or may not +/// be known before iterating through all the data. When deserializing, +/// the length is determined by looking at the serialized data. +/// - **tuple** +/// - A statically sized heterogeneous sequence of values for which the +/// length will be known at deserialization time without looking at the +/// serialized data, for example `(u8,)` or `(String, u64, Vec)` or +/// `[u64; 10]`. +/// - **tuple_struct** +/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. +/// - **tuple_variant** +/// - For example the `E::T` in `enum E { T(u8, u8) }`. +/// - **map** +/// - A heterogeneous key-value pairing, for example `BTreeMap`. +/// - **struct** +/// - A heterogeneous key-value pairing in which the keys are strings and +/// will be known at deserialization time without looking at the +/// serialized data, for example `struct S { r: u8, g: u8, b: u8 }`. +/// - **struct_variant** +/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. +/// +/// Many Serde serializers produce text or binary data as output, for example +/// JSON or Postcard. This is not a requirement of the `Serializer` trait, and +/// there are serializers that do not produce text or binary output. One example +/// is the `serde_json::value::Serializer` (distinct from the main `serde_json` +/// serializer) that produces a `serde_json::Value` data structure in memory as +/// output. +/// +/// [Serde data model]: https://serde.rs/data-model.html +/// +/// # Example implementation +/// +/// The [example data format] presented on the website contains example code for +/// a basic JSON `Serializer`. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait Serializer: Sized { + /// The output type produced by this `Serializer` during successful + /// serialization. Most serializers that produce text or binary output + /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer + /// contained within the `Serializer` instance. Serializers that build + /// in-memory data structures may be simplified by using `Ok` to propagate + /// the data structure around. + /// + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + type Ok; + + /// The error type when some error occurs during serialization. + type Error: Error; + + /// Type returned from [`serialize_seq`] for serializing the content of the + /// sequence. + /// + /// [`serialize_seq`]: #tymethod.serialize_seq + type SerializeSeq: SerializeSeq; + + /// Type returned from [`serialize_tuple`] for serializing the content of + /// the tuple. + /// + /// [`serialize_tuple`]: #tymethod.serialize_tuple + type SerializeTuple: SerializeTuple; + + /// Type returned from [`serialize_tuple_struct`] for serializing the + /// content of the tuple struct. + /// + /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct + type SerializeTupleStruct: SerializeTupleStruct; + + /// Type returned from [`serialize_tuple_variant`] for serializing the + /// content of the tuple variant. + /// + /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant + type SerializeTupleVariant: SerializeTupleVariant; + + /// Type returned from [`serialize_map`] for serializing the content of the + /// map. + /// + /// [`serialize_map`]: #tymethod.serialize_map + type SerializeMap: SerializeMap; + + /// Type returned from [`serialize_struct`] for serializing the content of + /// the struct. + /// + /// [`serialize_struct`]: #tymethod.serialize_struct + type SerializeStruct: SerializeStruct; + + /// Type returned from [`serialize_struct_variant`] for serializing the + /// content of the struct variant. + /// + /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant + type SerializeStructVariant: SerializeStructVariant; + + /// Serialize a `bool` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for bool { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_bool(*self) + /// } + /// } + /// ``` + fn serialize_bool(self, v: bool) -> Result; + + /// Serialize an `i8` value. + /// + /// If the format does not differentiate between `i8` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for i8 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i8(*self) + /// } + /// } + /// ``` + fn serialize_i8(self, v: i8) -> Result; + + /// Serialize an `i16` value. + /// + /// If the format does not differentiate between `i16` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for i16 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i16(*self) + /// } + /// } + /// ``` + fn serialize_i16(self, v: i16) -> Result; + + /// Serialize an `i32` value. + /// + /// If the format does not differentiate between `i32` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for i32 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i32(*self) + /// } + /// } + /// ``` + fn serialize_i32(self, v: i32) -> Result; + + /// Serialize an `i64` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for i64 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i64(*self) + /// } + /// } + /// ``` + fn serialize_i64(self, v: i64) -> Result; + + /// Serialize an `i128` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for i128 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_i128(*self) + /// } + /// } + /// ``` + /// + /// The default behavior unconditionally returns an error. + fn serialize_i128(self, v: i128) -> Result { + let _ = v; + Err(Error::custom("i128 is not supported")) + } + + /// Serialize a `u8` value. + /// + /// If the format does not differentiate between `u8` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for u8 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u8(*self) + /// } + /// } + /// ``` + fn serialize_u8(self, v: u8) -> Result; + + /// Serialize a `u16` value. + /// + /// If the format does not differentiate between `u16` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for u16 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u16(*self) + /// } + /// } + /// ``` + fn serialize_u16(self, v: u16) -> Result; + + /// Serialize a `u32` value. + /// + /// If the format does not differentiate between `u32` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for u32 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u32(*self) + /// } + /// } + /// ``` + fn serialize_u32(self, v: u32) -> Result; + + /// Serialize a `u64` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for u64 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u64(*self) + /// } + /// } + /// ``` + fn serialize_u64(self, v: u64) -> Result; + + /// Serialize a `u128` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for u128 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_u128(*self) + /// } + /// } + /// ``` + /// + /// The default behavior unconditionally returns an error. + fn serialize_u128(self, v: u128) -> Result { + let _ = v; + Err(Error::custom("u128 is not supported")) + } + + /// Serialize an `f32` value. + /// + /// If the format does not differentiate between `f32` and `f64`, a + /// reasonable implementation would be to cast the value to `f64` and + /// forward to `serialize_f64`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for f32 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_f32(*self) + /// } + /// } + /// ``` + fn serialize_f32(self, v: f32) -> Result; + + /// Serialize an `f64` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for f64 { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_f64(*self) + /// } + /// } + /// ``` + fn serialize_f64(self, v: f64) -> Result; + + /// Serialize a character. + /// + /// If the format does not support characters, it is reasonable to serialize + /// it as a single element `str` or a `u32`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for char { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_char(*self) + /// } + /// } + /// ``` + fn serialize_char(self, v: char) -> Result; + + /// Serialize a `&str`. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for str { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_str(self) + /// } + /// } + /// ``` + fn serialize_str(self, v: &str) -> Result; + + /// Serialize a chunk of raw byte data. + /// + /// Enables serializers to serialize byte slices more compactly or more + /// efficiently than other types of slices. If no efficient implementation + /// is available, a reasonable implementation would be to forward to + /// `serialize_seq`. If forwarded, the implementation looks usually just + /// like this: + /// + /// ```edition2021 + /// # use serde::ser::{Serializer, SerializeSeq}; + /// # use serde::__private::doc::Error; + /// # + /// # struct MySerializer; + /// # + /// # impl Serializer for MySerializer { + /// # type Ok = (); + /// # type Error = Error; + /// # + /// fn serialize_bytes(self, v: &[u8]) -> Result { + /// let mut seq = self.serialize_seq(Some(v.len()))?; + /// for b in v { + /// seq.serialize_element(b)?; + /// } + /// seq.end() + /// } + /// # + /// # serde::__serialize_unimplemented! { + /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some + /// # unit unit_struct unit_variant newtype_struct newtype_variant + /// # seq tuple tuple_struct tuple_variant map struct struct_variant + /// # } + /// # } + /// ``` + fn serialize_bytes(self, v: &[u8]) -> Result; + + /// Serialize a [`None`] value. + /// + /// ```edition2021 + /// # use serde::{Serialize, Serializer}; + /// # + /// # enum Option { + /// # Some(T), + /// # None, + /// # } + /// # + /// # use self::Option::{Some, None}; + /// # + /// impl Serialize for Option + /// where + /// T: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// Some(ref value) => serializer.serialize_some(value), + /// None => serializer.serialize_none(), + /// } + /// } + /// } + /// # + /// # fn main() {} + /// ``` + /// + /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None + fn serialize_none(self) -> Result; + + /// Serialize a [`Some(T)`] value. + /// + /// ```edition2021 + /// # use serde::{Serialize, Serializer}; + /// # + /// # enum Option { + /// # Some(T), + /// # None, + /// # } + /// # + /// # use self::Option::{Some, None}; + /// # + /// impl Serialize for Option + /// where + /// T: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// Some(ref value) => serializer.serialize_some(value), + /// None => serializer.serialize_none(), + /// } + /// } + /// } + /// # + /// # fn main() {} + /// ``` + /// + /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some + fn serialize_some(self, value: &T) -> Result + where + T: ?Sized + Serialize; + + /// Serialize a `()` value. + /// + /// ```edition2021 + /// # use serde::Serializer; + /// # + /// # serde::__private_serialize!(); + /// # + /// impl Serialize for () { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_unit() + /// } + /// } + /// ``` + fn serialize_unit(self) -> Result; + + /// Serialize a unit struct like `struct Unit` or `PhantomData`. + /// + /// A reasonable implementation would be to forward to `serialize_unit`. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// struct Nothing; + /// + /// impl Serialize for Nothing { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_unit_struct("Nothing") + /// } + /// } + /// ``` + fn serialize_unit_struct(self, name: &'static str) -> Result; + + /// Serialize a unit variant like `E::A` in `enum E { A, B }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// enum E { + /// A, + /// B, + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::A => serializer.serialize_unit_variant("E", 0, "A"), + /// E::B => serializer.serialize_unit_variant("E", 1, "B"), + /// } + /// } + /// } + /// ``` + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result; + + /// Serialize a newtype struct like `struct Millimeters(u8)`. + /// + /// Serializers are encouraged to treat newtype structs as insignificant + /// wrappers around the data they contain. A reasonable implementation would + /// be to forward to `value.serialize(self)`. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// struct Millimeters(u8); + /// + /// impl Serialize for Millimeters { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.serialize_newtype_struct("Millimeters", &self.0) + /// } + /// } + /// ``` + fn serialize_newtype_struct( + self, + name: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize; + + /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. The `value` is the data contained within this newtype variant. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// enum E { + /// M(String), + /// N(u8), + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s), + /// E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n), + /// } + /// } + /// } + /// ``` + fn serialize_newtype_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize; + + /// Begin to serialize a variably sized sequence. This call must be + /// followed by zero or more calls to `serialize_element`, then a call to + /// `end`. + /// + /// The argument is the number of elements in the sequence, which may or may + /// not be computable before the sequence is iterated. Some serializers only + /// support sequences whose length is known up front. + /// + /// ```edition2021 + /// # use std::marker::PhantomData; + /// # + /// # struct Vec(PhantomData); + /// # + /// # impl Vec { + /// # fn len(&self) -> usize { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # impl<'a, T> IntoIterator for &'a Vec { + /// # type Item = &'a T; + /// # type IntoIter = Box>; + /// # + /// # fn into_iter(self) -> Self::IntoIter { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{Serialize, SerializeSeq, Serializer}; + /// + /// impl Serialize for Vec + /// where + /// T: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut seq = serializer.serialize_seq(Some(self.len()))?; + /// for element in self { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// } + /// } + /// ``` + fn serialize_seq(self, len: Option) -> Result; + + /// Begin to serialize a statically sized sequence whose length will be + /// known at deserialization time without looking at the serialized data. + /// This call must be followed by zero or more calls to `serialize_element`, + /// then a call to `end`. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTuple, Serializer}; + /// + /// # mod fool { + /// # trait Serialize {} + /// impl Serialize for (A, B, C) + /// # {} + /// # } + /// # + /// # struct Tuple3(A, B, C); + /// # + /// # impl Serialize for Tuple3 + /// where + /// A: Serialize, + /// B: Serialize, + /// C: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut tup = serializer.serialize_tuple(3)?; + /// tup.serialize_element(&self.0)?; + /// tup.serialize_element(&self.1)?; + /// tup.serialize_element(&self.2)?; + /// tup.end() + /// } + /// } + /// ``` + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTuple, Serializer}; + /// + /// const VRAM_SIZE: usize = 386; + /// struct Vram([u16; VRAM_SIZE]); + /// + /// impl Serialize for Vram { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?; + /// for element in &self.0[..] { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// } + /// } + /// ``` + fn serialize_tuple(self, len: usize) -> Result; + + /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This + /// call must be followed by zero or more calls to `serialize_field`, then a + /// call to `end`. + /// + /// The `name` is the name of the tuple struct and the `len` is the number + /// of data fields that will be serialized. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; + /// + /// struct Rgb(u8, u8, u8); + /// + /// impl Serialize for Rgb { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; + /// ts.serialize_field(&self.0)?; + /// ts.serialize_field(&self.1)?; + /// ts.serialize_field(&self.2)?; + /// ts.end() + /// } + /// } + /// ``` + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result; + + /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8) + /// }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; + /// + /// enum E { + /// T(u8, u8), + /// U(String, u32, u32), + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::T(ref a, ref b) => { + /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; + /// tv.serialize_field(a)?; + /// tv.serialize_field(b)?; + /// tv.end() + /// } + /// E::U(ref a, ref b, ref c) => { + /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; + /// tv.serialize_field(a)?; + /// tv.serialize_field(b)?; + /// tv.serialize_field(c)?; + /// tv.end() + /// } + /// } + /// } + /// } + /// ``` + fn serialize_tuple_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result; + + /// Begin to serialize a map. This call must be followed by zero or more + /// calls to `serialize_key` and `serialize_value`, then a call to `end`. + /// + /// The argument is the number of elements in the map, which may or may not + /// be computable before the map is iterated. Some serializers only support + /// maps whose length is known up front. + /// + /// ```edition2021 + /// # use std::marker::PhantomData; + /// # + /// # struct HashMap(PhantomData, PhantomData); + /// # + /// # impl HashMap { + /// # fn len(&self) -> usize { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # impl<'a, K, V> IntoIterator for &'a HashMap { + /// # type Item = (&'a K, &'a V); + /// # type IntoIter = Box>; + /// # + /// # fn into_iter(self) -> Self::IntoIter { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{Serialize, SerializeMap, Serializer}; + /// + /// impl Serialize for HashMap + /// where + /// K: Serialize, + /// V: Serialize, + /// { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut map = serializer.serialize_map(Some(self.len()))?; + /// for (k, v) in self { + /// map.serialize_entry(k, v)?; + /// } + /// map.end() + /// } + /// } + /// ``` + fn serialize_map(self, len: Option) -> Result; + + /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`. + /// This call must be followed by zero or more calls to `serialize_field`, + /// then a call to `end`. + /// + /// The `name` is the name of the struct and the `len` is the number of + /// data fields that will be serialized. `len` does not include fields + /// which are skipped with [`SerializeStruct::skip_field`]. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeStruct, Serializer}; + /// + /// struct Rgb { + /// r: u8, + /// g: u8, + /// b: u8, + /// } + /// + /// impl Serialize for Rgb { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// let mut rgb = serializer.serialize_struct("Rgb", 3)?; + /// rgb.serialize_field("r", &self.r)?; + /// rgb.serialize_field("g", &self.g)?; + /// rgb.serialize_field("b", &self.b)?; + /// rgb.end() + /// } + /// } + /// ``` + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result; + + /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, + /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// `len` does not include fields which are skipped with + /// [`SerializeStructVariant::skip_field`]. + /// + /// ```edition2021 + /// use serde::ser::{Serialize, SerializeStructVariant, Serializer}; + /// + /// enum E { + /// S { r: u8, g: u8, b: u8 }, + /// } + /// + /// impl Serialize for E { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// match *self { + /// E::S { + /// ref r, + /// ref g, + /// ref b, + /// } => { + /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; + /// sv.serialize_field("r", r)?; + /// sv.serialize_field("g", g)?; + /// sv.serialize_field("b", b)?; + /// sv.end() + /// } + /// } + /// } + /// } + /// ``` + fn serialize_struct_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result; + + /// Collect an iterator as a sequence. + /// + /// The default implementation serializes each item yielded by the iterator + /// using [`serialize_seq`]. Implementors should not need to override this + /// method. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// + /// struct SecretlyOneHigher { + /// data: Vec, + /// } + /// + /// impl Serialize for SecretlyOneHigher { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_seq(self.data.iter().map(|x| x + 1)) + /// } + /// } + /// ``` + /// + /// [`serialize_seq`]: #tymethod.serialize_seq + fn collect_seq(self, iter: I) -> Result + where + I: IntoIterator, + ::Item: Serialize, + { + let mut iter = iter.into_iter(); + let mut serializer = tri!(self.serialize_seq(iterator_len_hint(&iter))); + tri!(iter.try_for_each(|item| serializer.serialize_element(&item))); + serializer.end() + } + + /// Collect an iterator as a map. + /// + /// The default implementation serializes each pair yielded by the iterator + /// using [`serialize_map`]. Implementors should not need to override this + /// method. + /// + /// ```edition2021 + /// use serde::{Serialize, Serializer}; + /// use std::collections::BTreeSet; + /// + /// struct MapToUnit { + /// keys: BTreeSet, + /// } + /// + /// // Serializes as a map in which the values are all unit. + /// impl Serialize for MapToUnit { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_map(self.keys.iter().map(|k| (k, ()))) + /// } + /// } + /// ``` + /// + /// [`serialize_map`]: #tymethod.serialize_map + fn collect_map(self, iter: I) -> Result + where + K: Serialize, + V: Serialize, + I: IntoIterator, + { + let mut iter = iter.into_iter(); + let mut serializer = tri!(self.serialize_map(iterator_len_hint(&iter))); + tri!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value))); + serializer.end() + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// The default implementation builds a heap-allocated [`String`] and + /// delegates to [`serialize_str`]. Serializers are encouraged to provide a + /// more efficient implementation if possible. + /// + /// ```edition2021 + /// # struct DateTime; + /// # + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for DateTime { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset())) + /// } + /// } + /// ``` + /// + /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html + /// [`serialize_str`]: #tymethod.serialize_str + #[cfg(any(feature = "std", feature = "alloc"))] + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display, + { + self.serialize_str(&value.to_string()) + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// Serializers that use `no_std` are required to provide an implementation + /// of this method. If no more sensible behavior is possible, the + /// implementation is expected to return an error. + /// + /// ```edition2021 + /// # struct DateTime; + /// # + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for DateTime { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset())) + /// } + /// } + /// ``` + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display; + + /// Determine whether `Serialize` implementations should serialize in + /// human-readable form. + /// + /// Some types have a human-readable form that may be somewhat expensive to + /// construct, as well as a binary form that is compact and efficient. + /// Generally text-based formats like JSON and YAML will prefer to use the + /// human-readable one and binary formats like Postcard will prefer the + /// compact one. + /// + /// ```edition2021 + /// # use std::fmt::{self, Display}; + /// # + /// # struct Timestamp; + /// # + /// # impl Timestamp { + /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() } + /// # } + /// # + /// # impl Display for Timestamp { + /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for Timestamp { + /// fn serialize(&self, serializer: S) -> Result + /// where + /// S: Serializer, + /// { + /// if serializer.is_human_readable() { + /// // Serialize to a human-readable string "2015-05-15T17:01:00Z". + /// self.to_string().serialize(serializer) + /// } else { + /// // Serialize to a compact binary representation. + /// self.seconds_since_epoch().serialize(serializer) + /// } + /// } + /// } + /// ``` + /// + /// The default implementation of this method returns `true`. Data formats + /// may override this to `false` to request a compact form for types that + /// support one. Note that modifying this method to change a format from + /// human-readable to compact or vice versa should be regarded as a breaking + /// change, as a value serialized in human-readable mode is not required to + /// deserialize from the same data in compact mode. + #[inline] + fn is_human_readable(&self) -> bool { + true + } +} + +/// Returned from `Serializer::serialize_seq`. +/// +/// # Example use +/// +/// ```edition2021 +/// # use std::marker::PhantomData; +/// # +/// # struct Vec(PhantomData); +/// # +/// # impl Vec { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, T> IntoIterator for &'a Vec { +/// # type Item = &'a T; +/// # type IntoIter = Box>; +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, SerializeSeq, Serializer}; +/// +/// impl Serialize for Vec +/// where +/// T: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut seq = serializer.serialize_seq(Some(self.len()))?; +/// for element in self { +/// seq.serialize_element(element)?; +/// } +/// seq.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeSeq` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SerializeSeq { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a sequence element. + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a sequence. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_tuple`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeTuple, Serializer}; +/// +/// # mod fool { +/// # trait Serialize {} +/// impl Serialize for (A, B, C) +/// # {} +/// # } +/// # +/// # struct Tuple3(A, B, C); +/// # +/// # impl Serialize for Tuple3 +/// where +/// A: Serialize, +/// B: Serialize, +/// C: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut tup = serializer.serialize_tuple(3)?; +/// tup.serialize_element(&self.0)?; +/// tup.serialize_element(&self.1)?; +/// tup.serialize_element(&self.2)?; +/// tup.end() +/// } +/// } +/// ``` +/// +/// ```edition2021 +/// # use std::marker::PhantomData; +/// # +/// # struct Array(PhantomData); +/// # +/// # impl Array { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, T> IntoIterator for &'a Array { +/// # type Item = &'a T; +/// # type IntoIter = Box>; +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, SerializeTuple, Serializer}; +/// +/// # mod fool { +/// # trait Serialize {} +/// impl Serialize for [T; 16] +/// # {} +/// # } +/// # +/// # impl Serialize for Array +/// where +/// T: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut seq = serializer.serialize_tuple(16)?; +/// for element in self { +/// seq.serialize_element(element)?; +/// } +/// seq.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeTuple` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SerializeTuple { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple element. + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a tuple. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_tuple_struct`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; +/// +/// struct Rgb(u8, u8, u8); +/// +/// impl Serialize for Rgb { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; +/// ts.serialize_field(&self.0)?; +/// ts.serialize_field(&self.1)?; +/// ts.serialize_field(&self.2)?; +/// ts.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeTupleStruct` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SerializeTupleStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple struct field. + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a tuple struct. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_tuple_variant`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; +/// +/// enum E { +/// T(u8, u8), +/// U(String, u32, u32), +/// } +/// +/// impl Serialize for E { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// match *self { +/// E::T(ref a, ref b) => { +/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; +/// tv.serialize_field(a)?; +/// tv.serialize_field(b)?; +/// tv.end() +/// } +/// E::U(ref a, ref b, ref c) => { +/// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; +/// tv.serialize_field(a)?; +/// tv.serialize_field(b)?; +/// tv.serialize_field(c)?; +/// tv.end() +/// } +/// } +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeTupleVariant` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SerializeTupleVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple variant field. + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Finish serializing a tuple variant. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_map`. +/// +/// # Example use +/// +/// ```edition2021 +/// # use std::marker::PhantomData; +/// # +/// # struct HashMap(PhantomData, PhantomData); +/// # +/// # impl HashMap { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, K, V> IntoIterator for &'a HashMap { +/// # type Item = (&'a K, &'a V); +/// # type IntoIter = Box>; +/// # +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, SerializeMap, Serializer}; +/// +/// impl Serialize for HashMap +/// where +/// K: Serialize, +/// V: Serialize, +/// { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut map = serializer.serialize_map(Some(self.len()))?; +/// for (k, v) in self { +/// map.serialize_entry(k, v)?; +/// } +/// map.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeMap` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SerializeMap { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a map key. + /// + /// If possible, `Serialize` implementations are encouraged to use + /// `serialize_entry` instead as it may be implemented more efficiently in + /// some formats compared to a pair of calls to `serialize_key` and + /// `serialize_value`. + fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Serialize a map value. + /// + /// # Panics + /// + /// Calling `serialize_value` before `serialize_key` is incorrect and is + /// allowed to panic or produce bogus results. + fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Serialize a map entry consisting of a key and a value. + /// + /// Some [`Serialize`] types are not able to hold a key and value in memory + /// at the same time so `SerializeMap` implementations are required to + /// support [`serialize_key`] and [`serialize_value`] individually. The + /// `serialize_entry` method allows serializers to optimize for the case + /// where key and value are both available. [`Serialize`] implementations + /// are encouraged to use `serialize_entry` if possible. + /// + /// The default implementation delegates to [`serialize_key`] and + /// [`serialize_value`]. This is appropriate for serializers that do not + /// care about performance or are not able to optimize `serialize_entry` any + /// better than this. + /// + /// [`Serialize`]: ../trait.Serialize.html + /// [`serialize_key`]: #tymethod.serialize_key + /// [`serialize_value`]: #tymethod.serialize_value + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), Self::Error> + where + K: ?Sized + Serialize, + V: ?Sized + Serialize, + { + tri!(self.serialize_key(key)); + self.serialize_value(value) + } + + /// Finish serializing a map. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_struct`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeStruct, Serializer}; +/// +/// struct Rgb { +/// r: u8, +/// g: u8, +/// b: u8, +/// } +/// +/// impl Serialize for Rgb { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// let mut rgb = serializer.serialize_struct("Rgb", 3)?; +/// rgb.serialize_field("r", &self.r)?; +/// rgb.serialize_field("g", &self.g)?; +/// rgb.serialize_field("b", &self.b)?; +/// rgb.end() +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeStruct` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SerializeStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct field. + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Indicate that a struct field has been skipped. + /// + /// The default implementation does nothing. + #[inline] + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + let _ = key; + Ok(()) + } + + /// Finish serializing a struct. + fn end(self) -> Result; +} + +/// Returned from `Serializer::serialize_struct_variant`. +/// +/// # Example use +/// +/// ```edition2021 +/// use serde::ser::{Serialize, SerializeStructVariant, Serializer}; +/// +/// enum E { +/// S { r: u8, g: u8, b: u8 }, +/// } +/// +/// impl Serialize for E { +/// fn serialize(&self, serializer: S) -> Result +/// where +/// S: Serializer, +/// { +/// match *self { +/// E::S { +/// ref r, +/// ref g, +/// ref b, +/// } => { +/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; +/// sv.serialize_field("r", r)?; +/// sv.serialize_field("g", g)?; +/// sv.serialize_field("b", b)?; +/// sv.end() +/// } +/// } +/// } +/// } +/// ``` +/// +/// # Example implementation +/// +/// The [example data format] presented on the website demonstrates an +/// implementation of `SerializeStructVariant` for a basic JSON data format. +/// +/// [example data format]: https://serde.rs/data-format.html +pub trait SerializeStructVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct variant field. + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize; + + /// Indicate that a struct variant field has been skipped. + /// + /// The default implementation does nothing. + #[inline] + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + let _ = key; + Ok(()) + } + + /// Finish serializing a struct variant. + fn end(self) -> Result; +} + +fn iterator_len_hint(iter: &I) -> Option +where + I: Iterator, +{ + match iter.size_hint() { + (lo, Some(hi)) if lo == hi => Some(lo), + _ => None, + } +} diff --git a/bitbox02-bt/vendor/serde/src/std_error.rs b/bitbox02-bt/vendor/serde/src/std_error.rs new file mode 100644 index 0000000..f15a4d7 --- /dev/null +++ b/bitbox02-bt/vendor/serde/src/std_error.rs @@ -0,0 +1,48 @@ +use crate::lib::{Debug, Display}; + +/// Either a re-export of std::error::Error or a new identical trait, depending +/// on whether Serde's "std" feature is enabled. +/// +/// Serde's error traits [`serde::ser::Error`] and [`serde::de::Error`] require +/// [`std::error::Error`] as a supertrait, but only when Serde is built with +/// "std" enabled. Data formats that don't care about no\_std support should +/// generally provide their error types with a `std::error::Error` impl +/// directly: +/// +/// ```edition2021 +/// #[derive(Debug)] +/// struct MySerError {...} +/// +/// impl serde::ser::Error for MySerError {...} +/// +/// impl std::fmt::Display for MySerError {...} +/// +/// // We don't support no_std! +/// impl std::error::Error for MySerError {} +/// ``` +/// +/// Data formats that *do* support no\_std may either have a "std" feature of +/// their own: +/// +/// ```toml +/// [features] +/// std = ["serde/std"] +/// ``` +/// +/// ```edition2021 +/// #[cfg(feature = "std")] +/// impl std::error::Error for MySerError {} +/// ``` +/// +/// ... or else provide the std Error impl unconditionally via Serde's +/// re-export: +/// +/// ```edition2021 +/// impl serde::ser::StdError for MySerError {} +/// ``` +pub trait Error: Debug + Display { + /// The underlying cause of this error, if any. + fn source(&self) -> Option<&(Error + 'static)> { + None + } +} diff --git a/bitbox02-bt/vendor/serde_derive/.cargo-checksum.json b/bitbox02-bt/vendor/serde_derive/.cargo-checksum.json new file mode 100644 index 0000000..0927fc9 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"f02849531e614dd38ab37ad86c0e4f5bf16ede7becaa75ebbb6604170ea294e6","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"731c044fc5f98b37a89e9049c9214267db98763309cb63146b45c029640f82a3","crates-io.md":"407d92b2932923f8708aaf31db266fd7db32e2b0afa6c569d134b680b74a1920","src/bound.rs":"6c5c20785ac95af9480f8d0de35a7e844cc36a16012f6468db148acd03cb15c2","src/de.rs":"e0a2186fb31e24b95cdfc499b1adad295bb3eac0448a41fc37f7609cadda52c7","src/dummy.rs":"9533dfee23f20d92ea75734c739022820c2787ded0d54f459feacdeb770ec912","src/fragment.rs":"6757cb4c3131d4300f093572efc273c4ab5a20e3e1efb54a311dcfa52d0bd6eb","src/internals/ast.rs":"171478e83d203193cd96f2c9c922bd240214e05fdf76add73fb7e029784bace8","src/internals/attr.rs":"8ab89c54ec7713a16767971507733f6692eff1919fe7add6911b33c40dfc45a7","src/internals/case.rs":"10c8dda2b32d8c6c6b63cf09cdc63d02375af7e95ecefe8fecb34f93b65191bb","src/internals/check.rs":"d842eb9912fd29311060b67f3bc62c438eb7b5d86093355acb4de7eee02a0ef8","src/internals/ctxt.rs":"83a4e6fbe0e439d578478883594407e03f2f340541be479bdf0b04a202633a37","src/internals/mod.rs":"ed021ca635c18132a0e5c3d90f21b7f65def0a61e946421a30200b5b9ab6ad43","src/internals/receiver.rs":"710f875da3bad3e2a7fc1df40ab6805bb5e971b6a2a04c1b643b8a0aa29e8496","src/internals/respan.rs":"899753859c58ce5f532a3ec4584796a52f13ed5a0533191e48c953ba5c1b52ff","src/internals/symbol.rs":"d619e88caa3c7a09b03014257f2b349ee922290062d9b97b4dd19d0e64532690","src/lib.rs":"67d0a9e8509324573bf42467f98eb3d9e4e15da67410a3e23bb87bdbd742f5ed","src/pretend.rs":"7facc10a5b805564dd95735ae11118ec17ca6adcc49a59764e7c920e27b9fc4a","src/ser.rs":"120588172988a1078af4a090fbe6ffc2f9ba3ac6993f9baebea17cfe5ac6e7fa","src/this.rs":"87818dc80cbb521b51938a653d09daf10aafc220bb10425948de82ad670fcb85"},"package":"243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/serde_derive/Cargo.toml b/bitbox02-bt/vendor/serde_derive/Cargo.toml new file mode 100644 index 0000000..2bd5bb3 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/Cargo.toml @@ -0,0 +1,79 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2015" +rust-version = "1.56" +name = "serde_derive" +version = "1.0.210" +authors = [ + "Erick Tryzelaar ", + "David Tolnay ", +] +build = false +exclude = ["build.rs"] +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]" +homepage = "https://serde.rs" +documentation = "https://serde.rs/derive.html" +readme = "crates-io.md" +keywords = [ + "serde", + "serialization", + "no_std", + "derive", +] +categories = [ + "no-std", + "no-std::no-alloc", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/serde-rs/serde" + +[package.metadata.docs.rs] +rustdoc-args = ["--generate-link-to-definition"] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +name = "serde_derive" +path = "src/lib.rs" +proc-macro = true + +[dependencies.proc-macro2] +version = "1.0.74" +features = ["proc-macro"] +default-features = false + +[dependencies.quote] +version = "1.0.35" +features = ["proc-macro"] +default-features = false + +[dependencies.syn] +version = "2.0.46" +features = [ + "clone-impls", + "derive", + "parsing", + "printing", + "proc-macro", +] +default-features = false + +[dev-dependencies.serde] +version = "1" + +[features] +default = [] +deserialize_in_place = [] diff --git a/bitbox02-bt/vendor/serde_derive/LICENSE-APACHE b/bitbox02-bt/vendor/serde_derive/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/serde_derive/LICENSE-MIT b/bitbox02-bt/vendor/serde_derive/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/serde_derive/README.md b/bitbox02-bt/vendor/serde_derive/README.md new file mode 100644 index 0000000..3129294 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/README.md @@ -0,0 +1,114 @@ +# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.31] [![serde_derive msrv]][Rust 1.56] + +[Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/serde/ci.yml?branch=master +[actions]: https://github.com/serde-rs/serde/actions?query=branch%3Amaster +[Latest Version]: https://img.shields.io/crates/v/serde.svg +[crates.io]: https://crates.io/crates/serde +[serde msrv]: https://img.shields.io/crates/msrv/serde.svg?label=serde%20msrv&color=lightgray +[serde_derive msrv]: https://img.shields.io/crates/msrv/serde_derive.svg?label=serde_derive%20msrv&color=lightgray +[Rust 1.31]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html +[Rust 1.56]: https://blog.rust-lang.org/2021/10/21/Rust-1.56.0.html + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.rs/serde) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + + +

+ +```rust +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde is one of the most widely used Rust libraries so any place that Rustaceans +congregate will be able to help you out. For chat, consider trying the +[#rust-questions] or [#rust-beginners] channels of the unofficial community +Discord (invite: ), the [#rust-usage] or +[#beginners] channels of the official Rust Project Discord (invite: +), or the [#general][zulip] stream in Zulip. For +asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the +[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust +[Discourse forum][discourse]. It's acceptable to file a support issue in this +repo but they tend not to get as many eyes as any of the above and may get +closed without a response after some time. + +[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513 +[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281 +[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848 +[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612 +[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general +[stackoverflow]: https://stackoverflow.com/questions/tagged/rust +[/r/rust]: https://www.reddit.com/r/rust +[discourse]: https://users.rust-lang.org + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/serde_derive/crates-io.md b/bitbox02-bt/vendor/serde_derive/crates-io.md new file mode 100644 index 0000000..b49a548 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/crates-io.md @@ -0,0 +1,65 @@ + + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.rs/serde) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + +```rust +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde is one of the most widely used Rust libraries so any place that Rustaceans +congregate will be able to help you out. For chat, consider trying the +[#rust-questions] or [#rust-beginners] channels of the unofficial community +Discord (invite: ), the [#rust-usage] +or [#beginners] channels of the official Rust Project Discord (invite: +), or the [#general][zulip] stream in Zulip. For +asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the +[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust +[Discourse forum][discourse]. It's acceptable to file a support issue in this +repo but they tend not to get as many eyes as any of the above and may get +closed without a response after some time. + +[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513 +[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281 +[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848 +[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612 +[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general +[stackoverflow]: https://stackoverflow.com/questions/tagged/rust +[/r/rust]: https://www.reddit.com/r/rust +[discourse]: https://users.rust-lang.org diff --git a/bitbox02-bt/vendor/serde_derive/src/bound.rs b/bitbox02-bt/vendor/serde_derive/src/bound.rs new file mode 100644 index 0000000..fe8ccff --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/bound.rs @@ -0,0 +1,408 @@ +use crate::internals::ast::{Container, Data}; +use crate::internals::{attr, ungroup}; +use proc_macro2::Span; +use std::collections::HashSet; +use syn::punctuated::{Pair, Punctuated}; +use syn::Token; + +// Remove the default from every type parameter because in the generated impls +// they look like associated types: "error: associated type bindings are not +// allowed here". +pub fn without_defaults(generics: &syn::Generics) -> syn::Generics { + syn::Generics { + params: generics + .params + .iter() + .map(|param| match param { + syn::GenericParam::Type(param) => syn::GenericParam::Type(syn::TypeParam { + eq_token: None, + default: None, + ..param.clone() + }), + _ => param.clone(), + }) + .collect(), + ..generics.clone() + } +} + +pub fn with_where_predicates( + generics: &syn::Generics, + predicates: &[syn::WherePredicate], +) -> syn::Generics { + let mut generics = generics.clone(); + generics + .make_where_clause() + .predicates + .extend(predicates.iter().cloned()); + generics +} + +pub fn with_where_predicates_from_fields( + cont: &Container, + generics: &syn::Generics, + from_field: fn(&attr::Field) -> Option<&[syn::WherePredicate]>, +) -> syn::Generics { + let predicates = cont + .data + .all_fields() + .filter_map(|field| from_field(&field.attrs)) + .flat_map(<[syn::WherePredicate]>::to_vec); + + let mut generics = generics.clone(); + generics.make_where_clause().predicates.extend(predicates); + generics +} + +pub fn with_where_predicates_from_variants( + cont: &Container, + generics: &syn::Generics, + from_variant: fn(&attr::Variant) -> Option<&[syn::WherePredicate]>, +) -> syn::Generics { + let variants = match &cont.data { + Data::Enum(variants) => variants, + Data::Struct(_, _) => { + return generics.clone(); + } + }; + + let predicates = variants + .iter() + .filter_map(|variant| from_variant(&variant.attrs)) + .flat_map(<[syn::WherePredicate]>::to_vec); + + let mut generics = generics.clone(); + generics.make_where_clause().predicates.extend(predicates); + generics +} + +// Puts the given bound on any generic type parameters that are used in fields +// for which filter returns true. +// +// For example, the following struct needs the bound `A: Serialize, B: +// Serialize`. +// +// struct S<'b, A, B: 'b, C> { +// a: A, +// b: Option<&'b B> +// #[serde(skip_serializing)] +// c: C, +// } +pub fn with_bound( + cont: &Container, + generics: &syn::Generics, + filter: fn(&attr::Field, Option<&attr::Variant>) -> bool, + bound: &syn::Path, +) -> syn::Generics { + struct FindTyParams<'ast> { + // Set of all generic type parameters on the current struct (A, B, C in + // the example). Initialized up front. + all_type_params: HashSet, + + // Set of generic type parameters used in fields for which filter + // returns true (A and B in the example). Filled in as the visitor sees + // them. + relevant_type_params: HashSet, + + // Fields whose type is an associated type of one of the generic type + // parameters. + associated_type_usage: Vec<&'ast syn::TypePath>, + } + + impl<'ast> FindTyParams<'ast> { + fn visit_field(&mut self, field: &'ast syn::Field) { + if let syn::Type::Path(ty) = ungroup(&field.ty) { + if let Some(Pair::Punctuated(t, _)) = ty.path.segments.pairs().next() { + if self.all_type_params.contains(&t.ident) { + self.associated_type_usage.push(ty); + } + } + } + self.visit_type(&field.ty); + } + + fn visit_path(&mut self, path: &'ast syn::Path) { + if let Some(seg) = path.segments.last() { + if seg.ident == "PhantomData" { + // Hardcoded exception, because PhantomData implements + // Serialize and Deserialize whether or not T implements it. + return; + } + } + if path.leading_colon.is_none() && path.segments.len() == 1 { + let id = &path.segments[0].ident; + if self.all_type_params.contains(id) { + self.relevant_type_params.insert(id.clone()); + } + } + for segment in &path.segments { + self.visit_path_segment(segment); + } + } + + // Everything below is simply traversing the syntax tree. + + fn visit_type(&mut self, ty: &'ast syn::Type) { + match ty { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + syn::Type::Array(ty) => self.visit_type(&ty.elem), + syn::Type::BareFn(ty) => { + for arg in &ty.inputs { + self.visit_type(&arg.ty); + } + self.visit_return_type(&ty.output); + } + syn::Type::Group(ty) => self.visit_type(&ty.elem), + syn::Type::ImplTrait(ty) => { + for bound in &ty.bounds { + self.visit_type_param_bound(bound); + } + } + syn::Type::Macro(ty) => self.visit_macro(&ty.mac), + syn::Type::Paren(ty) => self.visit_type(&ty.elem), + syn::Type::Path(ty) => { + if let Some(qself) = &ty.qself { + self.visit_type(&qself.ty); + } + self.visit_path(&ty.path); + } + syn::Type::Ptr(ty) => self.visit_type(&ty.elem), + syn::Type::Reference(ty) => self.visit_type(&ty.elem), + syn::Type::Slice(ty) => self.visit_type(&ty.elem), + syn::Type::TraitObject(ty) => { + for bound in &ty.bounds { + self.visit_type_param_bound(bound); + } + } + syn::Type::Tuple(ty) => { + for elem in &ty.elems { + self.visit_type(elem); + } + } + + syn::Type::Infer(_) | syn::Type::Never(_) | syn::Type::Verbatim(_) => {} + + _ => {} + } + } + + fn visit_path_segment(&mut self, segment: &'ast syn::PathSegment) { + self.visit_path_arguments(&segment.arguments); + } + + fn visit_path_arguments(&mut self, arguments: &'ast syn::PathArguments) { + match arguments { + syn::PathArguments::None => {} + syn::PathArguments::AngleBracketed(arguments) => { + for arg in &arguments.args { + match arg { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + syn::GenericArgument::Type(arg) => self.visit_type(arg), + syn::GenericArgument::AssocType(arg) => self.visit_type(&arg.ty), + syn::GenericArgument::Lifetime(_) + | syn::GenericArgument::Const(_) + | syn::GenericArgument::AssocConst(_) + | syn::GenericArgument::Constraint(_) => {} + _ => {} + } + } + } + syn::PathArguments::Parenthesized(arguments) => { + for argument in &arguments.inputs { + self.visit_type(argument); + } + self.visit_return_type(&arguments.output); + } + } + } + + fn visit_return_type(&mut self, return_type: &'ast syn::ReturnType) { + match return_type { + syn::ReturnType::Default => {} + syn::ReturnType::Type(_, output) => self.visit_type(output), + } + } + + fn visit_type_param_bound(&mut self, bound: &'ast syn::TypeParamBound) { + match bound { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + syn::TypeParamBound::Trait(bound) => self.visit_path(&bound.path), + syn::TypeParamBound::Lifetime(_) | syn::TypeParamBound::Verbatim(_) => {} + _ => {} + } + } + + // Type parameter should not be considered used by a macro path. + // + // struct TypeMacro { + // mac: T!(), + // marker: PhantomData, + // } + fn visit_macro(&mut self, _mac: &'ast syn::Macro) {} + } + + let all_type_params = generics + .type_params() + .map(|param| param.ident.clone()) + .collect(); + + let mut visitor = FindTyParams { + all_type_params, + relevant_type_params: HashSet::new(), + associated_type_usage: Vec::new(), + }; + match &cont.data { + Data::Enum(variants) => { + for variant in variants { + let relevant_fields = variant + .fields + .iter() + .filter(|field| filter(&field.attrs, Some(&variant.attrs))); + for field in relevant_fields { + visitor.visit_field(field.original); + } + } + } + Data::Struct(_, fields) => { + for field in fields.iter().filter(|field| filter(&field.attrs, None)) { + visitor.visit_field(field.original); + } + } + } + + let relevant_type_params = visitor.relevant_type_params; + let associated_type_usage = visitor.associated_type_usage; + let new_predicates = generics + .type_params() + .map(|param| param.ident.clone()) + .filter(|id| relevant_type_params.contains(id)) + .map(|id| syn::TypePath { + qself: None, + path: id.into(), + }) + .chain(associated_type_usage.into_iter().cloned()) + .map(|bounded_ty| { + syn::WherePredicate::Type(syn::PredicateType { + lifetimes: None, + // the type parameter that is being bounded e.g. T + bounded_ty: syn::Type::Path(bounded_ty), + colon_token: ::default(), + // the bound e.g. Serialize + bounds: vec![syn::TypeParamBound::Trait(syn::TraitBound { + paren_token: None, + modifier: syn::TraitBoundModifier::None, + lifetimes: None, + path: bound.clone(), + })] + .into_iter() + .collect(), + }) + }); + + let mut generics = generics.clone(); + generics + .make_where_clause() + .predicates + .extend(new_predicates); + generics +} + +pub fn with_self_bound( + cont: &Container, + generics: &syn::Generics, + bound: &syn::Path, +) -> syn::Generics { + let mut generics = generics.clone(); + generics + .make_where_clause() + .predicates + .push(syn::WherePredicate::Type(syn::PredicateType { + lifetimes: None, + // the type that is being bounded e.g. MyStruct<'a, T> + bounded_ty: type_of_item(cont), + colon_token: ::default(), + // the bound e.g. Default + bounds: vec![syn::TypeParamBound::Trait(syn::TraitBound { + paren_token: None, + modifier: syn::TraitBoundModifier::None, + lifetimes: None, + path: bound.clone(), + })] + .into_iter() + .collect(), + })); + generics +} + +pub fn with_lifetime_bound(generics: &syn::Generics, lifetime: &str) -> syn::Generics { + let bound = syn::Lifetime::new(lifetime, Span::call_site()); + let def = syn::LifetimeParam { + attrs: Vec::new(), + lifetime: bound.clone(), + colon_token: None, + bounds: Punctuated::new(), + }; + + let params = Some(syn::GenericParam::Lifetime(def)) + .into_iter() + .chain(generics.params.iter().cloned().map(|mut param| { + match &mut param { + syn::GenericParam::Lifetime(param) => { + param.bounds.push(bound.clone()); + } + syn::GenericParam::Type(param) => { + param + .bounds + .push(syn::TypeParamBound::Lifetime(bound.clone())); + } + syn::GenericParam::Const(_) => {} + } + param + })) + .collect(); + + syn::Generics { + params, + ..generics.clone() + } +} + +fn type_of_item(cont: &Container) -> syn::Type { + syn::Type::Path(syn::TypePath { + qself: None, + path: syn::Path { + leading_colon: None, + segments: vec![syn::PathSegment { + ident: cont.ident.clone(), + arguments: syn::PathArguments::AngleBracketed( + syn::AngleBracketedGenericArguments { + colon2_token: None, + lt_token: ::default(), + args: cont + .generics + .params + .iter() + .map(|param| match param { + syn::GenericParam::Type(param) => { + syn::GenericArgument::Type(syn::Type::Path(syn::TypePath { + qself: None, + path: param.ident.clone().into(), + })) + } + syn::GenericParam::Lifetime(param) => { + syn::GenericArgument::Lifetime(param.lifetime.clone()) + } + syn::GenericParam::Const(_) => { + panic!("Serde does not support const generics yet"); + } + }) + .collect(), + gt_token: ]>::default(), + }, + ), + }] + .into_iter() + .collect(), + }, + }) +} diff --git a/bitbox02-bt/vendor/serde_derive/src/de.rs b/bitbox02-bt/vendor/serde_derive/src/de.rs new file mode 100644 index 0000000..996e97e --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/de.rs @@ -0,0 +1,3172 @@ +use crate::fragment::{Expr, Fragment, Match, Stmts}; +use crate::internals::ast::{Container, Data, Field, Style, Variant}; +use crate::internals::{attr, replace_receiver, ungroup, Ctxt, Derive}; +use crate::{bound, dummy, pretend, this}; +use proc_macro2::{Literal, Span, TokenStream}; +use quote::{quote, quote_spanned, ToTokens}; +use std::collections::BTreeSet; +use std::ptr; +use syn::punctuated::Punctuated; +use syn::spanned::Spanned; +use syn::{parse_quote, Ident, Index, Member}; + +pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result { + replace_receiver(input); + + let ctxt = Ctxt::new(); + let cont = match Container::from_ast(&ctxt, input, Derive::Deserialize) { + Some(cont) => cont, + None => return Err(ctxt.check().unwrap_err()), + }; + precondition(&ctxt, &cont); + ctxt.check()?; + + let ident = &cont.ident; + let params = Parameters::new(&cont); + let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms); + let body = Stmts(deserialize_body(&cont, ¶ms)); + let delife = params.borrowed.de_lifetime(); + let serde = cont.attrs.serde_path(); + + let impl_block = if let Some(remote) = cont.attrs.remote() { + let vis = &input.vis; + let used = pretend::pretend_used(&cont, params.is_packed); + quote! { + impl #de_impl_generics #ident #ty_generics #where_clause { + #vis fn deserialize<__D>(__deserializer: __D) -> #serde::__private::Result<#remote #ty_generics, __D::Error> + where + __D: #serde::Deserializer<#delife>, + { + #used + #body + } + } + } + } else { + let fn_deserialize_in_place = deserialize_in_place_body(&cont, ¶ms); + + quote! { + #[automatically_derived] + impl #de_impl_generics #serde::Deserialize<#delife> for #ident #ty_generics #where_clause { + fn deserialize<__D>(__deserializer: __D) -> #serde::__private::Result + where + __D: #serde::Deserializer<#delife>, + { + #body + } + + #fn_deserialize_in_place + } + } + }; + + Ok(dummy::wrap_in_const( + cont.attrs.custom_serde_path(), + impl_block, + )) +} + +fn precondition(cx: &Ctxt, cont: &Container) { + precondition_sized(cx, cont); + precondition_no_de_lifetime(cx, cont); +} + +fn precondition_sized(cx: &Ctxt, cont: &Container) { + if let Data::Struct(_, fields) = &cont.data { + if let Some(last) = fields.last() { + if let syn::Type::Slice(_) = ungroup(last.ty) { + cx.error_spanned_by( + cont.original, + "cannot deserialize a dynamically sized struct", + ); + } + } + } +} + +fn precondition_no_de_lifetime(cx: &Ctxt, cont: &Container) { + if let BorrowedLifetimes::Borrowed(_) = borrowed_lifetimes(cont) { + for param in cont.generics.lifetimes() { + if param.lifetime.to_string() == "'de" { + cx.error_spanned_by( + ¶m.lifetime, + "cannot deserialize when there is a lifetime parameter called 'de", + ); + return; + } + } + } +} + +struct Parameters { + /// Name of the type the `derive` is on. + local: syn::Ident, + + /// Path to the type the impl is for. Either a single `Ident` for local + /// types (does not include generic parameters) or `some::remote::Path` for + /// remote types. + this_type: syn::Path, + + /// Same as `this_type` but using `::` for generic parameters for use in + /// expression position. + this_value: syn::Path, + + /// Generics including any explicit and inferred bounds for the impl. + generics: syn::Generics, + + /// Lifetimes borrowed from the deserializer. These will become bounds on + /// the `'de` lifetime of the deserializer. + borrowed: BorrowedLifetimes, + + /// At least one field has a serde(getter) attribute, implying that the + /// remote type has a private field. + has_getter: bool, + + /// Type has a repr(packed) attribute. + is_packed: bool, +} + +impl Parameters { + fn new(cont: &Container) -> Self { + let local = cont.ident.clone(); + let this_type = this::this_type(cont); + let this_value = this::this_value(cont); + let borrowed = borrowed_lifetimes(cont); + let generics = build_generics(cont, &borrowed); + let has_getter = cont.data.has_getter(); + let is_packed = cont.attrs.is_packed(); + + Parameters { + local, + this_type, + this_value, + generics, + borrowed, + has_getter, + is_packed, + } + } + + /// Type name to use in error messages and `&'static str` arguments to + /// various Deserializer methods. + fn type_name(&self) -> String { + self.this_type.segments.last().unwrap().ident.to_string() + } +} + +// All the generics in the input, plus a bound `T: Deserialize` for each generic +// field type that will be deserialized by us, plus a bound `T: Default` for +// each generic field type that will be set to a default value. +fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics { + let generics = bound::without_defaults(cont.generics); + + let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound); + + let generics = + bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::de_bound); + + match cont.attrs.de_bound() { + Some(predicates) => bound::with_where_predicates(&generics, predicates), + None => { + let generics = match *cont.attrs.default() { + attr::Default::Default => bound::with_self_bound( + cont, + &generics, + &parse_quote!(_serde::__private::Default), + ), + attr::Default::None | attr::Default::Path(_) => generics, + }; + + let delife = borrowed.de_lifetime(); + let generics = bound::with_bound( + cont, + &generics, + needs_deserialize_bound, + &parse_quote!(_serde::Deserialize<#delife>), + ); + + bound::with_bound( + cont, + &generics, + requires_default, + &parse_quote!(_serde::__private::Default), + ) + } + } +} + +// Fields with a `skip_deserializing` or `deserialize_with` attribute, or which +// belong to a variant with a `skip_deserializing` or `deserialize_with` +// attribute, are not deserialized by us so we do not generate a bound. Fields +// with a `bound` attribute specify their own bound so we do not generate one. +// All other fields may need a `T: Deserialize` bound where T is the type of the +// field. +fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { + !field.skip_deserializing() + && field.deserialize_with().is_none() + && field.de_bound().is_none() + && variant.map_or(true, |variant| { + !variant.skip_deserializing() + && variant.deserialize_with().is_none() + && variant.de_bound().is_none() + }) +} + +// Fields with a `default` attribute (not `default=...`), and fields with a +// `skip_deserializing` attribute that do not also have `default=...`. +fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool { + if let attr::Default::Default = *field.default() { + true + } else { + false + } +} + +enum BorrowedLifetimes { + Borrowed(BTreeSet), + Static, +} + +impl BorrowedLifetimes { + fn de_lifetime(&self) -> syn::Lifetime { + match *self { + BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de", Span::call_site()), + BorrowedLifetimes::Static => syn::Lifetime::new("'static", Span::call_site()), + } + } + + fn de_lifetime_param(&self) -> Option { + match self { + BorrowedLifetimes::Borrowed(bounds) => Some(syn::LifetimeParam { + attrs: Vec::new(), + lifetime: syn::Lifetime::new("'de", Span::call_site()), + colon_token: None, + bounds: bounds.iter().cloned().collect(), + }), + BorrowedLifetimes::Static => None, + } + } +} + +// The union of lifetimes borrowed by each field of the container. +// +// These turn into bounds on the `'de` lifetime of the Deserialize impl. If +// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is: +// +// impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c> +// +// If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant +// and we use plain `'static` instead of `'de`. +fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes { + let mut lifetimes = BTreeSet::new(); + for field in cont.data.all_fields() { + if !field.attrs.skip_deserializing() { + lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned()); + } + } + if lifetimes.iter().any(|b| b.to_string() == "'static") { + BorrowedLifetimes::Static + } else { + BorrowedLifetimes::Borrowed(lifetimes) + } +} + +fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment { + if cont.attrs.transparent() { + deserialize_transparent(cont, params) + } else if let Some(type_from) = cont.attrs.type_from() { + deserialize_from(type_from) + } else if let Some(type_try_from) = cont.attrs.type_try_from() { + deserialize_try_from(type_try_from) + } else if let attr::Identifier::No = cont.attrs.identifier() { + match &cont.data { + Data::Enum(variants) => deserialize_enum(params, variants, &cont.attrs), + Data::Struct(Style::Struct, fields) => { + deserialize_struct(params, fields, &cont.attrs, StructForm::Struct) + } + Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { + deserialize_tuple(params, fields, &cont.attrs, TupleForm::Tuple) + } + Data::Struct(Style::Unit, _) => deserialize_unit_struct(params, &cont.attrs), + } + } else { + match &cont.data { + Data::Enum(variants) => deserialize_custom_identifier(params, variants, &cont.attrs), + Data::Struct(_, _) => unreachable!("checked in serde_derive_internals"), + } + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option { + // Only remote derives have getters, and we do not generate + // deserialize_in_place for remote derives. + assert!(!params.has_getter); + + if cont.attrs.transparent() + || cont.attrs.type_from().is_some() + || cont.attrs.type_try_from().is_some() + || cont.attrs.identifier().is_some() + || cont + .data + .all_fields() + .all(|f| f.attrs.deserialize_with().is_some()) + { + return None; + } + + let code = match &cont.data { + Data::Struct(Style::Struct, fields) => { + deserialize_struct_in_place(params, fields, &cont.attrs)? + } + Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => { + deserialize_tuple_in_place(params, fields, &cont.attrs) + } + Data::Enum(_) | Data::Struct(Style::Unit, _) => { + return None; + } + }; + + let delife = params.borrowed.de_lifetime(); + let stmts = Stmts(code); + + let fn_deserialize_in_place = quote_block! { + fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::__private::Result<(), __D::Error> + where + __D: _serde::Deserializer<#delife>, + { + #stmts + } + }; + + Some(Stmts(fn_deserialize_in_place)) +} + +#[cfg(not(feature = "deserialize_in_place"))] +fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option { + None +} + +fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment { + let fields = match &cont.data { + Data::Struct(_, fields) => fields, + Data::Enum(_) => unreachable!(), + }; + + let this_value = ¶ms.this_value; + let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap(); + + let path = match transparent_field.attrs.deserialize_with() { + Some(path) => quote!(#path), + None => { + let span = transparent_field.original.span(); + quote_spanned!(span=> _serde::Deserialize::deserialize) + } + }; + + let assign = fields.iter().map(|field| { + let member = &field.member; + if ptr::eq(field, transparent_field) { + quote!(#member: __transparent) + } else { + let value = match field.attrs.default() { + attr::Default::Default => quote!(_serde::__private::Default::default()), + attr::Default::Path(path) => quote!(#path()), + attr::Default::None => quote!(_serde::__private::PhantomData), + }; + quote!(#member: #value) + } + }); + + quote_block! { + _serde::__private::Result::map( + #path(__deserializer), + |__transparent| #this_value { #(#assign),* }) + } +} + +fn deserialize_from(type_from: &syn::Type) -> Fragment { + quote_block! { + _serde::__private::Result::map( + <#type_from as _serde::Deserialize>::deserialize(__deserializer), + _serde::__private::From::from) + } +} + +fn deserialize_try_from(type_try_from: &syn::Type) -> Fragment { + quote_block! { + _serde::__private::Result::and_then( + <#type_try_from as _serde::Deserialize>::deserialize(__deserializer), + |v| _serde::__private::TryFrom::try_from(v).map_err(_serde::de::Error::custom)) + } +} + +fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fragment { + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let type_name = cattrs.name().deserialize_name(); + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let expecting = format!("unit struct {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + quote_block! { + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + #[inline] + fn visit_unit<__E>(self) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(#this_value) + } + } + + _serde::Deserializer::deserialize_unit_struct( + __deserializer, + #type_name, + __Visitor { + marker: _serde::__private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData, + }, + ) + } +} + +enum TupleForm<'a> { + Tuple, + /// Contains a variant name + ExternallyTagged(&'a syn::Ident), + /// Contains a variant name and an intermediate deserializer from which actual + /// deserialization will be performed + Untagged(&'a syn::Ident, TokenStream), +} + +fn deserialize_tuple( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + form: TupleForm, +) -> Fragment { + assert!( + !has_flatten(fields), + "tuples and tuple variants cannot have flatten fields" + ); + + let field_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + // If there are getters (implying private fields), construct the local type + // and use an `Into` conversion to get the remote type. If there are no + // getters then construct the target type directly. + let construct = if params.has_getter { + let local = ¶ms.local; + quote!(#local) + } else { + quote!(#this_value) + }; + + let type_path = match form { + TupleForm::Tuple => construct, + TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => { + quote!(#construct::#variant_ident) + } + }; + let expecting = match form { + TupleForm::Tuple => format!("tuple struct {}", params.type_name()), + TupleForm::ExternallyTagged(variant_ident) | TupleForm::Untagged(variant_ident, _) => { + format!("tuple variant {}::{}", params.type_name(), variant_ident) + } + }; + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let nfields = fields.len(); + + let visit_newtype_struct = match form { + TupleForm::Tuple if nfields == 1 => { + Some(deserialize_newtype_struct(&type_path, params, &fields[0])) + } + _ => None, + }; + + let visit_seq = Stmts(deserialize_seq( + &type_path, params, fields, false, cattrs, expecting, + )); + + let visitor_expr = quote! { + __Visitor { + marker: _serde::__private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData, + } + }; + let dispatch = match form { + TupleForm::Tuple if nfields == 1 => { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr) + } + } + TupleForm::Tuple => { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr) + } + } + TupleForm::ExternallyTagged(_) => quote! { + _serde::de::VariantAccess::tuple_variant(__variant, #field_count, #visitor_expr) + }, + TupleForm::Untagged(_, deserializer) => quote! { + _serde::Deserializer::deserialize_tuple(#deserializer, #field_count, #visitor_expr) + }, + }; + + let visitor_var = if field_count == 0 { + quote!(_) + } else { + quote!(mut __seq) + }; + + quote_block! { + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + #visit_newtype_struct + + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::__private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + } + + #dispatch + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_tuple_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + assert!( + !has_flatten(fields), + "tuples and tuple variants cannot have flatten fields" + ); + + let field_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + + let this_type = ¶ms.this_type; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let expecting = format!("tuple struct {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let nfields = fields.len(); + + let visit_newtype_struct = if nfields == 1 { + // We do not generate deserialize_in_place if every field has a + // deserialize_with. + assert!(fields[0].attrs.deserialize_with().is_none()); + + Some(quote! { + #[inline] + fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::__private::Result + where + __E: _serde::Deserializer<#delife>, + { + _serde::Deserialize::deserialize_in_place(__e, &mut self.place.0) + } + }) + } else { + None + }; + + let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); + + let visitor_expr = quote! { + __Visitor { + place: __place, + lifetime: _serde::__private::PhantomData, + } + }; + + let type_name = cattrs.name().deserialize_name(); + let dispatch = if nfields == 1 { + quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) + } else { + quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #field_count, #visitor_expr)) + }; + + let visitor_var = if field_count == 0 { + quote!(_) + } else { + quote!(mut __seq) + }; + + let in_place_impl_generics = de_impl_generics.in_place(); + let in_place_ty_generics = de_ty_generics.in_place(); + let place_life = place_lifetime(); + + quote_block! { + #[doc(hidden)] + struct __Visitor #in_place_impl_generics #where_clause { + place: &#place_life mut #this_type #ty_generics, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { + type Value = (); + + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + #visit_newtype_struct + + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::__private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + } + + #dispatch + } +} + +fn deserialize_seq( + type_path: &TokenStream, + params: &Parameters, + fields: &[Field], + is_struct: bool, + cattrs: &attr::Container, + expecting: &str, +) -> Fragment { + let vars = (0..fields.len()).map(field_i as fn(_) -> _); + + let deserialized_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + let expecting = if deserialized_count == 1 { + format!("{} with 1 element", expecting) + } else { + format!("{} with {} elements", expecting, deserialized_count) + }; + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let mut index_in_seq = 0_usize; + let let_values = vars.clone().zip(fields).map(|(var, field)| { + if field.attrs.skip_deserializing() { + let default = Expr(expr_is_missing(field, cattrs)); + quote! { + let #var = #default; + } + } else { + let visit = match field.attrs.deserialize_with() { + None => { + let field_ty = field.ty; + let span = field.original.span(); + let func = + quote_spanned!(span=> _serde::de::SeqAccess::next_element::<#field_ty>); + quote!(#func(&mut __seq)?) + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + _serde::__private::Option::map( + _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)?, + |__wrap| __wrap.value) + }) + } + }; + let value_if_none = expr_is_missing_seq(None, index_in_seq, field, cattrs, expecting); + let assign = quote! { + let #var = match #visit { + _serde::__private::Some(__value) => __value, + _serde::__private::None => #value_if_none, + }; + }; + index_in_seq += 1; + assign + } + }); + + let mut result = if is_struct { + let names = fields.iter().map(|f| &f.member); + quote! { + #type_path { #( #names: #vars ),* } + } + } else { + quote! { + #type_path ( #(#vars),* ) + } + }; + + if params.has_getter { + let this_type = ¶ms.this_type; + let (_, ty_generics, _) = params.generics.split_for_impl(); + result = quote! { + _serde::__private::Into::<#this_type #ty_generics>::into(#result) + }; + } + + let let_default = match cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: Self::Value = _serde::__private::Default::default(); + )), + attr::Default::Path(path) => Some(quote!( + let __default: Self::Value = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + quote_block! { + #let_default + #(#let_values)* + _serde::__private::Ok(#result) + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_seq_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + expecting: &str, +) -> Fragment { + let deserialized_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + let expecting = if deserialized_count == 1 { + format!("{} with 1 element", expecting) + } else { + format!("{} with {} elements", expecting, deserialized_count) + }; + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let mut index_in_seq = 0usize; + let write_values = fields.iter().map(|field| { + let member = &field.member; + + if field.attrs.skip_deserializing() { + let default = Expr(expr_is_missing(field, cattrs)); + quote! { + self.place.#member = #default; + } + } else { + let value_if_none = expr_is_missing_seq(Some(quote!(self.place.#member = )), index_in_seq, field, cattrs, expecting); + let write = match field.attrs.deserialize_with() { + None => { + quote! { + if let _serde::__private::None = _serde::de::SeqAccess::next_element_seed(&mut __seq, + _serde::__private::de::InPlaceSeed(&mut self.place.#member))? + { + #value_if_none; + } + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + match _serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)? { + _serde::__private::Some(__wrap) => { + self.place.#member = __wrap.value; + } + _serde::__private::None => { + #value_if_none; + } + } + }) + } + }; + index_in_seq += 1; + write + } + }); + + let this_type = ¶ms.this_type; + let (_, ty_generics, _) = params.generics.split_for_impl(); + let let_default = match cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: #this_type #ty_generics = _serde::__private::Default::default(); + )), + attr::Default::Path(path) => Some(quote!( + let __default: #this_type #ty_generics = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + quote_block! { + #let_default + #(#write_values)* + _serde::__private::Ok(()) + } +} + +fn deserialize_newtype_struct( + type_path: &TokenStream, + params: &Parameters, + field: &Field, +) -> TokenStream { + let delife = params.borrowed.de_lifetime(); + let field_ty = field.ty; + + let value = match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); + quote! { + #func(__e)? + } + } + Some(path) => { + quote! { + #path(__e)? + } + } + }; + + let mut result = quote!(#type_path(__field0)); + if params.has_getter { + let this_type = ¶ms.this_type; + let (_, ty_generics, _) = params.generics.split_for_impl(); + result = quote! { + _serde::__private::Into::<#this_type #ty_generics>::into(#result) + }; + } + + quote! { + #[inline] + fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::__private::Result + where + __E: _serde::Deserializer<#delife>, + { + let __field0: #field_ty = #value; + _serde::__private::Ok(#result) + } + } +} + +enum StructForm<'a> { + Struct, + /// Contains a variant name + ExternallyTagged(&'a syn::Ident), + /// Contains a variant name and an intermediate deserializer from which actual + /// deserialization will be performed + InternallyTagged(&'a syn::Ident, TokenStream), + /// Contains a variant name and an intermediate deserializer from which actual + /// deserialization will be performed + Untagged(&'a syn::Ident, TokenStream), +} + +fn deserialize_struct( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + form: StructForm, +) -> Fragment { + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + // If there are getters (implying private fields), construct the local type + // and use an `Into` conversion to get the remote type. If there are no + // getters then construct the target type directly. + let construct = if params.has_getter { + let local = ¶ms.local; + quote!(#local) + } else { + quote!(#this_value) + }; + + let type_path = match form { + StructForm::Struct => construct, + StructForm::ExternallyTagged(variant_ident) + | StructForm::InternallyTagged(variant_ident, _) + | StructForm::Untagged(variant_ident, _) => quote!(#construct::#variant_ident), + }; + let expecting = match form { + StructForm::Struct => format!("struct {}", params.type_name()), + StructForm::ExternallyTagged(variant_ident) + | StructForm::InternallyTagged(variant_ident, _) + | StructForm::Untagged(variant_ident, _) => { + format!("struct variant {}::{}", params.type_name(), variant_ident) + } + }; + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let field_names_idents: Vec<_> = fields + .iter() + .enumerate() + // Skip fields that shouldn't be deserialized or that were flattened, + // so they don't appear in the storage in their literal form + .filter(|&(_, field)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(i, field)| { + ( + field.attrs.name().deserialize_name(), + field_i(i), + field.attrs.aliases(), + ) + }) + .collect(); + + let has_flatten = has_flatten(fields); + let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs, has_flatten); + + // untagged struct variants do not get a visit_seq method. The same applies to + // structs that only have a map representation. + let visit_seq = match form { + StructForm::Untagged(..) => None, + _ if has_flatten => None, + _ => { + let mut_seq = if field_names_idents.is_empty() { + quote!(_) + } else { + quote!(mut __seq) + }; + + let visit_seq = Stmts(deserialize_seq( + &type_path, params, fields, true, cattrs, expecting, + )); + + Some(quote! { + #[inline] + fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::__private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + }) + } + }; + let visit_map = Stmts(deserialize_map( + &type_path, + params, + fields, + cattrs, + has_flatten, + )); + + let visitor_seed = match form { + StructForm::ExternallyTagged(..) if has_flatten => Some(quote! { + impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn deserialize<__D>(self, __deserializer: __D) -> _serde::__private::Result + where + __D: _serde::Deserializer<#delife>, + { + _serde::Deserializer::deserialize_map(__deserializer, self) + } + } + }), + _ => None, + }; + + let fields_stmt = if has_flatten { + None + } else { + let field_names = field_names_idents + .iter() + .flat_map(|&(_, _, aliases)| aliases); + + Some(quote! { + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; + }) + }; + + let visitor_expr = quote! { + __Visitor { + marker: _serde::__private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData, + } + }; + let dispatch = match form { + StructForm::Struct if has_flatten => quote! { + _serde::Deserializer::deserialize_map(__deserializer, #visitor_expr) + }, + StructForm::Struct => { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) + } + } + StructForm::ExternallyTagged(_) if has_flatten => quote! { + _serde::de::VariantAccess::newtype_variant_seed(__variant, #visitor_expr) + }, + StructForm::ExternallyTagged(_) => quote! { + _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) + }, + StructForm::InternallyTagged(_, deserializer) => quote! { + _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) + }, + StructForm::Untagged(_, deserializer) => quote! { + _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) + }, + }; + + quote_block! { + #field_visitor + + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + #visit_seq + + #[inline] + fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result + where + __A: _serde::de::MapAccess<#delife>, + { + #visit_map + } + } + + #visitor_seed + + #fields_stmt + + #dispatch + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_struct_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Option { + // for now we do not support in_place deserialization for structs that + // are represented as map. + if has_flatten(fields) { + return None; + } + + let this_type = ¶ms.this_type; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let expecting = format!("struct {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let field_names_idents: Vec<_> = fields + .iter() + .enumerate() + .filter(|&(_, field)| !field.attrs.skip_deserializing()) + .map(|(i, field)| { + ( + field.attrs.name().deserialize_name(), + field_i(i), + field.attrs.aliases(), + ) + }) + .collect(); + + let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs, false); + + let mut_seq = if field_names_idents.is_empty() { + quote!(_) + } else { + quote!(mut __seq) + }; + let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, expecting)); + let visit_map = Stmts(deserialize_map_in_place(params, fields, cattrs)); + let field_names = field_names_idents + .iter() + .flat_map(|&(_, _, aliases)| aliases); + let type_name = cattrs.name().deserialize_name(); + + let in_place_impl_generics = de_impl_generics.in_place(); + let in_place_ty_generics = de_ty_generics.in_place(); + let place_life = place_lifetime(); + + Some(quote_block! { + #field_visitor + + #[doc(hidden)] + struct __Visitor #in_place_impl_generics #where_clause { + place: &#place_life mut #this_type #ty_generics, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { + type Value = (); + + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + #[inline] + fn visit_seq<__A>(self, #mut_seq: __A) -> _serde::__private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + #visit_seq + } + + #[inline] + fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result + where + __A: _serde::de::MapAccess<#delife>, + { + #visit_map + } + } + + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; + + _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, __Visitor { + place: __place, + lifetime: _serde::__private::PhantomData, + }) + }) +} + +fn deserialize_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + // The variants have already been checked (in ast.rs) that all untagged variants appear at the end + match variants.iter().position(|var| var.attrs.untagged()) { + Some(variant_idx) => { + let (tagged, untagged) = variants.split_at(variant_idx); + let tagged_frag = Expr(deserialize_homogeneous_enum(params, tagged, cattrs)); + deserialize_untagged_enum_after(params, untagged, cattrs, Some(tagged_frag)) + } + None => deserialize_homogeneous_enum(params, variants, cattrs), + } +} + +fn deserialize_homogeneous_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + match cattrs.tag() { + attr::TagType::External => deserialize_externally_tagged_enum(params, variants, cattrs), + attr::TagType::Internal { tag } => { + deserialize_internally_tagged_enum(params, variants, cattrs, tag) + } + attr::TagType::Adjacent { tag, content } => { + deserialize_adjacently_tagged_enum(params, variants, cattrs, tag, content) + } + attr::TagType::None => deserialize_untagged_enum(params, variants, cattrs), + } +} + +fn prepare_enum_variant_enum(variants: &[Variant]) -> (TokenStream, Stmts) { + let mut deserialized_variants = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()); + + let variant_names_idents: Vec<_> = deserialized_variants + .clone() + .map(|(i, variant)| { + ( + variant.attrs.name().deserialize_name(), + field_i(i), + variant.attrs.aliases(), + ) + }) + .collect(); + + let fallthrough = deserialized_variants + .position(|(_, variant)| variant.attrs.other()) + .map(|other_idx| { + let ignore_variant = variant_names_idents[other_idx].1.clone(); + quote!(_serde::__private::Ok(__Field::#ignore_variant)) + }); + + let variants_stmt = { + let variant_names = variant_names_idents.iter().map(|(name, _, _)| name); + quote! { + #[doc(hidden)] + const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; + } + }; + + let variant_visitor = Stmts(deserialize_generated_identifier( + &variant_names_idents, + false, // variant identifiers do not depend on the presence of flatten fields + true, + None, + fallthrough, + )); + + (variants_stmt, variant_visitor) +} + +fn deserialize_externally_tagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let this_type = ¶ms.this_type; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let type_name = cattrs.name().deserialize_name(); + let expecting = format!("enum {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants); + + // Match arms to extract a variant from a string + let variant_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_name = field_i(i); + + let block = Match(deserialize_externally_tagged_variant( + params, variant, cattrs, + )); + + quote! { + (__Field::#variant_name, __variant) => #block + } + }); + + let all_skipped = variants + .iter() + .all(|variant| variant.attrs.skip_deserializing()); + let match_variant = if all_skipped { + // This is an empty enum like `enum Impossible {}` or an enum in which + // all variants have `#[serde(skip_deserializing)]`. + quote! { + // FIXME: Once feature(exhaustive_patterns) is stable: + // let _serde::__private::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data); + // _serde::__private::Err(__err) + _serde::__private::Result::map( + _serde::de::EnumAccess::variant::<__Field>(__data), + |(__impossible, _)| match __impossible {}) + } + } else { + quote! { + match _serde::de::EnumAccess::variant(__data)? { + #(#variant_arms)* + } + } + }; + + quote_block! { + #variant_visitor + + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + fn visit_enum<__A>(self, __data: __A) -> _serde::__private::Result + where + __A: _serde::de::EnumAccess<#delife>, + { + #match_variant + } + } + + #variants_stmt + + _serde::Deserializer::deserialize_enum( + __deserializer, + #type_name, + VARIANTS, + __Visitor { + marker: _serde::__private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData, + }, + ) + } +} + +fn deserialize_internally_tagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + tag: &str, +) -> Fragment { + let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants); + + // Match arms to extract a variant from a string + let variant_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_name = field_i(i); + + let block = Match(deserialize_internally_tagged_variant( + params, + variant, + cattrs, + quote!(__deserializer), + )); + + quote! { + __Field::#variant_name => #block + } + }); + + let expecting = format!("internally tagged enum {}", params.type_name()); + let expecting = cattrs.expecting().unwrap_or(&expecting); + + quote_block! { + #variant_visitor + + #variants_stmt + + let (__tag, __content) = _serde::Deserializer::deserialize_any( + __deserializer, + _serde::__private::de::TaggedContentVisitor::<__Field>::new(#tag, #expecting))?; + let __deserializer = _serde::__private::de::ContentDeserializer::<__D::Error>::new(__content); + + match __tag { + #(#variant_arms)* + } + } +} + +fn deserialize_adjacently_tagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + tag: &str, + content: &str, +) -> Fragment { + let this_type = ¶ms.this_type; + let this_value = ¶ms.this_value; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants); + + let variant_arms: &Vec<_> = &variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_index = field_i(i); + + let block = Match(deserialize_untagged_variant( + params, + variant, + cattrs, + quote!(__deserializer), + )); + + quote! { + __Field::#variant_index => #block + } + }) + .collect(); + + let rust_name = params.type_name(); + let expecting = format!("adjacently tagged enum {}", rust_name); + let expecting = cattrs.expecting().unwrap_or(&expecting); + let type_name = cattrs.name().deserialize_name(); + let deny_unknown_fields = cattrs.deny_unknown_fields(); + + // If unknown fields are allowed, we pick the visitor that can step over + // those. Otherwise we pick the visitor that fails on unknown keys. + let field_visitor_ty = if deny_unknown_fields { + quote! { _serde::__private::de::TagOrContentFieldVisitor } + } else { + quote! { _serde::__private::de::TagContentOtherFieldVisitor } + }; + + let tag_or_content = quote! { + #field_visitor_ty { + tag: #tag, + content: #content, + } + }; + + let variant_seed = quote! { + _serde::__private::de::AdjacentlyTaggedEnumVariantSeed::<__Field> { + enum_name: #rust_name, + variants: VARIANTS, + fields_enum: _serde::__private::PhantomData + } + }; + + let mut missing_content = quote! { + _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#content)) + }; + let mut missing_content_fallthrough = quote!(); + let missing_content_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .filter_map(|(i, variant)| { + let variant_index = field_i(i); + let variant_ident = &variant.ident; + + let arm = match variant.style { + Style::Unit => quote! { + _serde::__private::Ok(#this_value::#variant_ident) + }, + Style::Newtype if variant.attrs.deserialize_with().is_none() => { + let span = variant.original.span(); + let func = quote_spanned!(span=> _serde::__private::de::missing_field); + quote! { + #func(#content).map(#this_value::#variant_ident) + } + } + _ => { + missing_content_fallthrough = quote!(_ => #missing_content); + return None; + } + }; + Some(quote! { + __Field::#variant_index => #arm, + }) + }) + .collect::>(); + if !missing_content_arms.is_empty() { + missing_content = quote! { + match __field { + #(#missing_content_arms)* + #missing_content_fallthrough + } + }; + } + + // Advance the map by one key, returning early in case of error. + let next_key = quote! { + _serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)? + }; + + let variant_from_map = quote! { + _serde::de::MapAccess::next_value_seed(&mut __map, #variant_seed)? + }; + + // When allowing unknown fields, we want to transparently step through keys + // we don't care about until we find `tag`, `content`, or run out of keys. + let next_relevant_key = if deny_unknown_fields { + next_key + } else { + quote!({ + let mut __rk : _serde::__private::Option<_serde::__private::de::TagOrContentField> = _serde::__private::None; + while let _serde::__private::Some(__k) = #next_key { + match __k { + _serde::__private::de::TagContentOtherField::Other => { + let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; + continue; + }, + _serde::__private::de::TagContentOtherField::Tag => { + __rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag); + break; + } + _serde::__private::de::TagContentOtherField::Content => { + __rk = _serde::__private::Some(_serde::__private::de::TagOrContentField::Content); + break; + } + } + } + + __rk + }) + }; + + // Step through remaining keys, looking for duplicates of previously-seen + // keys. When unknown fields are denied, any key that isn't a duplicate will + // at this point immediately produce an error. + let visit_remaining_keys = quote! { + match #next_relevant_key { + _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { + _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) + } + _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { + _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) + } + _serde::__private::None => _serde::__private::Ok(__ret), + } + }; + + let finish_content_then_tag = if variant_arms.is_empty() { + quote! { + match #variant_from_map {} + } + } else { + quote! { + let __ret = match #variant_from_map { + // Deserialize the buffered content now that we know the variant. + #(#variant_arms)* + }?; + // Visit remaining keys, looking for duplicates. + #visit_remaining_keys + } + }; + + quote_block! { + #variant_visitor + + #variants_stmt + + #[doc(hidden)] + struct __Seed #de_impl_generics #where_clause { + field: __Field, + marker: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn deserialize<__D>(self, __deserializer: __D) -> _serde::__private::Result + where + __D: _serde::Deserializer<#delife>, + { + match self.field { + #(#variant_arms)* + } + } + } + + #[doc(hidden)] + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result + where + __A: _serde::de::MapAccess<#delife>, + { + // Visit the first relevant key. + match #next_relevant_key { + // First key is the tag. + _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { + // Parse the tag. + let __field = #variant_from_map; + // Visit the second key. + match #next_relevant_key { + // Second key is a duplicate of the tag. + _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { + _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) + } + // Second key is the content. + _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { + let __ret = _serde::de::MapAccess::next_value_seed(&mut __map, + __Seed { + field: __field, + marker: _serde::__private::PhantomData, + lifetime: _serde::__private::PhantomData, + })?; + // Visit remaining keys, looking for duplicates. + #visit_remaining_keys + } + // There is no second key; might be okay if the we have a unit variant. + _serde::__private::None => #missing_content + } + } + // First key is the content. + _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { + // Buffer up the content. + let __content = _serde::de::MapAccess::next_value::<_serde::__private::de::Content>(&mut __map)?; + // Visit the second key. + match #next_relevant_key { + // Second key is the tag. + _serde::__private::Some(_serde::__private::de::TagOrContentField::Tag) => { + let __deserializer = _serde::__private::de::ContentDeserializer::<__A::Error>::new(__content); + #finish_content_then_tag + } + // Second key is a duplicate of the content. + _serde::__private::Some(_serde::__private::de::TagOrContentField::Content) => { + _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) + } + // There is no second key. + _serde::__private::None => { + _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) + } + } + } + // There is no first key. + _serde::__private::None => { + _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) + } + } + } + + fn visit_seq<__A>(self, mut __seq: __A) -> _serde::__private::Result + where + __A: _serde::de::SeqAccess<#delife>, + { + // Visit the first element - the tag. + match _serde::de::SeqAccess::next_element(&mut __seq)? { + _serde::__private::Some(__field) => { + // Visit the second element - the content. + match _serde::de::SeqAccess::next_element_seed( + &mut __seq, + __Seed { + field: __field, + marker: _serde::__private::PhantomData, + lifetime: _serde::__private::PhantomData, + }, + )? { + _serde::__private::Some(__ret) => _serde::__private::Ok(__ret), + // There is no second element. + _serde::__private::None => { + _serde::__private::Err(_serde::de::Error::invalid_length(1, &self)) + } + } + } + // There is no first element. + _serde::__private::None => { + _serde::__private::Err(_serde::de::Error::invalid_length(0, &self)) + } + } + } + } + + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[#tag, #content]; + _serde::Deserializer::deserialize_struct( + __deserializer, + #type_name, + FIELDS, + __Visitor { + marker: _serde::__private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData, + }, + ) + } +} + +fn deserialize_untagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let first_attempt = None; + deserialize_untagged_enum_after(params, variants, cattrs, first_attempt) +} + +fn deserialize_untagged_enum_after( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + first_attempt: Option, +) -> Fragment { + let attempts = variants + .iter() + .filter(|variant| !variant.attrs.skip_deserializing()) + .map(|variant| { + Expr(deserialize_untagged_variant( + params, + variant, + cattrs, + quote!(__deserializer), + )) + }); + // TODO this message could be better by saving the errors from the failed + // attempts. The heuristic used by TOML was to count the number of fields + // processed before an error, and use the error that happened after the + // largest number of fields. I'm not sure I like that. Maybe it would be + // better to save all the errors and combine them into one message that + // explains why none of the variants matched. + let fallthrough_msg = format!( + "data did not match any variant of untagged enum {}", + params.type_name() + ); + let fallthrough_msg = cattrs.expecting().unwrap_or(&fallthrough_msg); + + // Ignore any error associated with non-untagged deserialization so that we + // can fall through to the untagged variants. This may be infallible so we + // need to provide the error type. + let first_attempt = first_attempt.map(|expr| { + quote! { + if let _serde::__private::Result::<_, __D::Error>::Ok(__ok) = (|| #expr)() { + return _serde::__private::Ok(__ok); + } + } + }); + + quote_block! { + let __content = <_serde::__private::de::Content as _serde::Deserialize>::deserialize(__deserializer)?; + let __deserializer = _serde::__private::de::ContentRefDeserializer::<__D::Error>::new(&__content); + + #first_attempt + + #( + if let _serde::__private::Ok(__ok) = #attempts { + return _serde::__private::Ok(__ok); + } + )* + + _serde::__private::Err(_serde::de::Error::custom(#fallthrough_msg)) + } +} + +fn deserialize_externally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, +) -> Fragment { + if let Some(path) = variant.attrs.deserialize_with() { + let (wrapper, wrapper_ty, unwrap_fn) = wrap_deserialize_variant_with(params, variant, path); + return quote_block! { + #wrapper + _serde::__private::Result::map( + _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn) + }; + } + + let variant_ident = &variant.ident; + + match variant.style { + Style::Unit => { + let this_value = ¶ms.this_value; + quote_block! { + _serde::de::VariantAccess::unit_variant(__variant)?; + _serde::__private::Ok(#this_value::#variant_ident) + } + } + Style::Newtype => deserialize_externally_tagged_newtype_variant( + variant_ident, + params, + &variant.fields[0], + cattrs, + ), + Style::Tuple => deserialize_tuple( + params, + &variant.fields, + cattrs, + TupleForm::ExternallyTagged(variant_ident), + ), + Style::Struct => deserialize_struct( + params, + &variant.fields, + cattrs, + StructForm::ExternallyTagged(variant_ident), + ), + } +} + +// Generates significant part of the visit_seq and visit_map bodies of visitors +// for the variants of internally tagged enum. +fn deserialize_internally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + deserializer: TokenStream, +) -> Fragment { + if variant.attrs.deserialize_with().is_some() { + return deserialize_untagged_variant(params, variant, cattrs, deserializer); + } + + let variant_ident = &variant.ident; + + match effective_style(variant) { + Style::Unit => { + let this_value = ¶ms.this_value; + let type_name = params.type_name(); + let variant_name = variant.ident.to_string(); + let default = variant.fields.first().map(|field| { + let default = Expr(expr_is_missing(field, cattrs)); + quote!((#default)) + }); + quote_block! { + _serde::Deserializer::deserialize_any(#deserializer, _serde::__private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))?; + _serde::__private::Ok(#this_value::#variant_ident #default) + } + } + Style::Newtype => deserialize_untagged_newtype_variant( + variant_ident, + params, + &variant.fields[0], + &deserializer, + ), + Style::Struct => deserialize_struct( + params, + &variant.fields, + cattrs, + StructForm::InternallyTagged(variant_ident, deserializer), + ), + Style::Tuple => unreachable!("checked in serde_derive_internals"), + } +} + +fn deserialize_untagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + deserializer: TokenStream, +) -> Fragment { + if let Some(path) = variant.attrs.deserialize_with() { + let unwrap_fn = unwrap_to_variant_closure(params, variant, false); + return quote_block! { + _serde::__private::Result::map(#path(#deserializer), #unwrap_fn) + }; + } + + let variant_ident = &variant.ident; + + match effective_style(variant) { + Style::Unit => { + let this_value = ¶ms.this_value; + let type_name = params.type_name(); + let variant_name = variant.ident.to_string(); + let default = variant.fields.first().map(|field| { + let default = Expr(expr_is_missing(field, cattrs)); + quote!((#default)) + }); + quote_expr! { + match _serde::Deserializer::deserialize_any( + #deserializer, + _serde::__private::de::UntaggedUnitVisitor::new(#type_name, #variant_name) + ) { + _serde::__private::Ok(()) => _serde::__private::Ok(#this_value::#variant_ident #default), + _serde::__private::Err(__err) => _serde::__private::Err(__err), + } + } + } + Style::Newtype => deserialize_untagged_newtype_variant( + variant_ident, + params, + &variant.fields[0], + &deserializer, + ), + Style::Tuple => deserialize_tuple( + params, + &variant.fields, + cattrs, + TupleForm::Untagged(variant_ident, deserializer), + ), + Style::Struct => deserialize_struct( + params, + &variant.fields, + cattrs, + StructForm::Untagged(variant_ident, deserializer), + ), + } +} + +fn deserialize_externally_tagged_newtype_variant( + variant_ident: &syn::Ident, + params: &Parameters, + field: &Field, + cattrs: &attr::Container, +) -> Fragment { + let this_value = ¶ms.this_value; + + if field.attrs.skip_deserializing() { + let default = Expr(expr_is_missing(field, cattrs)); + return quote_block! { + _serde::de::VariantAccess::unit_variant(__variant)?; + _serde::__private::Ok(#this_value::#variant_ident(#default)) + }; + } + + match field.attrs.deserialize_with() { + None => { + let field_ty = field.ty; + let span = field.original.span(); + let func = + quote_spanned!(span=> _serde::de::VariantAccess::newtype_variant::<#field_ty>); + quote_expr! { + _serde::__private::Result::map(#func(__variant), #this_value::#variant_ident) + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote_block! { + #wrapper + _serde::__private::Result::map( + _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), + |__wrapper| #this_value::#variant_ident(__wrapper.value)) + } + } + } +} + +fn deserialize_untagged_newtype_variant( + variant_ident: &syn::Ident, + params: &Parameters, + field: &Field, + deserializer: &TokenStream, +) -> Fragment { + let this_value = ¶ms.this_value; + let field_ty = field.ty; + match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize); + quote_expr! { + _serde::__private::Result::map(#func(#deserializer), #this_value::#variant_ident) + } + } + Some(path) => { + quote_block! { + let __value: _serde::__private::Result<#field_ty, _> = #path(#deserializer); + _serde::__private::Result::map(__value, #this_value::#variant_ident) + } + } + } +} + +fn deserialize_generated_identifier( + fields: &[(&str, Ident, &BTreeSet)], + has_flatten: bool, + is_variant: bool, + ignore_variant: Option, + fallthrough: Option, +) -> Fragment { + let this_value = quote!(__Field); + let field_idents: &Vec<_> = &fields.iter().map(|(_, ident, _)| ident).collect(); + + let visitor_impl = Stmts(deserialize_identifier( + &this_value, + fields, + is_variant, + fallthrough, + None, + !is_variant && has_flatten, + None, + )); + + let lifetime = if !is_variant && has_flatten { + Some(quote!(<'de>)) + } else { + None + }; + + quote_block! { + #[allow(non_camel_case_types)] + #[doc(hidden)] + enum __Field #lifetime { + #(#field_idents,)* + #ignore_variant + } + + #[doc(hidden)] + struct __FieldVisitor; + + impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { + type Value = __Field #lifetime; + + #visitor_impl + } + + impl<'de> _serde::Deserialize<'de> for __Field #lifetime { + #[inline] + fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result + where + __D: _serde::Deserializer<'de>, + { + _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor) + } + } + } +} + +/// Generates enum and its `Deserialize` implementation that represents each +/// non-skipped field of the struct +fn deserialize_field_identifier( + fields: &[(&str, Ident, &BTreeSet)], + cattrs: &attr::Container, + has_flatten: bool, +) -> Stmts { + let (ignore_variant, fallthrough) = if has_flatten { + let ignore_variant = quote!(__other(_serde::__private::de::Content<'de>),); + let fallthrough = quote!(_serde::__private::Ok(__Field::__other(__value))); + (Some(ignore_variant), Some(fallthrough)) + } else if cattrs.deny_unknown_fields() { + (None, None) + } else { + let ignore_variant = quote!(__ignore,); + let fallthrough = quote!(_serde::__private::Ok(__Field::__ignore)); + (Some(ignore_variant), Some(fallthrough)) + }; + + Stmts(deserialize_generated_identifier( + fields, + has_flatten, + false, + ignore_variant, + fallthrough, + )) +} + +// Generates `Deserialize::deserialize` body for an enum with +// `serde(field_identifier)` or `serde(variant_identifier)` attribute. +fn deserialize_custom_identifier( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let is_variant = match cattrs.identifier() { + attr::Identifier::Variant => true, + attr::Identifier::Field => false, + attr::Identifier::No => unreachable!(), + }; + + let this_type = params.this_type.to_token_stream(); + let this_value = params.this_value.to_token_stream(); + + let (ordinary, fallthrough, fallthrough_borrowed) = if let Some(last) = variants.last() { + let last_ident = &last.ident; + if last.attrs.other() { + // Process `serde(other)` attribute. It would always be found on the + // last variant (checked in `check_identifier`), so all preceding + // are ordinary variants. + let ordinary = &variants[..variants.len() - 1]; + let fallthrough = quote!(_serde::__private::Ok(#this_value::#last_ident)); + (ordinary, Some(fallthrough), None) + } else if let Style::Newtype = last.style { + let ordinary = &variants[..variants.len() - 1]; + let fallthrough = |value| { + quote! { + _serde::__private::Result::map( + _serde::Deserialize::deserialize( + _serde::__private::de::IdentifierDeserializer::from(#value) + ), + #this_value::#last_ident) + } + }; + ( + ordinary, + Some(fallthrough(quote!(__value))), + Some(fallthrough(quote!(_serde::__private::de::Borrowed( + __value + )))), + ) + } else { + (variants, None, None) + } + } else { + (variants, None, None) + }; + + let names_idents: Vec<_> = ordinary + .iter() + .map(|variant| { + ( + variant.attrs.name().deserialize_name(), + variant.ident.clone(), + variant.attrs.aliases(), + ) + }) + .collect(); + + let names = names_idents.iter().flat_map(|&(_, _, aliases)| aliases); + + let names_const = if fallthrough.is_some() { + None + } else if is_variant { + let variants = quote! { + #[doc(hidden)] + const VARIANTS: &'static [&'static str] = &[ #(#names),* ]; + }; + Some(variants) + } else { + let fields = quote! { + #[doc(hidden)] + const FIELDS: &'static [&'static str] = &[ #(#names),* ]; + }; + Some(fields) + }; + + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + let visitor_impl = Stmts(deserialize_identifier( + &this_value, + &names_idents, + is_variant, + fallthrough, + fallthrough_borrowed, + false, + cattrs.expecting(), + )); + + quote_block! { + #names_const + + #[doc(hidden)] + struct __FieldVisitor #de_impl_generics #where_clause { + marker: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause { + type Value = #this_type #ty_generics; + + #visitor_impl + } + + let __visitor = __FieldVisitor { + marker: _serde::__private::PhantomData::<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData, + }; + _serde::Deserializer::deserialize_identifier(__deserializer, __visitor) + } +} + +fn deserialize_identifier( + this_value: &TokenStream, + fields: &[(&str, Ident, &BTreeSet)], + is_variant: bool, + fallthrough: Option, + fallthrough_borrowed: Option, + collect_other_fields: bool, + expecting: Option<&str>, +) -> Fragment { + let str_mapping = fields.iter().map(|(_, ident, aliases)| { + // `aliases` also contains a main name + quote!(#(#aliases)|* => _serde::__private::Ok(#this_value::#ident)) + }); + let bytes_mapping = fields.iter().map(|(_, ident, aliases)| { + // `aliases` also contains a main name + let aliases = aliases + .iter() + .map(|alias| Literal::byte_string(alias.as_bytes())); + quote!(#(#aliases)|* => _serde::__private::Ok(#this_value::#ident)) + }); + + let expecting = expecting.unwrap_or(if is_variant { + "variant identifier" + } else { + "field identifier" + }); + + let bytes_to_str = if fallthrough.is_some() || collect_other_fields { + None + } else { + Some(quote! { + let __value = &_serde::__private::from_utf8_lossy(__value); + }) + }; + + let ( + value_as_str_content, + value_as_borrowed_str_content, + value_as_bytes_content, + value_as_borrowed_bytes_content, + ) = if collect_other_fields { + ( + Some(quote! { + let __value = _serde::__private::de::Content::String(_serde::__private::ToString::to_string(__value)); + }), + Some(quote! { + let __value = _serde::__private::de::Content::Str(__value); + }), + Some(quote! { + let __value = _serde::__private::de::Content::ByteBuf(__value.to_vec()); + }), + Some(quote! { + let __value = _serde::__private::de::Content::Bytes(__value); + }), + ) + } else { + (None, None, None, None) + }; + + let fallthrough_arm_tokens; + let fallthrough_arm = if let Some(fallthrough) = &fallthrough { + fallthrough + } else if is_variant { + fallthrough_arm_tokens = quote! { + _serde::__private::Err(_serde::de::Error::unknown_variant(__value, VARIANTS)) + }; + &fallthrough_arm_tokens + } else { + fallthrough_arm_tokens = quote! { + _serde::__private::Err(_serde::de::Error::unknown_field(__value, FIELDS)) + }; + &fallthrough_arm_tokens + }; + + let visit_other = if collect_other_fields { + quote! { + fn visit_bool<__E>(self, __value: bool) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Bool(__value))) + } + + fn visit_i8<__E>(self, __value: i8) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I8(__value))) + } + + fn visit_i16<__E>(self, __value: i16) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I16(__value))) + } + + fn visit_i32<__E>(self, __value: i32) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I32(__value))) + } + + fn visit_i64<__E>(self, __value: i64) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::I64(__value))) + } + + fn visit_u8<__E>(self, __value: u8) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U8(__value))) + } + + fn visit_u16<__E>(self, __value: u16) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U16(__value))) + } + + fn visit_u32<__E>(self, __value: u32) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U32(__value))) + } + + fn visit_u64<__E>(self, __value: u64) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::U64(__value))) + } + + fn visit_f32<__E>(self, __value: f32) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::F32(__value))) + } + + fn visit_f64<__E>(self, __value: f64) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::F64(__value))) + } + + fn visit_char<__E>(self, __value: char) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Char(__value))) + } + + fn visit_unit<__E>(self) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + _serde::__private::Ok(__Field::__other(_serde::__private::de::Content::Unit)) + } + } + } else { + let u64_mapping = fields.iter().enumerate().map(|(i, (_, ident, _))| { + let i = i as u64; + quote!(#i => _serde::__private::Ok(#this_value::#ident)) + }); + + let u64_fallthrough_arm_tokens; + let u64_fallthrough_arm = if let Some(fallthrough) = &fallthrough { + fallthrough + } else { + let index_expecting = if is_variant { "variant" } else { "field" }; + let fallthrough_msg = format!("{} index 0 <= i < {}", index_expecting, fields.len()); + u64_fallthrough_arm_tokens = quote! { + _serde::__private::Err(_serde::de::Error::invalid_value( + _serde::de::Unexpected::Unsigned(__value), + &#fallthrough_msg, + )) + }; + &u64_fallthrough_arm_tokens + }; + + quote! { + fn visit_u64<__E>(self, __value: u64) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#u64_mapping,)* + _ => #u64_fallthrough_arm, + } + } + } + }; + + let visit_borrowed = if fallthrough_borrowed.is_some() || collect_other_fields { + let str_mapping = str_mapping.clone(); + let bytes_mapping = bytes_mapping.clone(); + let fallthrough_borrowed_arm = fallthrough_borrowed.as_ref().unwrap_or(fallthrough_arm); + Some(quote! { + fn visit_borrowed_str<__E>(self, __value: &'de str) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#str_mapping,)* + _ => { + #value_as_borrowed_str_content + #fallthrough_borrowed_arm + } + } + } + + fn visit_borrowed_bytes<__E>(self, __value: &'de [u8]) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#bytes_mapping,)* + _ => { + #bytes_to_str + #value_as_borrowed_bytes_content + #fallthrough_borrowed_arm + } + } + } + }) + } else { + None + }; + + quote_block! { + fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result { + _serde::__private::Formatter::write_str(__formatter, #expecting) + } + + #visit_other + + fn visit_str<__E>(self, __value: &str) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#str_mapping,)* + _ => { + #value_as_str_content + #fallthrough_arm + } + } + } + + fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::__private::Result + where + __E: _serde::de::Error, + { + match __value { + #(#bytes_mapping,)* + _ => { + #bytes_to_str + #value_as_bytes_content + #fallthrough_arm + } + } + } + + #visit_borrowed + } +} + +fn deserialize_map( + struct_path: &TokenStream, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + has_flatten: bool, +) -> Fragment { + // Create the field names for the fields. + let fields_names: Vec<_> = fields + .iter() + .enumerate() + .map(|(i, field)| (field, field_i(i))) + .collect(); + + // Declare each field that will be deserialized. + let let_values = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(field, name)| { + let field_ty = field.ty; + quote! { + let mut #name: _serde::__private::Option<#field_ty> = _serde::__private::None; + } + }); + + // Collect contents for flatten fields into a buffer + let let_collect = if has_flatten { + Some(quote! { + let mut __collect = _serde::__private::Vec::<_serde::__private::Option<( + _serde::__private::de::Content, + _serde::__private::de::Content + )>>::new(); + }) + } else { + None + }; + + // Match arms to extract a value for a field. + let value_arms = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(field, name)| { + let deser_name = field.attrs.name().deserialize_name(); + + let visit = match field.attrs.deserialize_with() { + None => { + let field_ty = field.ty; + let span = field.original.span(); + let func = + quote_spanned!(span=> _serde::de::MapAccess::next_value::<#field_ty>); + quote! { + #func(&mut __map)? + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { + _serde::__private::Ok(__wrapper) => __wrapper.value, + _serde::__private::Err(__err) => { + return _serde::__private::Err(__err); + } + } + }) + } + }; + quote! { + __Field::#name => { + if _serde::__private::Option::is_some(&#name) { + return _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); + } + #name = _serde::__private::Some(#visit); + } + } + }); + + // Visit ignored values to consume them + let ignored_arm = if has_flatten { + Some(quote! { + __Field::__other(__name) => { + __collect.push(_serde::__private::Some(( + __name, + _serde::de::MapAccess::next_value(&mut __map)?))); + } + }) + } else if cattrs.deny_unknown_fields() { + None + } else { + Some(quote! { + _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } + }) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + let match_keys = if cattrs.deny_unknown_fields() && all_skipped { + quote! { + // FIXME: Once feature(exhaustive_patterns) is stable: + // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; + _serde::__private::Option::map( + _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, + |__impossible| match __impossible {}); + } + } else { + quote! { + while let _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { + match __key { + #(#value_arms)* + #ignored_arm + } + } + } + }; + + let extract_values = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(field, name)| { + let missing_expr = Match(expr_is_missing(field, cattrs)); + + quote! { + let #name = match #name { + _serde::__private::Some(#name) => #name, + _serde::__private::None => #missing_expr + }; + } + }); + + let extract_collected = fields_names + .iter() + .filter(|&&(field, _)| field.attrs.flatten() && !field.attrs.skip_deserializing()) + .map(|(field, name)| { + let field_ty = field.ty; + let func = match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + quote_spanned!(span=> _serde::de::Deserialize::deserialize) + } + Some(path) => quote!(#path), + }; + quote! { + let #name: #field_ty = #func( + _serde::__private::de::FlatMapDeserializer( + &mut __collect, + _serde::__private::PhantomData))?; + } + }); + + let collected_deny_unknown_fields = if has_flatten && cattrs.deny_unknown_fields() { + Some(quote! { + if let _serde::__private::Some(_serde::__private::Some((__key, _))) = + __collect.into_iter().filter(_serde::__private::Option::is_some).next() + { + if let _serde::__private::Some(__key) = __key.as_str() { + return _serde::__private::Err( + _serde::de::Error::custom(format_args!("unknown field `{}`", &__key))); + } else { + return _serde::__private::Err( + _serde::de::Error::custom(format_args!("unexpected map key"))); + } + } + }) + } else { + None + }; + + let result = fields_names.iter().map(|(field, name)| { + let member = &field.member; + if field.attrs.skip_deserializing() { + let value = Expr(expr_is_missing(field, cattrs)); + quote!(#member: #value) + } else { + quote!(#member: #name) + } + }); + + let let_default = match cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: Self::Value = _serde::__private::Default::default(); + )), + attr::Default::Path(path) => Some(quote!( + let __default: Self::Value = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + let mut result = quote!(#struct_path { #(#result),* }); + if params.has_getter { + let this_type = ¶ms.this_type; + let (_, ty_generics, _) = params.generics.split_for_impl(); + result = quote! { + _serde::__private::Into::<#this_type #ty_generics>::into(#result) + }; + } + + quote_block! { + #(#let_values)* + + #let_collect + + #match_keys + + #let_default + + #(#extract_values)* + + #(#extract_collected)* + + #collected_deny_unknown_fields + + _serde::__private::Ok(#result) + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_map_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + assert!( + !has_flatten(fields), + "inplace deserialization of maps does not support flatten fields" + ); + + // Create the field names for the fields. + let fields_names: Vec<_> = fields + .iter() + .enumerate() + .map(|(i, field)| (field, field_i(i))) + .collect(); + + // For deserialize_in_place, declare booleans for each field that will be + // deserialized. + let let_flags = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|(_, name)| { + quote! { + let mut #name: bool = false; + } + }); + + // Match arms to extract a value for a field. + let value_arms_from = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|(field, name)| { + let deser_name = field.attrs.name().deserialize_name(); + let member = &field.member; + + let visit = match field.attrs.deserialize_with() { + None => { + quote! { + _serde::de::MapAccess::next_value_seed(&mut __map, _serde::__private::de::InPlaceSeed(&mut self.place.#member))? + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + self.place.#member = match _serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map) { + _serde::__private::Ok(__wrapper) => __wrapper.value, + _serde::__private::Err(__err) => { + return _serde::__private::Err(__err); + } + }; + }) + } + }; + quote! { + __Field::#name => { + if #name { + return _serde::__private::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); + } + #visit; + #name = true; + } + } + }); + + // Visit ignored values to consume them + let ignored_arm = if cattrs.deny_unknown_fields() { + None + } else { + Some(quote! { + _ => { let _ = _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?; } + }) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + + let match_keys = if cattrs.deny_unknown_fields() && all_skipped { + quote! { + // FIXME: Once feature(exhaustive_patterns) is stable: + // let _serde::__private::None::<__Field> = _serde::de::MapAccess::next_key(&mut __map)?; + _serde::__private::Option::map( + _serde::de::MapAccess::next_key::<__Field>(&mut __map)?, + |__impossible| match __impossible {}); + } + } else { + quote! { + while let _serde::__private::Some(__key) = _serde::de::MapAccess::next_key::<__Field>(&mut __map)? { + match __key { + #(#value_arms_from)* + #ignored_arm + } + } + } + }; + + let check_flags = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|(field, name)| { + let missing_expr = expr_is_missing(field, cattrs); + // If missing_expr unconditionally returns an error, don't try + // to assign its value to self.place. + if field.attrs.default().is_none() + && cattrs.default().is_none() + && field.attrs.deserialize_with().is_some() + { + let missing_expr = Stmts(missing_expr); + quote! { + if !#name { + #missing_expr; + } + } + } else { + let member = &field.member; + let missing_expr = Expr(missing_expr); + quote! { + if !#name { + self.place.#member = #missing_expr; + }; + } + } + }); + + let this_type = ¶ms.this_type; + let (_, _, ty_generics, _) = split_with_de_lifetime(params); + + let let_default = match cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: #this_type #ty_generics = _serde::__private::Default::default(); + )), + attr::Default::Path(path) => Some(quote!( + let __default: #this_type #ty_generics = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + quote_block! { + #(#let_flags)* + + #match_keys + + #let_default + + #(#check_flags)* + + _serde::__private::Ok(()) + } +} + +fn field_i(i: usize) -> Ident { + Ident::new(&format!("__field{}", i), Span::call_site()) +} + +/// This function wraps the expression in `#[serde(deserialize_with = "...")]` +/// in a trait to prevent it from accessing the internal `Deserialize` state. +fn wrap_deserialize_with( + params: &Parameters, + value_ty: &TokenStream, + deserialize_with: &syn::ExprPath, +) -> (TokenStream, TokenStream) { + let this_type = ¶ms.this_type; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let wrapper = quote! { + #[doc(hidden)] + struct __DeserializeWith #de_impl_generics #where_clause { + value: #value_ty, + phantom: _serde::__private::PhantomData<#this_type #ty_generics>, + lifetime: _serde::__private::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause { + fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result + where + __D: _serde::Deserializer<#delife>, + { + _serde::__private::Ok(__DeserializeWith { + value: #deserialize_with(__deserializer)?, + phantom: _serde::__private::PhantomData, + lifetime: _serde::__private::PhantomData, + }) + } + } + }; + + let wrapper_ty = quote!(__DeserializeWith #de_ty_generics); + + (wrapper, wrapper_ty) +} + +fn wrap_deserialize_field_with( + params: &Parameters, + field_ty: &syn::Type, + deserialize_with: &syn::ExprPath, +) -> (TokenStream, TokenStream) { + wrap_deserialize_with(params, "e!(#field_ty), deserialize_with) +} + +fn wrap_deserialize_variant_with( + params: &Parameters, + variant: &Variant, + deserialize_with: &syn::ExprPath, +) -> (TokenStream, TokenStream, TokenStream) { + let field_tys = variant.fields.iter().map(|field| field.ty); + let (wrapper, wrapper_ty) = + wrap_deserialize_with(params, "e!((#(#field_tys),*)), deserialize_with); + + let unwrap_fn = unwrap_to_variant_closure(params, variant, true); + + (wrapper, wrapper_ty, unwrap_fn) +} + +// Generates closure that converts single input parameter to the final value. +fn unwrap_to_variant_closure( + params: &Parameters, + variant: &Variant, + with_wrapper: bool, +) -> TokenStream { + let this_value = ¶ms.this_value; + let variant_ident = &variant.ident; + + let (arg, wrapper) = if with_wrapper { + (quote! { __wrap }, quote! { __wrap.value }) + } else { + let field_tys = variant.fields.iter().map(|field| field.ty); + (quote! { __wrap: (#(#field_tys),*) }, quote! { __wrap }) + }; + + let field_access = (0..variant.fields.len()).map(|n| { + Member::Unnamed(Index { + index: n as u32, + span: Span::call_site(), + }) + }); + + match variant.style { + Style::Struct if variant.fields.len() == 1 => { + let member = &variant.fields[0].member; + quote! { + |#arg| #this_value::#variant_ident { #member: #wrapper } + } + } + Style::Struct => { + let members = variant.fields.iter().map(|field| &field.member); + quote! { + |#arg| #this_value::#variant_ident { #(#members: #wrapper.#field_access),* } + } + } + Style::Tuple => quote! { + |#arg| #this_value::#variant_ident(#(#wrapper.#field_access),*) + }, + Style::Newtype => quote! { + |#arg| #this_value::#variant_ident(#wrapper) + }, + Style::Unit => quote! { + |#arg| #this_value::#variant_ident + }, + } +} + +fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { + match field.attrs.default() { + attr::Default::Default => { + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::__private::Default::default); + return quote_expr!(#func()); + } + attr::Default::Path(path) => { + return quote_expr!(#path()); + } + attr::Default::None => { /* below */ } + } + + match *cattrs.default() { + attr::Default::Default | attr::Default::Path(_) => { + let member = &field.member; + return quote_expr!(__default.#member); + } + attr::Default::None => { /* below */ } + } + + let name = field.attrs.name().deserialize_name(); + match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::__private::de::missing_field); + quote_expr! { + #func(#name)? + } + } + Some(_) => { + quote_expr! { + return _serde::__private::Err(<__A::Error as _serde::de::Error>::missing_field(#name)) + } + } + } +} + +fn expr_is_missing_seq( + assign_to: Option, + index: usize, + field: &Field, + cattrs: &attr::Container, + expecting: &str, +) -> TokenStream { + match field.attrs.default() { + attr::Default::Default => { + let span = field.original.span(); + return quote_spanned!(span=> #assign_to _serde::__private::Default::default()); + } + attr::Default::Path(path) => { + return quote_spanned!(path.span()=> #assign_to #path()); + } + attr::Default::None => { /* below */ } + } + + match *cattrs.default() { + attr::Default::Default | attr::Default::Path(_) => { + let member = &field.member; + quote!(#assign_to __default.#member) + } + attr::Default::None => quote!( + return _serde::__private::Err(_serde::de::Error::invalid_length(#index, &#expecting)) + ), + } +} + +fn effective_style(variant: &Variant) -> Style { + match variant.style { + Style::Newtype if variant.fields[0].attrs.skip_deserializing() => Style::Unit, + other => other, + } +} + +/// True if there is any field with a `#[serde(flatten)]` attribute, other than +/// fields which are skipped. +fn has_flatten(fields: &[Field]) -> bool { + fields + .iter() + .any(|field| field.attrs.flatten() && !field.attrs.skip_deserializing()) +} + +struct DeImplGenerics<'a>(&'a Parameters); +#[cfg(feature = "deserialize_in_place")] +struct InPlaceImplGenerics<'a>(&'a Parameters); + +impl<'a> ToTokens for DeImplGenerics<'a> { + fn to_tokens(&self, tokens: &mut TokenStream) { + let mut generics = self.0.generics.clone(); + if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() { + generics.params = Some(syn::GenericParam::Lifetime(de_lifetime)) + .into_iter() + .chain(generics.params) + .collect(); + } + let (impl_generics, _, _) = generics.split_for_impl(); + impl_generics.to_tokens(tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> ToTokens for InPlaceImplGenerics<'a> { + fn to_tokens(&self, tokens: &mut TokenStream) { + let place_lifetime = place_lifetime(); + let mut generics = self.0.generics.clone(); + + // Add lifetime for `&'place mut Self, and `'a: 'place` + for param in &mut generics.params { + match param { + syn::GenericParam::Lifetime(param) => { + param.bounds.push(place_lifetime.lifetime.clone()); + } + syn::GenericParam::Type(param) => { + param.bounds.push(syn::TypeParamBound::Lifetime( + place_lifetime.lifetime.clone(), + )); + } + syn::GenericParam::Const(_) => {} + } + } + generics.params = Some(syn::GenericParam::Lifetime(place_lifetime)) + .into_iter() + .chain(generics.params) + .collect(); + if let Some(de_lifetime) = self.0.borrowed.de_lifetime_param() { + generics.params = Some(syn::GenericParam::Lifetime(de_lifetime)) + .into_iter() + .chain(generics.params) + .collect(); + } + let (impl_generics, _, _) = generics.split_for_impl(); + impl_generics.to_tokens(tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> DeImplGenerics<'a> { + fn in_place(self) -> InPlaceImplGenerics<'a> { + InPlaceImplGenerics(self.0) + } +} + +struct DeTypeGenerics<'a>(&'a Parameters); +#[cfg(feature = "deserialize_in_place")] +struct InPlaceTypeGenerics<'a>(&'a Parameters); + +fn de_type_generics_to_tokens( + mut generics: syn::Generics, + borrowed: &BorrowedLifetimes, + tokens: &mut TokenStream, +) { + if borrowed.de_lifetime_param().is_some() { + let def = syn::LifetimeParam { + attrs: Vec::new(), + lifetime: syn::Lifetime::new("'de", Span::call_site()), + colon_token: None, + bounds: Punctuated::new(), + }; + // Prepend 'de lifetime to list of generics + generics.params = Some(syn::GenericParam::Lifetime(def)) + .into_iter() + .chain(generics.params) + .collect(); + } + let (_, ty_generics, _) = generics.split_for_impl(); + ty_generics.to_tokens(tokens); +} + +impl<'a> ToTokens for DeTypeGenerics<'a> { + fn to_tokens(&self, tokens: &mut TokenStream) { + de_type_generics_to_tokens(self.0.generics.clone(), &self.0.borrowed, tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> ToTokens for InPlaceTypeGenerics<'a> { + fn to_tokens(&self, tokens: &mut TokenStream) { + let mut generics = self.0.generics.clone(); + generics.params = Some(syn::GenericParam::Lifetime(place_lifetime())) + .into_iter() + .chain(generics.params) + .collect(); + + de_type_generics_to_tokens(generics, &self.0.borrowed, tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> DeTypeGenerics<'a> { + fn in_place(self) -> InPlaceTypeGenerics<'a> { + InPlaceTypeGenerics(self.0) + } +} + +#[cfg(feature = "deserialize_in_place")] +fn place_lifetime() -> syn::LifetimeParam { + syn::LifetimeParam { + attrs: Vec::new(), + lifetime: syn::Lifetime::new("'place", Span::call_site()), + colon_token: None, + bounds: Punctuated::new(), + } +} + +fn split_with_de_lifetime( + params: &Parameters, +) -> ( + DeImplGenerics, + DeTypeGenerics, + syn::TypeGenerics, + Option<&syn::WhereClause>, +) { + let de_impl_generics = DeImplGenerics(params); + let de_ty_generics = DeTypeGenerics(params); + let (_, ty_generics, where_clause) = params.generics.split_for_impl(); + (de_impl_generics, de_ty_generics, ty_generics, where_clause) +} diff --git a/bitbox02-bt/vendor/serde_derive/src/dummy.rs b/bitbox02-bt/vendor/serde_derive/src/dummy.rs new file mode 100644 index 0000000..095f950 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/dummy.rs @@ -0,0 +1,23 @@ +use proc_macro2::TokenStream; +use quote::quote; + +pub fn wrap_in_const(serde_path: Option<&syn::Path>, code: TokenStream) -> TokenStream { + let use_serde = match serde_path { + Some(path) => quote! { + use #path as _serde; + }, + None => quote! { + #[allow(unused_extern_crates, clippy::useless_attribute)] + extern crate serde as _serde; + }, + }; + + quote! { + #[doc(hidden)] + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const _: () = { + #use_serde + #code + }; + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/fragment.rs b/bitbox02-bt/vendor/serde_derive/src/fragment.rs new file mode 100644 index 0000000..6627c26 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/fragment.rs @@ -0,0 +1,74 @@ +use proc_macro2::TokenStream; +use quote::ToTokens; +use syn::{token, Token}; + +pub enum Fragment { + /// Tokens that can be used as an expression. + Expr(TokenStream), + /// Tokens that can be used inside a block. The surrounding curly braces are + /// not part of these tokens. + Block(TokenStream), +} + +macro_rules! quote_expr { + ($($tt:tt)*) => { + $crate::fragment::Fragment::Expr(quote!($($tt)*)) + } +} + +macro_rules! quote_block { + ($($tt:tt)*) => { + $crate::fragment::Fragment::Block(quote!($($tt)*)) + } +} + +/// Interpolate a fragment in place of an expression. This involves surrounding +/// Block fragments in curly braces. +pub struct Expr(pub Fragment); +impl ToTokens for Expr { + fn to_tokens(&self, out: &mut TokenStream) { + match &self.0 { + Fragment::Expr(expr) => expr.to_tokens(out), + Fragment::Block(block) => { + token::Brace::default().surround(out, |out| block.to_tokens(out)); + } + } + } +} + +/// Interpolate a fragment as the statements of a block. +pub struct Stmts(pub Fragment); +impl ToTokens for Stmts { + fn to_tokens(&self, out: &mut TokenStream) { + match &self.0 { + Fragment::Expr(expr) => expr.to_tokens(out), + Fragment::Block(block) => block.to_tokens(out), + } + } +} + +/// Interpolate a fragment as the value part of a `match` expression. This +/// involves putting a comma after expressions and curly braces around blocks. +pub struct Match(pub Fragment); +impl ToTokens for Match { + fn to_tokens(&self, out: &mut TokenStream) { + match &self.0 { + Fragment::Expr(expr) => { + expr.to_tokens(out); + ::default().to_tokens(out); + } + Fragment::Block(block) => { + token::Brace::default().surround(out, |out| block.to_tokens(out)); + } + } + } +} + +impl AsRef for Fragment { + fn as_ref(&self) -> &TokenStream { + match self { + Fragment::Expr(expr) => expr, + Fragment::Block(block) => block, + } + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/ast.rs b/bitbox02-bt/vendor/serde_derive/src/internals/ast.rs new file mode 100644 index 0000000..3293823 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/ast.rs @@ -0,0 +1,205 @@ +//! A Serde ast, parsed from the Syn ast and ready to generate Rust code. + +use crate::internals::{attr, check, Ctxt, Derive}; +use syn::punctuated::Punctuated; +use syn::Token; + +/// A source data structure annotated with `#[derive(Serialize)]` and/or `#[derive(Deserialize)]`, +/// parsed into an internal representation. +pub struct Container<'a> { + /// The struct or enum name (without generics). + pub ident: syn::Ident, + /// Attributes on the structure, parsed for Serde. + pub attrs: attr::Container, + /// The contents of the struct or enum. + pub data: Data<'a>, + /// Any generics on the struct or enum. + pub generics: &'a syn::Generics, + /// Original input. + pub original: &'a syn::DeriveInput, +} + +/// The fields of a struct or enum. +/// +/// Analogous to `syn::Data`. +pub enum Data<'a> { + Enum(Vec>), + Struct(Style, Vec>), +} + +/// A variant of an enum. +pub struct Variant<'a> { + pub ident: syn::Ident, + pub attrs: attr::Variant, + pub style: Style, + pub fields: Vec>, + pub original: &'a syn::Variant, +} + +/// A field of a struct. +pub struct Field<'a> { + pub member: syn::Member, + pub attrs: attr::Field, + pub ty: &'a syn::Type, + pub original: &'a syn::Field, +} + +#[derive(Copy, Clone)] +pub enum Style { + /// Named fields. + Struct, + /// Many unnamed fields. + Tuple, + /// One unnamed field. + Newtype, + /// No fields. + Unit, +} + +impl<'a> Container<'a> { + /// Convert the raw Syn ast into a parsed container object, collecting errors in `cx`. + pub fn from_ast( + cx: &Ctxt, + item: &'a syn::DeriveInput, + derive: Derive, + ) -> Option> { + let attrs = attr::Container::from_ast(cx, item); + + let mut data = match &item.data { + syn::Data::Enum(data) => Data::Enum(enum_from_ast(cx, &data.variants, attrs.default())), + syn::Data::Struct(data) => { + let (style, fields) = struct_from_ast(cx, &data.fields, None, attrs.default()); + Data::Struct(style, fields) + } + syn::Data::Union(_) => { + cx.error_spanned_by(item, "Serde does not support derive for unions"); + return None; + } + }; + + match &mut data { + Data::Enum(variants) => { + for variant in variants { + variant.attrs.rename_by_rules(attrs.rename_all_rules()); + for field in &mut variant.fields { + field.attrs.rename_by_rules( + variant + .attrs + .rename_all_rules() + .or(attrs.rename_all_fields_rules()), + ); + } + } + } + Data::Struct(_, fields) => { + for field in fields { + field.attrs.rename_by_rules(attrs.rename_all_rules()); + } + } + } + + let mut item = Container { + ident: item.ident.clone(), + attrs, + data, + generics: &item.generics, + original: item, + }; + check::check(cx, &mut item, derive); + Some(item) + } +} + +impl<'a> Data<'a> { + pub fn all_fields(&'a self) -> Box> + 'a> { + match self { + Data::Enum(variants) => { + Box::new(variants.iter().flat_map(|variant| variant.fields.iter())) + } + Data::Struct(_, fields) => Box::new(fields.iter()), + } + } + + pub fn has_getter(&self) -> bool { + self.all_fields().any(|f| f.attrs.getter().is_some()) + } +} + +fn enum_from_ast<'a>( + cx: &Ctxt, + variants: &'a Punctuated, + container_default: &attr::Default, +) -> Vec> { + let variants: Vec = variants + .iter() + .map(|variant| { + let attrs = attr::Variant::from_ast(cx, variant); + let (style, fields) = + struct_from_ast(cx, &variant.fields, Some(&attrs), container_default); + Variant { + ident: variant.ident.clone(), + attrs, + style, + fields, + original: variant, + } + }) + .collect(); + + let index_of_last_tagged_variant = variants + .iter() + .rposition(|variant| !variant.attrs.untagged()); + if let Some(index_of_last_tagged_variant) = index_of_last_tagged_variant { + for variant in &variants[..index_of_last_tagged_variant] { + if variant.attrs.untagged() { + cx.error_spanned_by(&variant.ident, "all variants with the #[serde(untagged)] attribute must be placed at the end of the enum"); + } + } + } + + variants +} + +fn struct_from_ast<'a>( + cx: &Ctxt, + fields: &'a syn::Fields, + attrs: Option<&attr::Variant>, + container_default: &attr::Default, +) -> (Style, Vec>) { + match fields { + syn::Fields::Named(fields) => ( + Style::Struct, + fields_from_ast(cx, &fields.named, attrs, container_default), + ), + syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => ( + Style::Newtype, + fields_from_ast(cx, &fields.unnamed, attrs, container_default), + ), + syn::Fields::Unnamed(fields) => ( + Style::Tuple, + fields_from_ast(cx, &fields.unnamed, attrs, container_default), + ), + syn::Fields::Unit => (Style::Unit, Vec::new()), + } +} + +fn fields_from_ast<'a>( + cx: &Ctxt, + fields: &'a Punctuated, + attrs: Option<&attr::Variant>, + container_default: &attr::Default, +) -> Vec> { + fields + .iter() + .enumerate() + .map(|(i, field)| Field { + member: match &field.ident { + Some(ident) => syn::Member::Named(ident.clone()), + None => syn::Member::Unnamed(i.into()), + }, + attrs: attr::Field::from_ast(cx, i, field, attrs, container_default), + ty: &field.ty, + original: field, + }) + .collect() +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/attr.rs b/bitbox02-bt/vendor/serde_derive/src/internals/attr.rs new file mode 100644 index 0000000..ac5f5d9 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/attr.rs @@ -0,0 +1,1871 @@ +use crate::internals::symbol::*; +use crate::internals::{ungroup, Ctxt}; +use proc_macro2::{Spacing, Span, TokenStream, TokenTree}; +use quote::ToTokens; +use std::borrow::Cow; +use std::collections::BTreeSet; +use std::iter::FromIterator; +use syn::meta::ParseNestedMeta; +use syn::parse::ParseStream; +use syn::punctuated::Punctuated; +use syn::{parse_quote, token, Ident, Lifetime, Token}; + +// This module handles parsing of `#[serde(...)]` attributes. The entrypoints +// are `attr::Container::from_ast`, `attr::Variant::from_ast`, and +// `attr::Field::from_ast`. Each returns an instance of the corresponding +// struct. Note that none of them return a Result. Unrecognized, malformed, or +// duplicated attributes result in a span_err but otherwise are ignored. The +// user will see errors simultaneously for all bad attributes in the crate +// rather than just the first. + +pub use crate::internals::case::RenameRule; + +struct Attr<'c, T> { + cx: &'c Ctxt, + name: Symbol, + tokens: TokenStream, + value: Option, +} + +impl<'c, T> Attr<'c, T> { + fn none(cx: &'c Ctxt, name: Symbol) -> Self { + Attr { + cx, + name, + tokens: TokenStream::new(), + value: None, + } + } + + fn set(&mut self, obj: A, value: T) { + let tokens = obj.into_token_stream(); + + if self.value.is_some() { + let msg = format!("duplicate serde attribute `{}`", self.name); + self.cx.error_spanned_by(tokens, msg); + } else { + self.tokens = tokens; + self.value = Some(value); + } + } + + fn set_opt(&mut self, obj: A, value: Option) { + if let Some(value) = value { + self.set(obj, value); + } + } + + fn set_if_none(&mut self, value: T) { + if self.value.is_none() { + self.value = Some(value); + } + } + + fn get(self) -> Option { + self.value + } + + fn get_with_tokens(self) -> Option<(TokenStream, T)> { + match self.value { + Some(v) => Some((self.tokens, v)), + None => None, + } + } +} + +struct BoolAttr<'c>(Attr<'c, ()>); + +impl<'c> BoolAttr<'c> { + fn none(cx: &'c Ctxt, name: Symbol) -> Self { + BoolAttr(Attr::none(cx, name)) + } + + fn set_true(&mut self, obj: A) { + self.0.set(obj, ()); + } + + fn get(&self) -> bool { + self.0.value.is_some() + } +} + +struct VecAttr<'c, T> { + cx: &'c Ctxt, + name: Symbol, + first_dup_tokens: TokenStream, + values: Vec, +} + +impl<'c, T> VecAttr<'c, T> { + fn none(cx: &'c Ctxt, name: Symbol) -> Self { + VecAttr { + cx, + name, + first_dup_tokens: TokenStream::new(), + values: Vec::new(), + } + } + + fn insert(&mut self, obj: A, value: T) { + if self.values.len() == 1 { + self.first_dup_tokens = obj.into_token_stream(); + } + self.values.push(value); + } + + fn at_most_one(mut self) -> Option { + if self.values.len() > 1 { + let dup_token = self.first_dup_tokens; + let msg = format!("duplicate serde attribute `{}`", self.name); + self.cx.error_spanned_by(dup_token, msg); + None + } else { + self.values.pop() + } + } + + fn get(self) -> Vec { + self.values + } +} + +pub struct Name { + serialize: String, + serialize_renamed: bool, + deserialize: String, + deserialize_renamed: bool, + deserialize_aliases: BTreeSet, +} + +fn unraw(ident: &Ident) -> String { + ident.to_string().trim_start_matches("r#").to_owned() +} + +impl Name { + fn from_attrs( + source_name: String, + ser_name: Attr, + de_name: Attr, + de_aliases: Option>, + ) -> Name { + let mut alias_set = BTreeSet::new(); + if let Some(de_aliases) = de_aliases { + for alias_name in de_aliases.get() { + alias_set.insert(alias_name); + } + } + + let ser_name = ser_name.get(); + let ser_renamed = ser_name.is_some(); + let de_name = de_name.get(); + let de_renamed = de_name.is_some(); + Name { + serialize: ser_name.unwrap_or_else(|| source_name.clone()), + serialize_renamed: ser_renamed, + deserialize: de_name.unwrap_or(source_name), + deserialize_renamed: de_renamed, + deserialize_aliases: alias_set, + } + } + + /// Return the container name for the container when serializing. + pub fn serialize_name(&self) -> &str { + &self.serialize + } + + /// Return the container name for the container when deserializing. + pub fn deserialize_name(&self) -> &str { + &self.deserialize + } + + fn deserialize_aliases(&self) -> &BTreeSet { + &self.deserialize_aliases + } +} + +#[derive(Copy, Clone)] +pub struct RenameAllRules { + pub serialize: RenameRule, + pub deserialize: RenameRule, +} + +impl RenameAllRules { + /// Returns a new `RenameAllRules` with the individual rules of `self` and + /// `other_rules` joined by `RenameRules::or`. + pub fn or(self, other_rules: Self) -> Self { + Self { + serialize: self.serialize.or(other_rules.serialize), + deserialize: self.deserialize.or(other_rules.deserialize), + } + } +} + +/// Represents struct or enum attribute information. +pub struct Container { + name: Name, + transparent: bool, + deny_unknown_fields: bool, + default: Default, + rename_all_rules: RenameAllRules, + rename_all_fields_rules: RenameAllRules, + ser_bound: Option>, + de_bound: Option>, + tag: TagType, + type_from: Option, + type_try_from: Option, + type_into: Option, + remote: Option, + identifier: Identifier, + serde_path: Option, + is_packed: bool, + /// Error message generated when type can't be deserialized + expecting: Option, + non_exhaustive: bool, +} + +/// Styles of representing an enum. +pub enum TagType { + /// The default. + /// + /// ```json + /// {"variant1": {"key1": "value1", "key2": "value2"}} + /// ``` + External, + + /// `#[serde(tag = "type")]` + /// + /// ```json + /// {"type": "variant1", "key1": "value1", "key2": "value2"} + /// ``` + Internal { tag: String }, + + /// `#[serde(tag = "t", content = "c")]` + /// + /// ```json + /// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}} + /// ``` + Adjacent { tag: String, content: String }, + + /// `#[serde(untagged)]` + /// + /// ```json + /// {"key1": "value1", "key2": "value2"} + /// ``` + None, +} + +/// Whether this enum represents the fields of a struct or the variants of an +/// enum. +#[derive(Copy, Clone)] +pub enum Identifier { + /// It does not. + No, + + /// This enum represents the fields of a struct. All of the variants must be + /// unit variants, except possibly one which is annotated with + /// `#[serde(other)]` and is a newtype variant. + Field, + + /// This enum represents the variants of an enum. All of the variants must + /// be unit variants. + Variant, +} + +impl Identifier { + #[cfg(feature = "deserialize_in_place")] + pub fn is_some(self) -> bool { + match self { + Identifier::No => false, + Identifier::Field | Identifier::Variant => true, + } + } +} + +impl Container { + /// Extract out the `#[serde(...)]` attributes from an item. + pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self { + let mut ser_name = Attr::none(cx, RENAME); + let mut de_name = Attr::none(cx, RENAME); + let mut transparent = BoolAttr::none(cx, TRANSPARENT); + let mut deny_unknown_fields = BoolAttr::none(cx, DENY_UNKNOWN_FIELDS); + let mut default = Attr::none(cx, DEFAULT); + let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL); + let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL); + let mut rename_all_fields_ser_rule = Attr::none(cx, RENAME_ALL_FIELDS); + let mut rename_all_fields_de_rule = Attr::none(cx, RENAME_ALL_FIELDS); + let mut ser_bound = Attr::none(cx, BOUND); + let mut de_bound = Attr::none(cx, BOUND); + let mut untagged = BoolAttr::none(cx, UNTAGGED); + let mut internal_tag = Attr::none(cx, TAG); + let mut content = Attr::none(cx, CONTENT); + let mut type_from = Attr::none(cx, FROM); + let mut type_try_from = Attr::none(cx, TRY_FROM); + let mut type_into = Attr::none(cx, INTO); + let mut remote = Attr::none(cx, REMOTE); + let mut field_identifier = BoolAttr::none(cx, FIELD_IDENTIFIER); + let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER); + let mut serde_path = Attr::none(cx, CRATE); + let mut expecting = Attr::none(cx, EXPECTING); + let mut non_exhaustive = false; + + for attr in &item.attrs { + if attr.path() != SERDE { + non_exhaustive |= + matches!(&attr.meta, syn::Meta::Path(path) if path == NON_EXHAUSTIVE); + continue; + } + + if let syn::Meta::List(meta) = &attr.meta { + if meta.tokens.is_empty() { + continue; + } + } + + if let Err(err) = attr.parse_nested_meta(|meta| { + if meta.path == RENAME { + // #[serde(rename = "foo")] + // #[serde(rename(serialize = "foo", deserialize = "bar"))] + let (ser, de) = get_renames(cx, RENAME, &meta)?; + ser_name.set_opt(&meta.path, ser.as_ref().map(syn::LitStr::value)); + de_name.set_opt(&meta.path, de.as_ref().map(syn::LitStr::value)); + } else if meta.path == RENAME_ALL { + // #[serde(rename_all = "foo")] + // #[serde(rename_all(serialize = "foo", deserialize = "bar"))] + let one_name = meta.input.peek(Token![=]); + let (ser, de) = get_renames(cx, RENAME_ALL, &meta)?; + if let Some(ser) = ser { + match RenameRule::from_str(&ser.value()) { + Ok(rename_rule) => rename_all_ser_rule.set(&meta.path, rename_rule), + Err(err) => cx.error_spanned_by(ser, err), + } + } + if let Some(de) = de { + match RenameRule::from_str(&de.value()) { + Ok(rename_rule) => rename_all_de_rule.set(&meta.path, rename_rule), + Err(err) => { + if !one_name { + cx.error_spanned_by(de, err); + } + } + } + } + } else if meta.path == RENAME_ALL_FIELDS { + // #[serde(rename_all_fields = "foo")] + // #[serde(rename_all_fields(serialize = "foo", deserialize = "bar"))] + let one_name = meta.input.peek(Token![=]); + let (ser, de) = get_renames(cx, RENAME_ALL_FIELDS, &meta)?; + + match item.data { + syn::Data::Enum(_) => { + if let Some(ser) = ser { + match RenameRule::from_str(&ser.value()) { + Ok(rename_rule) => { + rename_all_fields_ser_rule.set(&meta.path, rename_rule); + } + Err(err) => cx.error_spanned_by(ser, err), + } + } + if let Some(de) = de { + match RenameRule::from_str(&de.value()) { + Ok(rename_rule) => { + rename_all_fields_de_rule.set(&meta.path, rename_rule); + } + Err(err) => { + if !one_name { + cx.error_spanned_by(de, err); + } + } + } + } + } + syn::Data::Struct(_) => { + let msg = "#[serde(rename_all_fields)] can only be used on enums"; + cx.syn_error(meta.error(msg)); + } + syn::Data::Union(_) => { + let msg = "#[serde(rename_all_fields)] can only be used on enums"; + cx.syn_error(meta.error(msg)); + } + } + } else if meta.path == TRANSPARENT { + // #[serde(transparent)] + transparent.set_true(meta.path); + } else if meta.path == DENY_UNKNOWN_FIELDS { + // #[serde(deny_unknown_fields)] + deny_unknown_fields.set_true(meta.path); + } else if meta.path == DEFAULT { + if meta.input.peek(Token![=]) { + // #[serde(default = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, DEFAULT, &meta)? { + match &item.data { + syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields { + syn::Fields::Named(_) | syn::Fields::Unnamed(_) => { + default.set(&meta.path, Default::Path(path)); + } + syn::Fields::Unit => { + let msg = "#[serde(default = \"...\")] can only be used on structs that have fields"; + cx.syn_error(meta.error(msg)); + } + }, + syn::Data::Enum(_) => { + let msg = "#[serde(default = \"...\")] can only be used on structs"; + cx.syn_error(meta.error(msg)); + } + syn::Data::Union(_) => { + let msg = "#[serde(default = \"...\")] can only be used on structs"; + cx.syn_error(meta.error(msg)); + } + } + } + } else { + // #[serde(default)] + match &item.data { + syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields { + syn::Fields::Named(_) | syn::Fields::Unnamed(_) => { + default.set(meta.path, Default::Default); + } + syn::Fields::Unit => { + let msg = "#[serde(default)] can only be used on structs that have fields"; + cx.error_spanned_by(fields, msg); + } + }, + syn::Data::Enum(_) => { + let msg = "#[serde(default)] can only be used on structs"; + cx.syn_error(meta.error(msg)); + } + syn::Data::Union(_) => { + let msg = "#[serde(default)] can only be used on structs"; + cx.syn_error(meta.error(msg)); + } + } + } + } else if meta.path == BOUND { + // #[serde(bound = "T: SomeBound")] + // #[serde(bound(serialize = "...", deserialize = "..."))] + let (ser, de) = get_where_predicates(cx, &meta)?; + ser_bound.set_opt(&meta.path, ser); + de_bound.set_opt(&meta.path, de); + } else if meta.path == UNTAGGED { + // #[serde(untagged)] + match item.data { + syn::Data::Enum(_) => { + untagged.set_true(&meta.path); + } + syn::Data::Struct(_) => { + let msg = "#[serde(untagged)] can only be used on enums"; + cx.syn_error(meta.error(msg)); + } + syn::Data::Union(_) => { + let msg = "#[serde(untagged)] can only be used on enums"; + cx.syn_error(meta.error(msg)); + } + } + } else if meta.path == TAG { + // #[serde(tag = "type")] + if let Some(s) = get_lit_str(cx, TAG, &meta)? { + match &item.data { + syn::Data::Enum(_) => { + internal_tag.set(&meta.path, s.value()); + } + syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields { + syn::Fields::Named(_) => { + internal_tag.set(&meta.path, s.value()); + } + syn::Fields::Unnamed(_) | syn::Fields::Unit => { + let msg = "#[serde(tag = \"...\")] can only be used on enums and structs with named fields"; + cx.syn_error(meta.error(msg)); + } + }, + syn::Data::Union(_) => { + let msg = "#[serde(tag = \"...\")] can only be used on enums and structs with named fields"; + cx.syn_error(meta.error(msg)); + } + } + } + } else if meta.path == CONTENT { + // #[serde(content = "c")] + if let Some(s) = get_lit_str(cx, CONTENT, &meta)? { + match &item.data { + syn::Data::Enum(_) => { + content.set(&meta.path, s.value()); + } + syn::Data::Struct(_) => { + let msg = "#[serde(content = \"...\")] can only be used on enums"; + cx.syn_error(meta.error(msg)); + } + syn::Data::Union(_) => { + let msg = "#[serde(content = \"...\")] can only be used on enums"; + cx.syn_error(meta.error(msg)); + } + } + } + } else if meta.path == FROM { + // #[serde(from = "Type")] + if let Some(from_ty) = parse_lit_into_ty(cx, FROM, &meta)? { + type_from.set_opt(&meta.path, Some(from_ty)); + } + } else if meta.path == TRY_FROM { + // #[serde(try_from = "Type")] + if let Some(try_from_ty) = parse_lit_into_ty(cx, TRY_FROM, &meta)? { + type_try_from.set_opt(&meta.path, Some(try_from_ty)); + } + } else if meta.path == INTO { + // #[serde(into = "Type")] + if let Some(into_ty) = parse_lit_into_ty(cx, INTO, &meta)? { + type_into.set_opt(&meta.path, Some(into_ty)); + } + } else if meta.path == REMOTE { + // #[serde(remote = "...")] + if let Some(path) = parse_lit_into_path(cx, REMOTE, &meta)? { + if is_primitive_path(&path, "Self") { + remote.set(&meta.path, item.ident.clone().into()); + } else { + remote.set(&meta.path, path); + } + } + } else if meta.path == FIELD_IDENTIFIER { + // #[serde(field_identifier)] + field_identifier.set_true(&meta.path); + } else if meta.path == VARIANT_IDENTIFIER { + // #[serde(variant_identifier)] + variant_identifier.set_true(&meta.path); + } else if meta.path == CRATE { + // #[serde(crate = "foo")] + if let Some(path) = parse_lit_into_path(cx, CRATE, &meta)? { + serde_path.set(&meta.path, path); + } + } else if meta.path == EXPECTING { + // #[serde(expecting = "a message")] + if let Some(s) = get_lit_str(cx, EXPECTING, &meta)? { + expecting.set(&meta.path, s.value()); + } + } else { + let path = meta.path.to_token_stream().to_string().replace(' ', ""); + return Err( + meta.error(format_args!("unknown serde container attribute `{}`", path)) + ); + } + Ok(()) + }) { + cx.syn_error(err); + } + } + + let mut is_packed = false; + for attr in &item.attrs { + if attr.path() == REPR { + let _ = attr.parse_args_with(|input: ParseStream| { + while let Some(token) = input.parse()? { + if let TokenTree::Ident(ident) = token { + is_packed |= ident == "packed"; + } + } + Ok(()) + }); + } + } + + Container { + name: Name::from_attrs(unraw(&item.ident), ser_name, de_name, None), + transparent: transparent.get(), + deny_unknown_fields: deny_unknown_fields.get(), + default: default.get().unwrap_or(Default::None), + rename_all_rules: RenameAllRules { + serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None), + deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None), + }, + rename_all_fields_rules: RenameAllRules { + serialize: rename_all_fields_ser_rule.get().unwrap_or(RenameRule::None), + deserialize: rename_all_fields_de_rule.get().unwrap_or(RenameRule::None), + }, + ser_bound: ser_bound.get(), + de_bound: de_bound.get(), + tag: decide_tag(cx, item, untagged, internal_tag, content), + type_from: type_from.get(), + type_try_from: type_try_from.get(), + type_into: type_into.get(), + remote: remote.get(), + identifier: decide_identifier(cx, item, field_identifier, variant_identifier), + serde_path: serde_path.get(), + is_packed, + expecting: expecting.get(), + non_exhaustive, + } + } + + pub fn name(&self) -> &Name { + &self.name + } + + pub fn rename_all_rules(&self) -> RenameAllRules { + self.rename_all_rules + } + + pub fn rename_all_fields_rules(&self) -> RenameAllRules { + self.rename_all_fields_rules + } + + pub fn transparent(&self) -> bool { + self.transparent + } + + pub fn deny_unknown_fields(&self) -> bool { + self.deny_unknown_fields + } + + pub fn default(&self) -> &Default { + &self.default + } + + pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { + self.ser_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { + self.de_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn tag(&self) -> &TagType { + &self.tag + } + + pub fn type_from(&self) -> Option<&syn::Type> { + self.type_from.as_ref() + } + + pub fn type_try_from(&self) -> Option<&syn::Type> { + self.type_try_from.as_ref() + } + + pub fn type_into(&self) -> Option<&syn::Type> { + self.type_into.as_ref() + } + + pub fn remote(&self) -> Option<&syn::Path> { + self.remote.as_ref() + } + + pub fn is_packed(&self) -> bool { + self.is_packed + } + + pub fn identifier(&self) -> Identifier { + self.identifier + } + + pub fn custom_serde_path(&self) -> Option<&syn::Path> { + self.serde_path.as_ref() + } + + pub fn serde_path(&self) -> Cow { + self.custom_serde_path() + .map_or_else(|| Cow::Owned(parse_quote!(_serde)), Cow::Borrowed) + } + + /// Error message generated when type can't be deserialized. + /// If `None`, default message will be used + pub fn expecting(&self) -> Option<&str> { + self.expecting.as_ref().map(String::as_ref) + } + + pub fn non_exhaustive(&self) -> bool { + self.non_exhaustive + } +} + +fn decide_tag( + cx: &Ctxt, + item: &syn::DeriveInput, + untagged: BoolAttr, + internal_tag: Attr, + content: Attr, +) -> TagType { + match ( + untagged.0.get_with_tokens(), + internal_tag.get_with_tokens(), + content.get_with_tokens(), + ) { + (None, None, None) => TagType::External, + (Some(_), None, None) => TagType::None, + (None, Some((_, tag)), None) => { + // Check that there are no tuple variants. + if let syn::Data::Enum(data) = &item.data { + for variant in &data.variants { + match &variant.fields { + syn::Fields::Named(_) | syn::Fields::Unit => {} + syn::Fields::Unnamed(fields) => { + if fields.unnamed.len() != 1 { + let msg = + "#[serde(tag = \"...\")] cannot be used with tuple variants"; + cx.error_spanned_by(variant, msg); + break; + } + } + } + } + } + TagType::Internal { tag } + } + (Some((untagged_tokens, ())), Some((tag_tokens, _)), None) => { + let msg = "enum cannot be both untagged and internally tagged"; + cx.error_spanned_by(untagged_tokens, msg); + cx.error_spanned_by(tag_tokens, msg); + TagType::External // doesn't matter, will error + } + (None, None, Some((content_tokens, _))) => { + let msg = "#[serde(tag = \"...\", content = \"...\")] must be used together"; + cx.error_spanned_by(content_tokens, msg); + TagType::External + } + (Some((untagged_tokens, ())), None, Some((content_tokens, _))) => { + let msg = "untagged enum cannot have #[serde(content = \"...\")]"; + cx.error_spanned_by(untagged_tokens, msg); + cx.error_spanned_by(content_tokens, msg); + TagType::External + } + (None, Some((_, tag)), Some((_, content))) => TagType::Adjacent { tag, content }, + (Some((untagged_tokens, ())), Some((tag_tokens, _)), Some((content_tokens, _))) => { + let msg = "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]"; + cx.error_spanned_by(untagged_tokens, msg); + cx.error_spanned_by(tag_tokens, msg); + cx.error_spanned_by(content_tokens, msg); + TagType::External + } + } +} + +fn decide_identifier( + cx: &Ctxt, + item: &syn::DeriveInput, + field_identifier: BoolAttr, + variant_identifier: BoolAttr, +) -> Identifier { + match ( + &item.data, + field_identifier.0.get_with_tokens(), + variant_identifier.0.get_with_tokens(), + ) { + (_, None, None) => Identifier::No, + (_, Some((field_identifier_tokens, ())), Some((variant_identifier_tokens, ()))) => { + let msg = + "#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set"; + cx.error_spanned_by(field_identifier_tokens, msg); + cx.error_spanned_by(variant_identifier_tokens, msg); + Identifier::No + } + (syn::Data::Enum(_), Some(_), None) => Identifier::Field, + (syn::Data::Enum(_), None, Some(_)) => Identifier::Variant, + (syn::Data::Struct(syn::DataStruct { struct_token, .. }), Some(_), None) => { + let msg = "#[serde(field_identifier)] can only be used on an enum"; + cx.error_spanned_by(struct_token, msg); + Identifier::No + } + (syn::Data::Union(syn::DataUnion { union_token, .. }), Some(_), None) => { + let msg = "#[serde(field_identifier)] can only be used on an enum"; + cx.error_spanned_by(union_token, msg); + Identifier::No + } + (syn::Data::Struct(syn::DataStruct { struct_token, .. }), None, Some(_)) => { + let msg = "#[serde(variant_identifier)] can only be used on an enum"; + cx.error_spanned_by(struct_token, msg); + Identifier::No + } + (syn::Data::Union(syn::DataUnion { union_token, .. }), None, Some(_)) => { + let msg = "#[serde(variant_identifier)] can only be used on an enum"; + cx.error_spanned_by(union_token, msg); + Identifier::No + } + } +} + +/// Represents variant attribute information +pub struct Variant { + name: Name, + rename_all_rules: RenameAllRules, + ser_bound: Option>, + de_bound: Option>, + skip_deserializing: bool, + skip_serializing: bool, + other: bool, + serialize_with: Option, + deserialize_with: Option, + borrow: Option, + untagged: bool, +} + +struct BorrowAttribute { + path: syn::Path, + lifetimes: Option>, +} + +impl Variant { + pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self { + let mut ser_name = Attr::none(cx, RENAME); + let mut de_name = Attr::none(cx, RENAME); + let mut de_aliases = VecAttr::none(cx, RENAME); + let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING); + let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING); + let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL); + let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL); + let mut ser_bound = Attr::none(cx, BOUND); + let mut de_bound = Attr::none(cx, BOUND); + let mut other = BoolAttr::none(cx, OTHER); + let mut serialize_with = Attr::none(cx, SERIALIZE_WITH); + let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH); + let mut borrow = Attr::none(cx, BORROW); + let mut untagged = BoolAttr::none(cx, UNTAGGED); + + for attr in &variant.attrs { + if attr.path() != SERDE { + continue; + } + + if let syn::Meta::List(meta) = &attr.meta { + if meta.tokens.is_empty() { + continue; + } + } + + if let Err(err) = attr.parse_nested_meta(|meta| { + if meta.path == RENAME { + // #[serde(rename = "foo")] + // #[serde(rename(serialize = "foo", deserialize = "bar"))] + let (ser, de) = get_multiple_renames(cx, &meta)?; + ser_name.set_opt(&meta.path, ser.as_ref().map(syn::LitStr::value)); + for de_value in de { + de_name.set_if_none(de_value.value()); + de_aliases.insert(&meta.path, de_value.value()); + } + } else if meta.path == ALIAS { + // #[serde(alias = "foo")] + if let Some(s) = get_lit_str(cx, ALIAS, &meta)? { + de_aliases.insert(&meta.path, s.value()); + } + } else if meta.path == RENAME_ALL { + // #[serde(rename_all = "foo")] + // #[serde(rename_all(serialize = "foo", deserialize = "bar"))] + let one_name = meta.input.peek(Token![=]); + let (ser, de) = get_renames(cx, RENAME_ALL, &meta)?; + if let Some(ser) = ser { + match RenameRule::from_str(&ser.value()) { + Ok(rename_rule) => rename_all_ser_rule.set(&meta.path, rename_rule), + Err(err) => cx.error_spanned_by(ser, err), + } + } + if let Some(de) = de { + match RenameRule::from_str(&de.value()) { + Ok(rename_rule) => rename_all_de_rule.set(&meta.path, rename_rule), + Err(err) => { + if !one_name { + cx.error_spanned_by(de, err); + } + } + } + } + } else if meta.path == SKIP { + // #[serde(skip)] + skip_serializing.set_true(&meta.path); + skip_deserializing.set_true(&meta.path); + } else if meta.path == SKIP_DESERIALIZING { + // #[serde(skip_deserializing)] + skip_deserializing.set_true(&meta.path); + } else if meta.path == SKIP_SERIALIZING { + // #[serde(skip_serializing)] + skip_serializing.set_true(&meta.path); + } else if meta.path == OTHER { + // #[serde(other)] + other.set_true(&meta.path); + } else if meta.path == BOUND { + // #[serde(bound = "T: SomeBound")] + // #[serde(bound(serialize = "...", deserialize = "..."))] + let (ser, de) = get_where_predicates(cx, &meta)?; + ser_bound.set_opt(&meta.path, ser); + de_bound.set_opt(&meta.path, de); + } else if meta.path == WITH { + // #[serde(with = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, WITH, &meta)? { + let mut ser_path = path.clone(); + ser_path + .path + .segments + .push(Ident::new("serialize", Span::call_site()).into()); + serialize_with.set(&meta.path, ser_path); + let mut de_path = path; + de_path + .path + .segments + .push(Ident::new("deserialize", Span::call_site()).into()); + deserialize_with.set(&meta.path, de_path); + } + } else if meta.path == SERIALIZE_WITH { + // #[serde(serialize_with = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &meta)? { + serialize_with.set(&meta.path, path); + } + } else if meta.path == DESERIALIZE_WITH { + // #[serde(deserialize_with = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &meta)? { + deserialize_with.set(&meta.path, path); + } + } else if meta.path == BORROW { + let borrow_attribute = if meta.input.peek(Token![=]) { + // #[serde(borrow = "'a + 'b")] + let lifetimes = parse_lit_into_lifetimes(cx, &meta)?; + BorrowAttribute { + path: meta.path.clone(), + lifetimes: Some(lifetimes), + } + } else { + // #[serde(borrow)] + BorrowAttribute { + path: meta.path.clone(), + lifetimes: None, + } + }; + match &variant.fields { + syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => { + borrow.set(&meta.path, borrow_attribute); + } + _ => { + let msg = "#[serde(borrow)] may only be used on newtype variants"; + cx.error_spanned_by(variant, msg); + } + } + } else if meta.path == UNTAGGED { + untagged.set_true(&meta.path); + } else { + let path = meta.path.to_token_stream().to_string().replace(' ', ""); + return Err( + meta.error(format_args!("unknown serde variant attribute `{}`", path)) + ); + } + Ok(()) + }) { + cx.syn_error(err); + } + } + + Variant { + name: Name::from_attrs(unraw(&variant.ident), ser_name, de_name, Some(de_aliases)), + rename_all_rules: RenameAllRules { + serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None), + deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None), + }, + ser_bound: ser_bound.get(), + de_bound: de_bound.get(), + skip_deserializing: skip_deserializing.get(), + skip_serializing: skip_serializing.get(), + other: other.get(), + serialize_with: serialize_with.get(), + deserialize_with: deserialize_with.get(), + borrow: borrow.get(), + untagged: untagged.get(), + } + } + + pub fn name(&self) -> &Name { + &self.name + } + + pub fn aliases(&self) -> &BTreeSet { + self.name.deserialize_aliases() + } + + pub fn rename_by_rules(&mut self, rules: RenameAllRules) { + if !self.name.serialize_renamed { + self.name.serialize = rules.serialize.apply_to_variant(&self.name.serialize); + } + if !self.name.deserialize_renamed { + self.name.deserialize = rules.deserialize.apply_to_variant(&self.name.deserialize); + } + self.name + .deserialize_aliases + .insert(self.name.deserialize.clone()); + } + + pub fn rename_all_rules(&self) -> RenameAllRules { + self.rename_all_rules + } + + pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { + self.ser_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { + self.de_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn skip_deserializing(&self) -> bool { + self.skip_deserializing + } + + pub fn skip_serializing(&self) -> bool { + self.skip_serializing + } + + pub fn other(&self) -> bool { + self.other + } + + pub fn serialize_with(&self) -> Option<&syn::ExprPath> { + self.serialize_with.as_ref() + } + + pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { + self.deserialize_with.as_ref() + } + + pub fn untagged(&self) -> bool { + self.untagged + } +} + +/// Represents field attribute information +pub struct Field { + name: Name, + skip_serializing: bool, + skip_deserializing: bool, + skip_serializing_if: Option, + default: Default, + serialize_with: Option, + deserialize_with: Option, + ser_bound: Option>, + de_bound: Option>, + borrowed_lifetimes: BTreeSet, + getter: Option, + flatten: bool, + transparent: bool, +} + +/// Represents the default to use for a field when deserializing. +pub enum Default { + /// Field must always be specified because it does not have a default. + None, + /// The default is given by `std::default::Default::default()`. + Default, + /// The default is given by this function. + Path(syn::ExprPath), +} + +impl Default { + pub fn is_none(&self) -> bool { + match self { + Default::None => true, + Default::Default | Default::Path(_) => false, + } + } +} + +impl Field { + /// Extract out the `#[serde(...)]` attributes from a struct field. + pub fn from_ast( + cx: &Ctxt, + index: usize, + field: &syn::Field, + attrs: Option<&Variant>, + container_default: &Default, + ) -> Self { + let mut ser_name = Attr::none(cx, RENAME); + let mut de_name = Attr::none(cx, RENAME); + let mut de_aliases = VecAttr::none(cx, RENAME); + let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING); + let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING); + let mut skip_serializing_if = Attr::none(cx, SKIP_SERIALIZING_IF); + let mut default = Attr::none(cx, DEFAULT); + let mut serialize_with = Attr::none(cx, SERIALIZE_WITH); + let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH); + let mut ser_bound = Attr::none(cx, BOUND); + let mut de_bound = Attr::none(cx, BOUND); + let mut borrowed_lifetimes = Attr::none(cx, BORROW); + let mut getter = Attr::none(cx, GETTER); + let mut flatten = BoolAttr::none(cx, FLATTEN); + + let ident = match &field.ident { + Some(ident) => unraw(ident), + None => index.to_string(), + }; + + if let Some(borrow_attribute) = attrs.and_then(|variant| variant.borrow.as_ref()) { + if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, field) { + if let Some(lifetimes) = &borrow_attribute.lifetimes { + for lifetime in lifetimes { + if !borrowable.contains(lifetime) { + let msg = + format!("field `{}` does not have lifetime {}", ident, lifetime); + cx.error_spanned_by(field, msg); + } + } + borrowed_lifetimes.set(&borrow_attribute.path, lifetimes.clone()); + } else { + borrowed_lifetimes.set(&borrow_attribute.path, borrowable); + } + } + } + + for attr in &field.attrs { + if attr.path() != SERDE { + continue; + } + + if let syn::Meta::List(meta) = &attr.meta { + if meta.tokens.is_empty() { + continue; + } + } + + if let Err(err) = attr.parse_nested_meta(|meta| { + if meta.path == RENAME { + // #[serde(rename = "foo")] + // #[serde(rename(serialize = "foo", deserialize = "bar"))] + let (ser, de) = get_multiple_renames(cx, &meta)?; + ser_name.set_opt(&meta.path, ser.as_ref().map(syn::LitStr::value)); + for de_value in de { + de_name.set_if_none(de_value.value()); + de_aliases.insert(&meta.path, de_value.value()); + } + } else if meta.path == ALIAS { + // #[serde(alias = "foo")] + if let Some(s) = get_lit_str(cx, ALIAS, &meta)? { + de_aliases.insert(&meta.path, s.value()); + } + } else if meta.path == DEFAULT { + if meta.input.peek(Token![=]) { + // #[serde(default = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, DEFAULT, &meta)? { + default.set(&meta.path, Default::Path(path)); + } + } else { + // #[serde(default)] + default.set(&meta.path, Default::Default); + } + } else if meta.path == SKIP_SERIALIZING { + // #[serde(skip_serializing)] + skip_serializing.set_true(&meta.path); + } else if meta.path == SKIP_DESERIALIZING { + // #[serde(skip_deserializing)] + skip_deserializing.set_true(&meta.path); + } else if meta.path == SKIP { + // #[serde(skip)] + skip_serializing.set_true(&meta.path); + skip_deserializing.set_true(&meta.path); + } else if meta.path == SKIP_SERIALIZING_IF { + // #[serde(skip_serializing_if = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, SKIP_SERIALIZING_IF, &meta)? { + skip_serializing_if.set(&meta.path, path); + } + } else if meta.path == SERIALIZE_WITH { + // #[serde(serialize_with = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &meta)? { + serialize_with.set(&meta.path, path); + } + } else if meta.path == DESERIALIZE_WITH { + // #[serde(deserialize_with = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &meta)? { + deserialize_with.set(&meta.path, path); + } + } else if meta.path == WITH { + // #[serde(with = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, WITH, &meta)? { + let mut ser_path = path.clone(); + ser_path + .path + .segments + .push(Ident::new("serialize", Span::call_site()).into()); + serialize_with.set(&meta.path, ser_path); + let mut de_path = path; + de_path + .path + .segments + .push(Ident::new("deserialize", Span::call_site()).into()); + deserialize_with.set(&meta.path, de_path); + } + } else if meta.path == BOUND { + // #[serde(bound = "T: SomeBound")] + // #[serde(bound(serialize = "...", deserialize = "..."))] + let (ser, de) = get_where_predicates(cx, &meta)?; + ser_bound.set_opt(&meta.path, ser); + de_bound.set_opt(&meta.path, de); + } else if meta.path == BORROW { + if meta.input.peek(Token![=]) { + // #[serde(borrow = "'a + 'b")] + let lifetimes = parse_lit_into_lifetimes(cx, &meta)?; + if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, field) { + for lifetime in &lifetimes { + if !borrowable.contains(lifetime) { + let msg = format!( + "field `{}` does not have lifetime {}", + ident, lifetime, + ); + cx.error_spanned_by(field, msg); + } + } + borrowed_lifetimes.set(&meta.path, lifetimes); + } + } else { + // #[serde(borrow)] + if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, field) { + borrowed_lifetimes.set(&meta.path, borrowable); + } + } + } else if meta.path == GETTER { + // #[serde(getter = "...")] + if let Some(path) = parse_lit_into_expr_path(cx, GETTER, &meta)? { + getter.set(&meta.path, path); + } + } else if meta.path == FLATTEN { + // #[serde(flatten)] + flatten.set_true(&meta.path); + } else { + let path = meta.path.to_token_stream().to_string().replace(' ', ""); + return Err( + meta.error(format_args!("unknown serde field attribute `{}`", path)) + ); + } + Ok(()) + }) { + cx.syn_error(err); + } + } + + // Is skip_deserializing, initialize the field to Default::default() unless a + // different default is specified by `#[serde(default = "...")]` on + // ourselves or our container (e.g. the struct we are in). + if let Default::None = *container_default { + if skip_deserializing.0.value.is_some() { + default.set_if_none(Default::Default); + } + } + + let mut borrowed_lifetimes = borrowed_lifetimes.get().unwrap_or_default(); + if !borrowed_lifetimes.is_empty() { + // Cow and Cow<[u8]> never borrow by default: + // + // impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T> + // + // A #[serde(borrow)] attribute enables borrowing that corresponds + // roughly to these impls: + // + // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str> + // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]> + if is_cow(&field.ty, is_str) { + let mut path = syn::Path { + leading_colon: None, + segments: Punctuated::new(), + }; + let span = Span::call_site(); + path.segments.push(Ident::new("_serde", span).into()); + path.segments.push(Ident::new("__private", span).into()); + path.segments.push(Ident::new("de", span).into()); + path.segments + .push(Ident::new("borrow_cow_str", span).into()); + let expr = syn::ExprPath { + attrs: Vec::new(), + qself: None, + path, + }; + deserialize_with.set_if_none(expr); + } else if is_cow(&field.ty, is_slice_u8) { + let mut path = syn::Path { + leading_colon: None, + segments: Punctuated::new(), + }; + let span = Span::call_site(); + path.segments.push(Ident::new("_serde", span).into()); + path.segments.push(Ident::new("__private", span).into()); + path.segments.push(Ident::new("de", span).into()); + path.segments + .push(Ident::new("borrow_cow_bytes", span).into()); + let expr = syn::ExprPath { + attrs: Vec::new(), + qself: None, + path, + }; + deserialize_with.set_if_none(expr); + } + } else if is_implicitly_borrowed(&field.ty) { + // Types &str and &[u8] are always implicitly borrowed. No need for + // a #[serde(borrow)]. + collect_lifetimes(&field.ty, &mut borrowed_lifetimes); + } + + Field { + name: Name::from_attrs(ident, ser_name, de_name, Some(de_aliases)), + skip_serializing: skip_serializing.get(), + skip_deserializing: skip_deserializing.get(), + skip_serializing_if: skip_serializing_if.get(), + default: default.get().unwrap_or(Default::None), + serialize_with: serialize_with.get(), + deserialize_with: deserialize_with.get(), + ser_bound: ser_bound.get(), + de_bound: de_bound.get(), + borrowed_lifetimes, + getter: getter.get(), + flatten: flatten.get(), + transparent: false, + } + } + + pub fn name(&self) -> &Name { + &self.name + } + + pub fn aliases(&self) -> &BTreeSet { + self.name.deserialize_aliases() + } + + pub fn rename_by_rules(&mut self, rules: RenameAllRules) { + if !self.name.serialize_renamed { + self.name.serialize = rules.serialize.apply_to_field(&self.name.serialize); + } + if !self.name.deserialize_renamed { + self.name.deserialize = rules.deserialize.apply_to_field(&self.name.deserialize); + } + self.name + .deserialize_aliases + .insert(self.name.deserialize.clone()); + } + + pub fn skip_serializing(&self) -> bool { + self.skip_serializing + } + + pub fn skip_deserializing(&self) -> bool { + self.skip_deserializing + } + + pub fn skip_serializing_if(&self) -> Option<&syn::ExprPath> { + self.skip_serializing_if.as_ref() + } + + pub fn default(&self) -> &Default { + &self.default + } + + pub fn serialize_with(&self) -> Option<&syn::ExprPath> { + self.serialize_with.as_ref() + } + + pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { + self.deserialize_with.as_ref() + } + + pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { + self.ser_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { + self.de_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn borrowed_lifetimes(&self) -> &BTreeSet { + &self.borrowed_lifetimes + } + + pub fn getter(&self) -> Option<&syn::ExprPath> { + self.getter.as_ref() + } + + pub fn flatten(&self) -> bool { + self.flatten + } + + pub fn transparent(&self) -> bool { + self.transparent + } + + pub fn mark_transparent(&mut self) { + self.transparent = true; + } +} + +type SerAndDe = (Option, Option); + +fn get_ser_and_de<'c, T, F, R>( + cx: &'c Ctxt, + attr_name: Symbol, + meta: &ParseNestedMeta, + f: F, +) -> syn::Result<(VecAttr<'c, T>, VecAttr<'c, T>)> +where + T: Clone, + F: Fn(&Ctxt, Symbol, Symbol, &ParseNestedMeta) -> syn::Result, + R: Into>, +{ + let mut ser_meta = VecAttr::none(cx, attr_name); + let mut de_meta = VecAttr::none(cx, attr_name); + + let lookahead = meta.input.lookahead1(); + if lookahead.peek(Token![=]) { + if let Some(both) = f(cx, attr_name, attr_name, meta)?.into() { + ser_meta.insert(&meta.path, both.clone()); + de_meta.insert(&meta.path, both); + } + } else if lookahead.peek(token::Paren) { + meta.parse_nested_meta(|meta| { + if meta.path == SERIALIZE { + if let Some(v) = f(cx, attr_name, SERIALIZE, &meta)?.into() { + ser_meta.insert(&meta.path, v); + } + } else if meta.path == DESERIALIZE { + if let Some(v) = f(cx, attr_name, DESERIALIZE, &meta)?.into() { + de_meta.insert(&meta.path, v); + } + } else { + return Err(meta.error(format_args!( + "malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`", + attr_name, + ))); + } + Ok(()) + })?; + } else { + return Err(lookahead.error()); + } + + Ok((ser_meta, de_meta)) +} + +fn get_renames( + cx: &Ctxt, + attr_name: Symbol, + meta: &ParseNestedMeta, +) -> syn::Result> { + let (ser, de) = get_ser_and_de(cx, attr_name, meta, get_lit_str2)?; + Ok((ser.at_most_one(), de.at_most_one())) +} + +fn get_multiple_renames( + cx: &Ctxt, + meta: &ParseNestedMeta, +) -> syn::Result<(Option, Vec)> { + let (ser, de) = get_ser_and_de(cx, RENAME, meta, get_lit_str2)?; + Ok((ser.at_most_one(), de.get())) +} + +fn get_where_predicates( + cx: &Ctxt, + meta: &ParseNestedMeta, +) -> syn::Result>> { + let (ser, de) = get_ser_and_de(cx, BOUND, meta, parse_lit_into_where)?; + Ok((ser.at_most_one(), de.at_most_one())) +} + +fn get_lit_str( + cx: &Ctxt, + attr_name: Symbol, + meta: &ParseNestedMeta, +) -> syn::Result> { + get_lit_str2(cx, attr_name, attr_name, meta) +} + +fn get_lit_str2( + cx: &Ctxt, + attr_name: Symbol, + meta_item_name: Symbol, + meta: &ParseNestedMeta, +) -> syn::Result> { + let expr: syn::Expr = meta.value()?.parse()?; + let mut value = &expr; + while let syn::Expr::Group(e) = value { + value = &e.expr; + } + if let syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(lit), + .. + }) = value + { + let suffix = lit.suffix(); + if !suffix.is_empty() { + cx.error_spanned_by( + lit, + format!("unexpected suffix `{}` on string literal", suffix), + ); + } + Ok(Some(lit.clone())) + } else { + cx.error_spanned_by( + expr, + format!( + "expected serde {} attribute to be a string: `{} = \"...\"`", + attr_name, meta_item_name + ), + ); + Ok(None) + } +} + +fn parse_lit_into_path( + cx: &Ctxt, + attr_name: Symbol, + meta: &ParseNestedMeta, +) -> syn::Result> { + let string = match get_lit_str(cx, attr_name, meta)? { + Some(string) => string, + None => return Ok(None), + }; + + Ok(match string.parse() { + Ok(path) => Some(path), + Err(_) => { + cx.error_spanned_by( + &string, + format!("failed to parse path: {:?}", string.value()), + ); + None + } + }) +} + +fn parse_lit_into_expr_path( + cx: &Ctxt, + attr_name: Symbol, + meta: &ParseNestedMeta, +) -> syn::Result> { + let string = match get_lit_str(cx, attr_name, meta)? { + Some(string) => string, + None => return Ok(None), + }; + + Ok(match string.parse() { + Ok(expr) => Some(expr), + Err(_) => { + cx.error_spanned_by( + &string, + format!("failed to parse path: {:?}", string.value()), + ); + None + } + }) +} + +fn parse_lit_into_where( + cx: &Ctxt, + attr_name: Symbol, + meta_item_name: Symbol, + meta: &ParseNestedMeta, +) -> syn::Result> { + let string = match get_lit_str2(cx, attr_name, meta_item_name, meta)? { + Some(string) => string, + None => return Ok(Vec::new()), + }; + + Ok( + match string.parse_with(Punctuated::::parse_terminated) { + Ok(predicates) => Vec::from_iter(predicates), + Err(err) => { + cx.error_spanned_by(string, err); + Vec::new() + } + }, + ) +} + +fn parse_lit_into_ty( + cx: &Ctxt, + attr_name: Symbol, + meta: &ParseNestedMeta, +) -> syn::Result> { + let string = match get_lit_str(cx, attr_name, meta)? { + Some(string) => string, + None => return Ok(None), + }; + + Ok(match string.parse() { + Ok(ty) => Some(ty), + Err(_) => { + cx.error_spanned_by( + &string, + format!("failed to parse type: {} = {:?}", attr_name, string.value()), + ); + None + } + }) +} + +// Parses a string literal like "'a + 'b + 'c" containing a nonempty list of +// lifetimes separated by `+`. +fn parse_lit_into_lifetimes( + cx: &Ctxt, + meta: &ParseNestedMeta, +) -> syn::Result> { + let string = match get_lit_str(cx, BORROW, meta)? { + Some(string) => string, + None => return Ok(BTreeSet::new()), + }; + + if let Ok(lifetimes) = string.parse_with(|input: ParseStream| { + let mut set = BTreeSet::new(); + while !input.is_empty() { + let lifetime: Lifetime = input.parse()?; + if !set.insert(lifetime.clone()) { + cx.error_spanned_by( + &string, + format!("duplicate borrowed lifetime `{}`", lifetime), + ); + } + if input.is_empty() { + break; + } + input.parse::()?; + } + Ok(set) + }) { + if lifetimes.is_empty() { + cx.error_spanned_by(string, "at least one lifetime must be borrowed"); + } + return Ok(lifetimes); + } + + cx.error_spanned_by( + &string, + format!("failed to parse borrowed lifetimes: {:?}", string.value()), + ); + Ok(BTreeSet::new()) +} + +fn is_implicitly_borrowed(ty: &syn::Type) -> bool { + is_implicitly_borrowed_reference(ty) || is_option(ty, is_implicitly_borrowed_reference) +} + +fn is_implicitly_borrowed_reference(ty: &syn::Type) -> bool { + is_reference(ty, is_str) || is_reference(ty, is_slice_u8) +} + +// Whether the type looks like it might be `std::borrow::Cow` where elem="T". +// This can have false negatives and false positives. +// +// False negative: +// +// use std::borrow::Cow as Pig; +// +// #[derive(Deserialize)] +// struct S<'a> { +// #[serde(borrow)] +// pig: Pig<'a, str>, +// } +// +// False positive: +// +// type str = [i16]; +// +// #[derive(Deserialize)] +// struct S<'a> { +// #[serde(borrow)] +// cow: Cow<'a, str>, +// } +fn is_cow(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { + let path = match ungroup(ty) { + syn::Type::Path(ty) => &ty.path, + _ => { + return false; + } + }; + let seg = match path.segments.last() { + Some(seg) => seg, + None => { + return false; + } + }; + let args = match &seg.arguments { + syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args, + _ => { + return false; + } + }; + seg.ident == "Cow" + && args.len() == 2 + && match (&args[0], &args[1]) { + (syn::GenericArgument::Lifetime(_), syn::GenericArgument::Type(arg)) => elem(arg), + _ => false, + } +} + +fn is_option(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { + let path = match ungroup(ty) { + syn::Type::Path(ty) => &ty.path, + _ => { + return false; + } + }; + let seg = match path.segments.last() { + Some(seg) => seg, + None => { + return false; + } + }; + let args = match &seg.arguments { + syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args, + _ => { + return false; + } + }; + seg.ident == "Option" + && args.len() == 1 + && match &args[0] { + syn::GenericArgument::Type(arg) => elem(arg), + _ => false, + } +} + +// Whether the type looks like it might be `&T` where elem="T". This can have +// false negatives and false positives. +// +// False negative: +// +// type Yarn = str; +// +// #[derive(Deserialize)] +// struct S<'a> { +// r: &'a Yarn, +// } +// +// False positive: +// +// type str = [i16]; +// +// #[derive(Deserialize)] +// struct S<'a> { +// r: &'a str, +// } +fn is_reference(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { + match ungroup(ty) { + syn::Type::Reference(ty) => ty.mutability.is_none() && elem(&ty.elem), + _ => false, + } +} + +fn is_str(ty: &syn::Type) -> bool { + is_primitive_type(ty, "str") +} + +fn is_slice_u8(ty: &syn::Type) -> bool { + match ungroup(ty) { + syn::Type::Slice(ty) => is_primitive_type(&ty.elem, "u8"), + _ => false, + } +} + +fn is_primitive_type(ty: &syn::Type, primitive: &str) -> bool { + match ungroup(ty) { + syn::Type::Path(ty) => ty.qself.is_none() && is_primitive_path(&ty.path, primitive), + _ => false, + } +} + +fn is_primitive_path(path: &syn::Path, primitive: &str) -> bool { + path.leading_colon.is_none() + && path.segments.len() == 1 + && path.segments[0].ident == primitive + && path.segments[0].arguments.is_empty() +} + +// All lifetimes that this type could borrow from a Deserializer. +// +// For example a type `S<'a, 'b>` could borrow `'a` and `'b`. On the other hand +// a type `for<'a> fn(&'a str)` could not borrow `'a` from the Deserializer. +// +// This is used when there is an explicit or implicit `#[serde(borrow)]` +// attribute on the field so there must be at least one borrowable lifetime. +fn borrowable_lifetimes( + cx: &Ctxt, + name: &str, + field: &syn::Field, +) -> Result, ()> { + let mut lifetimes = BTreeSet::new(); + collect_lifetimes(&field.ty, &mut lifetimes); + if lifetimes.is_empty() { + let msg = format!("field `{}` has no lifetimes to borrow", name); + cx.error_spanned_by(field, msg); + Err(()) + } else { + Ok(lifetimes) + } +} + +fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet) { + match ty { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + syn::Type::Slice(ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Array(ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Ptr(ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Reference(ty) => { + out.extend(ty.lifetime.iter().cloned()); + collect_lifetimes(&ty.elem, out); + } + syn::Type::Tuple(ty) => { + for elem in &ty.elems { + collect_lifetimes(elem, out); + } + } + syn::Type::Path(ty) => { + if let Some(qself) = &ty.qself { + collect_lifetimes(&qself.ty, out); + } + for seg in &ty.path.segments { + if let syn::PathArguments::AngleBracketed(bracketed) = &seg.arguments { + for arg in &bracketed.args { + match arg { + syn::GenericArgument::Lifetime(lifetime) => { + out.insert(lifetime.clone()); + } + syn::GenericArgument::Type(ty) => { + collect_lifetimes(ty, out); + } + syn::GenericArgument::AssocType(binding) => { + collect_lifetimes(&binding.ty, out); + } + syn::GenericArgument::Const(_) + | syn::GenericArgument::AssocConst(_) + | syn::GenericArgument::Constraint(_) + | _ => {} + } + } + } + } + } + syn::Type::Paren(ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Group(ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Macro(ty) => { + collect_lifetimes_from_tokens(ty.mac.tokens.clone(), out); + } + syn::Type::BareFn(_) + | syn::Type::Never(_) + | syn::Type::TraitObject(_) + | syn::Type::ImplTrait(_) + | syn::Type::Infer(_) + | syn::Type::Verbatim(_) => {} + + _ => {} + } +} + +fn collect_lifetimes_from_tokens(tokens: TokenStream, out: &mut BTreeSet) { + let mut iter = tokens.into_iter(); + while let Some(tt) = iter.next() { + match &tt { + TokenTree::Punct(op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => { + if let Some(TokenTree::Ident(ident)) = iter.next() { + out.insert(syn::Lifetime { + apostrophe: op.span(), + ident, + }); + } + } + TokenTree::Group(group) => { + let tokens = group.stream(); + collect_lifetimes_from_tokens(tokens, out); + } + _ => {} + } + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/case.rs b/bitbox02-bt/vendor/serde_derive/src/internals/case.rs new file mode 100644 index 0000000..8c8c02e --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/case.rs @@ -0,0 +1,200 @@ +//! Code to convert the Rust-styled field/variant (e.g. `my_field`, `MyType`) to the +//! case of the source (e.g. `my-field`, `MY_FIELD`). + +use self::RenameRule::*; +use std::fmt::{self, Debug, Display}; + +/// The different possible ways to change case of fields in a struct, or variants in an enum. +#[derive(Copy, Clone, PartialEq)] +pub enum RenameRule { + /// Don't apply a default rename rule. + None, + /// Rename direct children to "lowercase" style. + LowerCase, + /// Rename direct children to "UPPERCASE" style. + UpperCase, + /// Rename direct children to "PascalCase" style, as typically used for + /// enum variants. + PascalCase, + /// Rename direct children to "camelCase" style. + CamelCase, + /// Rename direct children to "snake_case" style, as commonly used for + /// fields. + SnakeCase, + /// Rename direct children to "SCREAMING_SNAKE_CASE" style, as commonly + /// used for constants. + ScreamingSnakeCase, + /// Rename direct children to "kebab-case" style. + KebabCase, + /// Rename direct children to "SCREAMING-KEBAB-CASE" style. + ScreamingKebabCase, +} + +static RENAME_RULES: &[(&str, RenameRule)] = &[ + ("lowercase", LowerCase), + ("UPPERCASE", UpperCase), + ("PascalCase", PascalCase), + ("camelCase", CamelCase), + ("snake_case", SnakeCase), + ("SCREAMING_SNAKE_CASE", ScreamingSnakeCase), + ("kebab-case", KebabCase), + ("SCREAMING-KEBAB-CASE", ScreamingKebabCase), +]; + +impl RenameRule { + pub fn from_str(rename_all_str: &str) -> Result { + for (name, rule) in RENAME_RULES { + if rename_all_str == *name { + return Ok(*rule); + } + } + Err(ParseError { + unknown: rename_all_str, + }) + } + + /// Apply a renaming rule to an enum variant, returning the version expected in the source. + pub fn apply_to_variant(self, variant: &str) -> String { + match self { + None | PascalCase => variant.to_owned(), + LowerCase => variant.to_ascii_lowercase(), + UpperCase => variant.to_ascii_uppercase(), + CamelCase => variant[..1].to_ascii_lowercase() + &variant[1..], + SnakeCase => { + let mut snake = String::new(); + for (i, ch) in variant.char_indices() { + if i > 0 && ch.is_uppercase() { + snake.push('_'); + } + snake.push(ch.to_ascii_lowercase()); + } + snake + } + ScreamingSnakeCase => SnakeCase.apply_to_variant(variant).to_ascii_uppercase(), + KebabCase => SnakeCase.apply_to_variant(variant).replace('_', "-"), + ScreamingKebabCase => ScreamingSnakeCase + .apply_to_variant(variant) + .replace('_', "-"), + } + } + + /// Apply a renaming rule to a struct field, returning the version expected in the source. + pub fn apply_to_field(self, field: &str) -> String { + match self { + None | LowerCase | SnakeCase => field.to_owned(), + UpperCase => field.to_ascii_uppercase(), + PascalCase => { + let mut pascal = String::new(); + let mut capitalize = true; + for ch in field.chars() { + if ch == '_' { + capitalize = true; + } else if capitalize { + pascal.push(ch.to_ascii_uppercase()); + capitalize = false; + } else { + pascal.push(ch); + } + } + pascal + } + CamelCase => { + let pascal = PascalCase.apply_to_field(field); + pascal[..1].to_ascii_lowercase() + &pascal[1..] + } + ScreamingSnakeCase => field.to_ascii_uppercase(), + KebabCase => field.replace('_', "-"), + ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-"), + } + } + + /// Returns the `RenameRule` if it is not `None`, `rule_b` otherwise. + pub fn or(self, rule_b: Self) -> Self { + match self { + None => rule_b, + _ => self, + } + } +} + +pub struct ParseError<'a> { + unknown: &'a str, +} + +impl<'a> Display for ParseError<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("unknown rename rule `rename_all = ")?; + Debug::fmt(self.unknown, f)?; + f.write_str("`, expected one of ")?; + for (i, (name, _rule)) in RENAME_RULES.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + Debug::fmt(name, f)?; + } + Ok(()) + } +} + +#[test] +fn rename_variants() { + for &(original, lower, upper, camel, snake, screaming, kebab, screaming_kebab) in &[ + ( + "Outcome", "outcome", "OUTCOME", "outcome", "outcome", "OUTCOME", "outcome", "OUTCOME", + ), + ( + "VeryTasty", + "verytasty", + "VERYTASTY", + "veryTasty", + "very_tasty", + "VERY_TASTY", + "very-tasty", + "VERY-TASTY", + ), + ("A", "a", "A", "a", "a", "A", "a", "A"), + ("Z42", "z42", "Z42", "z42", "z42", "Z42", "z42", "Z42"), + ] { + assert_eq!(None.apply_to_variant(original), original); + assert_eq!(LowerCase.apply_to_variant(original), lower); + assert_eq!(UpperCase.apply_to_variant(original), upper); + assert_eq!(PascalCase.apply_to_variant(original), original); + assert_eq!(CamelCase.apply_to_variant(original), camel); + assert_eq!(SnakeCase.apply_to_variant(original), snake); + assert_eq!(ScreamingSnakeCase.apply_to_variant(original), screaming); + assert_eq!(KebabCase.apply_to_variant(original), kebab); + assert_eq!( + ScreamingKebabCase.apply_to_variant(original), + screaming_kebab + ); + } +} + +#[test] +fn rename_fields() { + for &(original, upper, pascal, camel, screaming, kebab, screaming_kebab) in &[ + ( + "outcome", "OUTCOME", "Outcome", "outcome", "OUTCOME", "outcome", "OUTCOME", + ), + ( + "very_tasty", + "VERY_TASTY", + "VeryTasty", + "veryTasty", + "VERY_TASTY", + "very-tasty", + "VERY-TASTY", + ), + ("a", "A", "A", "a", "A", "a", "A"), + ("z42", "Z42", "Z42", "z42", "Z42", "z42", "Z42"), + ] { + assert_eq!(None.apply_to_field(original), original); + assert_eq!(UpperCase.apply_to_field(original), upper); + assert_eq!(PascalCase.apply_to_field(original), pascal); + assert_eq!(CamelCase.apply_to_field(original), camel); + assert_eq!(SnakeCase.apply_to_field(original), original); + assert_eq!(ScreamingSnakeCase.apply_to_field(original), screaming); + assert_eq!(KebabCase.apply_to_field(original), kebab); + assert_eq!(ScreamingKebabCase.apply_to_field(original), screaming_kebab); + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/check.rs b/bitbox02-bt/vendor/serde_derive/src/internals/check.rs new file mode 100644 index 0000000..52b0f37 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/check.rs @@ -0,0 +1,477 @@ +use crate::internals::ast::{Container, Data, Field, Style}; +use crate::internals::attr::{Default, Identifier, TagType}; +use crate::internals::{ungroup, Ctxt, Derive}; +use syn::{Member, Type}; + +// Cross-cutting checks that require looking at more than a single attrs object. +// Simpler checks should happen when parsing and building the attrs. +pub fn check(cx: &Ctxt, cont: &mut Container, derive: Derive) { + check_default_on_tuple(cx, cont); + check_remote_generic(cx, cont); + check_getter(cx, cont); + check_flatten(cx, cont); + check_identifier(cx, cont); + check_variant_skip_attrs(cx, cont); + check_internal_tag_field_name_conflict(cx, cont); + check_adjacent_tag_conflict(cx, cont); + check_transparent(cx, cont, derive); + check_from_and_try_from(cx, cont); +} + +// If some field of a tuple struct is marked #[serde(default)] then all fields +// after it must also be marked with that attribute, or the struct must have a +// container-level serde(default) attribute. A field's default value is only +// used for tuple fields if the sequence is exhausted at that point; that means +// all subsequent fields will fail to deserialize if they don't have their own +// default. +fn check_default_on_tuple(cx: &Ctxt, cont: &Container) { + if let Default::None = cont.attrs.default() { + if let Data::Struct(Style::Tuple, fields) = &cont.data { + let mut first_default_index = None; + for (i, field) in fields.iter().enumerate() { + // Skipped fields automatically get the #[serde(default)] + // attribute. We are interested only on non-skipped fields here. + if field.attrs.skip_deserializing() { + continue; + } + if let Default::None = field.attrs.default() { + if let Some(first) = first_default_index { + cx.error_spanned_by( + field.ty, + format!("field must have #[serde(default)] because previous field {} has #[serde(default)]", first), + ); + } + continue; + } + if first_default_index.is_none() { + first_default_index = Some(i); + } + } + } + } +} + +// Remote derive definition type must have either all of the generics of the +// remote type: +// +// #[serde(remote = "Generic")] +// struct Generic {…} +// +// or none of them, i.e. defining impls for one concrete instantiation of the +// remote type only: +// +// #[serde(remote = "Generic")] +// struct ConcreteDef {…} +// +fn check_remote_generic(cx: &Ctxt, cont: &Container) { + if let Some(remote) = cont.attrs.remote() { + let local_has_generic = !cont.generics.params.is_empty(); + let remote_has_generic = !remote.segments.last().unwrap().arguments.is_none(); + if local_has_generic && remote_has_generic { + cx.error_spanned_by(remote, "remove generic parameters from this path"); + } + } +} + +// Getters are only allowed inside structs (not enums) with the `remote` +// attribute. +fn check_getter(cx: &Ctxt, cont: &Container) { + match cont.data { + Data::Enum(_) => { + if cont.data.has_getter() { + cx.error_spanned_by( + cont.original, + "#[serde(getter = \"...\")] is not allowed in an enum", + ); + } + } + Data::Struct(_, _) => { + if cont.data.has_getter() && cont.attrs.remote().is_none() { + cx.error_spanned_by( + cont.original, + "#[serde(getter = \"...\")] can only be used in structs that have #[serde(remote = \"...\")]", + ); + } + } + } +} + +// Flattening has some restrictions we can test. +fn check_flatten(cx: &Ctxt, cont: &Container) { + match &cont.data { + Data::Enum(variants) => { + for variant in variants { + for field in &variant.fields { + check_flatten_field(cx, variant.style, field); + } + } + } + Data::Struct(style, fields) => { + for field in fields { + check_flatten_field(cx, *style, field); + } + } + } +} + +fn check_flatten_field(cx: &Ctxt, style: Style, field: &Field) { + if !field.attrs.flatten() { + return; + } + match style { + Style::Tuple => { + cx.error_spanned_by( + field.original, + "#[serde(flatten)] cannot be used on tuple structs", + ); + } + Style::Newtype => { + cx.error_spanned_by( + field.original, + "#[serde(flatten)] cannot be used on newtype structs", + ); + } + _ => {} + } +} + +// The `other` attribute must be used at most once and it must be the last +// variant of an enum. +// +// Inside a `variant_identifier` all variants must be unit variants. Inside a +// `field_identifier` all but possibly one variant must be unit variants. The +// last variant may be a newtype variant which is an implicit "other" case. +fn check_identifier(cx: &Ctxt, cont: &Container) { + let variants = match &cont.data { + Data::Enum(variants) => variants, + Data::Struct(_, _) => return, + }; + + for (i, variant) in variants.iter().enumerate() { + match ( + variant.style, + cont.attrs.identifier(), + variant.attrs.other(), + cont.attrs.tag(), + ) { + // The `other` attribute may not be used in a variant_identifier. + (_, Identifier::Variant, true, _) => { + cx.error_spanned_by( + variant.original, + "#[serde(other)] may not be used on a variant identifier", + ); + } + + // Variant with `other` attribute cannot appear in untagged enum + (_, Identifier::No, true, &TagType::None) => { + cx.error_spanned_by( + variant.original, + "#[serde(other)] cannot appear on untagged enum", + ); + } + + // Variant with `other` attribute must be the last one. + (Style::Unit, Identifier::Field, true, _) | (Style::Unit, Identifier::No, true, _) => { + if i < variants.len() - 1 { + cx.error_spanned_by( + variant.original, + "#[serde(other)] must be on the last variant", + ); + } + } + + // Variant with `other` attribute must be a unit variant. + (_, Identifier::Field, true, _) | (_, Identifier::No, true, _) => { + cx.error_spanned_by( + variant.original, + "#[serde(other)] must be on a unit variant", + ); + } + + // Any sort of variant is allowed if this is not an identifier. + (_, Identifier::No, false, _) => {} + + // Unit variant without `other` attribute is always fine. + (Style::Unit, _, false, _) => {} + + // The last field is allowed to be a newtype catch-all. + (Style::Newtype, Identifier::Field, false, _) => { + if i < variants.len() - 1 { + cx.error_spanned_by( + variant.original, + format!("`{}` must be the last variant", variant.ident), + ); + } + } + + (_, Identifier::Field, false, _) => { + cx.error_spanned_by( + variant.original, + "#[serde(field_identifier)] may only contain unit variants", + ); + } + + (_, Identifier::Variant, false, _) => { + cx.error_spanned_by( + variant.original, + "#[serde(variant_identifier)] may only contain unit variants", + ); + } + } + } +} + +// Skip-(de)serializing attributes are not allowed on variants marked +// (de)serialize_with. +fn check_variant_skip_attrs(cx: &Ctxt, cont: &Container) { + let variants = match &cont.data { + Data::Enum(variants) => variants, + Data::Struct(_, _) => return, + }; + + for variant in variants { + if variant.attrs.serialize_with().is_some() { + if variant.attrs.skip_serializing() { + cx.error_spanned_by( + variant.original, + format!( + "variant `{}` cannot have both #[serde(serialize_with)] and #[serde(skip_serializing)]", + variant.ident + ), + ); + } + + for field in &variant.fields { + let member = member_message(&field.member); + + if field.attrs.skip_serializing() { + cx.error_spanned_by( + variant.original, + format!( + "variant `{}` cannot have both #[serde(serialize_with)] and a field {} marked with #[serde(skip_serializing)]", + variant.ident, member + ), + ); + } + + if field.attrs.skip_serializing_if().is_some() { + cx.error_spanned_by( + variant.original, + format!( + "variant `{}` cannot have both #[serde(serialize_with)] and a field {} marked with #[serde(skip_serializing_if)]", + variant.ident, member + ), + ); + } + } + } + + if variant.attrs.deserialize_with().is_some() { + if variant.attrs.skip_deserializing() { + cx.error_spanned_by( + variant.original, + format!( + "variant `{}` cannot have both #[serde(deserialize_with)] and #[serde(skip_deserializing)]", + variant.ident + ), + ); + } + + for field in &variant.fields { + if field.attrs.skip_deserializing() { + let member = member_message(&field.member); + + cx.error_spanned_by( + variant.original, + format!( + "variant `{}` cannot have both #[serde(deserialize_with)] and a field {} marked with #[serde(skip_deserializing)]", + variant.ident, member + ), + ); + } + } + } + } +} + +// The tag of an internally-tagged struct variant must not be the same as either +// one of its fields, as this would result in duplicate keys in the serialized +// output and/or ambiguity in the to-be-deserialized input. +fn check_internal_tag_field_name_conflict(cx: &Ctxt, cont: &Container) { + let variants = match &cont.data { + Data::Enum(variants) => variants, + Data::Struct(_, _) => return, + }; + + let tag = match cont.attrs.tag() { + TagType::Internal { tag } => tag.as_str(), + TagType::External | TagType::Adjacent { .. } | TagType::None => return, + }; + + let diagnose_conflict = || { + cx.error_spanned_by( + cont.original, + format!("variant field name `{}` conflicts with internal tag", tag), + ); + }; + + for variant in variants { + match variant.style { + Style::Struct => { + if variant.attrs.untagged() { + continue; + } + for field in &variant.fields { + let check_ser = + !(field.attrs.skip_serializing() || variant.attrs.skip_serializing()); + let check_de = + !(field.attrs.skip_deserializing() || variant.attrs.skip_deserializing()); + let name = field.attrs.name(); + let ser_name = name.serialize_name(); + + if check_ser && ser_name == tag { + diagnose_conflict(); + return; + } + + for de_name in field.attrs.aliases() { + if check_de && de_name == tag { + diagnose_conflict(); + return; + } + } + } + } + Style::Unit | Style::Newtype | Style::Tuple => {} + } + } +} + +// In the case of adjacently-tagged enums, the type and the contents tag must +// differ, for the same reason. +fn check_adjacent_tag_conflict(cx: &Ctxt, cont: &Container) { + let (type_tag, content_tag) = match cont.attrs.tag() { + TagType::Adjacent { tag, content } => (tag, content), + TagType::Internal { .. } | TagType::External | TagType::None => return, + }; + + if type_tag == content_tag { + cx.error_spanned_by( + cont.original, + format!( + "enum tags `{}` for type and content conflict with each other", + type_tag + ), + ); + } +} + +// Enums and unit structs cannot be transparent. +fn check_transparent(cx: &Ctxt, cont: &mut Container, derive: Derive) { + if !cont.attrs.transparent() { + return; + } + + if cont.attrs.type_from().is_some() { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] is not allowed with #[serde(from = \"...\")]", + ); + } + + if cont.attrs.type_try_from().is_some() { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] is not allowed with #[serde(try_from = \"...\")]", + ); + } + + if cont.attrs.type_into().is_some() { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] is not allowed with #[serde(into = \"...\")]", + ); + } + + let fields = match &mut cont.data { + Data::Enum(_) => { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] is not allowed on an enum", + ); + return; + } + Data::Struct(Style::Unit, _) => { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] is not allowed on a unit struct", + ); + return; + } + Data::Struct(_, fields) => fields, + }; + + let mut transparent_field = None; + + for field in fields { + if allow_transparent(field, derive) { + if transparent_field.is_some() { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] requires struct to have at most one transparent field", + ); + return; + } + transparent_field = Some(field); + } + } + + match transparent_field { + Some(transparent_field) => transparent_field.attrs.mark_transparent(), + None => match derive { + Derive::Serialize => { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] requires at least one field that is not skipped", + ); + } + Derive::Deserialize => { + cx.error_spanned_by( + cont.original, + "#[serde(transparent)] requires at least one field that is neither skipped nor has a default", + ); + } + }, + } +} + +fn member_message(member: &Member) -> String { + match member { + Member::Named(ident) => format!("`{}`", ident), + Member::Unnamed(i) => format!("#{}", i.index), + } +} + +fn allow_transparent(field: &Field, derive: Derive) -> bool { + if let Type::Path(ty) = ungroup(field.ty) { + if let Some(seg) = ty.path.segments.last() { + if seg.ident == "PhantomData" { + return false; + } + } + } + + match derive { + Derive::Serialize => !field.attrs.skip_serializing(), + Derive::Deserialize => !field.attrs.skip_deserializing() && field.attrs.default().is_none(), + } +} + +fn check_from_and_try_from(cx: &Ctxt, cont: &mut Container) { + if cont.attrs.type_from().is_some() && cont.attrs.type_try_from().is_some() { + cx.error_spanned_by( + cont.original, + "#[serde(from = \"...\")] and #[serde(try_from = \"...\")] conflict with each other", + ); + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/ctxt.rs b/bitbox02-bt/vendor/serde_derive/src/internals/ctxt.rs new file mode 100644 index 0000000..a47bfa4 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/ctxt.rs @@ -0,0 +1,68 @@ +use quote::ToTokens; +use std::cell::RefCell; +use std::fmt::Display; +use std::thread; + +/// A type to collect errors together and format them. +/// +/// Dropping this object will cause a panic. It must be consumed using `check`. +/// +/// References can be shared since this type uses run-time exclusive mut checking. +#[derive(Default)] +pub struct Ctxt { + // The contents will be set to `None` during checking. This is so that checking can be + // enforced. + errors: RefCell>>, +} + +impl Ctxt { + /// Create a new context object. + /// + /// This object contains no errors, but will still trigger a panic if it is not `check`ed. + pub fn new() -> Self { + Ctxt { + errors: RefCell::new(Some(Vec::new())), + } + } + + /// Add an error to the context object with a tokenenizable object. + /// + /// The object is used for spanning in error messages. + pub fn error_spanned_by(&self, obj: A, msg: T) { + self.errors + .borrow_mut() + .as_mut() + .unwrap() + // Curb monomorphization from generating too many identical methods. + .push(syn::Error::new_spanned(obj.into_token_stream(), msg)); + } + + /// Add one of Syn's parse errors. + pub fn syn_error(&self, err: syn::Error) { + self.errors.borrow_mut().as_mut().unwrap().push(err); + } + + /// Consume this object, producing a formatted error string if there are errors. + pub fn check(self) -> syn::Result<()> { + let mut errors = self.errors.borrow_mut().take().unwrap().into_iter(); + + let mut combined = match errors.next() { + Some(first) => first, + None => return Ok(()), + }; + + for rest in errors { + combined.combine(rest); + } + + Err(combined) + } +} + +impl Drop for Ctxt { + fn drop(&mut self) { + if !thread::panicking() && self.errors.borrow().is_some() { + panic!("forgot to check for errors"); + } + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/mod.rs b/bitbox02-bt/vendor/serde_derive/src/internals/mod.rs new file mode 100644 index 0000000..f98ef08 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/mod.rs @@ -0,0 +1,27 @@ +pub mod ast; +pub mod attr; + +mod case; +mod check; +mod ctxt; +mod receiver; +mod respan; +mod symbol; + +use syn::Type; + +pub use self::ctxt::Ctxt; +pub use self::receiver::replace_receiver; + +#[derive(Copy, Clone)] +pub enum Derive { + Serialize, + Deserialize, +} + +pub fn ungroup(mut ty: &Type) -> &Type { + while let Type::Group(group) = ty { + ty = &group.elem; + } + ty +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/receiver.rs b/bitbox02-bt/vendor/serde_derive/src/internals/receiver.rs new file mode 100644 index 0000000..852e857 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/receiver.rs @@ -0,0 +1,292 @@ +use crate::internals::respan::respan; +use proc_macro2::Span; +use quote::ToTokens; +use std::mem; +use syn::punctuated::Punctuated; +use syn::{ + parse_quote, Data, DeriveInput, Expr, ExprPath, GenericArgument, GenericParam, Generics, Macro, + Path, PathArguments, QSelf, ReturnType, Token, Type, TypeParamBound, TypePath, WherePredicate, +}; + +pub fn replace_receiver(input: &mut DeriveInput) { + let self_ty = { + let ident = &input.ident; + let ty_generics = input.generics.split_for_impl().1; + parse_quote!(#ident #ty_generics) + }; + let mut visitor = ReplaceReceiver(&self_ty); + visitor.visit_generics_mut(&mut input.generics); + visitor.visit_data_mut(&mut input.data); +} + +struct ReplaceReceiver<'a>(&'a TypePath); + +impl ReplaceReceiver<'_> { + fn self_ty(&self, span: Span) -> TypePath { + let tokens = self.0.to_token_stream(); + let respanned = respan(tokens, span); + syn::parse2(respanned).unwrap() + } + + fn self_to_qself(&self, qself: &mut Option, path: &mut Path) { + if path.leading_colon.is_some() || path.segments[0].ident != "Self" { + return; + } + + if path.segments.len() == 1 { + self.self_to_expr_path(path); + return; + } + + let span = path.segments[0].ident.span(); + *qself = Some(QSelf { + lt_token: Token![<](span), + ty: Box::new(Type::Path(self.self_ty(span))), + position: 0, + as_token: None, + gt_token: Token![>](span), + }); + + path.leading_colon = Some(**path.segments.pairs().next().unwrap().punct().unwrap()); + + let segments = mem::replace(&mut path.segments, Punctuated::new()); + path.segments = segments.into_pairs().skip(1).collect(); + } + + fn self_to_expr_path(&self, path: &mut Path) { + let self_ty = self.self_ty(path.segments[0].ident.span()); + let variant = mem::replace(path, self_ty.path); + for segment in &mut path.segments { + if let PathArguments::AngleBracketed(bracketed) = &mut segment.arguments { + if bracketed.colon2_token.is_none() && !bracketed.args.is_empty() { + bracketed.colon2_token = Some(::default()); + } + } + } + if variant.segments.len() > 1 { + path.segments.push_punct(::default()); + path.segments.extend(variant.segments.into_pairs().skip(1)); + } + } +} + +impl ReplaceReceiver<'_> { + // `Self` -> `Receiver` + fn visit_type_mut(&mut self, ty: &mut Type) { + let span = if let Type::Path(node) = ty { + if node.qself.is_none() && node.path.is_ident("Self") { + node.path.segments[0].ident.span() + } else { + self.visit_type_path_mut(node); + return; + } + } else { + self.visit_type_mut_impl(ty); + return; + }; + *ty = Type::Path(self.self_ty(span)); + } + + // `Self::Assoc` -> `::Assoc` + fn visit_type_path_mut(&mut self, ty: &mut TypePath) { + if ty.qself.is_none() { + self.self_to_qself(&mut ty.qself, &mut ty.path); + } + self.visit_type_path_mut_impl(ty); + } + + // `Self::method` -> `::method` + fn visit_expr_path_mut(&mut self, expr: &mut ExprPath) { + if expr.qself.is_none() { + self.self_to_qself(&mut expr.qself, &mut expr.path); + } + self.visit_expr_path_mut_impl(expr); + } + + // Everything below is simply traversing the syntax tree. + + fn visit_type_mut_impl(&mut self, ty: &mut Type) { + match ty { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + Type::Array(ty) => { + self.visit_type_mut(&mut ty.elem); + self.visit_expr_mut(&mut ty.len); + } + Type::BareFn(ty) => { + for arg in &mut ty.inputs { + self.visit_type_mut(&mut arg.ty); + } + self.visit_return_type_mut(&mut ty.output); + } + Type::Group(ty) => self.visit_type_mut(&mut ty.elem), + Type::ImplTrait(ty) => { + for bound in &mut ty.bounds { + self.visit_type_param_bound_mut(bound); + } + } + Type::Macro(ty) => self.visit_macro_mut(&mut ty.mac), + Type::Paren(ty) => self.visit_type_mut(&mut ty.elem), + Type::Path(ty) => { + if let Some(qself) = &mut ty.qself { + self.visit_type_mut(&mut qself.ty); + } + self.visit_path_mut(&mut ty.path); + } + Type::Ptr(ty) => self.visit_type_mut(&mut ty.elem), + Type::Reference(ty) => self.visit_type_mut(&mut ty.elem), + Type::Slice(ty) => self.visit_type_mut(&mut ty.elem), + Type::TraitObject(ty) => { + for bound in &mut ty.bounds { + self.visit_type_param_bound_mut(bound); + } + } + Type::Tuple(ty) => { + for elem in &mut ty.elems { + self.visit_type_mut(elem); + } + } + + Type::Infer(_) | Type::Never(_) | Type::Verbatim(_) => {} + + _ => {} + } + } + + fn visit_type_path_mut_impl(&mut self, ty: &mut TypePath) { + if let Some(qself) = &mut ty.qself { + self.visit_type_mut(&mut qself.ty); + } + self.visit_path_mut(&mut ty.path); + } + + fn visit_expr_path_mut_impl(&mut self, expr: &mut ExprPath) { + if let Some(qself) = &mut expr.qself { + self.visit_type_mut(&mut qself.ty); + } + self.visit_path_mut(&mut expr.path); + } + + fn visit_path_mut(&mut self, path: &mut Path) { + for segment in &mut path.segments { + self.visit_path_arguments_mut(&mut segment.arguments); + } + } + + fn visit_path_arguments_mut(&mut self, arguments: &mut PathArguments) { + match arguments { + PathArguments::None => {} + PathArguments::AngleBracketed(arguments) => { + for arg in &mut arguments.args { + match arg { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + GenericArgument::Type(arg) => self.visit_type_mut(arg), + GenericArgument::AssocType(arg) => self.visit_type_mut(&mut arg.ty), + GenericArgument::Lifetime(_) + | GenericArgument::Const(_) + | GenericArgument::AssocConst(_) + | GenericArgument::Constraint(_) => {} + _ => {} + } + } + } + PathArguments::Parenthesized(arguments) => { + for argument in &mut arguments.inputs { + self.visit_type_mut(argument); + } + self.visit_return_type_mut(&mut arguments.output); + } + } + } + + fn visit_return_type_mut(&mut self, return_type: &mut ReturnType) { + match return_type { + ReturnType::Default => {} + ReturnType::Type(_, output) => self.visit_type_mut(output), + } + } + + fn visit_type_param_bound_mut(&mut self, bound: &mut TypeParamBound) { + match bound { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + TypeParamBound::Trait(bound) => self.visit_path_mut(&mut bound.path), + TypeParamBound::Lifetime(_) | TypeParamBound::Verbatim(_) => {} + _ => {} + } + } + + fn visit_generics_mut(&mut self, generics: &mut Generics) { + for param in &mut generics.params { + match param { + GenericParam::Type(param) => { + for bound in &mut param.bounds { + self.visit_type_param_bound_mut(bound); + } + } + GenericParam::Lifetime(_) | GenericParam::Const(_) => {} + } + } + if let Some(where_clause) = &mut generics.where_clause { + for predicate in &mut where_clause.predicates { + match predicate { + #![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))] + WherePredicate::Type(predicate) => { + self.visit_type_mut(&mut predicate.bounded_ty); + for bound in &mut predicate.bounds { + self.visit_type_param_bound_mut(bound); + } + } + WherePredicate::Lifetime(_) => {} + _ => {} + } + } + } + } + + fn visit_data_mut(&mut self, data: &mut Data) { + match data { + Data::Struct(data) => { + for field in &mut data.fields { + self.visit_type_mut(&mut field.ty); + } + } + Data::Enum(data) => { + for variant in &mut data.variants { + for field in &mut variant.fields { + self.visit_type_mut(&mut field.ty); + } + } + } + Data::Union(_) => {} + } + } + + fn visit_expr_mut(&mut self, expr: &mut Expr) { + match expr { + Expr::Binary(expr) => { + self.visit_expr_mut(&mut expr.left); + self.visit_expr_mut(&mut expr.right); + } + Expr::Call(expr) => { + self.visit_expr_mut(&mut expr.func); + for arg in &mut expr.args { + self.visit_expr_mut(arg); + } + } + Expr::Cast(expr) => { + self.visit_expr_mut(&mut expr.expr); + self.visit_type_mut(&mut expr.ty); + } + Expr::Field(expr) => self.visit_expr_mut(&mut expr.base), + Expr::Index(expr) => { + self.visit_expr_mut(&mut expr.expr); + self.visit_expr_mut(&mut expr.index); + } + Expr::Paren(expr) => self.visit_expr_mut(&mut expr.expr), + Expr::Path(expr) => self.visit_expr_path_mut(expr), + Expr::Unary(expr) => self.visit_expr_mut(&mut expr.expr), + _ => {} + } + } + + fn visit_macro_mut(&mut self, _mac: &mut Macro) {} +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/respan.rs b/bitbox02-bt/vendor/serde_derive/src/internals/respan.rs new file mode 100644 index 0000000..dcec701 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/respan.rs @@ -0,0 +1,16 @@ +use proc_macro2::{Group, Span, TokenStream, TokenTree}; + +pub(crate) fn respan(stream: TokenStream, span: Span) -> TokenStream { + stream + .into_iter() + .map(|token| respan_token(token, span)) + .collect() +} + +fn respan_token(mut token: TokenTree, span: Span) -> TokenTree { + if let TokenTree::Group(g) = &mut token { + *g = Group::new(g.delimiter(), respan(g.stream(), span)); + } + token.set_span(span); + token +} diff --git a/bitbox02-bt/vendor/serde_derive/src/internals/symbol.rs b/bitbox02-bt/vendor/serde_derive/src/internals/symbol.rs new file mode 100644 index 0000000..572391a --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/internals/symbol.rs @@ -0,0 +1,71 @@ +use std::fmt::{self, Display}; +use syn::{Ident, Path}; + +#[derive(Copy, Clone)] +pub struct Symbol(&'static str); + +pub const ALIAS: Symbol = Symbol("alias"); +pub const BORROW: Symbol = Symbol("borrow"); +pub const BOUND: Symbol = Symbol("bound"); +pub const CONTENT: Symbol = Symbol("content"); +pub const CRATE: Symbol = Symbol("crate"); +pub const DEFAULT: Symbol = Symbol("default"); +pub const DENY_UNKNOWN_FIELDS: Symbol = Symbol("deny_unknown_fields"); +pub const DESERIALIZE: Symbol = Symbol("deserialize"); +pub const DESERIALIZE_WITH: Symbol = Symbol("deserialize_with"); +pub const EXPECTING: Symbol = Symbol("expecting"); +pub const FIELD_IDENTIFIER: Symbol = Symbol("field_identifier"); +pub const FLATTEN: Symbol = Symbol("flatten"); +pub const FROM: Symbol = Symbol("from"); +pub const GETTER: Symbol = Symbol("getter"); +pub const INTO: Symbol = Symbol("into"); +pub const NON_EXHAUSTIVE: Symbol = Symbol("non_exhaustive"); +pub const OTHER: Symbol = Symbol("other"); +pub const REMOTE: Symbol = Symbol("remote"); +pub const RENAME: Symbol = Symbol("rename"); +pub const RENAME_ALL: Symbol = Symbol("rename_all"); +pub const RENAME_ALL_FIELDS: Symbol = Symbol("rename_all_fields"); +pub const REPR: Symbol = Symbol("repr"); +pub const SERDE: Symbol = Symbol("serde"); +pub const SERIALIZE: Symbol = Symbol("serialize"); +pub const SERIALIZE_WITH: Symbol = Symbol("serialize_with"); +pub const SKIP: Symbol = Symbol("skip"); +pub const SKIP_DESERIALIZING: Symbol = Symbol("skip_deserializing"); +pub const SKIP_SERIALIZING: Symbol = Symbol("skip_serializing"); +pub const SKIP_SERIALIZING_IF: Symbol = Symbol("skip_serializing_if"); +pub const TAG: Symbol = Symbol("tag"); +pub const TRANSPARENT: Symbol = Symbol("transparent"); +pub const TRY_FROM: Symbol = Symbol("try_from"); +pub const UNTAGGED: Symbol = Symbol("untagged"); +pub const VARIANT_IDENTIFIER: Symbol = Symbol("variant_identifier"); +pub const WITH: Symbol = Symbol("with"); + +impl PartialEq for Ident { + fn eq(&self, word: &Symbol) -> bool { + self == word.0 + } +} + +impl<'a> PartialEq for &'a Ident { + fn eq(&self, word: &Symbol) -> bool { + *self == word.0 + } +} + +impl PartialEq for Path { + fn eq(&self, word: &Symbol) -> bool { + self.is_ident(word.0) + } +} + +impl<'a> PartialEq for &'a Path { + fn eq(&self, word: &Symbol) -> bool { + self.is_ident(word.0) + } +} + +impl Display for Symbol { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.0) + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/lib.rs b/bitbox02-bt/vendor/serde_derive/src/lib.rs new file mode 100644 index 0000000..bedd1cb --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/lib.rs @@ -0,0 +1,102 @@ +//! This crate provides Serde's two derive macros. +//! +//! ```edition2021 +//! # use serde_derive::{Deserialize, Serialize}; +//! # +//! #[derive(Serialize, Deserialize)] +//! # struct S; +//! # +//! # fn main() {} +//! ``` +//! +//! Please refer to [https://serde.rs/derive.html] for how to set this up. +//! +//! [https://serde.rs/derive.html]: https://serde.rs/derive.html + +#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.210")] +#![cfg_attr(not(check_cfg), allow(unexpected_cfgs))] +// Ignored clippy lints +#![allow( + // clippy false positive: https://github.com/rust-lang/rust-clippy/issues/7054 + clippy::branches_sharing_code, + clippy::cognitive_complexity, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7575 + clippy::collapsible_match, + clippy::derive_partial_eq_without_eq, + clippy::enum_variant_names, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6797 + clippy::manual_map, + clippy::match_like_matches_macro, + clippy::needless_pass_by_value, + clippy::too_many_arguments, + clippy::trivially_copy_pass_by_ref, + clippy::used_underscore_binding, + clippy::wildcard_in_or_patterns, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704 + clippy::unnested_or_patterns, +)] +// Ignored clippy_pedantic lints +#![allow( + clippy::cast_possible_truncation, + clippy::checked_conversions, + clippy::doc_markdown, + clippy::enum_glob_use, + clippy::indexing_slicing, + clippy::items_after_statements, + clippy::let_underscore_untyped, + clippy::manual_assert, + clippy::map_err_ignore, + clippy::match_same_arms, + // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6984 + clippy::match_wildcard_for_single_variants, + clippy::module_name_repetitions, + clippy::must_use_candidate, + clippy::similar_names, + clippy::single_match_else, + clippy::struct_excessive_bools, + clippy::too_many_lines, + clippy::unseparated_literal_suffix, + clippy::unused_self, + clippy::use_self, + clippy::wildcard_imports +)] +#![cfg_attr(all(test, exhaustive), feature(non_exhaustive_omitted_patterns_lint))] + +extern crate proc_macro2; +extern crate quote; +extern crate syn; + +extern crate proc_macro; + +mod internals; + +use proc_macro::TokenStream; +use syn::parse_macro_input; +use syn::DeriveInput; + +#[macro_use] +mod bound; +#[macro_use] +mod fragment; + +mod de; +mod dummy; +mod pretend; +mod ser; +mod this; + +#[proc_macro_derive(Serialize, attributes(serde))] +pub fn derive_serialize(input: TokenStream) -> TokenStream { + let mut input = parse_macro_input!(input as DeriveInput); + ser::expand_derive_serialize(&mut input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +#[proc_macro_derive(Deserialize, attributes(serde))] +pub fn derive_deserialize(input: TokenStream) -> TokenStream { + let mut input = parse_macro_input!(input as DeriveInput); + de::expand_derive_deserialize(&mut input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} diff --git a/bitbox02-bt/vendor/serde_derive/src/pretend.rs b/bitbox02-bt/vendor/serde_derive/src/pretend.rs new file mode 100644 index 0000000..2c9e779 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/pretend.rs @@ -0,0 +1,185 @@ +use crate::internals::ast::{Container, Data, Field, Style, Variant}; +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; + +// Suppress dead_code warnings that would otherwise appear when using a remote +// derive. Other than this pretend code, a struct annotated with remote derive +// never has its fields referenced and an enum annotated with remote derive +// never has its variants constructed. +// +// warning: field is never used: `i` +// --> src/main.rs:4:20 +// | +// 4 | struct StructDef { i: i32 } +// | ^^^^^^ +// +// warning: variant is never constructed: `V` +// --> src/main.rs:8:16 +// | +// 8 | enum EnumDef { V } +// | ^ +// +pub fn pretend_used(cont: &Container, is_packed: bool) -> TokenStream { + let pretend_fields = pretend_fields_used(cont, is_packed); + let pretend_variants = pretend_variants_used(cont); + + quote! { + #pretend_fields + #pretend_variants + } +} + +// For structs with named fields, expands to: +// +// match None::<&T> { +// Some(T { a: __v0, b: __v1 }) => {} +// _ => {} +// } +// +// For packed structs on sufficiently new rustc, expands to: +// +// match None::<&T> { +// Some(__v @ T { a: _, b: _ }) => { +// let _ = addr_of!(__v.a); +// let _ = addr_of!(__v.b); +// } +// _ => {} +// } +// +// For packed structs on older rustc, we assume Sized and !Drop, and expand to: +// +// match None:: { +// Some(T { a: __v0, b: __v1 }) => {} +// _ => {} +// } +// +// For enums, expands to the following but only including struct variants: +// +// match None::<&T> { +// Some(T::A { a: __v0 }) => {} +// Some(T::B { b: __v0 }) => {} +// _ => {} +// } +// +fn pretend_fields_used(cont: &Container, is_packed: bool) -> TokenStream { + match &cont.data { + Data::Enum(variants) => pretend_fields_used_enum(cont, variants), + Data::Struct(Style::Struct | Style::Tuple | Style::Newtype, fields) => { + if is_packed { + pretend_fields_used_struct_packed(cont, fields) + } else { + pretend_fields_used_struct(cont, fields) + } + } + Data::Struct(Style::Unit, _) => quote!(), + } +} + +fn pretend_fields_used_struct(cont: &Container, fields: &[Field]) -> TokenStream { + let type_ident = &cont.ident; + let (_, ty_generics, _) = cont.generics.split_for_impl(); + + let members = fields.iter().map(|field| &field.member); + let placeholders = (0usize..).map(|i| format_ident!("__v{}", i)); + + quote! { + match _serde::__private::None::<&#type_ident #ty_generics> { + _serde::__private::Some(#type_ident { #(#members: #placeholders),* }) => {} + _ => {} + } + } +} + +fn pretend_fields_used_struct_packed(cont: &Container, fields: &[Field]) -> TokenStream { + let type_ident = &cont.ident; + let (_, ty_generics, _) = cont.generics.split_for_impl(); + + let members = fields.iter().map(|field| &field.member).collect::>(); + + quote! { + match _serde::__private::None::<&#type_ident #ty_generics> { + _serde::__private::Some(__v @ #type_ident { #(#members: _),* }) => { + #( + let _ = _serde::__private::ptr::addr_of!(__v.#members); + )* + } + _ => {} + } + } +} + +fn pretend_fields_used_enum(cont: &Container, variants: &[Variant]) -> TokenStream { + let type_ident = &cont.ident; + let (_, ty_generics, _) = cont.generics.split_for_impl(); + + let patterns = variants + .iter() + .filter_map(|variant| match variant.style { + Style::Struct | Style::Tuple | Style::Newtype => { + let variant_ident = &variant.ident; + let members = variant.fields.iter().map(|field| &field.member); + let placeholders = (0usize..).map(|i| format_ident!("__v{}", i)); + Some(quote!(#type_ident::#variant_ident { #(#members: #placeholders),* })) + } + Style::Unit => None, + }) + .collect::>(); + + quote! { + match _serde::__private::None::<&#type_ident #ty_generics> { + #( + _serde::__private::Some(#patterns) => {} + )* + _ => {} + } + } +} + +// Expands to one of these per enum variant: +// +// match None { +// Some((__v0, __v1,)) => { +// let _ = E::V { a: __v0, b: __v1 }; +// } +// _ => {} +// } +// +fn pretend_variants_used(cont: &Container) -> TokenStream { + let variants = match &cont.data { + Data::Enum(variants) => variants, + Data::Struct(_, _) => { + return quote!(); + } + }; + + let type_ident = &cont.ident; + let (_, ty_generics, _) = cont.generics.split_for_impl(); + let turbofish = ty_generics.as_turbofish(); + + let cases = variants.iter().map(|variant| { + let variant_ident = &variant.ident; + let placeholders = &(0..variant.fields.len()) + .map(|i| format_ident!("__v{}", i)) + .collect::>(); + + let pat = match variant.style { + Style::Struct => { + let members = variant.fields.iter().map(|field| &field.member); + quote!({ #(#members: #placeholders),* }) + } + Style::Tuple | Style::Newtype => quote!(( #(#placeholders),* )), + Style::Unit => quote!(), + }; + + quote! { + match _serde::__private::None { + _serde::__private::Some((#(#placeholders,)*)) => { + let _ = #type_ident::#variant_ident #turbofish #pat; + } + _ => {} + } + } + }); + + quote!(#(#cases)*) +} diff --git a/bitbox02-bt/vendor/serde_derive/src/ser.rs b/bitbox02-bt/vendor/serde_derive/src/ser.rs new file mode 100644 index 0000000..35f8ca4 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/ser.rs @@ -0,0 +1,1350 @@ +use crate::fragment::{Fragment, Match, Stmts}; +use crate::internals::ast::{Container, Data, Field, Style, Variant}; +use crate::internals::{attr, replace_receiver, Ctxt, Derive}; +use crate::{bound, dummy, pretend, this}; +use proc_macro2::{Span, TokenStream}; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::{parse_quote, Ident, Index, Member}; + +pub fn expand_derive_serialize(input: &mut syn::DeriveInput) -> syn::Result { + replace_receiver(input); + + let ctxt = Ctxt::new(); + let cont = match Container::from_ast(&ctxt, input, Derive::Serialize) { + Some(cont) => cont, + None => return Err(ctxt.check().unwrap_err()), + }; + precondition(&ctxt, &cont); + ctxt.check()?; + + let ident = &cont.ident; + let params = Parameters::new(&cont); + let (impl_generics, ty_generics, where_clause) = params.generics.split_for_impl(); + let body = Stmts(serialize_body(&cont, ¶ms)); + let serde = cont.attrs.serde_path(); + + let impl_block = if let Some(remote) = cont.attrs.remote() { + let vis = &input.vis; + let used = pretend::pretend_used(&cont, params.is_packed); + quote! { + impl #impl_generics #ident #ty_generics #where_clause { + #vis fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> #serde::__private::Result<__S::Ok, __S::Error> + where + __S: #serde::Serializer, + { + #used + #body + } + } + } + } else { + quote! { + #[automatically_derived] + impl #impl_generics #serde::Serialize for #ident #ty_generics #where_clause { + fn serialize<__S>(&self, __serializer: __S) -> #serde::__private::Result<__S::Ok, __S::Error> + where + __S: #serde::Serializer, + { + #body + } + } + } + }; + + Ok(dummy::wrap_in_const( + cont.attrs.custom_serde_path(), + impl_block, + )) +} + +fn precondition(cx: &Ctxt, cont: &Container) { + match cont.attrs.identifier() { + attr::Identifier::No => {} + attr::Identifier::Field => { + cx.error_spanned_by(cont.original, "field identifiers cannot be serialized"); + } + attr::Identifier::Variant => { + cx.error_spanned_by(cont.original, "variant identifiers cannot be serialized"); + } + } +} + +struct Parameters { + /// Variable holding the value being serialized. Either `self` for local + /// types or `__self` for remote types. + self_var: Ident, + + /// Path to the type the impl is for. Either a single `Ident` for local + /// types (does not include generic parameters) or `some::remote::Path` for + /// remote types. + this_type: syn::Path, + + /// Same as `this_type` but using `::` for generic parameters for use in + /// expression position. + this_value: syn::Path, + + /// Generics including any explicit and inferred bounds for the impl. + generics: syn::Generics, + + /// Type has a `serde(remote = "...")` attribute. + is_remote: bool, + + /// Type has a repr(packed) attribute. + is_packed: bool, +} + +impl Parameters { + fn new(cont: &Container) -> Self { + let is_remote = cont.attrs.remote().is_some(); + let self_var = if is_remote { + Ident::new("__self", Span::call_site()) + } else { + Ident::new("self", Span::call_site()) + }; + + let this_type = this::this_type(cont); + let this_value = this::this_value(cont); + let is_packed = cont.attrs.is_packed(); + let generics = build_generics(cont); + + Parameters { + self_var, + this_type, + this_value, + generics, + is_remote, + is_packed, + } + } + + /// Type name to use in error messages and `&'static str` arguments to + /// various Serializer methods. + fn type_name(&self) -> String { + self.this_type.segments.last().unwrap().ident.to_string() + } +} + +// All the generics in the input, plus a bound `T: Serialize` for each generic +// field type that will be serialized by us. +fn build_generics(cont: &Container) -> syn::Generics { + let generics = bound::without_defaults(cont.generics); + + let generics = + bound::with_where_predicates_from_fields(cont, &generics, attr::Field::ser_bound); + + let generics = + bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::ser_bound); + + match cont.attrs.ser_bound() { + Some(predicates) => bound::with_where_predicates(&generics, predicates), + None => bound::with_bound( + cont, + &generics, + needs_serialize_bound, + &parse_quote!(_serde::Serialize), + ), + } +} + +// Fields with a `skip_serializing` or `serialize_with` attribute, or which +// belong to a variant with a 'skip_serializing` or `serialize_with` attribute, +// are not serialized by us so we do not generate a bound. Fields with a `bound` +// attribute specify their own bound so we do not generate one. All other fields +// may need a `T: Serialize` bound where T is the type of the field. +fn needs_serialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { + !field.skip_serializing() + && field.serialize_with().is_none() + && field.ser_bound().is_none() + && variant.map_or(true, |variant| { + !variant.skip_serializing() + && variant.serialize_with().is_none() + && variant.ser_bound().is_none() + }) +} + +fn serialize_body(cont: &Container, params: &Parameters) -> Fragment { + if cont.attrs.transparent() { + serialize_transparent(cont, params) + } else if let Some(type_into) = cont.attrs.type_into() { + serialize_into(params, type_into) + } else { + match &cont.data { + Data::Enum(variants) => serialize_enum(params, variants, &cont.attrs), + Data::Struct(Style::Struct, fields) => serialize_struct(params, fields, &cont.attrs), + Data::Struct(Style::Tuple, fields) => { + serialize_tuple_struct(params, fields, &cont.attrs) + } + Data::Struct(Style::Newtype, fields) => { + serialize_newtype_struct(params, &fields[0], &cont.attrs) + } + Data::Struct(Style::Unit, _) => serialize_unit_struct(&cont.attrs), + } + } +} + +fn serialize_transparent(cont: &Container, params: &Parameters) -> Fragment { + let fields = match &cont.data { + Data::Struct(_, fields) => fields, + Data::Enum(_) => unreachable!(), + }; + + let self_var = ¶ms.self_var; + let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap(); + let member = &transparent_field.member; + + let path = match transparent_field.attrs.serialize_with() { + Some(path) => quote!(#path), + None => { + let span = transparent_field.original.span(); + quote_spanned!(span=> _serde::Serialize::serialize) + } + }; + + quote_block! { + #path(&#self_var.#member, __serializer) + } +} + +fn serialize_into(params: &Parameters, type_into: &syn::Type) -> Fragment { + let self_var = ¶ms.self_var; + quote_block! { + _serde::Serialize::serialize( + &_serde::__private::Into::<#type_into>::into(_serde::__private::Clone::clone(#self_var)), + __serializer) + } +} + +fn serialize_unit_struct(cattrs: &attr::Container) -> Fragment { + let type_name = cattrs.name().serialize_name(); + + quote_expr! { + _serde::Serializer::serialize_unit_struct(__serializer, #type_name) + } +} + +fn serialize_newtype_struct( + params: &Parameters, + field: &Field, + cattrs: &attr::Container, +) -> Fragment { + let type_name = cattrs.name().serialize_name(); + + let mut field_expr = get_member( + params, + field, + &Member::Unnamed(Index { + index: 0, + span: Span::call_site(), + }), + ); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::Serializer::serialize_newtype_struct); + quote_expr! { + #func(__serializer, #type_name, #field_expr) + } +} + +fn serialize_tuple_struct( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + let serialize_stmts = + serialize_tuple_struct_visitor(fields, params, false, &TupleTrait::SerializeTupleStruct); + + let type_name = cattrs.name().serialize_name(); + + let mut serialized_fields = fields + .iter() + .enumerate() + .filter(|(_, field)| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some()); + + let len = serialized_fields + .map(|(i, field)| match field.attrs.skip_serializing_if() { + None => quote!(1), + Some(path) => { + let index = syn::Index { + index: i as u32, + span: Span::call_site(), + }; + let field_expr = get_member(params, field, &Member::Unnamed(index)); + quote!(if #path(#field_expr) { 0 } else { 1 }) + } + }) + .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); + + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_tuple_struct(__serializer, #type_name, #len)?; + #(#serialize_stmts)* + _serde::ser::SerializeTupleStruct::end(__serde_state) + } +} + +fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment { + assert!( + fields.len() as u64 <= u64::from(u32::MAX), + "too many fields in {}: {}, maximum supported count is {}", + cattrs.name().serialize_name(), + fields.len(), + u32::MAX, + ); + + let has_non_skipped_flatten = fields + .iter() + .any(|field| field.attrs.flatten() && !field.attrs.skip_serializing()); + if has_non_skipped_flatten { + serialize_struct_as_map(params, fields, cattrs) + } else { + serialize_struct_as_struct(params, fields, cattrs) + } +} + +fn serialize_struct_tag_field(cattrs: &attr::Container, struct_trait: &StructTrait) -> TokenStream { + match cattrs.tag() { + attr::TagType::Internal { tag } => { + let type_name = cattrs.name().serialize_name(); + let func = struct_trait.serialize_field(Span::call_site()); + quote! { + #func(&mut __serde_state, #tag, #type_name)?; + } + } + _ => quote! {}, + } +} + +fn serialize_struct_as_struct( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + let serialize_fields = + serialize_struct_visitor(fields, params, false, &StructTrait::SerializeStruct); + + let type_name = cattrs.name().serialize_name(); + + let tag_field = serialize_struct_tag_field(cattrs, &StructTrait::SerializeStruct); + let tag_field_exists = !tag_field.is_empty(); + + let mut serialized_fields = fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some() || tag_field_exists); + + let len = serialized_fields + .map(|field| match field.attrs.skip_serializing_if() { + None => quote!(1), + Some(path) => { + let field_expr = get_member(params, field, &field.member); + quote!(if #path(#field_expr) { 0 } else { 1 }) + } + }) + .fold( + quote!(#tag_field_exists as usize), + |sum, expr| quote!(#sum + #expr), + ); + + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_struct(__serializer, #type_name, #len)?; + #tag_field + #(#serialize_fields)* + _serde::ser::SerializeStruct::end(__serde_state) + } +} + +fn serialize_struct_as_map( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + let serialize_fields = + serialize_struct_visitor(fields, params, false, &StructTrait::SerializeMap); + + let tag_field = serialize_struct_tag_field(cattrs, &StructTrait::SerializeMap); + let tag_field_exists = !tag_field.is_empty(); + + let mut serialized_fields = fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some() || tag_field_exists); + + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_map(__serializer, _serde::__private::None)?; + #tag_field + #(#serialize_fields)* + _serde::ser::SerializeMap::end(__serde_state) + } +} + +fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Container) -> Fragment { + assert!(variants.len() as u64 <= u64::from(u32::MAX)); + + let self_var = ¶ms.self_var; + + let mut arms: Vec<_> = variants + .iter() + .enumerate() + .map(|(variant_index, variant)| { + serialize_variant(params, variant, variant_index as u32, cattrs) + }) + .collect(); + + if cattrs.remote().is_some() && cattrs.non_exhaustive() { + arms.push(quote! { + ref unrecognized => _serde::__private::Err(_serde::ser::Error::custom(_serde::__private::ser::CannotSerializeVariant(unrecognized))), + }); + } + + quote_expr! { + match *#self_var { + #(#arms)* + } + } +} + +fn serialize_variant( + params: &Parameters, + variant: &Variant, + variant_index: u32, + cattrs: &attr::Container, +) -> TokenStream { + let this_value = ¶ms.this_value; + let variant_ident = &variant.ident; + + if variant.attrs.skip_serializing() { + let skipped_msg = format!( + "the enum variant {}::{} cannot be serialized", + params.type_name(), + variant_ident + ); + let skipped_err = quote! { + _serde::__private::Err(_serde::ser::Error::custom(#skipped_msg)) + }; + let fields_pat = match variant.style { + Style::Unit => quote!(), + Style::Newtype | Style::Tuple => quote!((..)), + Style::Struct => quote!({ .. }), + }; + quote! { + #this_value::#variant_ident #fields_pat => #skipped_err, + } + } else { + // variant wasn't skipped + let case = match variant.style { + Style::Unit => { + quote! { + #this_value::#variant_ident + } + } + Style::Newtype => { + quote! { + #this_value::#variant_ident(ref __field0) + } + } + Style::Tuple => { + let field_names = (0..variant.fields.len()) + .map(|i| Ident::new(&format!("__field{}", i), Span::call_site())); + quote! { + #this_value::#variant_ident(#(ref #field_names),*) + } + } + Style::Struct => { + let members = variant.fields.iter().map(|f| &f.member); + quote! { + #this_value::#variant_ident { #(ref #members),* } + } + } + }; + + let body = Match(match (cattrs.tag(), variant.attrs.untagged()) { + (attr::TagType::External, false) => { + serialize_externally_tagged_variant(params, variant, variant_index, cattrs) + } + (attr::TagType::Internal { tag }, false) => { + serialize_internally_tagged_variant(params, variant, cattrs, tag) + } + (attr::TagType::Adjacent { tag, content }, false) => { + serialize_adjacently_tagged_variant( + params, + variant, + cattrs, + variant_index, + tag, + content, + ) + } + (attr::TagType::None, _) | (_, true) => { + serialize_untagged_variant(params, variant, cattrs) + } + }); + + quote! { + #case => #body + } + } +} + +fn serialize_externally_tagged_variant( + params: &Parameters, + variant: &Variant, + variant_index: u32, + cattrs: &attr::Container, +) -> Fragment { + let type_name = cattrs.name().serialize_name(); + let variant_name = variant.attrs.name().serialize_name(); + + if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + return quote_expr! { + _serde::Serializer::serialize_newtype_variant( + __serializer, + #type_name, + #variant_index, + #variant_name, + #ser, + ) + }; + } + + match effective_style(variant) { + Style::Unit => { + quote_expr! { + _serde::Serializer::serialize_unit_variant( + __serializer, + #type_name, + #variant_index, + #variant_name, + ) + } + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::Serializer::serialize_newtype_variant); + quote_expr! { + #func( + __serializer, + #type_name, + #variant_index, + #variant_name, + #field_expr, + ) + } + } + Style::Tuple => serialize_tuple_variant( + TupleVariant::ExternallyTagged { + type_name, + variant_index, + variant_name, + }, + params, + &variant.fields, + ), + Style::Struct => serialize_struct_variant( + StructVariant::ExternallyTagged { + variant_index, + variant_name, + }, + params, + &variant.fields, + type_name, + ), + } +} + +fn serialize_internally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + tag: &str, +) -> Fragment { + let type_name = cattrs.name().serialize_name(); + let variant_name = variant.attrs.name().serialize_name(); + + let enum_ident_str = params.type_name(); + let variant_ident_str = variant.ident.to_string(); + + if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + return quote_expr! { + _serde::__private::ser::serialize_tagged_newtype( + __serializer, + #enum_ident_str, + #variant_ident_str, + #tag, + #variant_name, + #ser, + ) + }; + } + + match effective_style(variant) { + Style::Unit => { + quote_block! { + let mut __struct = _serde::Serializer::serialize_struct( + __serializer, #type_name, 1)?; + _serde::ser::SerializeStruct::serialize_field( + &mut __struct, #tag, #variant_name)?; + _serde::ser::SerializeStruct::end(__struct) + } + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::__private::ser::serialize_tagged_newtype); + quote_expr! { + #func( + __serializer, + #enum_ident_str, + #variant_ident_str, + #tag, + #variant_name, + #field_expr, + ) + } + } + Style::Struct => serialize_struct_variant( + StructVariant::InternallyTagged { tag, variant_name }, + params, + &variant.fields, + type_name, + ), + Style::Tuple => unreachable!("checked in serde_derive_internals"), + } +} + +fn serialize_adjacently_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + variant_index: u32, + tag: &str, + content: &str, +) -> Fragment { + let this_type = ¶ms.this_type; + let type_name = cattrs.name().serialize_name(); + let variant_name = variant.attrs.name().serialize_name(); + let serialize_variant = quote! { + &_serde::__private::ser::AdjacentlyTaggedEnumVariant { + enum_name: #type_name, + variant_index: #variant_index, + variant_name: #variant_name, + } + }; + + let inner = Stmts(if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + quote_expr! { + _serde::Serialize::serialize(#ser, __serializer) + } + } else { + match effective_style(variant) { + Style::Unit => { + return quote_block! { + let mut __struct = _serde::Serializer::serialize_struct( + __serializer, #type_name, 1)?; + _serde::ser::SerializeStruct::serialize_field( + &mut __struct, #tag, #serialize_variant)?; + _serde::ser::SerializeStruct::end(__struct) + }; + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::ser::SerializeStruct::serialize_field); + return quote_block! { + let mut __struct = _serde::Serializer::serialize_struct( + __serializer, #type_name, 2)?; + _serde::ser::SerializeStruct::serialize_field( + &mut __struct, #tag, #serialize_variant)?; + #func( + &mut __struct, #content, #field_expr)?; + _serde::ser::SerializeStruct::end(__struct) + }; + } + Style::Tuple => { + serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields) + } + Style::Struct => serialize_struct_variant( + StructVariant::Untagged, + params, + &variant.fields, + variant_name, + ), + } + }); + + let fields_ty = variant.fields.iter().map(|f| &f.ty); + let fields_ident: &[_] = &match variant.style { + Style::Unit => { + if variant.attrs.serialize_with().is_some() { + vec![] + } else { + unreachable!() + } + } + Style::Newtype => vec![Member::Named(Ident::new("__field0", Span::call_site()))], + Style::Tuple => (0..variant.fields.len()) + .map(|i| Member::Named(Ident::new(&format!("__field{}", i), Span::call_site()))) + .collect(), + Style::Struct => variant.fields.iter().map(|f| f.member.clone()).collect(), + }; + + let (_, ty_generics, where_clause) = params.generics.split_for_impl(); + + let wrapper_generics = if fields_ident.is_empty() { + params.generics.clone() + } else { + bound::with_lifetime_bound(¶ms.generics, "'__a") + }; + let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl(); + + quote_block! { + #[doc(hidden)] + struct __AdjacentlyTagged #wrapper_generics #where_clause { + data: (#(&'__a #fields_ty,)*), + phantom: _serde::__private::PhantomData<#this_type #ty_generics>, + } + + impl #wrapper_impl_generics _serde::Serialize for __AdjacentlyTagged #wrapper_ty_generics #where_clause { + fn serialize<__S>(&self, __serializer: __S) -> _serde::__private::Result<__S::Ok, __S::Error> + where + __S: _serde::Serializer, + { + // Elements that have skip_serializing will be unused. + #[allow(unused_variables)] + let (#(#fields_ident,)*) = self.data; + #inner + } + } + + let mut __struct = _serde::Serializer::serialize_struct( + __serializer, #type_name, 2)?; + _serde::ser::SerializeStruct::serialize_field( + &mut __struct, #tag, #serialize_variant)?; + _serde::ser::SerializeStruct::serialize_field( + &mut __struct, #content, &__AdjacentlyTagged { + data: (#(#fields_ident,)*), + phantom: _serde::__private::PhantomData::<#this_type #ty_generics>, + })?; + _serde::ser::SerializeStruct::end(__struct) + } +} + +fn serialize_untagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, +) -> Fragment { + if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + return quote_expr! { + _serde::Serialize::serialize(#ser, __serializer) + }; + } + + match effective_style(variant) { + Style::Unit => { + quote_expr! { + _serde::Serializer::serialize_unit(__serializer) + } + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::Serialize::serialize); + quote_expr! { + #func(#field_expr, __serializer) + } + } + Style::Tuple => serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields), + Style::Struct => { + let type_name = cattrs.name().serialize_name(); + serialize_struct_variant(StructVariant::Untagged, params, &variant.fields, type_name) + } + } +} + +enum TupleVariant<'a> { + ExternallyTagged { + type_name: &'a str, + variant_index: u32, + variant_name: &'a str, + }, + Untagged, +} + +fn serialize_tuple_variant( + context: TupleVariant, + params: &Parameters, + fields: &[Field], +) -> Fragment { + let tuple_trait = match context { + TupleVariant::ExternallyTagged { .. } => TupleTrait::SerializeTupleVariant, + TupleVariant::Untagged => TupleTrait::SerializeTuple, + }; + + let serialize_stmts = serialize_tuple_struct_visitor(fields, params, true, &tuple_trait); + + let mut serialized_fields = fields + .iter() + .enumerate() + .filter(|(_, field)| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some()); + + let len = serialized_fields + .map(|(i, field)| match field.attrs.skip_serializing_if() { + None => quote!(1), + Some(path) => { + let field_expr = Ident::new(&format!("__field{}", i), Span::call_site()); + quote!(if #path(#field_expr) { 0 } else { 1 }) + } + }) + .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); + + match context { + TupleVariant::ExternallyTagged { + type_name, + variant_index, + variant_name, + } => { + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_tuple_variant( + __serializer, + #type_name, + #variant_index, + #variant_name, + #len)?; + #(#serialize_stmts)* + _serde::ser::SerializeTupleVariant::end(__serde_state) + } + } + TupleVariant::Untagged => { + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_tuple( + __serializer, + #len)?; + #(#serialize_stmts)* + _serde::ser::SerializeTuple::end(__serde_state) + } + } + } +} + +enum StructVariant<'a> { + ExternallyTagged { + variant_index: u32, + variant_name: &'a str, + }, + InternallyTagged { + tag: &'a str, + variant_name: &'a str, + }, + Untagged, +} + +fn serialize_struct_variant( + context: StructVariant, + params: &Parameters, + fields: &[Field], + name: &str, +) -> Fragment { + if fields.iter().any(|field| field.attrs.flatten()) { + return serialize_struct_variant_with_flatten(context, params, fields, name); + } + + let struct_trait = match context { + StructVariant::ExternallyTagged { .. } => StructTrait::SerializeStructVariant, + StructVariant::InternallyTagged { .. } | StructVariant::Untagged => { + StructTrait::SerializeStruct + } + }; + + let serialize_fields = serialize_struct_visitor(fields, params, true, &struct_trait); + + let mut serialized_fields = fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some()); + + let len = serialized_fields + .map(|field| { + let member = &field.member; + + match field.attrs.skip_serializing_if() { + Some(path) => quote!(if #path(#member) { 0 } else { 1 }), + None => quote!(1), + } + }) + .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); + + match context { + StructVariant::ExternallyTagged { + variant_index, + variant_name, + } => { + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_struct_variant( + __serializer, + #name, + #variant_index, + #variant_name, + #len, + )?; + #(#serialize_fields)* + _serde::ser::SerializeStructVariant::end(__serde_state) + } + } + StructVariant::InternallyTagged { tag, variant_name } => { + quote_block! { + let mut __serde_state = _serde::Serializer::serialize_struct( + __serializer, + #name, + #len + 1, + )?; + _serde::ser::SerializeStruct::serialize_field( + &mut __serde_state, + #tag, + #variant_name, + )?; + #(#serialize_fields)* + _serde::ser::SerializeStruct::end(__serde_state) + } + } + StructVariant::Untagged => { + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_struct( + __serializer, + #name, + #len, + )?; + #(#serialize_fields)* + _serde::ser::SerializeStruct::end(__serde_state) + } + } + } +} + +fn serialize_struct_variant_with_flatten( + context: StructVariant, + params: &Parameters, + fields: &[Field], + name: &str, +) -> Fragment { + let struct_trait = StructTrait::SerializeMap; + let serialize_fields = serialize_struct_visitor(fields, params, true, &struct_trait); + + let mut serialized_fields = fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some()); + + match context { + StructVariant::ExternallyTagged { + variant_index, + variant_name, + } => { + let this_type = ¶ms.this_type; + let fields_ty = fields.iter().map(|f| &f.ty); + let members = &fields.iter().map(|f| &f.member).collect::>(); + + let (_, ty_generics, where_clause) = params.generics.split_for_impl(); + let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, "'__a"); + let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl(); + + quote_block! { + #[doc(hidden)] + struct __EnumFlatten #wrapper_generics #where_clause { + data: (#(&'__a #fields_ty,)*), + phantom: _serde::__private::PhantomData<#this_type #ty_generics>, + } + + impl #wrapper_impl_generics _serde::Serialize for __EnumFlatten #wrapper_ty_generics #where_clause { + fn serialize<__S>(&self, __serializer: __S) -> _serde::__private::Result<__S::Ok, __S::Error> + where + __S: _serde::Serializer, + { + let (#(#members,)*) = self.data; + let #let_mut __serde_state = _serde::Serializer::serialize_map( + __serializer, + _serde::__private::None)?; + #(#serialize_fields)* + _serde::ser::SerializeMap::end(__serde_state) + } + } + + _serde::Serializer::serialize_newtype_variant( + __serializer, + #name, + #variant_index, + #variant_name, + &__EnumFlatten { + data: (#(#members,)*), + phantom: _serde::__private::PhantomData::<#this_type #ty_generics>, + }) + } + } + StructVariant::InternallyTagged { tag, variant_name } => { + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_map( + __serializer, + _serde::__private::None)?; + _serde::ser::SerializeMap::serialize_entry( + &mut __serde_state, + #tag, + #variant_name, + )?; + #(#serialize_fields)* + _serde::ser::SerializeMap::end(__serde_state) + } + } + StructVariant::Untagged => { + quote_block! { + let #let_mut __serde_state = _serde::Serializer::serialize_map( + __serializer, + _serde::__private::None)?; + #(#serialize_fields)* + _serde::ser::SerializeMap::end(__serde_state) + } + } + } +} + +fn serialize_tuple_struct_visitor( + fields: &[Field], + params: &Parameters, + is_enum: bool, + tuple_trait: &TupleTrait, +) -> Vec { + fields + .iter() + .enumerate() + .filter(|(_, field)| !field.attrs.skip_serializing()) + .map(|(i, field)| { + let mut field_expr = if is_enum { + let id = Ident::new(&format!("__field{}", i), Span::call_site()); + quote!(#id) + } else { + get_member( + params, + field, + &Member::Unnamed(Index { + index: i as u32, + span: Span::call_site(), + }), + ) + }; + + let skip = field + .attrs + .skip_serializing_if() + .map(|path| quote!(#path(#field_expr))); + + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = tuple_trait.serialize_element(span); + let ser = quote! { + #func(&mut __serde_state, #field_expr)?; + }; + + match skip { + None => ser, + Some(skip) => quote!(if !#skip { #ser }), + } + }) + .collect() +} + +fn serialize_struct_visitor( + fields: &[Field], + params: &Parameters, + is_enum: bool, + struct_trait: &StructTrait, +) -> Vec { + fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .map(|field| { + let member = &field.member; + + let mut field_expr = if is_enum { + quote!(#member) + } else { + get_member(params, field, member) + }; + + let key_expr = field.attrs.name().serialize_name(); + + let skip = field + .attrs + .skip_serializing_if() + .map(|path| quote!(#path(#field_expr))); + + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let ser = if field.attrs.flatten() { + let func = quote_spanned!(span=> _serde::Serialize::serialize); + quote! { + #func(&#field_expr, _serde::__private::ser::FlatMapSerializer(&mut __serde_state))?; + } + } else { + let func = struct_trait.serialize_field(span); + quote! { + #func(&mut __serde_state, #key_expr, #field_expr)?; + } + }; + + match skip { + None => ser, + Some(skip) => { + if let Some(skip_func) = struct_trait.skip_field(span) { + quote! { + if !#skip { + #ser + } else { + #skip_func(&mut __serde_state, #key_expr)?; + } + } + } else { + quote! { + if !#skip { + #ser + } + } + } + } + } + }) + .collect() +} + +fn wrap_serialize_field_with( + params: &Parameters, + field_ty: &syn::Type, + serialize_with: &syn::ExprPath, + field_expr: &TokenStream, +) -> TokenStream { + wrap_serialize_with(params, serialize_with, &[field_ty], &[quote!(#field_expr)]) +} + +fn wrap_serialize_variant_with( + params: &Parameters, + serialize_with: &syn::ExprPath, + variant: &Variant, +) -> TokenStream { + let field_tys: Vec<_> = variant.fields.iter().map(|field| field.ty).collect(); + let field_exprs: Vec<_> = variant + .fields + .iter() + .map(|field| { + let id = match &field.member { + Member::Named(ident) => ident.clone(), + Member::Unnamed(member) => { + Ident::new(&format!("__field{}", member.index), Span::call_site()) + } + }; + quote!(#id) + }) + .collect(); + wrap_serialize_with( + params, + serialize_with, + field_tys.as_slice(), + field_exprs.as_slice(), + ) +} + +fn wrap_serialize_with( + params: &Parameters, + serialize_with: &syn::ExprPath, + field_tys: &[&syn::Type], + field_exprs: &[TokenStream], +) -> TokenStream { + let this_type = ¶ms.this_type; + let (_, ty_generics, where_clause) = params.generics.split_for_impl(); + + let wrapper_generics = if field_exprs.is_empty() { + params.generics.clone() + } else { + bound::with_lifetime_bound(¶ms.generics, "'__a") + }; + let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl(); + + let field_access = (0..field_exprs.len()).map(|n| { + Member::Unnamed(Index { + index: n as u32, + span: Span::call_site(), + }) + }); + + quote!({ + #[doc(hidden)] + struct __SerializeWith #wrapper_impl_generics #where_clause { + values: (#(&'__a #field_tys, )*), + phantom: _serde::__private::PhantomData<#this_type #ty_generics>, + } + + impl #wrapper_impl_generics _serde::Serialize for __SerializeWith #wrapper_ty_generics #where_clause { + fn serialize<__S>(&self, __s: __S) -> _serde::__private::Result<__S::Ok, __S::Error> + where + __S: _serde::Serializer, + { + #serialize_with(#(self.values.#field_access, )* __s) + } + } + + &__SerializeWith { + values: (#(#field_exprs, )*), + phantom: _serde::__private::PhantomData::<#this_type #ty_generics>, + } + }) +} + +// Serialization of an empty struct results in code like: +// +// let mut __serde_state = serializer.serialize_struct("S", 0)?; +// _serde::ser::SerializeStruct::end(__serde_state) +// +// where we want to omit the `mut` to avoid a warning. +fn mut_if(is_mut: bool) -> Option { + if is_mut { + Some(quote!(mut)) + } else { + None + } +} + +fn get_member(params: &Parameters, field: &Field, member: &Member) -> TokenStream { + let self_var = ¶ms.self_var; + match (params.is_remote, field.attrs.getter()) { + (false, None) => { + if params.is_packed { + quote!(&{#self_var.#member}) + } else { + quote!(&#self_var.#member) + } + } + (true, None) => { + let inner = if params.is_packed { + quote!(&{#self_var.#member}) + } else { + quote!(&#self_var.#member) + }; + let ty = field.ty; + quote!(_serde::__private::ser::constrain::<#ty>(#inner)) + } + (true, Some(getter)) => { + let ty = field.ty; + quote!(_serde::__private::ser::constrain::<#ty>(&#getter(#self_var))) + } + (false, Some(_)) => { + unreachable!("getter is only allowed for remote impls"); + } + } +} + +fn effective_style(variant: &Variant) -> Style { + match variant.style { + Style::Newtype if variant.fields[0].attrs.skip_serializing() => Style::Unit, + other => other, + } +} + +enum StructTrait { + SerializeMap, + SerializeStruct, + SerializeStructVariant, +} + +impl StructTrait { + fn serialize_field(&self, span: Span) -> TokenStream { + match *self { + StructTrait::SerializeMap => { + quote_spanned!(span=> _serde::ser::SerializeMap::serialize_entry) + } + StructTrait::SerializeStruct => { + quote_spanned!(span=> _serde::ser::SerializeStruct::serialize_field) + } + StructTrait::SerializeStructVariant => { + quote_spanned!(span=> _serde::ser::SerializeStructVariant::serialize_field) + } + } + } + + fn skip_field(&self, span: Span) -> Option { + match *self { + StructTrait::SerializeMap => None, + StructTrait::SerializeStruct => { + Some(quote_spanned!(span=> _serde::ser::SerializeStruct::skip_field)) + } + StructTrait::SerializeStructVariant => { + Some(quote_spanned!(span=> _serde::ser::SerializeStructVariant::skip_field)) + } + } + } +} + +enum TupleTrait { + SerializeTuple, + SerializeTupleStruct, + SerializeTupleVariant, +} + +impl TupleTrait { + fn serialize_element(&self, span: Span) -> TokenStream { + match *self { + TupleTrait::SerializeTuple => { + quote_spanned!(span=> _serde::ser::SerializeTuple::serialize_element) + } + TupleTrait::SerializeTupleStruct => { + quote_spanned!(span=> _serde::ser::SerializeTupleStruct::serialize_field) + } + TupleTrait::SerializeTupleVariant => { + quote_spanned!(span=> _serde::ser::SerializeTupleVariant::serialize_field) + } + } + } +} diff --git a/bitbox02-bt/vendor/serde_derive/src/this.rs b/bitbox02-bt/vendor/serde_derive/src/this.rs new file mode 100644 index 0000000..941cea4 --- /dev/null +++ b/bitbox02-bt/vendor/serde_derive/src/this.rs @@ -0,0 +1,32 @@ +use crate::internals::ast::Container; +use syn::{Path, PathArguments, Token}; + +pub fn this_type(cont: &Container) -> Path { + if let Some(remote) = cont.attrs.remote() { + let mut this = remote.clone(); + for segment in &mut this.segments { + if let PathArguments::AngleBracketed(arguments) = &mut segment.arguments { + arguments.colon2_token = None; + } + } + this + } else { + Path::from(cont.ident.clone()) + } +} + +pub fn this_value(cont: &Container) -> Path { + if let Some(remote) = cont.attrs.remote() { + let mut this = remote.clone(); + for segment in &mut this.segments { + if let PathArguments::AngleBracketed(arguments) = &mut segment.arguments { + if arguments.colon2_token.is_none() { + arguments.colon2_token = Some(Token![::](arguments.lt_token.span)); + } + } + } + this + } else { + Path::from(cont.ident.clone()) + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/.cargo-checksum.json b/bitbox02-bt/vendor/serde_yaml/.cargo-checksum.json new file mode 100644 index 0000000..b96c4a8 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"2aff50a39422e68805e272871afd09f3a1fed4bb09ba817822f0807122a4dab7","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"b348939f67d0992b0c02e2caae54492dd15777c1e210d2fad6fc780f2dcbb9ee","src/de.rs":"b5416aa3576e454aa92ee3fab10550f8de7d0d6e4d96a9a6a3afdafab12d12bc","src/error.rs":"7734732a5fc907e9a424cc7df48ca4a46cf5d57bedf3e328b0b31c5166d3421a","src/lib.rs":"692711afeed399e985ef8bb23731c6484838317437c7ed8551661b4e41818da7","src/libyaml/cstr.rs":"37792e227a594ece956fb24da6b335ed902df760e7095af6197ea48c5ba1ce46","src/libyaml/emitter.rs":"2e6d50dba004b5e9ad7831e0f2c87c28f7752871f338f5e90750ebfe571634f0","src/libyaml/error.rs":"c8db3f27d7427d57b5f0b7b2400f4fff0b962104b8b45cd457145e1a6e84111f","src/libyaml/mod.rs":"a163ac16fc849a93e864beb794000487c4a1f40618060ed8f43f5f05178c0348","src/libyaml/parser.rs":"14d5c804ef1449616d77eb177eae7055009fc009d0406261d50e7b00c6c50dcd","src/libyaml/tag.rs":"9b3937b6983397446d9e7a417ac0735bff87e26bfafbca4205fac5e38c68cea2","src/libyaml/util.rs":"1550d2dcad69ba783f320c985a1e02b784e7f4c75700aad7820902dca256737b","src/loader.rs":"6360fd9a8e051e94ce3b3445af4042d7bee470d3822f452f8d22a6e36fd6bb88","src/mapping.rs":"345cdb55f36a25045dad40ead7cefeac82acb786bc09e608c46ea5d8e2ccabe0","src/number.rs":"f723b17e21825c9b793de69ef17b5811322428ed62c34426c9f5a138550839e0","src/path.rs":"44d339ce1814effd10ba131ae0393df215f09dbfb35ab4d678f49d4081f58dd4","src/ser.rs":"371dae16bdffc02dc99a6447cc1c8eae610a89b48302e9c9ed6e0b2b9cbdc094","src/value/de.rs":"c7f25d5ace625000ea7b6387f2ad8d8e93ab882702b9c6953854d9f41defc0d5","src/value/debug.rs":"a1efda5de70e9ef85057490384968367335694bd22fb6a5c2096192797c87be9","src/value/from.rs":"f694791e39e1ff03cb31aeb7c9780ab404afd378b513409fb4c245d56bbc969e","src/value/index.rs":"0969af1324c7b59d0e0b410144f25282fe0889fa6416cdc2c301f7f6d9114b5b","src/value/mod.rs":"bb8f14fb534e5d305e1e5c889bf4cb409f7d502030bda0629014ca05608fc2e1","src/value/partial_eq.rs":"69b5ed7a3735818e3e1140fca8a6318f4868045139bf4ea325c9738ea1bf1347","src/value/ser.rs":"35fcb93d0c6f7f72225c94fad85fc958f927a1f9a1ec97918cb97ec82b7df878","src/value/tagged.rs":"cdf3ff8ec39bb360b10f0e352dded4e5d6bacd3a131a707b8211e1635a1249d2","src/with.rs":"c83b0740a7700b436648310fa41f708bce8d61eb762ddcfc8a9d314bd7761ef0","tests/test_de.rs":"ad02c6e8e413f79132f6ffa9832ca5545d8eb21bf417ead31c88e75f669529a8","tests/test_error.rs":"a9d0a1bc59d123af4c59f4dc2c5d94d1a7eefa08c9cbb3116b8c821440ef8bc5","tests/test_serde.rs":"6ac4939a989f8689efa46e957608566fa69f34de7435a234e87a63c8cc8158fc","tests/test_value.rs":"8fe55f0108c84ec78c0de0e36bfc8d9f40a3eb8060d43edd7b9e170ce484a85c"},"package":"6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/serde_yaml/Cargo.toml b/bitbox02-bt/vendor/serde_yaml/Cargo.toml new file mode 100644 index 0000000..749e18b --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/Cargo.toml @@ -0,0 +1,62 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.64" +name = "serde_yaml" +version = "0.9.34+deprecated" +authors = ["David Tolnay "] +description = "YAML data format for Serde" +documentation = "https://docs.rs/serde_yaml/" +readme = "README.md" +keywords = [ + "yaml", + "serde", + "serialization", +] +categories = [ + "encoding", + "parser-implementations", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/serde-yaml" + +[package.metadata.docs.rs] +rustdoc-args = ["--generate-link-to-definition"] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +doc-scrape-examples = false + +[dependencies.indexmap] +version = "2.2.1" + +[dependencies.itoa] +version = "1.0" + +[dependencies.ryu] +version = "1.0" + +[dependencies.serde] +version = "1.0.195" + +[dependencies.unsafe-libyaml] +version = "0.2.11" + +[dev-dependencies.anyhow] +version = "1.0.79" + +[dev-dependencies.indoc] +version = "2.0" + +[dev-dependencies.serde_derive] +version = "1.0.195" diff --git a/bitbox02-bt/vendor/serde_yaml/LICENSE-APACHE b/bitbox02-bt/vendor/serde_yaml/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/bitbox02-bt/vendor/serde_yaml/LICENSE-MIT b/bitbox02-bt/vendor/serde_yaml/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/serde_yaml/README.md b/bitbox02-bt/vendor/serde_yaml/README.md new file mode 100644 index 0000000..3434617 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/README.md @@ -0,0 +1,152 @@ +Serde YAML +========== + +[github](https://github.com/dtolnay/serde-yaml) +[crates.io](https://crates.io/crates/serde_yaml) +[docs.rs](https://docs.rs/serde_yaml) +[build status](https://github.com/dtolnay/serde-yaml/actions?query=branch%3Amaster) + +Rust library for using the [Serde] serialization framework with data in [YAML] +file format. _(This project is no longer maintained.)_ + +[Serde]: https://github.com/serde-rs/serde +[YAML]: https://yaml.org/ + +## Dependency + +```toml +[dependencies] +serde = "1.0" +serde_yaml = "0.9" +``` + +Release notes are available under [GitHub releases]. + +[GitHub releases]: https://github.com/dtolnay/serde-yaml/releases + +## Using Serde YAML + +[API documentation is available in rustdoc form][docs.rs] but the general idea +is: + +[docs.rs]: https://docs.rs/serde_yaml + +```rust +use std::collections::BTreeMap; + +fn main() -> Result<(), serde_yaml::Error> { + // You have some type. + let mut map = BTreeMap::new(); + map.insert("x".to_string(), 1.0); + map.insert("y".to_string(), 2.0); + + // Serialize it to a YAML string. + let yaml = serde_yaml::to_string(&map)?; + assert_eq!(yaml, "x: 1.0\ny: 2.0\n"); + + // Deserialize it back to a Rust type. + let deserialized_map: BTreeMap = serde_yaml::from_str(&yaml)?; + assert_eq!(map, deserialized_map); + Ok(()) +} +``` + +It can also be used with Serde's derive macros to handle structs and enums +defined in your program. + +```toml +[dependencies] +serde = { version = "1.0", features = ["derive"] } +serde_yaml = "0.9" +``` + +Structs serialize in the obvious way: + +```rust +use serde::{Serialize, Deserialize}; + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +struct Point { + x: f64, + y: f64, +} + +fn main() -> Result<(), serde_yaml::Error> { + let point = Point { x: 1.0, y: 2.0 }; + + let yaml = serde_yaml::to_string(&point)?; + assert_eq!(yaml, "x: 1.0\ny: 2.0\n"); + + let deserialized_point: Point = serde_yaml::from_str(&yaml)?; + assert_eq!(point, deserialized_point); + Ok(()) +} +``` + +Enums serialize using YAML's `!tag` syntax to identify the variant name. + +```rust +use serde::{Serialize, Deserialize}; + +#[derive(Serialize, Deserialize, PartialEq, Debug)] +enum Enum { + Unit, + Newtype(usize), + Tuple(usize, usize, usize), + Struct { x: f64, y: f64 }, +} + +fn main() -> Result<(), serde_yaml::Error> { + let yaml = " + - !Newtype 1 + - !Tuple [0, 0, 0] + - !Struct {x: 1.0, y: 2.0} + "; + let values: Vec = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(values[0], Enum::Newtype(1)); + assert_eq!(values[1], Enum::Tuple(0, 0, 0)); + assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 }); + + // The last two in YAML's block style instead: + let yaml = " + - !Tuple + - 0 + - 0 + - 0 + - !Struct + x: 1.0 + y: 2.0 + "; + let values: Vec = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(values[0], Enum::Tuple(0, 0, 0)); + assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 }); + + // Variants with no data can be written using !Tag or just the string name. + let yaml = " + - Unit # serialization produces this one + - !Unit + "; + let values: Vec = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(values[0], Enum::Unit); + assert_eq!(values[1], Enum::Unit); + + Ok(()) +} +``` + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/serde_yaml/src/de.rs b/bitbox02-bt/vendor/serde_yaml/src/de.rs new file mode 100644 index 0000000..566f5f0 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/de.rs @@ -0,0 +1,1846 @@ +use crate::error::{self, Error, ErrorImpl}; +use crate::libyaml::error::Mark; +use crate::libyaml::parser::{MappingStart, Scalar, ScalarStyle, SequenceStart}; +use crate::libyaml::tag::Tag; +use crate::loader::{Document, Loader}; +use crate::path::Path; +use serde::de::value::StrDeserializer; +use serde::de::{ + self, Deserialize, DeserializeOwned, DeserializeSeed, Expected, IgnoredAny, Unexpected, Visitor, +}; +use std::fmt; +use std::io; +use std::mem; +use std::num::ParseIntError; +use std::str; +use std::sync::Arc; + +type Result = std::result::Result; + +/// A structure that deserializes YAML into Rust values. +/// +/// # Examples +/// +/// Deserializing a single document: +/// +/// ``` +/// use anyhow::Result; +/// use serde::Deserialize; +/// use serde_yaml::Value; +/// +/// fn main() -> Result<()> { +/// let input = "k: 107\n"; +/// let de = serde_yaml::Deserializer::from_str(input); +/// let value = Value::deserialize(de)?; +/// println!("{:?}", value); +/// Ok(()) +/// } +/// ``` +/// +/// Deserializing multi-doc YAML: +/// +/// ``` +/// use anyhow::Result; +/// use serde::Deserialize; +/// use serde_yaml::Value; +/// +/// fn main() -> Result<()> { +/// let input = "---\nk: 107\n...\n---\nj: 106\n"; +/// +/// for document in serde_yaml::Deserializer::from_str(input) { +/// let value = Value::deserialize(document)?; +/// println!("{:?}", value); +/// } +/// +/// Ok(()) +/// } +/// ``` +pub struct Deserializer<'de> { + progress: Progress<'de>, +} + +pub(crate) enum Progress<'de> { + Str(&'de str), + Slice(&'de [u8]), + Read(Box), + Iterable(Loader<'de>), + Document(Document<'de>), + Fail(Arc), +} + +impl<'de> Deserializer<'de> { + /// Creates a YAML deserializer from a `&str`. + pub fn from_str(s: &'de str) -> Self { + let progress = Progress::Str(s); + Deserializer { progress } + } + + /// Creates a YAML deserializer from a `&[u8]`. + pub fn from_slice(v: &'de [u8]) -> Self { + let progress = Progress::Slice(v); + Deserializer { progress } + } + + /// Creates a YAML deserializer from an `io::Read`. + /// + /// Reader-based deserializers do not support deserializing borrowed types + /// like `&str`, since the `std::io::Read` trait has no non-copying methods + /// -- everything it does involves copying bytes out of the data source. + pub fn from_reader(rdr: R) -> Self + where + R: io::Read + 'de, + { + let progress = Progress::Read(Box::new(rdr)); + Deserializer { progress } + } + + fn de( + self, + f: impl for<'document> FnOnce(&mut DeserializerFromEvents<'de, 'document>) -> Result, + ) -> Result { + let mut pos = 0; + let mut jumpcount = 0; + + match self.progress { + Progress::Iterable(_) => return Err(error::new(ErrorImpl::MoreThanOneDocument)), + Progress::Document(document) => { + let t = f(&mut DeserializerFromEvents { + document: &document, + pos: &mut pos, + jumpcount: &mut jumpcount, + path: Path::Root, + remaining_depth: 128, + current_enum: None, + })?; + if let Some(parse_error) = document.error { + return Err(error::shared(parse_error)); + } + return Ok(t); + } + _ => {} + } + + let mut loader = Loader::new(self.progress)?; + let document = match loader.next_document() { + Some(document) => document, + None => return Err(error::new(ErrorImpl::EndOfStream)), + }; + let t = f(&mut DeserializerFromEvents { + document: &document, + pos: &mut pos, + jumpcount: &mut jumpcount, + path: Path::Root, + remaining_depth: 128, + current_enum: None, + })?; + if let Some(parse_error) = document.error { + return Err(error::shared(parse_error)); + } + if loader.next_document().is_none() { + Ok(t) + } else { + Err(error::new(ErrorImpl::MoreThanOneDocument)) + } + } +} + +impl<'de> Iterator for Deserializer<'de> { + type Item = Self; + + fn next(&mut self) -> Option { + match &mut self.progress { + Progress::Iterable(loader) => { + let document = loader.next_document()?; + return Some(Deserializer { + progress: Progress::Document(document), + }); + } + Progress::Document(_) => return None, + Progress::Fail(err) => { + return Some(Deserializer { + progress: Progress::Fail(Arc::clone(err)), + }); + } + _ => {} + } + + let dummy = Progress::Str(""); + let input = mem::replace(&mut self.progress, dummy); + match Loader::new(input) { + Ok(loader) => { + self.progress = Progress::Iterable(loader); + self.next() + } + Err(err) => { + let fail = err.shared(); + self.progress = Progress::Fail(Arc::clone(&fail)); + Some(Deserializer { + progress: Progress::Fail(fail), + }) + } + } + } +} + +impl<'de> de::Deserializer<'de> for Deserializer<'de> { + type Error = Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_any(visitor)) + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_bool(visitor)) + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_i8(visitor)) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_i16(visitor)) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_i32(visitor)) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_i64(visitor)) + } + + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_i128(visitor)) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_u8(visitor)) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_u16(visitor)) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_u32(visitor)) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_u64(visitor)) + } + + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_u128(visitor)) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_f32(visitor)) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_f64(visitor)) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_char(visitor)) + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_str(visitor)) + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_string(visitor)) + } + + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_bytes(visitor)) + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_byte_buf(visitor)) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_option(visitor)) + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_unit(visitor)) + } + + fn deserialize_unit_struct(self, name: &'static str, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_unit_struct(name, visitor)) + } + + fn deserialize_newtype_struct(self, name: &'static str, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_newtype_struct(name, visitor)) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_seq(visitor)) + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_tuple(len, visitor)) + } + + fn deserialize_tuple_struct( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_tuple_struct(name, len, visitor)) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_map(visitor)) + } + + fn deserialize_struct( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_struct(name, fields, visitor)) + } + + fn deserialize_enum( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_enum(name, variants, visitor)) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_identifier(visitor)) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.de(|state| state.deserialize_ignored_any(visitor)) + } +} + +#[derive(Debug)] +pub(crate) enum Event<'de> { + Alias(usize), + Scalar(Scalar<'de>), + SequenceStart(SequenceStart), + SequenceEnd, + MappingStart(MappingStart), + MappingEnd, + Void, +} + +struct DeserializerFromEvents<'de, 'document> { + document: &'document Document<'de>, + pos: &'document mut usize, + jumpcount: &'document mut usize, + path: Path<'document>, + remaining_depth: u8, + current_enum: Option>, +} + +#[derive(Copy, Clone)] +struct CurrentEnum<'document> { + name: Option<&'static str>, + tag: &'document str, +} + +impl<'de, 'document> DeserializerFromEvents<'de, 'document> { + fn peek_event(&self) -> Result<&'document Event<'de>> { + self.peek_event_mark().map(|(event, _mark)| event) + } + + fn peek_event_mark(&self) -> Result<(&'document Event<'de>, Mark)> { + match self.document.events.get(*self.pos) { + Some((event, mark)) => Ok((event, *mark)), + None => Err(match &self.document.error { + Some(parse_error) => error::shared(Arc::clone(parse_error)), + None => error::new(ErrorImpl::EndOfStream), + }), + } + } + + fn next_event(&mut self) -> Result<&'document Event<'de>> { + self.next_event_mark().map(|(event, _mark)| event) + } + + fn next_event_mark(&mut self) -> Result<(&'document Event<'de>, Mark)> { + self.peek_event_mark().map(|(event, mark)| { + *self.pos += 1; + self.current_enum = None; + (event, mark) + }) + } + + fn jump<'anchor>( + &'anchor mut self, + pos: &'anchor mut usize, + ) -> Result> { + *self.jumpcount += 1; + if *self.jumpcount > self.document.events.len() * 100 { + return Err(error::new(ErrorImpl::RepetitionLimitExceeded)); + } + match self.document.aliases.get(pos) { + Some(found) => { + *pos = *found; + Ok(DeserializerFromEvents { + document: self.document, + pos, + jumpcount: self.jumpcount, + path: Path::Alias { parent: &self.path }, + remaining_depth: self.remaining_depth, + current_enum: None, + }) + } + None => panic!("unresolved alias: {}", *pos), + } + } + + fn ignore_any(&mut self) -> Result<()> { + enum Nest { + Sequence, + Mapping, + } + + let mut stack = Vec::new(); + + loop { + match self.next_event()? { + Event::Alias(_) | Event::Scalar(_) | Event::Void => {} + Event::SequenceStart(_) => { + stack.push(Nest::Sequence); + } + Event::MappingStart(_) => { + stack.push(Nest::Mapping); + } + Event::SequenceEnd => match stack.pop() { + Some(Nest::Sequence) => {} + None | Some(Nest::Mapping) => { + panic!("unexpected end of sequence"); + } + }, + Event::MappingEnd => match stack.pop() { + Some(Nest::Mapping) => {} + None | Some(Nest::Sequence) => { + panic!("unexpected end of mapping"); + } + }, + } + if stack.is_empty() { + return Ok(()); + } + } + } + + fn visit_sequence(&mut self, visitor: V, mark: Mark) -> Result + where + V: Visitor<'de>, + { + let (value, len) = self.recursion_check(mark, |de| { + let mut seq = SeqAccess { + empty: false, + de, + len: 0, + }; + let value = visitor.visit_seq(&mut seq)?; + Ok((value, seq.len)) + })?; + self.end_sequence(len)?; + Ok(value) + } + + fn visit_mapping(&mut self, visitor: V, mark: Mark) -> Result + where + V: Visitor<'de>, + { + let (value, len) = self.recursion_check(mark, |de| { + let mut map = MapAccess { + empty: false, + de, + len: 0, + key: None, + }; + let value = visitor.visit_map(&mut map)?; + Ok((value, map.len)) + })?; + self.end_mapping(len)?; + Ok(value) + } + + fn end_sequence(&mut self, len: usize) -> Result<()> { + let total = { + let mut seq = SeqAccess { + empty: false, + de: self, + len, + }; + while de::SeqAccess::next_element::(&mut seq)?.is_some() {} + seq.len + }; + match self.next_event()? { + Event::SequenceEnd | Event::Void => {} + _ => panic!("expected a SequenceEnd event"), + } + if total == len { + Ok(()) + } else { + struct ExpectedSeq(usize); + impl Expected for ExpectedSeq { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + write!(formatter, "sequence of 1 element") + } else { + write!(formatter, "sequence of {} elements", self.0) + } + } + } + Err(de::Error::invalid_length(total, &ExpectedSeq(len))) + } + } + + fn end_mapping(&mut self, len: usize) -> Result<()> { + let total = { + let mut map = MapAccess { + empty: false, + de: self, + len, + key: None, + }; + while de::MapAccess::next_entry::(&mut map)?.is_some() {} + map.len + }; + match self.next_event()? { + Event::MappingEnd | Event::Void => {} + _ => panic!("expected a MappingEnd event"), + } + if total == len { + Ok(()) + } else { + struct ExpectedMap(usize); + impl Expected for ExpectedMap { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + write!(formatter, "map containing 1 entry") + } else { + write!(formatter, "map containing {} entries", self.0) + } + } + } + Err(de::Error::invalid_length(total, &ExpectedMap(len))) + } + } + + fn recursion_check Result, T>( + &mut self, + mark: Mark, + f: F, + ) -> Result { + let previous_depth = self.remaining_depth; + self.remaining_depth = match previous_depth.checked_sub(1) { + Some(depth) => depth, + None => return Err(error::new(ErrorImpl::RecursionLimitExceeded(mark))), + }; + let result = f(self); + self.remaining_depth = previous_depth; + result + } +} + +struct SeqAccess<'de, 'document, 'seq> { + empty: bool, + de: &'seq mut DeserializerFromEvents<'de, 'document>, + len: usize, +} + +impl<'de, 'document, 'seq> de::SeqAccess<'de> for SeqAccess<'de, 'document, 'seq> { + type Error = Error; + + fn next_element_seed(&mut self, seed: T) -> Result> + where + T: DeserializeSeed<'de>, + { + if self.empty { + return Ok(None); + } + match self.de.peek_event()? { + Event::SequenceEnd | Event::Void => Ok(None), + _ => { + let mut element_de = DeserializerFromEvents { + document: self.de.document, + pos: self.de.pos, + jumpcount: self.de.jumpcount, + path: Path::Seq { + parent: &self.de.path, + index: self.len, + }, + remaining_depth: self.de.remaining_depth, + current_enum: None, + }; + self.len += 1; + seed.deserialize(&mut element_de).map(Some) + } + } + } +} + +struct MapAccess<'de, 'document, 'map> { + empty: bool, + de: &'map mut DeserializerFromEvents<'de, 'document>, + len: usize, + key: Option<&'document [u8]>, +} + +impl<'de, 'document, 'map> de::MapAccess<'de> for MapAccess<'de, 'document, 'map> { + type Error = Error; + + fn next_key_seed(&mut self, seed: K) -> Result> + where + K: DeserializeSeed<'de>, + { + if self.empty { + return Ok(None); + } + match self.de.peek_event()? { + Event::MappingEnd | Event::Void => Ok(None), + Event::Scalar(scalar) => { + self.len += 1; + self.key = Some(&scalar.value); + seed.deserialize(&mut *self.de).map(Some) + } + _ => { + self.len += 1; + self.key = None; + seed.deserialize(&mut *self.de).map(Some) + } + } + } + + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>, + { + let mut value_de = DeserializerFromEvents { + document: self.de.document, + pos: self.de.pos, + jumpcount: self.de.jumpcount, + path: if let Some(key) = self.key.and_then(|key| str::from_utf8(key).ok()) { + Path::Map { + parent: &self.de.path, + key, + } + } else { + Path::Unknown { + parent: &self.de.path, + } + }, + remaining_depth: self.de.remaining_depth, + current_enum: None, + }; + seed.deserialize(&mut value_de) + } +} + +struct EnumAccess<'de, 'document, 'variant> { + de: &'variant mut DeserializerFromEvents<'de, 'document>, + name: Option<&'static str>, + tag: &'document str, +} + +impl<'de, 'document, 'variant> de::EnumAccess<'de> for EnumAccess<'de, 'document, 'variant> { + type Error = Error; + type Variant = DeserializerFromEvents<'de, 'variant>; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant)> + where + V: DeserializeSeed<'de>, + { + let str_de = StrDeserializer::::new(self.tag); + let variant = seed.deserialize(str_de)?; + let visitor = DeserializerFromEvents { + document: self.de.document, + pos: self.de.pos, + jumpcount: self.de.jumpcount, + path: self.de.path, + remaining_depth: self.de.remaining_depth, + current_enum: Some(CurrentEnum { + name: self.name, + tag: self.tag, + }), + }; + Ok((variant, visitor)) + } +} + +impl<'de, 'document> de::VariantAccess<'de> for DeserializerFromEvents<'de, 'document> { + type Error = Error; + + fn unit_variant(mut self) -> Result<()> { + Deserialize::deserialize(&mut self) + } + + fn newtype_variant_seed(mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + seed.deserialize(&mut self) + } + + fn tuple_variant(mut self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + de::Deserializer::deserialize_seq(&mut self, visitor) + } + + fn struct_variant(mut self, fields: &'static [&'static str], visitor: V) -> Result + where + V: Visitor<'de>, + { + de::Deserializer::deserialize_struct(&mut self, "", fields, visitor) + } +} + +struct UnitVariantAccess<'de, 'document, 'variant> { + de: &'variant mut DeserializerFromEvents<'de, 'document>, +} + +impl<'de, 'document, 'variant> de::EnumAccess<'de> for UnitVariantAccess<'de, 'document, 'variant> { + type Error = Error; + type Variant = Self; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant)> + where + V: DeserializeSeed<'de>, + { + Ok((seed.deserialize(&mut *self.de)?, self)) + } +} + +impl<'de, 'document, 'variant> de::VariantAccess<'de> + for UnitVariantAccess<'de, 'document, 'variant> +{ + type Error = Error; + + fn unit_variant(self) -> Result<()> { + Ok(()) + } + + fn newtype_variant_seed(self, _seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"newtype variant", + )) + } + + fn tuple_variant(self, _len: usize, _visitor: V) -> Result + where + V: Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"tuple variant", + )) + } + + fn struct_variant(self, _fields: &'static [&'static str], _visitor: V) -> Result + where + V: Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"struct variant", + )) + } +} + +fn visit_scalar<'de, V>(visitor: V, scalar: &Scalar<'de>, tagged_already: bool) -> Result +where + V: Visitor<'de>, +{ + let v = match str::from_utf8(&scalar.value) { + Ok(v) => v, + Err(_) => { + return Err(de::Error::invalid_type( + Unexpected::Bytes(&scalar.value), + &visitor, + )) + } + }; + if let (Some(tag), false) = (&scalar.tag, tagged_already) { + if tag == Tag::BOOL { + return match parse_bool(v) { + Some(v) => visitor.visit_bool(v), + None => Err(de::Error::invalid_value(Unexpected::Str(v), &"a boolean")), + }; + } else if tag == Tag::INT { + return match visit_int(visitor, v) { + Ok(result) => result, + Err(_) => Err(de::Error::invalid_value(Unexpected::Str(v), &"an integer")), + }; + } else if tag == Tag::FLOAT { + return match parse_f64(v) { + Some(v) => visitor.visit_f64(v), + None => Err(de::Error::invalid_value(Unexpected::Str(v), &"a float")), + }; + } else if tag == Tag::NULL { + return match parse_null(v.as_bytes()) { + Some(()) => visitor.visit_unit(), + None => Err(de::Error::invalid_value(Unexpected::Str(v), &"null")), + }; + } else if tag.starts_with("!") && scalar.style == ScalarStyle::Plain { + return visit_untagged_scalar(visitor, v, scalar.repr, scalar.style); + } + } else if scalar.style == ScalarStyle::Plain { + return visit_untagged_scalar(visitor, v, scalar.repr, scalar.style); + } + if let Some(borrowed) = parse_borrowed_str(v, scalar.repr, scalar.style) { + visitor.visit_borrowed_str(borrowed) + } else { + visitor.visit_str(v) + } +} + +fn parse_borrowed_str<'de>( + utf8_value: &str, + repr: Option<&'de [u8]>, + style: ScalarStyle, +) -> Option<&'de str> { + let borrowed_repr = repr?; + let expected_offset = match style { + ScalarStyle::Plain => 0, + ScalarStyle::SingleQuoted | ScalarStyle::DoubleQuoted => 1, + ScalarStyle::Literal | ScalarStyle::Folded => return None, + }; + let expected_end = borrowed_repr.len().checked_sub(expected_offset)?; + let expected_start = expected_end.checked_sub(utf8_value.len())?; + let borrowed_bytes = borrowed_repr.get(expected_start..expected_end)?; + if borrowed_bytes == utf8_value.as_bytes() { + return Some(unsafe { str::from_utf8_unchecked(borrowed_bytes) }); + } + None +} + +fn parse_null(scalar: &[u8]) -> Option<()> { + match scalar { + b"null" | b"Null" | b"NULL" | b"~" => Some(()), + _ => None, + } +} + +fn parse_bool(scalar: &str) -> Option { + match scalar { + "true" | "True" | "TRUE" => Some(true), + "false" | "False" | "FALSE" => Some(false), + _ => None, + } +} + +fn parse_unsigned_int( + scalar: &str, + from_str_radix: fn(&str, radix: u32) -> Result, +) -> Option { + let unpositive = scalar.strip_prefix('+').unwrap_or(scalar); + if let Some(rest) = unpositive.strip_prefix("0x") { + if rest.starts_with(['+', '-']) { + return None; + } + if let Ok(int) = from_str_radix(rest, 16) { + return Some(int); + } + } + if let Some(rest) = unpositive.strip_prefix("0o") { + if rest.starts_with(['+', '-']) { + return None; + } + if let Ok(int) = from_str_radix(rest, 8) { + return Some(int); + } + } + if let Some(rest) = unpositive.strip_prefix("0b") { + if rest.starts_with(['+', '-']) { + return None; + } + if let Ok(int) = from_str_radix(rest, 2) { + return Some(int); + } + } + if unpositive.starts_with(['+', '-']) { + return None; + } + if digits_but_not_number(scalar) { + return None; + } + from_str_radix(unpositive, 10).ok() +} + +fn parse_signed_int( + scalar: &str, + from_str_radix: fn(&str, radix: u32) -> Result, +) -> Option { + let unpositive = if let Some(unpositive) = scalar.strip_prefix('+') { + if unpositive.starts_with(['+', '-']) { + return None; + } + unpositive + } else { + scalar + }; + if let Some(rest) = unpositive.strip_prefix("0x") { + if rest.starts_with(['+', '-']) { + return None; + } + if let Ok(int) = from_str_radix(rest, 16) { + return Some(int); + } + } + if let Some(rest) = scalar.strip_prefix("-0x") { + let negative = format!("-{}", rest); + if let Ok(int) = from_str_radix(&negative, 16) { + return Some(int); + } + } + if let Some(rest) = unpositive.strip_prefix("0o") { + if rest.starts_with(['+', '-']) { + return None; + } + if let Ok(int) = from_str_radix(rest, 8) { + return Some(int); + } + } + if let Some(rest) = scalar.strip_prefix("-0o") { + let negative = format!("-{}", rest); + if let Ok(int) = from_str_radix(&negative, 8) { + return Some(int); + } + } + if let Some(rest) = unpositive.strip_prefix("0b") { + if rest.starts_with(['+', '-']) { + return None; + } + if let Ok(int) = from_str_radix(rest, 2) { + return Some(int); + } + } + if let Some(rest) = scalar.strip_prefix("-0b") { + let negative = format!("-{}", rest); + if let Ok(int) = from_str_radix(&negative, 2) { + return Some(int); + } + } + if digits_but_not_number(scalar) { + return None; + } + from_str_radix(unpositive, 10).ok() +} + +fn parse_negative_int( + scalar: &str, + from_str_radix: fn(&str, radix: u32) -> Result, +) -> Option { + if let Some(rest) = scalar.strip_prefix("-0x") { + let negative = format!("-{}", rest); + if let Ok(int) = from_str_radix(&negative, 16) { + return Some(int); + } + } + if let Some(rest) = scalar.strip_prefix("-0o") { + let negative = format!("-{}", rest); + if let Ok(int) = from_str_radix(&negative, 8) { + return Some(int); + } + } + if let Some(rest) = scalar.strip_prefix("-0b") { + let negative = format!("-{}", rest); + if let Ok(int) = from_str_radix(&negative, 2) { + return Some(int); + } + } + if digits_but_not_number(scalar) { + return None; + } + from_str_radix(scalar, 10).ok() +} + +pub(crate) fn parse_f64(scalar: &str) -> Option { + let unpositive = if let Some(unpositive) = scalar.strip_prefix('+') { + if unpositive.starts_with(['+', '-']) { + return None; + } + unpositive + } else { + scalar + }; + if let ".inf" | ".Inf" | ".INF" = unpositive { + return Some(f64::INFINITY); + } + if let "-.inf" | "-.Inf" | "-.INF" = scalar { + return Some(f64::NEG_INFINITY); + } + if let ".nan" | ".NaN" | ".NAN" = scalar { + return Some(f64::NAN.copysign(1.0)); + } + if let Ok(float) = unpositive.parse::() { + if float.is_finite() { + return Some(float); + } + } + None +} + +pub(crate) fn digits_but_not_number(scalar: &str) -> bool { + // Leading zero(s) followed by numeric characters is a string according to + // the YAML 1.2 spec. https://yaml.org/spec/1.2/spec.html#id2761292 + let scalar = scalar.strip_prefix(['-', '+']).unwrap_or(scalar); + scalar.len() > 1 && scalar.starts_with('0') && scalar[1..].bytes().all(|b| b.is_ascii_digit()) +} + +pub(crate) fn visit_int<'de, V>(visitor: V, v: &str) -> Result, V> +where + V: Visitor<'de>, +{ + if let Some(int) = parse_unsigned_int(v, u64::from_str_radix) { + return Ok(visitor.visit_u64(int)); + } + if let Some(int) = parse_negative_int(v, i64::from_str_radix) { + return Ok(visitor.visit_i64(int)); + } + if let Some(int) = parse_unsigned_int(v, u128::from_str_radix) { + return Ok(visitor.visit_u128(int)); + } + if let Some(int) = parse_negative_int(v, i128::from_str_radix) { + return Ok(visitor.visit_i128(int)); + } + Err(visitor) +} + +pub(crate) fn visit_untagged_scalar<'de, V>( + visitor: V, + v: &str, + repr: Option<&'de [u8]>, + style: ScalarStyle, +) -> Result +where + V: Visitor<'de>, +{ + if v.is_empty() || parse_null(v.as_bytes()) == Some(()) { + return visitor.visit_unit(); + } + if let Some(boolean) = parse_bool(v) { + return visitor.visit_bool(boolean); + } + let visitor = match visit_int(visitor, v) { + Ok(result) => return result, + Err(visitor) => visitor, + }; + if !digits_but_not_number(v) { + if let Some(float) = parse_f64(v) { + return visitor.visit_f64(float); + } + } + if let Some(borrowed) = parse_borrowed_str(v, repr, style) { + visitor.visit_borrowed_str(borrowed) + } else { + visitor.visit_str(v) + } +} + +fn is_plain_or_tagged_literal_scalar( + expected: &str, + scalar: &Scalar, + tagged_already: bool, +) -> bool { + match (scalar.style, &scalar.tag, tagged_already) { + (ScalarStyle::Plain, _, _) => true, + (ScalarStyle::Literal, Some(tag), false) => tag == expected, + _ => false, + } +} + +fn invalid_type(event: &Event, exp: &dyn Expected) -> Error { + enum Void {} + + struct InvalidType<'a> { + exp: &'a dyn Expected, + } + + impl<'de, 'a> Visitor<'de> for InvalidType<'a> { + type Value = Void; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.exp.fmt(formatter) + } + } + + match event { + Event::Alias(_) => unreachable!(), + Event::Scalar(scalar) => { + let get_type = InvalidType { exp }; + match visit_scalar(get_type, scalar, false) { + Ok(void) => match void {}, + Err(invalid_type) => invalid_type, + } + } + Event::SequenceStart(_) => de::Error::invalid_type(Unexpected::Seq, exp), + Event::MappingStart(_) => de::Error::invalid_type(Unexpected::Map, exp), + Event::SequenceEnd => panic!("unexpected end of sequence"), + Event::MappingEnd => panic!("unexpected end of mapping"), + Event::Void => error::new(ErrorImpl::EndOfStream), + } +} + +fn parse_tag(libyaml_tag: &Option) -> Option<&str> { + let mut bytes: &[u8] = libyaml_tag.as_ref()?; + if let (b'!', rest) = bytes.split_first()? { + if !rest.is_empty() { + bytes = rest; + } + str::from_utf8(bytes).ok() + } else { + None + } +} + +impl<'de, 'document> de::Deserializer<'de> for &mut DeserializerFromEvents<'de, 'document> { + type Error = Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + fn enum_tag(tag: &Option, tagged_already: bool) -> Option<&str> { + if tagged_already { + return None; + } + parse_tag(tag) + } + loop { + match next { + Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_any(visitor), + Event::Scalar(scalar) => { + if let Some(tag) = enum_tag(&scalar.tag, tagged_already) { + *self.pos -= 1; + break visitor.visit_enum(EnumAccess { + de: self, + name: None, + tag, + }); + } + break visit_scalar(visitor, scalar, tagged_already); + } + Event::SequenceStart(sequence) => { + if let Some(tag) = enum_tag(&sequence.tag, tagged_already) { + *self.pos -= 1; + break visitor.visit_enum(EnumAccess { + de: self, + name: None, + tag, + }); + } + break self.visit_sequence(visitor, mark); + } + Event::MappingStart(mapping) => { + if let Some(tag) = enum_tag(&mapping.tag, tagged_already) { + *self.pos -= 1; + break visitor.visit_enum(EnumAccess { + de: self, + name: None, + tag, + }); + } + break self.visit_mapping(visitor, mark); + } + Event::SequenceEnd => panic!("unexpected end of sequence"), + Event::MappingEnd => panic!("unexpected end of mapping"), + Event::Void => break visitor.visit_none(), + } + } + // The de::Error impl creates errors with unknown line and column. Fill + // in the position here by looking at the current index in the input. + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + loop { + match next { + Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_bool(visitor), + Event::Scalar(scalar) + if is_plain_or_tagged_literal_scalar(Tag::BOOL, scalar, tagged_already) => + { + if let Ok(value) = str::from_utf8(&scalar.value) { + if let Some(boolean) = parse_bool(value) { + break visitor.visit_bool(boolean); + } + } + } + _ => {} + } + break Err(invalid_type(next, &visitor)); + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_i64(visitor) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_i64(visitor) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_i64(visitor) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + loop { + match next { + Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_i64(visitor), + Event::Scalar(scalar) + if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) => + { + if let Ok(value) = str::from_utf8(&scalar.value) { + if let Some(int) = parse_signed_int(value, i64::from_str_radix) { + break visitor.visit_i64(int); + } + } + } + _ => {} + } + break Err(invalid_type(next, &visitor)); + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + loop { + match next { + Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_i128(visitor), + Event::Scalar(scalar) + if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) => + { + if let Ok(value) = str::from_utf8(&scalar.value) { + if let Some(int) = parse_signed_int(value, i128::from_str_radix) { + break visitor.visit_i128(int); + } + } + } + _ => {} + } + break Err(invalid_type(next, &visitor)); + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_u64(visitor) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_u64(visitor) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_u64(visitor) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + loop { + match next { + Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_u64(visitor), + Event::Scalar(scalar) + if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) => + { + if let Ok(value) = str::from_utf8(&scalar.value) { + if let Some(int) = parse_unsigned_int(value, u64::from_str_radix) { + break visitor.visit_u64(int); + } + } + } + _ => {} + } + break Err(invalid_type(next, &visitor)); + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + loop { + match next { + Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_u128(visitor), + Event::Scalar(scalar) + if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) => + { + if let Ok(value) = str::from_utf8(&scalar.value) { + if let Some(int) = parse_unsigned_int(value, u128::from_str_radix) { + break visitor.visit_u128(int); + } + } + } + _ => {} + } + break Err(invalid_type(next, &visitor)); + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_f64(visitor) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + loop { + match next { + Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_f64(visitor), + Event::Scalar(scalar) + if is_plain_or_tagged_literal_scalar(Tag::FLOAT, scalar, tagged_already) => + { + if let Ok(value) = str::from_utf8(&scalar.value) { + if let Some(float) = parse_f64(value) { + break visitor.visit_f64(float); + } + } + } + _ => {} + } + break Err(invalid_type(next, &visitor)); + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_str(visitor) + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let (next, mark) = self.next_event_mark()?; + match next { + Event::Scalar(scalar) => { + if let Ok(v) = str::from_utf8(&scalar.value) { + if let Some(borrowed) = parse_borrowed_str(v, scalar.repr, scalar.style) { + visitor.visit_borrowed_str(borrowed) + } else { + visitor.visit_str(v) + } + } else { + Err(invalid_type(next, &visitor)) + } + } + Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_str(visitor), + other => Err(invalid_type(other, &visitor)), + } + .map_err(|err: Error| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_str(visitor) + } + + fn deserialize_bytes(self, _visitor: V) -> Result + where + V: Visitor<'de>, + { + Err(error::new(ErrorImpl::BytesUnsupported)) + } + + fn deserialize_byte_buf(self, _visitor: V) -> Result + where + V: Visitor<'de>, + { + Err(error::new(ErrorImpl::BytesUnsupported)) + } + + /// Parses `null` as None and any other values as `Some(...)`. + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let is_some = match self.peek_event()? { + Event::Alias(mut pos) => { + *self.pos += 1; + return self.jump(&mut pos)?.deserialize_option(visitor); + } + Event::Scalar(scalar) => { + let tagged_already = self.current_enum.is_some(); + if scalar.style != ScalarStyle::Plain { + true + } else if let (Some(tag), false) = (&scalar.tag, tagged_already) { + if tag == Tag::NULL { + if let Some(()) = parse_null(&scalar.value) { + false + } else if let Ok(v) = str::from_utf8(&scalar.value) { + return Err(de::Error::invalid_value(Unexpected::Str(v), &"null")); + } else { + return Err(de::Error::invalid_value( + Unexpected::Bytes(&scalar.value), + &"null", + )); + } + } else { + true + } + } else { + !scalar.value.is_empty() && parse_null(&scalar.value).is_none() + } + } + Event::SequenceStart(_) | Event::MappingStart(_) => true, + Event::SequenceEnd => panic!("unexpected end of sequence"), + Event::MappingEnd => panic!("unexpected end of mapping"), + Event::Void => false, + }; + if is_some { + visitor.visit_some(self) + } else { + *self.pos += 1; + self.current_enum = None; + visitor.visit_none() + } + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let tagged_already = self.current_enum.is_some(); + let (next, mark) = self.next_event_mark()?; + match next { + Event::Scalar(scalar) => { + let is_null = if scalar.style != ScalarStyle::Plain { + false + } else if let (Some(tag), false) = (&scalar.tag, tagged_already) { + tag == Tag::NULL && parse_null(&scalar.value).is_some() + } else { + scalar.value.is_empty() || parse_null(&scalar.value).is_some() + }; + if is_null { + visitor.visit_unit() + } else if let Ok(v) = str::from_utf8(&scalar.value) { + Err(de::Error::invalid_value(Unexpected::Str(v), &"null")) + } else { + Err(de::Error::invalid_value( + Unexpected::Bytes(&scalar.value), + &"null", + )) + } + } + Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_unit(visitor), + Event::Void => visitor.visit_unit(), + other => Err(invalid_type(other, &visitor)), + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_unit_struct(self, _name: &'static str, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_unit(visitor) + } + + /// Parses a newtype struct as the underlying value. + fn deserialize_newtype_struct(self, _name: &'static str, visitor: V) -> Result + where + V: Visitor<'de>, + { + let (_event, mark) = self.peek_event_mark()?; + self.recursion_check(mark, |de| visitor.visit_newtype_struct(de)) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let (next, mark) = self.next_event_mark()?; + match next { + Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_seq(visitor), + Event::SequenceStart(_) => self.visit_sequence(visitor, mark), + other => { + if match other { + Event::Void => true, + Event::Scalar(scalar) => { + scalar.value.is_empty() && scalar.style == ScalarStyle::Plain + } + _ => false, + } { + visitor.visit_seq(SeqAccess { + empty: true, + de: self, + len: 0, + }) + } else { + Err(invalid_type(other, &visitor)) + } + } + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_tuple(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let (next, mark) = self.next_event_mark()?; + match next { + Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_map(visitor), + Event::MappingStart(_) => self.visit_mapping(visitor, mark), + other => { + if match other { + Event::Void => true, + Event::Scalar(scalar) => { + scalar.value.is_empty() && scalar.style == ScalarStyle::Plain + } + _ => false, + } { + visitor.visit_map(MapAccess { + empty: true, + de: self, + len: 0, + key: None, + }) + } else { + Err(invalid_type(other, &visitor)) + } + } + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_struct( + self, + _name: &'static str, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_map(visitor) + } + + /// Parses an enum as a single key:value pair where the key identifies the + /// variant and the value gives the content. A String will also parse correctly + /// to a unit enum value. + fn deserialize_enum( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let (next, mark) = self.peek_event_mark()?; + loop { + if let Some(current_enum) = self.current_enum { + if let Event::Scalar(scalar) = next { + if !scalar.value.is_empty() { + break visitor.visit_enum(UnitVariantAccess { de: self }); + } + } + let message = if let Some(name) = current_enum.name { + format!( + "deserializing nested enum in {}::{} from YAML is not supported yet", + name, current_enum.tag, + ) + } else { + format!( + "deserializing nested enum in !{} from YAML is not supported yet", + current_enum.tag, + ) + }; + break Err(error::new(ErrorImpl::Message(message, None))); + } + break match next { + Event::Alias(mut pos) => { + *self.pos += 1; + self.jump(&mut pos)? + .deserialize_enum(name, variants, visitor) + } + Event::Scalar(scalar) => { + if let Some(tag) = parse_tag(&scalar.tag) { + return visitor.visit_enum(EnumAccess { + de: self, + name: Some(name), + tag, + }); + } + visitor.visit_enum(UnitVariantAccess { de: self }) + } + Event::MappingStart(mapping) => { + if let Some(tag) = parse_tag(&mapping.tag) { + return visitor.visit_enum(EnumAccess { + de: self, + name: Some(name), + tag, + }); + } + let err = + de::Error::invalid_type(Unexpected::Map, &"a YAML tag starting with '!'"); + Err(error::fix_mark(err, mark, self.path)) + } + Event::SequenceStart(sequence) => { + if let Some(tag) = parse_tag(&sequence.tag) { + return visitor.visit_enum(EnumAccess { + de: self, + name: Some(name), + tag, + }); + } + let err = + de::Error::invalid_type(Unexpected::Seq, &"a YAML tag starting with '!'"); + Err(error::fix_mark(err, mark, self.path)) + } + Event::SequenceEnd => panic!("unexpected end of sequence"), + Event::MappingEnd => panic!("unexpected end of mapping"), + Event::Void => Err(error::new(ErrorImpl::EndOfStream)), + }; + } + .map_err(|err| error::fix_mark(err, mark, self.path)) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_str(visitor) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.ignore_any()?; + visitor.visit_unit() + } +} + +/// Deserialize an instance of type `T` from a string of YAML text. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a YAML map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the YAML map or some number is too big to fit in the expected primitive +/// type. +pub fn from_str<'de, T>(s: &'de str) -> Result +where + T: Deserialize<'de>, +{ + T::deserialize(Deserializer::from_str(s)) +} + +/// Deserialize an instance of type `T` from an IO stream of YAML. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a YAML map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the YAML map or some number is too big to fit in the expected primitive +/// type. +pub fn from_reader(rdr: R) -> Result +where + R: io::Read, + T: DeserializeOwned, +{ + T::deserialize(Deserializer::from_reader(rdr)) +} + +/// Deserialize an instance of type `T` from bytes of YAML text. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a YAML map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the YAML map or some number is too big to fit in the expected primitive +/// type. +pub fn from_slice<'de, T>(v: &'de [u8]) -> Result +where + T: Deserialize<'de>, +{ + T::deserialize(Deserializer::from_slice(v)) +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/error.rs b/bitbox02-bt/vendor/serde_yaml/src/error.rs new file mode 100644 index 0000000..01f8ed1 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/error.rs @@ -0,0 +1,290 @@ +use crate::libyaml::{emitter, error as libyaml}; +use crate::path::Path; +use serde::{de, ser}; +use std::error::Error as StdError; +use std::fmt::{self, Debug, Display}; +use std::io; +use std::result; +use std::string; +use std::sync::Arc; + +/// An error that happened serializing or deserializing YAML data. +pub struct Error(Box); + +/// Alias for a `Result` with the error type `serde_yaml::Error`. +pub type Result = result::Result; + +#[derive(Debug)] +pub(crate) enum ErrorImpl { + Message(String, Option), + + Libyaml(libyaml::Error), + Io(io::Error), + FromUtf8(string::FromUtf8Error), + + EndOfStream, + MoreThanOneDocument, + RecursionLimitExceeded(libyaml::Mark), + RepetitionLimitExceeded, + BytesUnsupported, + UnknownAnchor(libyaml::Mark), + SerializeNestedEnum, + ScalarInMerge, + TaggedInMerge, + ScalarInMergeElement, + SequenceInMergeElement, + EmptyTag, + FailedToParseNumber, + + Shared(Arc), +} + +#[derive(Debug)] +pub(crate) struct Pos { + mark: libyaml::Mark, + path: String, +} + +/// The input location that an error occured. +#[derive(Debug)] +pub struct Location { + index: usize, + line: usize, + column: usize, +} + +impl Location { + /// The byte index of the error + pub fn index(&self) -> usize { + self.index + } + + /// The line of the error + pub fn line(&self) -> usize { + self.line + } + + /// The column of the error + pub fn column(&self) -> usize { + self.column + } + + // This is to keep decoupled with the yaml crate + #[doc(hidden)] + fn from_mark(mark: libyaml::Mark) -> Self { + Location { + index: mark.index() as usize, + // `line` and `column` returned from libyaml are 0-indexed but all error messages add +1 to this value + line: mark.line() as usize + 1, + column: mark.column() as usize + 1, + } + } +} + +impl Error { + /// Returns the Location from the error if one exists. + /// + /// Not all types of errors have a location so this can return `None`. + /// + /// # Examples + /// + /// ``` + /// # use serde_yaml::{Value, Error}; + /// # + /// // The `@` character as the first character makes this invalid yaml + /// let invalid_yaml: Result = serde_yaml::from_str("@invalid_yaml"); + /// + /// let location = invalid_yaml.unwrap_err().location().unwrap(); + /// + /// assert_eq!(location.line(), 1); + /// assert_eq!(location.column(), 1); + /// ``` + pub fn location(&self) -> Option { + self.0.location() + } +} + +pub(crate) fn new(inner: ErrorImpl) -> Error { + Error(Box::new(inner)) +} + +pub(crate) fn shared(shared: Arc) -> Error { + Error(Box::new(ErrorImpl::Shared(shared))) +} + +pub(crate) fn fix_mark(mut error: Error, mark: libyaml::Mark, path: Path) -> Error { + if let ErrorImpl::Message(_, none @ None) = error.0.as_mut() { + *none = Some(Pos { + mark, + path: path.to_string(), + }); + } + error +} + +impl Error { + pub(crate) fn shared(self) -> Arc { + if let ErrorImpl::Shared(err) = *self.0 { + err + } else { + Arc::from(self.0) + } + } +} + +impl From for Error { + fn from(err: libyaml::Error) -> Self { + Error(Box::new(ErrorImpl::Libyaml(err))) + } +} + +impl From for Error { + fn from(err: emitter::Error) -> Self { + match err { + emitter::Error::Libyaml(err) => Self::from(err), + emitter::Error::Io(err) => new(ErrorImpl::Io(err)), + } + } +} + +impl StdError for Error { + fn source(&self) -> Option<&(dyn StdError + 'static)> { + self.0.source() + } +} + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.display(f) + } +} + +// Remove two layers of verbosity from the debug representation. Humans often +// end up seeing this representation because it is what unwrap() shows. +impl Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.debug(f) + } +} + +impl ser::Error for Error { + fn custom(msg: T) -> Self { + Error(Box::new(ErrorImpl::Message(msg.to_string(), None))) + } +} + +impl de::Error for Error { + fn custom(msg: T) -> Self { + Error(Box::new(ErrorImpl::Message(msg.to_string(), None))) + } +} + +impl ErrorImpl { + fn location(&self) -> Option { + self.mark().map(Location::from_mark) + } + + fn source(&self) -> Option<&(dyn StdError + 'static)> { + match self { + ErrorImpl::Io(err) => err.source(), + ErrorImpl::FromUtf8(err) => err.source(), + ErrorImpl::Shared(err) => err.source(), + _ => None, + } + } + + fn mark(&self) -> Option { + match self { + ErrorImpl::Message(_, Some(Pos { mark, path: _ })) + | ErrorImpl::RecursionLimitExceeded(mark) + | ErrorImpl::UnknownAnchor(mark) => Some(*mark), + ErrorImpl::Libyaml(err) => Some(err.mark()), + ErrorImpl::Shared(err) => err.mark(), + _ => None, + } + } + + fn message_no_mark(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ErrorImpl::Message(msg, None) => f.write_str(msg), + ErrorImpl::Message(msg, Some(Pos { mark: _, path })) => { + if path != "." { + write!(f, "{}: ", path)?; + } + f.write_str(msg) + } + ErrorImpl::Libyaml(_) => unreachable!(), + ErrorImpl::Io(err) => Display::fmt(err, f), + ErrorImpl::FromUtf8(err) => Display::fmt(err, f), + ErrorImpl::EndOfStream => f.write_str("EOF while parsing a value"), + ErrorImpl::MoreThanOneDocument => f.write_str( + "deserializing from YAML containing more than one document is not supported", + ), + ErrorImpl::RecursionLimitExceeded(_mark) => f.write_str("recursion limit exceeded"), + ErrorImpl::RepetitionLimitExceeded => f.write_str("repetition limit exceeded"), + ErrorImpl::BytesUnsupported => { + f.write_str("serialization and deserialization of bytes in YAML is not implemented") + } + ErrorImpl::UnknownAnchor(_mark) => f.write_str("unknown anchor"), + ErrorImpl::SerializeNestedEnum => { + f.write_str("serializing nested enums in YAML is not supported yet") + } + ErrorImpl::ScalarInMerge => { + f.write_str("expected a mapping or list of mappings for merging, but found scalar") + } + ErrorImpl::TaggedInMerge => f.write_str("unexpected tagged value in merge"), + ErrorImpl::ScalarInMergeElement => { + f.write_str("expected a mapping for merging, but found scalar") + } + ErrorImpl::SequenceInMergeElement => { + f.write_str("expected a mapping for merging, but found sequence") + } + ErrorImpl::EmptyTag => f.write_str("empty YAML tag is not allowed"), + ErrorImpl::FailedToParseNumber => f.write_str("failed to parse YAML number"), + ErrorImpl::Shared(_) => unreachable!(), + } + } + + fn display(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ErrorImpl::Libyaml(err) => Display::fmt(err, f), + ErrorImpl::Shared(err) => err.display(f), + _ => { + self.message_no_mark(f)?; + if let Some(mark) = self.mark() { + if mark.line() != 0 || mark.column() != 0 { + write!(f, " at {}", mark)?; + } + } + Ok(()) + } + } + } + + fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ErrorImpl::Libyaml(err) => Debug::fmt(err, f), + ErrorImpl::Shared(err) => err.debug(f), + _ => { + f.write_str("Error(")?; + struct MessageNoMark<'a>(&'a ErrorImpl); + impl<'a> Display for MessageNoMark<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.message_no_mark(f) + } + } + let msg = MessageNoMark(self).to_string(); + Debug::fmt(&msg, f)?; + if let Some(mark) = self.mark() { + write!( + f, + ", line: {}, column: {}", + mark.line() + 1, + mark.column() + 1, + )?; + } + f.write_str(")") + } + } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/lib.rs b/bitbox02-bt/vendor/serde_yaml/src/lib.rs new file mode 100644 index 0000000..a719d02 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/lib.rs @@ -0,0 +1,191 @@ +//! [![github]](https://github.com/dtolnay/serde-yaml) [![crates-io]](https://crates.io/crates/serde-yaml) [![docs-rs]](https://docs.rs/serde-yaml) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs +//! +//!
+//! +//! Rust library for using the [Serde] serialization framework with data in +//! [YAML] file format. _(This project is no longer maintained.)_ +//! +//! [Serde]: https://github.com/serde-rs/serde +//! [YAML]: https://yaml.org/ +//! +//! # Examples +//! +//! ``` +//! use std::collections::BTreeMap; +//! +//! fn main() -> Result<(), serde_yaml::Error> { +//! // You have some type. +//! let mut map = BTreeMap::new(); +//! map.insert("x".to_string(), 1.0); +//! map.insert("y".to_string(), 2.0); +//! +//! // Serialize it to a YAML string. +//! let yaml = serde_yaml::to_string(&map)?; +//! assert_eq!(yaml, "x: 1.0\ny: 2.0\n"); +//! +//! // Deserialize it back to a Rust type. +//! let deserialized_map: BTreeMap = serde_yaml::from_str(&yaml)?; +//! assert_eq!(map, deserialized_map); +//! Ok(()) +//! } +//! ``` +//! +//! ## Using Serde derive +//! +//! It can also be used with Serde's derive macros to handle structs and enums +//! defined in your program. +//! +//! Structs serialize in the obvious way: +//! +//! ``` +//! # use serde_derive::{Serialize, Deserialize}; +//! use serde::{Serialize, Deserialize}; +//! +//! #[derive(Serialize, Deserialize, PartialEq, Debug)] +//! struct Point { +//! x: f64, +//! y: f64, +//! } +//! +//! fn main() -> Result<(), serde_yaml::Error> { +//! let point = Point { x: 1.0, y: 2.0 }; +//! +//! let yaml = serde_yaml::to_string(&point)?; +//! assert_eq!(yaml, "x: 1.0\ny: 2.0\n"); +//! +//! let deserialized_point: Point = serde_yaml::from_str(&yaml)?; +//! assert_eq!(point, deserialized_point); +//! Ok(()) +//! } +//! ``` +//! +//! Enums serialize using YAML's `!tag` syntax to identify the variant name. +//! +//! ``` +//! # use serde_derive::{Serialize, Deserialize}; +//! use serde::{Serialize, Deserialize}; +//! +//! #[derive(Serialize, Deserialize, PartialEq, Debug)] +//! enum Enum { +//! Unit, +//! Newtype(usize), +//! Tuple(usize, usize, usize), +//! Struct { x: f64, y: f64 }, +//! } +//! +//! fn main() -> Result<(), serde_yaml::Error> { +//! let yaml = " +//! - !Newtype 1 +//! - !Tuple [0, 0, 0] +//! - !Struct {x: 1.0, y: 2.0} +//! "; +//! let values: Vec = serde_yaml::from_str(yaml).unwrap(); +//! assert_eq!(values[0], Enum::Newtype(1)); +//! assert_eq!(values[1], Enum::Tuple(0, 0, 0)); +//! assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 }); +//! +//! // The last two in YAML's block style instead: +//! let yaml = " +//! - !Tuple +//! - 0 +//! - 0 +//! - 0 +//! - !Struct +//! x: 1.0 +//! y: 2.0 +//! "; +//! let values: Vec = serde_yaml::from_str(yaml).unwrap(); +//! assert_eq!(values[0], Enum::Tuple(0, 0, 0)); +//! assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 }); +//! +//! // Variants with no data can be written using !Tag or just the string name. +//! let yaml = " +//! - Unit # serialization produces this one +//! - !Unit +//! "; +//! let values: Vec = serde_yaml::from_str(yaml).unwrap(); +//! assert_eq!(values[0], Enum::Unit); +//! assert_eq!(values[1], Enum::Unit); +//! +//! Ok(()) +//! } +//! ``` + +#![doc(html_root_url = "https://docs.rs/serde_yaml/0.9.34+deprecated")] +#![deny(missing_docs, unsafe_op_in_unsafe_fn)] +// Suppressed clippy_pedantic lints +#![allow( + // buggy + clippy::iter_not_returning_iterator, // https://github.com/rust-lang/rust-clippy/issues/8285 + clippy::ptr_arg, // https://github.com/rust-lang/rust-clippy/issues/9218 + clippy::question_mark, // https://github.com/rust-lang/rust-clippy/issues/7859 + // private Deserializer::next + clippy::should_implement_trait, + // things are often more readable this way + clippy::cast_lossless, + clippy::checked_conversions, + clippy::if_not_else, + clippy::manual_assert, + clippy::match_like_matches_macro, + clippy::match_same_arms, + clippy::module_name_repetitions, + clippy::needless_pass_by_value, + clippy::redundant_else, + clippy::single_match_else, + // code is acceptable + clippy::blocks_in_conditions, + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_precision_loss, + clippy::cast_sign_loss, + clippy::derive_partial_eq_without_eq, + clippy::derived_hash_with_manual_eq, + clippy::doc_markdown, + clippy::items_after_statements, + clippy::let_underscore_untyped, + clippy::manual_map, + clippy::missing_panics_doc, + clippy::never_loop, + clippy::return_self_not_must_use, + clippy::too_many_lines, + clippy::uninlined_format_args, + clippy::unsafe_removed_from_name, + clippy::wildcard_in_or_patterns, + // noisy + clippy::missing_errors_doc, + clippy::must_use_candidate, +)] + +pub use crate::de::{from_reader, from_slice, from_str, Deserializer}; +pub use crate::error::{Error, Location, Result}; +pub use crate::ser::{to_string, to_writer, Serializer}; +#[doc(inline)] +pub use crate::value::{from_value, to_value, Index, Number, Sequence, Value}; + +#[doc(inline)] +pub use crate::mapping::Mapping; + +mod de; +mod error; +mod libyaml; +mod loader; +pub mod mapping; +mod number; +mod path; +mod ser; +pub mod value; +pub mod with; + +// Prevent downstream code from implementing the Index trait. +mod private { + pub trait Sealed {} + impl Sealed for usize {} + impl Sealed for str {} + impl Sealed for String {} + impl Sealed for crate::Value {} + impl<'a, T> Sealed for &'a T where T: ?Sized + Sealed {} +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/libyaml/cstr.rs b/bitbox02-bt/vendor/serde_yaml/src/libyaml/cstr.rs new file mode 100644 index 0000000..6e82535 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/libyaml/cstr.rs @@ -0,0 +1,127 @@ +use std::fmt::{self, Debug, Display, Write as _}; +use std::marker::PhantomData; +use std::ptr::NonNull; +use std::slice; +use std::str; + +#[derive(Copy, Clone)] +pub(crate) struct CStr<'a> { + ptr: NonNull, + marker: PhantomData<&'a [u8]>, +} + +unsafe impl<'a> Send for CStr<'a> {} +unsafe impl<'a> Sync for CStr<'a> {} + +impl<'a> CStr<'a> { + pub fn from_bytes_with_nul(bytes: &'static [u8]) -> Self { + assert_eq!(bytes.last(), Some(&b'\0')); + let ptr = NonNull::from(bytes).cast(); + unsafe { Self::from_ptr(ptr) } + } + + pub unsafe fn from_ptr(ptr: NonNull) -> Self { + CStr { + ptr: ptr.cast(), + marker: PhantomData, + } + } + + pub fn len(self) -> usize { + let start = self.ptr.as_ptr(); + let mut end = start; + unsafe { + while *end != 0 { + end = end.add(1); + } + end.offset_from(start) as usize + } + } + + pub fn to_bytes(self) -> &'a [u8] { + let len = self.len(); + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), len) } + } +} + +impl<'a> Display for CStr<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let ptr = self.ptr.as_ptr(); + let len = self.len(); + let bytes = unsafe { slice::from_raw_parts(ptr, len) }; + display_lossy(bytes, formatter) + } +} + +impl<'a> Debug for CStr<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let ptr = self.ptr.as_ptr(); + let len = self.len(); + let bytes = unsafe { slice::from_raw_parts(ptr, len) }; + debug_lossy(bytes, formatter) + } +} + +fn display_lossy(mut bytes: &[u8], formatter: &mut fmt::Formatter) -> fmt::Result { + loop { + match str::from_utf8(bytes) { + Ok(valid) => return formatter.write_str(valid), + Err(utf8_error) => { + let valid_up_to = utf8_error.valid_up_to(); + let valid = unsafe { str::from_utf8_unchecked(&bytes[..valid_up_to]) }; + formatter.write_str(valid)?; + formatter.write_char(char::REPLACEMENT_CHARACTER)?; + if let Some(error_len) = utf8_error.error_len() { + bytes = &bytes[valid_up_to + error_len..]; + } else { + return Ok(()); + } + } + } + } +} + +pub(crate) fn debug_lossy(mut bytes: &[u8], formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_char('"')?; + + while !bytes.is_empty() { + let from_utf8_result = str::from_utf8(bytes); + let valid = match from_utf8_result { + Ok(valid) => valid, + Err(utf8_error) => { + let valid_up_to = utf8_error.valid_up_to(); + unsafe { str::from_utf8_unchecked(&bytes[..valid_up_to]) } + } + }; + + let mut written = 0; + for (i, ch) in valid.char_indices() { + let esc = ch.escape_debug(); + if esc.len() != 1 && ch != '\'' { + formatter.write_str(&valid[written..i])?; + for ch in esc { + formatter.write_char(ch)?; + } + written = i + ch.len_utf8(); + } + } + formatter.write_str(&valid[written..])?; + + match from_utf8_result { + Ok(_valid) => break, + Err(utf8_error) => { + let end_of_broken = if let Some(error_len) = utf8_error.error_len() { + valid.len() + error_len + } else { + bytes.len() + }; + for b in &bytes[valid.len()..end_of_broken] { + write!(formatter, "\\x{:02x}", b)?; + } + bytes = &bytes[end_of_broken..]; + } + } + } + + formatter.write_char('"') +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/libyaml/emitter.rs b/bitbox02-bt/vendor/serde_yaml/src/libyaml/emitter.rs new file mode 100644 index 0000000..686f06e --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/libyaml/emitter.rs @@ -0,0 +1,217 @@ +use crate::libyaml; +use crate::libyaml::util::Owned; +use std::ffi::c_void; +use std::io; +use std::mem::{self, MaybeUninit}; +use std::ptr::{self, addr_of_mut}; +use std::slice; +use unsafe_libyaml as sys; + +#[derive(Debug)] +pub(crate) enum Error { + Libyaml(libyaml::error::Error), + Io(io::Error), +} + +pub(crate) struct Emitter<'a> { + pin: Owned>, +} + +struct EmitterPinned<'a> { + sys: sys::yaml_emitter_t, + write: Box, + write_error: Option, +} + +#[derive(Debug)] +pub(crate) enum Event<'a> { + StreamStart, + StreamEnd, + DocumentStart, + DocumentEnd, + Scalar(Scalar<'a>), + SequenceStart(Sequence), + SequenceEnd, + MappingStart(Mapping), + MappingEnd, +} + +#[derive(Debug)] +pub(crate) struct Scalar<'a> { + pub tag: Option, + pub value: &'a str, + pub style: ScalarStyle, +} + +#[derive(Debug)] +pub(crate) enum ScalarStyle { + Any, + Plain, + SingleQuoted, + Literal, +} + +#[derive(Debug)] +pub(crate) struct Sequence { + pub tag: Option, +} + +#[derive(Debug)] +pub(crate) struct Mapping { + pub tag: Option, +} + +impl<'a> Emitter<'a> { + pub fn new(write: Box) -> Emitter<'a> { + let owned = Owned::::new_uninit(); + let pin = unsafe { + let emitter = addr_of_mut!((*owned.ptr).sys); + if sys::yaml_emitter_initialize(emitter).fail { + panic!("malloc error: {}", libyaml::Error::emit_error(emitter)); + } + sys::yaml_emitter_set_unicode(emitter, true); + sys::yaml_emitter_set_width(emitter, -1); + addr_of_mut!((*owned.ptr).write).write(write); + addr_of_mut!((*owned.ptr).write_error).write(None); + sys::yaml_emitter_set_output(emitter, write_handler, owned.ptr.cast()); + Owned::assume_init(owned) + }; + Emitter { pin } + } + + pub fn emit(&mut self, event: Event) -> Result<(), Error> { + let mut sys_event = MaybeUninit::::uninit(); + let sys_event = sys_event.as_mut_ptr(); + unsafe { + let emitter = addr_of_mut!((*self.pin.ptr).sys); + let initialize_status = match event { + Event::StreamStart => { + sys::yaml_stream_start_event_initialize(sys_event, sys::YAML_UTF8_ENCODING) + } + Event::StreamEnd => sys::yaml_stream_end_event_initialize(sys_event), + Event::DocumentStart => { + let version_directive = ptr::null_mut(); + let tag_directives_start = ptr::null_mut(); + let tag_directives_end = ptr::null_mut(); + let implicit = true; + sys::yaml_document_start_event_initialize( + sys_event, + version_directive, + tag_directives_start, + tag_directives_end, + implicit, + ) + } + Event::DocumentEnd => { + let implicit = true; + sys::yaml_document_end_event_initialize(sys_event, implicit) + } + Event::Scalar(mut scalar) => { + let anchor = ptr::null(); + let tag = scalar.tag.as_mut().map_or_else(ptr::null, |tag| { + tag.push('\0'); + tag.as_ptr() + }); + let value = scalar.value.as_ptr(); + let length = scalar.value.len() as i32; + let plain_implicit = tag.is_null(); + let quoted_implicit = tag.is_null(); + let style = match scalar.style { + ScalarStyle::Any => sys::YAML_ANY_SCALAR_STYLE, + ScalarStyle::Plain => sys::YAML_PLAIN_SCALAR_STYLE, + ScalarStyle::SingleQuoted => sys::YAML_SINGLE_QUOTED_SCALAR_STYLE, + ScalarStyle::Literal => sys::YAML_LITERAL_SCALAR_STYLE, + }; + sys::yaml_scalar_event_initialize( + sys_event, + anchor, + tag, + value, + length, + plain_implicit, + quoted_implicit, + style, + ) + } + Event::SequenceStart(mut sequence) => { + let anchor = ptr::null(); + let tag = sequence.tag.as_mut().map_or_else(ptr::null, |tag| { + tag.push('\0'); + tag.as_ptr() + }); + let implicit = tag.is_null(); + let style = sys::YAML_ANY_SEQUENCE_STYLE; + sys::yaml_sequence_start_event_initialize( + sys_event, anchor, tag, implicit, style, + ) + } + Event::SequenceEnd => sys::yaml_sequence_end_event_initialize(sys_event), + Event::MappingStart(mut mapping) => { + let anchor = ptr::null(); + let tag = mapping.tag.as_mut().map_or_else(ptr::null, |tag| { + tag.push('\0'); + tag.as_ptr() + }); + let implicit = tag.is_null(); + let style = sys::YAML_ANY_MAPPING_STYLE; + sys::yaml_mapping_start_event_initialize( + sys_event, anchor, tag, implicit, style, + ) + } + Event::MappingEnd => sys::yaml_mapping_end_event_initialize(sys_event), + }; + if initialize_status.fail { + return Err(Error::Libyaml(libyaml::Error::emit_error(emitter))); + } + if sys::yaml_emitter_emit(emitter, sys_event).fail { + return Err(self.error()); + } + } + Ok(()) + } + + pub fn flush(&mut self) -> Result<(), Error> { + unsafe { + let emitter = addr_of_mut!((*self.pin.ptr).sys); + if sys::yaml_emitter_flush(emitter).fail { + return Err(self.error()); + } + } + Ok(()) + } + + pub fn into_inner(self) -> Box { + let sink = Box::new(io::sink()); + unsafe { mem::replace(&mut (*self.pin.ptr).write, sink) } + } + + fn error(&mut self) -> Error { + let emitter = unsafe { &mut *self.pin.ptr }; + if let Some(write_error) = emitter.write_error.take() { + Error::Io(write_error) + } else { + Error::Libyaml(unsafe { libyaml::Error::emit_error(&emitter.sys) }) + } + } +} + +unsafe fn write_handler(data: *mut c_void, buffer: *mut u8, size: u64) -> i32 { + let data = data.cast::(); + match io::Write::write_all(unsafe { &mut *(*data).write }, unsafe { + slice::from_raw_parts(buffer, size as usize) + }) { + Ok(()) => 1, + Err(err) => { + unsafe { + (*data).write_error = Some(err); + } + 0 + } + } +} + +impl<'a> Drop for EmitterPinned<'a> { + fn drop(&mut self) { + unsafe { sys::yaml_emitter_delete(&mut self.sys) } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/libyaml/error.rs b/bitbox02-bt/vendor/serde_yaml/src/libyaml/error.rs new file mode 100644 index 0000000..8397f6e --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/libyaml/error.rs @@ -0,0 +1,162 @@ +use crate::libyaml::cstr::CStr; +use std::fmt::{self, Debug, Display}; +use std::mem::MaybeUninit; +use std::ptr::NonNull; +use unsafe_libyaml as sys; + +pub(crate) type Result = std::result::Result; + +pub(crate) struct Error { + kind: sys::yaml_error_type_t, + problem: CStr<'static>, + problem_offset: u64, + problem_mark: Mark, + context: Option>, + context_mark: Mark, +} + +impl Error { + pub unsafe fn parse_error(parser: *const sys::yaml_parser_t) -> Self { + Error { + kind: unsafe { (*parser).error }, + problem: match NonNull::new(unsafe { (*parser).problem as *mut _ }) { + Some(problem) => unsafe { CStr::from_ptr(problem) }, + None => CStr::from_bytes_with_nul(b"libyaml parser failed but there is no error\0"), + }, + problem_offset: unsafe { (*parser).problem_offset }, + problem_mark: Mark { + sys: unsafe { (*parser).problem_mark }, + }, + context: match NonNull::new(unsafe { (*parser).context as *mut _ }) { + Some(context) => Some(unsafe { CStr::from_ptr(context) }), + None => None, + }, + context_mark: Mark { + sys: unsafe { (*parser).context_mark }, + }, + } + } + + pub unsafe fn emit_error(emitter: *const sys::yaml_emitter_t) -> Self { + Error { + kind: unsafe { (*emitter).error }, + problem: match NonNull::new(unsafe { (*emitter).problem as *mut _ }) { + Some(problem) => unsafe { CStr::from_ptr(problem) }, + None => { + CStr::from_bytes_with_nul(b"libyaml emitter failed but there is no error\0") + } + }, + problem_offset: 0, + problem_mark: Mark { + sys: unsafe { MaybeUninit::::zeroed().assume_init() }, + }, + context: None, + context_mark: Mark { + sys: unsafe { MaybeUninit::::zeroed().assume_init() }, + }, + } + } + + pub fn mark(&self) -> Mark { + self.problem_mark + } +} + +impl Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "{}", self.problem)?; + if self.problem_mark.sys.line != 0 || self.problem_mark.sys.column != 0 { + write!(formatter, " at {}", self.problem_mark)?; + } else if self.problem_offset != 0 { + write!(formatter, " at position {}", self.problem_offset)?; + } + if let Some(context) = &self.context { + write!(formatter, ", {}", context)?; + if (self.context_mark.sys.line != 0 || self.context_mark.sys.column != 0) + && (self.context_mark.sys.line != self.problem_mark.sys.line + || self.context_mark.sys.column != self.problem_mark.sys.column) + { + write!(formatter, " at {}", self.context_mark)?; + } + } + Ok(()) + } +} + +impl Debug for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Error"); + if let Some(kind) = match self.kind { + sys::YAML_MEMORY_ERROR => Some("MEMORY"), + sys::YAML_READER_ERROR => Some("READER"), + sys::YAML_SCANNER_ERROR => Some("SCANNER"), + sys::YAML_PARSER_ERROR => Some("PARSER"), + sys::YAML_COMPOSER_ERROR => Some("COMPOSER"), + sys::YAML_WRITER_ERROR => Some("WRITER"), + sys::YAML_EMITTER_ERROR => Some("EMITTER"), + _ => None, + } { + formatter.field("kind", &format_args!("{}", kind)); + } + formatter.field("problem", &self.problem); + if self.problem_mark.sys.line != 0 || self.problem_mark.sys.column != 0 { + formatter.field("problem_mark", &self.problem_mark); + } else if self.problem_offset != 0 { + formatter.field("problem_offset", &self.problem_offset); + } + if let Some(context) = &self.context { + formatter.field("context", context); + if self.context_mark.sys.line != 0 || self.context_mark.sys.column != 0 { + formatter.field("context_mark", &self.context_mark); + } + } + formatter.finish() + } +} + +#[derive(Copy, Clone)] +pub(crate) struct Mark { + pub(super) sys: sys::yaml_mark_t, +} + +impl Mark { + pub fn index(&self) -> u64 { + self.sys.index + } + + pub fn line(&self) -> u64 { + self.sys.line + } + + pub fn column(&self) -> u64 { + self.sys.column + } +} + +impl Display for Mark { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.sys.line != 0 || self.sys.column != 0 { + write!( + formatter, + "line {} column {}", + self.sys.line + 1, + self.sys.column + 1, + ) + } else { + write!(formatter, "position {}", self.sys.index) + } + } +} + +impl Debug for Mark { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("Mark"); + if self.sys.line != 0 || self.sys.column != 0 { + formatter.field("line", &(self.sys.line + 1)); + formatter.field("column", &(self.sys.column + 1)); + } else { + formatter.field("index", &self.sys.index); + } + formatter.finish() + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/libyaml/mod.rs b/bitbox02-bt/vendor/serde_yaml/src/libyaml/mod.rs new file mode 100644 index 0000000..9e160b1 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/libyaml/mod.rs @@ -0,0 +1,8 @@ +mod cstr; +pub mod emitter; +pub mod error; +pub mod parser; +pub mod tag; +mod util; + +use self::error::Error; diff --git a/bitbox02-bt/vendor/serde_yaml/src/libyaml/parser.rs b/bitbox02-bt/vendor/serde_yaml/src/libyaml/parser.rs new file mode 100644 index 0000000..3492edd --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/libyaml/parser.rs @@ -0,0 +1,201 @@ +use crate::libyaml::cstr::{self, CStr}; +use crate::libyaml::error::{Error, Mark, Result}; +use crate::libyaml::tag::Tag; +use crate::libyaml::util::Owned; +use std::borrow::Cow; +use std::fmt::{self, Debug}; +use std::mem::MaybeUninit; +use std::ptr::{addr_of_mut, NonNull}; +use std::slice; +use unsafe_libyaml as sys; + +pub(crate) struct Parser<'input> { + pin: Owned>, +} + +struct ParserPinned<'input> { + sys: sys::yaml_parser_t, + input: Cow<'input, [u8]>, +} + +#[derive(Debug)] +pub(crate) enum Event<'input> { + StreamStart, + StreamEnd, + DocumentStart, + DocumentEnd, + Alias(Anchor), + Scalar(Scalar<'input>), + SequenceStart(SequenceStart), + SequenceEnd, + MappingStart(MappingStart), + MappingEnd, +} + +pub(crate) struct Scalar<'input> { + pub anchor: Option, + pub tag: Option, + pub value: Box<[u8]>, + pub style: ScalarStyle, + pub repr: Option<&'input [u8]>, +} + +#[derive(Debug)] +pub(crate) struct SequenceStart { + pub anchor: Option, + pub tag: Option, +} + +#[derive(Debug)] +pub(crate) struct MappingStart { + pub anchor: Option, + pub tag: Option, +} + +#[derive(Ord, PartialOrd, Eq, PartialEq)] +pub(crate) struct Anchor(Box<[u8]>); + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub(crate) enum ScalarStyle { + Plain, + SingleQuoted, + DoubleQuoted, + Literal, + Folded, +} + +impl<'input> Parser<'input> { + pub fn new(input: Cow<'input, [u8]>) -> Parser<'input> { + let owned = Owned::::new_uninit(); + let pin = unsafe { + let parser = addr_of_mut!((*owned.ptr).sys); + if sys::yaml_parser_initialize(parser).fail { + panic!("malloc error: {}", Error::parse_error(parser)); + } + sys::yaml_parser_set_encoding(parser, sys::YAML_UTF8_ENCODING); + sys::yaml_parser_set_input_string(parser, input.as_ptr(), input.len() as u64); + addr_of_mut!((*owned.ptr).input).write(input); + Owned::assume_init(owned) + }; + Parser { pin } + } + + pub fn next(&mut self) -> Result<(Event<'input>, Mark)> { + let mut event = MaybeUninit::::uninit(); + unsafe { + let parser = addr_of_mut!((*self.pin.ptr).sys); + if (*parser).error != sys::YAML_NO_ERROR { + return Err(Error::parse_error(parser)); + } + let event = event.as_mut_ptr(); + if sys::yaml_parser_parse(parser, event).fail { + return Err(Error::parse_error(parser)); + } + let ret = convert_event(&*event, &(*self.pin.ptr).input); + let mark = Mark { + sys: (*event).start_mark, + }; + sys::yaml_event_delete(event); + Ok((ret, mark)) + } + } +} + +unsafe fn convert_event<'input>( + sys: &sys::yaml_event_t, + input: &Cow<'input, [u8]>, +) -> Event<'input> { + match sys.type_ { + sys::YAML_STREAM_START_EVENT => Event::StreamStart, + sys::YAML_STREAM_END_EVENT => Event::StreamEnd, + sys::YAML_DOCUMENT_START_EVENT => Event::DocumentStart, + sys::YAML_DOCUMENT_END_EVENT => Event::DocumentEnd, + sys::YAML_ALIAS_EVENT => { + Event::Alias(unsafe { optional_anchor(sys.data.alias.anchor) }.unwrap()) + } + sys::YAML_SCALAR_EVENT => Event::Scalar(Scalar { + anchor: unsafe { optional_anchor(sys.data.scalar.anchor) }, + tag: unsafe { optional_tag(sys.data.scalar.tag) }, + value: Box::from(unsafe { + slice::from_raw_parts(sys.data.scalar.value, sys.data.scalar.length as usize) + }), + style: match unsafe { sys.data.scalar.style } { + sys::YAML_PLAIN_SCALAR_STYLE => ScalarStyle::Plain, + sys::YAML_SINGLE_QUOTED_SCALAR_STYLE => ScalarStyle::SingleQuoted, + sys::YAML_DOUBLE_QUOTED_SCALAR_STYLE => ScalarStyle::DoubleQuoted, + sys::YAML_LITERAL_SCALAR_STYLE => ScalarStyle::Literal, + sys::YAML_FOLDED_SCALAR_STYLE => ScalarStyle::Folded, + sys::YAML_ANY_SCALAR_STYLE | _ => unreachable!(), + }, + repr: if let Cow::Borrowed(input) = input { + Some(&input[sys.start_mark.index as usize..sys.end_mark.index as usize]) + } else { + None + }, + }), + sys::YAML_SEQUENCE_START_EVENT => Event::SequenceStart(SequenceStart { + anchor: unsafe { optional_anchor(sys.data.sequence_start.anchor) }, + tag: unsafe { optional_tag(sys.data.sequence_start.tag) }, + }), + sys::YAML_SEQUENCE_END_EVENT => Event::SequenceEnd, + sys::YAML_MAPPING_START_EVENT => Event::MappingStart(MappingStart { + anchor: unsafe { optional_anchor(sys.data.mapping_start.anchor) }, + tag: unsafe { optional_tag(sys.data.mapping_start.tag) }, + }), + sys::YAML_MAPPING_END_EVENT => Event::MappingEnd, + sys::YAML_NO_EVENT => unreachable!(), + _ => unimplemented!(), + } +} + +unsafe fn optional_anchor(anchor: *const u8) -> Option { + let ptr = NonNull::new(anchor as *mut i8)?; + let cstr = unsafe { CStr::from_ptr(ptr) }; + Some(Anchor(Box::from(cstr.to_bytes()))) +} + +unsafe fn optional_tag(tag: *const u8) -> Option { + let ptr = NonNull::new(tag as *mut i8)?; + let cstr = unsafe { CStr::from_ptr(ptr) }; + Some(Tag(Box::from(cstr.to_bytes()))) +} + +impl<'input> Debug for Scalar<'input> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let Scalar { + anchor, + tag, + value, + style, + repr: _, + } = self; + + struct LossySlice<'a>(&'a [u8]); + + impl<'a> Debug for LossySlice<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + cstr::debug_lossy(self.0, formatter) + } + } + + formatter + .debug_struct("Scalar") + .field("anchor", anchor) + .field("tag", tag) + .field("value", &LossySlice(value)) + .field("style", style) + .finish() + } +} + +impl Debug for Anchor { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + cstr::debug_lossy(&self.0, formatter) + } +} + +impl<'input> Drop for ParserPinned<'input> { + fn drop(&mut self) { + unsafe { sys::yaml_parser_delete(&mut self.sys) } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/libyaml/tag.rs b/bitbox02-bt/vendor/serde_yaml/src/libyaml/tag.rs new file mode 100644 index 0000000..1f73185 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/libyaml/tag.rs @@ -0,0 +1,38 @@ +use crate::libyaml::cstr; +use std::fmt::{self, Debug}; +use std::ops::Deref; + +#[derive(Ord, PartialOrd, Eq, PartialEq)] +pub(crate) struct Tag(pub(in crate::libyaml) Box<[u8]>); + +impl Tag { + pub const NULL: &'static str = "tag:yaml.org,2002:null"; + pub const BOOL: &'static str = "tag:yaml.org,2002:bool"; + pub const INT: &'static str = "tag:yaml.org,2002:int"; + pub const FLOAT: &'static str = "tag:yaml.org,2002:float"; +} + +impl Tag { + pub fn starts_with(&self, prefix: &str) -> bool { + self.0.starts_with(prefix.as_bytes()) + } +} + +impl PartialEq for Tag { + fn eq(&self, other: &str) -> bool { + *self.0 == *other.as_bytes() + } +} + +impl Deref for Tag { + type Target = [u8]; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Debug for Tag { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + cstr::debug_lossy(&self.0, formatter) + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/libyaml/util.rs b/bitbox02-bt/vendor/serde_yaml/src/libyaml/util.rs new file mode 100644 index 0000000..1f5010d --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/libyaml/util.rs @@ -0,0 +1,48 @@ +use std::marker::PhantomData; +use std::mem::{self, MaybeUninit}; +use std::ops::Deref; +use std::ptr::{addr_of, NonNull}; + +pub(crate) struct Owned { + ptr: NonNull, + marker: PhantomData>, +} + +impl Owned { + pub fn new_uninit() -> Owned, T> { + // FIXME: use Box::new_uninit when stable + let boxed = Box::new(MaybeUninit::::uninit()); + Owned { + ptr: unsafe { NonNull::new_unchecked(Box::into_raw(boxed)) }, + marker: PhantomData, + } + } + + pub unsafe fn assume_init(definitely_init: Owned, T>) -> Owned { + let ptr = definitely_init.ptr; + mem::forget(definitely_init); + Owned { + ptr: ptr.cast(), + marker: PhantomData, + } + } +} + +#[repr(transparent)] +pub(crate) struct InitPtr { + pub ptr: *mut T, +} + +impl Deref for Owned { + type Target = InitPtr; + + fn deref(&self) -> &Self::Target { + unsafe { &*addr_of!(self.ptr).cast::>() } + } +} + +impl Drop for Owned { + fn drop(&mut self) { + let _ = unsafe { Box::from_raw(self.ptr.as_ptr()) }; + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/loader.rs b/bitbox02-bt/vendor/serde_yaml/src/loader.rs new file mode 100644 index 0000000..7c7c7b6 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/loader.rs @@ -0,0 +1,119 @@ +use crate::de::{Event, Progress}; +use crate::error::{self, Error, ErrorImpl, Result}; +use crate::libyaml::error::Mark; +use crate::libyaml::parser::{Event as YamlEvent, Parser}; +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::sync::Arc; + +pub(crate) struct Loader<'input> { + parser: Option>, + document_count: usize, +} + +pub(crate) struct Document<'input> { + pub events: Vec<(Event<'input>, Mark)>, + pub error: Option>, + /// Map from alias id to index in events. + pub aliases: BTreeMap, +} + +impl<'input> Loader<'input> { + pub fn new(progress: Progress<'input>) -> Result { + let input = match progress { + Progress::Str(s) => Cow::Borrowed(s.as_bytes()), + Progress::Slice(bytes) => Cow::Borrowed(bytes), + Progress::Read(mut rdr) => { + let mut buffer = Vec::new(); + if let Err(io_error) = rdr.read_to_end(&mut buffer) { + return Err(error::new(ErrorImpl::Io(io_error))); + } + Cow::Owned(buffer) + } + Progress::Iterable(_) | Progress::Document(_) => unreachable!(), + Progress::Fail(err) => return Err(error::shared(err)), + }; + + Ok(Loader { + parser: Some(Parser::new(input)), + document_count: 0, + }) + } + + pub fn next_document(&mut self) -> Option> { + let parser = match &mut self.parser { + Some(parser) => parser, + None => return None, + }; + + let first = self.document_count == 0; + self.document_count += 1; + + let mut anchors = BTreeMap::new(); + let mut document = Document { + events: Vec::new(), + error: None, + aliases: BTreeMap::new(), + }; + + loop { + let (event, mark) = match parser.next() { + Ok((event, mark)) => (event, mark), + Err(err) => { + document.error = Some(Error::from(err).shared()); + return Some(document); + } + }; + let event = match event { + YamlEvent::StreamStart => continue, + YamlEvent::StreamEnd => { + self.parser = None; + return if first { + if document.events.is_empty() { + document.events.push((Event::Void, mark)); + } + Some(document) + } else { + None + }; + } + YamlEvent::DocumentStart => continue, + YamlEvent::DocumentEnd => return Some(document), + YamlEvent::Alias(alias) => match anchors.get(&alias) { + Some(id) => Event::Alias(*id), + None => { + document.error = Some(error::new(ErrorImpl::UnknownAnchor(mark)).shared()); + return Some(document); + } + }, + YamlEvent::Scalar(mut scalar) => { + if let Some(anchor) = scalar.anchor.take() { + let id = anchors.len(); + anchors.insert(anchor, id); + document.aliases.insert(id, document.events.len()); + } + Event::Scalar(scalar) + } + YamlEvent::SequenceStart(mut sequence_start) => { + if let Some(anchor) = sequence_start.anchor.take() { + let id = anchors.len(); + anchors.insert(anchor, id); + document.aliases.insert(id, document.events.len()); + } + Event::SequenceStart(sequence_start) + } + YamlEvent::SequenceEnd => Event::SequenceEnd, + YamlEvent::MappingStart(mut mapping_start) => { + if let Some(anchor) = mapping_start.anchor.take() { + let id = anchors.len(); + anchors.insert(anchor, id); + document.aliases.insert(id, document.events.len()); + } + Event::MappingStart(mapping_start) + } + YamlEvent::MappingEnd => Event::MappingEnd, + }; + document.events.push((event, mark)); + } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/mapping.rs b/bitbox02-bt/vendor/serde_yaml/src/mapping.rs new file mode 100644 index 0000000..667cd4b --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/mapping.rs @@ -0,0 +1,851 @@ +//! A YAML mapping and its iterator types. + +use crate::{private, Value}; +use indexmap::IndexMap; +use serde::{Deserialize, Deserializer, Serialize}; +use std::cmp::Ordering; +use std::collections::hash_map::DefaultHasher; +use std::fmt::{self, Display}; +use std::hash::{Hash, Hasher}; +use std::mem; + +/// A YAML mapping in which the keys and values are both `serde_yaml::Value`. +#[derive(Clone, Default, Eq, PartialEq)] +pub struct Mapping { + map: IndexMap, +} + +impl Mapping { + /// Creates an empty YAML map. + #[inline] + pub fn new() -> Self { + Self::default() + } + + /// Creates an empty YAML map with the given initial capacity. + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + Mapping { + map: IndexMap::with_capacity(capacity), + } + } + + /// Reserves capacity for at least `additional` more elements to be inserted + /// into the map. The map may reserve more space to avoid frequent + /// allocations. + /// + /// # Panics + /// + /// Panics if the new allocation size overflows `usize`. + #[inline] + pub fn reserve(&mut self, additional: usize) { + self.map.reserve(additional); + } + + /// Shrinks the capacity of the map as much as possible. It will drop down + /// as much as possible while maintaining the internal rules and possibly + /// leaving some space in accordance with the resize policy. + #[inline] + pub fn shrink_to_fit(&mut self) { + self.map.shrink_to_fit(); + } + + /// Inserts a key-value pair into the map. If the key already existed, the + /// old value is returned. + #[inline] + pub fn insert(&mut self, k: Value, v: Value) -> Option { + self.map.insert(k, v) + } + + /// Checks if the map contains the given key. + #[inline] + pub fn contains_key(&self, index: I) -> bool { + index.is_key_into(self) + } + + /// Returns the value corresponding to the key in the map. + #[inline] + pub fn get(&self, index: I) -> Option<&Value> { + index.index_into(self) + } + + /// Returns the mutable reference corresponding to the key in the map. + #[inline] + pub fn get_mut(&mut self, index: I) -> Option<&mut Value> { + index.index_into_mut(self) + } + + /// Gets the given key's corresponding entry in the map for insertion and/or + /// in-place manipulation. + #[inline] + pub fn entry(&mut self, k: Value) -> Entry { + match self.map.entry(k) { + indexmap::map::Entry::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }), + indexmap::map::Entry::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }), + } + } + + /// Removes and returns the value corresponding to the key from the map. + /// + /// This is equivalent to [`.swap_remove(index)`][Self::swap_remove], + /// replacing this entry's position with the last element. If you need to + /// preserve the relative order of the keys in the map, use + /// [`.shift_remove(key)`][Self::shift_remove] instead. + #[inline] + pub fn remove(&mut self, index: I) -> Option { + self.swap_remove(index) + } + + /// Remove and return the key-value pair. + /// + /// This is equivalent to [`.swap_remove_entry(index)`][Self::swap_remove_entry], + /// replacing this entry's position with the last element. If you need to + /// preserve the relative order of the keys in the map, use + /// [`.shift_remove_entry(key)`][Self::shift_remove_entry] instead. + #[inline] + pub fn remove_entry(&mut self, index: I) -> Option<(Value, Value)> { + self.swap_remove_entry(index) + } + + /// Removes and returns the value corresponding to the key from the map. + /// + /// Like [`Vec::swap_remove`], the entry is removed by swapping it with the + /// last element of the map and popping it off. This perturbs the position + /// of what used to be the last element! + #[inline] + pub fn swap_remove(&mut self, index: I) -> Option { + index.swap_remove_from(self) + } + + /// Remove and return the key-value pair. + /// + /// Like [`Vec::swap_remove`], the entry is removed by swapping it with the + /// last element of the map and popping it off. This perturbs the position + /// of what used to be the last element! + #[inline] + pub fn swap_remove_entry(&mut self, index: I) -> Option<(Value, Value)> { + index.swap_remove_entry_from(self) + } + + /// Removes and returns the value corresponding to the key from the map. + /// + /// Like [`Vec::remove`], the entry is removed by shifting all of the + /// elements that follow it, preserving their relative order. This perturbs + /// the index of all of those elements! + #[inline] + pub fn shift_remove(&mut self, index: I) -> Option { + index.shift_remove_from(self) + } + + /// Remove and return the key-value pair. + /// + /// Like [`Vec::remove`], the entry is removed by shifting all of the + /// elements that follow it, preserving their relative order. This perturbs + /// the index of all of those elements! + #[inline] + pub fn shift_remove_entry(&mut self, index: I) -> Option<(Value, Value)> { + index.shift_remove_entry_from(self) + } + + /// Scan through each key-value pair in the map and keep those where the + /// closure `keep` returns true. + #[inline] + pub fn retain(&mut self, keep: F) + where + F: FnMut(&Value, &mut Value) -> bool, + { + self.map.retain(keep); + } + + /// Returns the maximum number of key-value pairs the map can hold without + /// reallocating. + #[inline] + pub fn capacity(&self) -> usize { + self.map.capacity() + } + + /// Returns the number of key-value pairs in the map. + #[inline] + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns whether the map is currently empty. + #[inline] + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + + /// Clears the map of all key-value pairs. + #[inline] + pub fn clear(&mut self) { + self.map.clear(); + } + + /// Returns a double-ended iterator visiting all key-value pairs in order of + /// insertion. Iterator element type is `(&'a Value, &'a Value)`. + #[inline] + pub fn iter(&self) -> Iter { + Iter { + iter: self.map.iter(), + } + } + + /// Returns a double-ended iterator visiting all key-value pairs in order of + /// insertion. Iterator element type is `(&'a Value, &'a mut ValuE)`. + #[inline] + pub fn iter_mut(&mut self) -> IterMut { + IterMut { + iter: self.map.iter_mut(), + } + } + + /// Return an iterator over the keys of the map. + pub fn keys(&self) -> Keys { + Keys { + iter: self.map.keys(), + } + } + + /// Return an owning iterator over the keys of the map. + pub fn into_keys(self) -> IntoKeys { + IntoKeys { + iter: self.map.into_keys(), + } + } + + /// Return an iterator over the values of the map. + pub fn values(&self) -> Values { + Values { + iter: self.map.values(), + } + } + + /// Return an iterator over mutable references to the values of the map. + pub fn values_mut(&mut self) -> ValuesMut { + ValuesMut { + iter: self.map.values_mut(), + } + } + + /// Return an owning iterator over the values of the map. + pub fn into_values(self) -> IntoValues { + IntoValues { + iter: self.map.into_values(), + } + } +} + +/// A type that can be used to index into a `serde_yaml::Mapping`. See the +/// methods `get`, `get_mut`, `contains_key`, and `remove` of `Value`. +/// +/// This trait is sealed and cannot be implemented for types outside of +/// `serde_yaml`. +pub trait Index: private::Sealed { + #[doc(hidden)] + fn is_key_into(&self, v: &Mapping) -> bool; + + #[doc(hidden)] + fn index_into<'a>(&self, v: &'a Mapping) -> Option<&'a Value>; + + #[doc(hidden)] + fn index_into_mut<'a>(&self, v: &'a mut Mapping) -> Option<&'a mut Value>; + + #[doc(hidden)] + fn swap_remove_from(&self, v: &mut Mapping) -> Option; + + #[doc(hidden)] + fn swap_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)>; + + #[doc(hidden)] + fn shift_remove_from(&self, v: &mut Mapping) -> Option; + + #[doc(hidden)] + fn shift_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)>; +} + +struct HashLikeValue<'a>(&'a str); + +impl<'a> indexmap::Equivalent for HashLikeValue<'a> { + fn equivalent(&self, key: &Value) -> bool { + match key { + Value::String(string) => self.0 == string, + _ => false, + } + } +} + +// NOTE: This impl must be consistent with Value's Hash impl. +impl<'a> Hash for HashLikeValue<'a> { + fn hash(&self, state: &mut H) { + const STRING: Value = Value::String(String::new()); + mem::discriminant(&STRING).hash(state); + self.0.hash(state); + } +} + +impl Index for Value { + fn is_key_into(&self, v: &Mapping) -> bool { + v.map.contains_key(self) + } + fn index_into<'a>(&self, v: &'a Mapping) -> Option<&'a Value> { + v.map.get(self) + } + fn index_into_mut<'a>(&self, v: &'a mut Mapping) -> Option<&'a mut Value> { + v.map.get_mut(self) + } + fn swap_remove_from(&self, v: &mut Mapping) -> Option { + v.map.swap_remove(self) + } + fn swap_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + v.map.swap_remove_entry(self) + } + fn shift_remove_from(&self, v: &mut Mapping) -> Option { + v.map.shift_remove(self) + } + fn shift_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + v.map.shift_remove_entry(self) + } +} + +impl Index for str { + fn is_key_into(&self, v: &Mapping) -> bool { + v.map.contains_key(&HashLikeValue(self)) + } + fn index_into<'a>(&self, v: &'a Mapping) -> Option<&'a Value> { + v.map.get(&HashLikeValue(self)) + } + fn index_into_mut<'a>(&self, v: &'a mut Mapping) -> Option<&'a mut Value> { + v.map.get_mut(&HashLikeValue(self)) + } + fn swap_remove_from(&self, v: &mut Mapping) -> Option { + v.map.swap_remove(&HashLikeValue(self)) + } + fn swap_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + v.map.swap_remove_entry(&HashLikeValue(self)) + } + fn shift_remove_from(&self, v: &mut Mapping) -> Option { + v.map.shift_remove(&HashLikeValue(self)) + } + fn shift_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + v.map.shift_remove_entry(&HashLikeValue(self)) + } +} + +impl Index for String { + fn is_key_into(&self, v: &Mapping) -> bool { + self.as_str().is_key_into(v) + } + fn index_into<'a>(&self, v: &'a Mapping) -> Option<&'a Value> { + self.as_str().index_into(v) + } + fn index_into_mut<'a>(&self, v: &'a mut Mapping) -> Option<&'a mut Value> { + self.as_str().index_into_mut(v) + } + fn swap_remove_from(&self, v: &mut Mapping) -> Option { + self.as_str().swap_remove_from(v) + } + fn swap_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + self.as_str().swap_remove_entry_from(v) + } + fn shift_remove_from(&self, v: &mut Mapping) -> Option { + self.as_str().shift_remove_from(v) + } + fn shift_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + self.as_str().shift_remove_entry_from(v) + } +} + +impl Index for &T +where + T: ?Sized + Index, +{ + fn is_key_into(&self, v: &Mapping) -> bool { + (**self).is_key_into(v) + } + fn index_into<'a>(&self, v: &'a Mapping) -> Option<&'a Value> { + (**self).index_into(v) + } + fn index_into_mut<'a>(&self, v: &'a mut Mapping) -> Option<&'a mut Value> { + (**self).index_into_mut(v) + } + fn swap_remove_from(&self, v: &mut Mapping) -> Option { + (**self).swap_remove_from(v) + } + fn swap_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + (**self).swap_remove_entry_from(v) + } + fn shift_remove_from(&self, v: &mut Mapping) -> Option { + (**self).shift_remove_from(v) + } + fn shift_remove_entry_from(&self, v: &mut Mapping) -> Option<(Value, Value)> { + (**self).shift_remove_entry_from(v) + } +} + +#[allow(clippy::derived_hash_with_manual_eq)] +impl Hash for Mapping { + fn hash(&self, state: &mut H) { + // Hash the kv pairs in a way that is not sensitive to their order. + let mut xor = 0; + for (k, v) in self { + let mut hasher = DefaultHasher::new(); + k.hash(&mut hasher); + v.hash(&mut hasher); + xor ^= hasher.finish(); + } + xor.hash(state); + } +} + +impl PartialOrd for Mapping { + fn partial_cmp(&self, other: &Self) -> Option { + let mut self_entries = Vec::from_iter(self); + let mut other_entries = Vec::from_iter(other); + + // Sort in an arbitrary order that is consistent with Value's PartialOrd + // impl. + fn total_cmp(a: &Value, b: &Value) -> Ordering { + match (a, b) { + (Value::Null, Value::Null) => Ordering::Equal, + (Value::Null, _) => Ordering::Less, + (_, Value::Null) => Ordering::Greater, + + (Value::Bool(a), Value::Bool(b)) => a.cmp(b), + (Value::Bool(_), _) => Ordering::Less, + (_, Value::Bool(_)) => Ordering::Greater, + + (Value::Number(a), Value::Number(b)) => a.total_cmp(b), + (Value::Number(_), _) => Ordering::Less, + (_, Value::Number(_)) => Ordering::Greater, + + (Value::String(a), Value::String(b)) => a.cmp(b), + (Value::String(_), _) => Ordering::Less, + (_, Value::String(_)) => Ordering::Greater, + + (Value::Sequence(a), Value::Sequence(b)) => iter_cmp_by(a, b, total_cmp), + (Value::Sequence(_), _) => Ordering::Less, + (_, Value::Sequence(_)) => Ordering::Greater, + + (Value::Mapping(a), Value::Mapping(b)) => { + iter_cmp_by(a, b, |(ak, av), (bk, bv)| { + total_cmp(ak, bk).then_with(|| total_cmp(av, bv)) + }) + } + (Value::Mapping(_), _) => Ordering::Less, + (_, Value::Mapping(_)) => Ordering::Greater, + + (Value::Tagged(a), Value::Tagged(b)) => a + .tag + .cmp(&b.tag) + .then_with(|| total_cmp(&a.value, &b.value)), + } + } + + fn iter_cmp_by(this: I, other: I, mut cmp: F) -> Ordering + where + I: IntoIterator, + F: FnMut(I::Item, I::Item) -> Ordering, + { + let mut this = this.into_iter(); + let mut other = other.into_iter(); + + loop { + let x = match this.next() { + None => { + if other.next().is_none() { + return Ordering::Equal; + } else { + return Ordering::Less; + } + } + Some(val) => val, + }; + + let y = match other.next() { + None => return Ordering::Greater, + Some(val) => val, + }; + + match cmp(x, y) { + Ordering::Equal => {} + non_eq => return non_eq, + } + } + } + + // While sorting by map key, we get to assume that no two keys are + // equal, otherwise they wouldn't both be in the map. This is not a safe + // assumption outside of this situation. + let total_cmp = |&(a, _): &_, &(b, _): &_| total_cmp(a, b); + self_entries.sort_by(total_cmp); + other_entries.sort_by(total_cmp); + self_entries.partial_cmp(&other_entries) + } +} + +impl std::ops::Index for Mapping +where + I: Index, +{ + type Output = Value; + + #[inline] + #[track_caller] + fn index(&self, index: I) -> &Value { + index.index_into(self).unwrap() + } +} + +impl std::ops::IndexMut for Mapping +where + I: Index, +{ + #[inline] + #[track_caller] + fn index_mut(&mut self, index: I) -> &mut Value { + index.index_into_mut(self).unwrap() + } +} + +impl Extend<(Value, Value)> for Mapping { + #[inline] + fn extend>(&mut self, iter: I) { + self.map.extend(iter); + } +} + +impl FromIterator<(Value, Value)> for Mapping { + #[inline] + fn from_iter>(iter: I) -> Self { + Mapping { + map: IndexMap::from_iter(iter), + } + } +} + +macro_rules! delegate_iterator { + (($name:ident $($generics:tt)*) => $item:ty) => { + impl $($generics)* Iterator for $name $($generics)* { + type Item = $item; + #[inline] + fn next(&mut self) -> Option { + self.iter.next() + } + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + } + + impl $($generics)* ExactSizeIterator for $name $($generics)* { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } + } + } +} + +/// Iterator over `&serde_yaml::Mapping`. +pub struct Iter<'a> { + iter: indexmap::map::Iter<'a, Value, Value>, +} + +delegate_iterator!((Iter<'a>) => (&'a Value, &'a Value)); + +impl<'a> IntoIterator for &'a Mapping { + type Item = (&'a Value, &'a Value); + type IntoIter = Iter<'a>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + Iter { + iter: self.map.iter(), + } + } +} + +/// Iterator over `&mut serde_yaml::Mapping`. +pub struct IterMut<'a> { + iter: indexmap::map::IterMut<'a, Value, Value>, +} + +delegate_iterator!((IterMut<'a>) => (&'a Value, &'a mut Value)); + +impl<'a> IntoIterator for &'a mut Mapping { + type Item = (&'a Value, &'a mut Value); + type IntoIter = IterMut<'a>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + IterMut { + iter: self.map.iter_mut(), + } + } +} + +/// Iterator over `serde_yaml::Mapping` by value. +pub struct IntoIter { + iter: indexmap::map::IntoIter, +} + +delegate_iterator!((IntoIter) => (Value, Value)); + +impl IntoIterator for Mapping { + type Item = (Value, Value); + type IntoIter = IntoIter; + #[inline] + fn into_iter(self) -> Self::IntoIter { + IntoIter { + iter: self.map.into_iter(), + } + } +} + +/// Iterator of the keys of a `&serde_yaml::Mapping`. +pub struct Keys<'a> { + iter: indexmap::map::Keys<'a, Value, Value>, +} + +delegate_iterator!((Keys<'a>) => &'a Value); + +/// Iterator of the keys of a `serde_yaml::Mapping`. +pub struct IntoKeys { + iter: indexmap::map::IntoKeys, +} + +delegate_iterator!((IntoKeys) => Value); + +/// Iterator of the values of a `&serde_yaml::Mapping`. +pub struct Values<'a> { + iter: indexmap::map::Values<'a, Value, Value>, +} + +delegate_iterator!((Values<'a>) => &'a Value); + +/// Iterator of the values of a `&mut serde_yaml::Mapping`. +pub struct ValuesMut<'a> { + iter: indexmap::map::ValuesMut<'a, Value, Value>, +} + +delegate_iterator!((ValuesMut<'a>) => &'a mut Value); + +/// Iterator of the values of a `serde_yaml::Mapping`. +pub struct IntoValues { + iter: indexmap::map::IntoValues, +} + +delegate_iterator!((IntoValues) => Value); + +/// Entry for an existing key-value pair or a vacant location to insert one. +pub enum Entry<'a> { + /// Existing slot with equivalent key. + Occupied(OccupiedEntry<'a>), + /// Vacant slot (no equivalent key in the map). + Vacant(VacantEntry<'a>), +} + +/// A view into an occupied entry in a [`Mapping`]. It is part of the [`Entry`] +/// enum. +pub struct OccupiedEntry<'a> { + occupied: indexmap::map::OccupiedEntry<'a, Value, Value>, +} + +/// A view into a vacant entry in a [`Mapping`]. It is part of the [`Entry`] +/// enum. +pub struct VacantEntry<'a> { + vacant: indexmap::map::VacantEntry<'a, Value, Value>, +} + +impl<'a> Entry<'a> { + /// Returns a reference to this entry's key. + pub fn key(&self) -> &Value { + match self { + Entry::Vacant(e) => e.key(), + Entry::Occupied(e) => e.key(), + } + } + + /// Ensures a value is in the entry by inserting the default if empty, and + /// returns a mutable reference to the value in the entry. + pub fn or_insert(self, default: Value) -> &'a mut Value { + match self { + Entry::Vacant(entry) => entry.insert(default), + Entry::Occupied(entry) => entry.into_mut(), + } + } + + /// Ensures a value is in the entry by inserting the result of the default + /// function if empty, and returns a mutable reference to the value in the + /// entry. + pub fn or_insert_with(self, default: F) -> &'a mut Value + where + F: FnOnce() -> Value, + { + match self { + Entry::Vacant(entry) => entry.insert(default()), + Entry::Occupied(entry) => entry.into_mut(), + } + } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the map. + pub fn and_modify(self, f: F) -> Self + where + F: FnOnce(&mut Value), + { + match self { + Entry::Occupied(mut entry) => { + f(entry.get_mut()); + Entry::Occupied(entry) + } + Entry::Vacant(entry) => Entry::Vacant(entry), + } + } +} + +impl<'a> OccupiedEntry<'a> { + /// Gets a reference to the key in the entry. + #[inline] + pub fn key(&self) -> &Value { + self.occupied.key() + } + + /// Gets a reference to the value in the entry. + #[inline] + pub fn get(&self) -> &Value { + self.occupied.get() + } + + /// Gets a mutable reference to the value in the entry. + #[inline] + pub fn get_mut(&mut self) -> &mut Value { + self.occupied.get_mut() + } + + /// Converts the entry into a mutable reference to its value. + #[inline] + pub fn into_mut(self) -> &'a mut Value { + self.occupied.into_mut() + } + + /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns + /// the entry's old value. + #[inline] + pub fn insert(&mut self, value: Value) -> Value { + self.occupied.insert(value) + } + + /// Takes the value of the entry out of the map, and returns it. + #[inline] + pub fn remove(self) -> Value { + self.occupied.swap_remove() + } + + /// Remove and return the key, value pair stored in the map for this entry. + #[inline] + pub fn remove_entry(self) -> (Value, Value) { + self.occupied.swap_remove_entry() + } +} + +impl<'a> VacantEntry<'a> { + /// Gets a reference to the key that would be used when inserting a value + /// through the VacantEntry. + #[inline] + pub fn key(&self) -> &Value { + self.vacant.key() + } + + /// Takes ownership of the key, leaving the entry vacant. + #[inline] + pub fn into_key(self) -> Value { + self.vacant.into_key() + } + + /// Sets the value of the entry with the VacantEntry's key, and returns a + /// mutable reference to it. + #[inline] + pub fn insert(self, value: Value) -> &'a mut Value { + self.vacant.insert(value) + } +} + +impl Serialize for Mapping { + #[inline] + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeMap; + let mut map_serializer = serializer.serialize_map(Some(self.len()))?; + for (k, v) in self { + map_serializer.serialize_entry(k, v)?; + } + map_serializer.end() + } +} + +impl<'de> Deserialize<'de> for Mapping { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct Visitor; + + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = Mapping; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a YAML mapping") + } + + #[inline] + fn visit_unit(self) -> Result + where + E: serde::de::Error, + { + Ok(Mapping::new()) + } + + #[inline] + fn visit_map(self, mut data: A) -> Result + where + A: serde::de::MapAccess<'de>, + { + let mut mapping = Mapping::new(); + + while let Some(key) = data.next_key()? { + match mapping.entry(key) { + Entry::Occupied(entry) => { + return Err(serde::de::Error::custom(DuplicateKeyError { entry })); + } + Entry::Vacant(entry) => { + let value = data.next_value()?; + entry.insert(value); + } + } + } + + Ok(mapping) + } + } + + deserializer.deserialize_map(Visitor) + } +} + +struct DuplicateKeyError<'a> { + entry: OccupiedEntry<'a>, +} + +impl<'a> Display for DuplicateKeyError<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("duplicate entry ")?; + match self.entry.key() { + Value::Null => formatter.write_str("with null key"), + Value::Bool(boolean) => write!(formatter, "with key `{}`", boolean), + Value::Number(number) => write!(formatter, "with key {}", number), + Value::String(string) => write!(formatter, "with key {:?}", string), + Value::Sequence(_) | Value::Mapping(_) | Value::Tagged(_) => { + formatter.write_str("in YAML map") + } + } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/number.rs b/bitbox02-bt/vendor/serde_yaml/src/number.rs new file mode 100644 index 0000000..5ebe395 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/number.rs @@ -0,0 +1,561 @@ +use crate::de; +use crate::error::{self, Error, ErrorImpl}; +use serde::de::{Unexpected, Visitor}; +use serde::{forward_to_deserialize_any, Deserialize, Deserializer, Serialize, Serializer}; +use std::cmp::Ordering; +use std::fmt::{self, Display}; +use std::hash::{Hash, Hasher}; +use std::str::FromStr; + +/// Represents a YAML number, whether integer or floating point. +#[derive(Clone, PartialEq, PartialOrd)] +pub struct Number { + n: N, +} + +// "N" is a prefix of "NegInt"... this is a false positive. +// https://github.com/Manishearth/rust-clippy/issues/1241 +#[allow(clippy::enum_variant_names)] +#[derive(Copy, Clone)] +enum N { + PosInt(u64), + /// Always less than zero. + NegInt(i64), + /// May be infinite or NaN. + Float(f64), +} + +impl Number { + /// Returns true if the `Number` is an integer between `i64::MIN` and + /// `i64::MAX`. + /// + /// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to + /// return the integer value. + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let big = i64::MAX as u64 + 10; + /// let v: serde_yaml::Value = serde_yaml::from_str(r#" + /// a: 64 + /// b: 9223372036854775817 + /// c: 256.0 + /// "#)?; + /// + /// assert!(v["a"].is_i64()); + /// + /// // Greater than i64::MAX. + /// assert!(!v["b"].is_i64()); + /// + /// // Numbers with a decimal point are not considered integers. + /// assert!(!v["c"].is_i64()); + /// # Ok(()) + /// # } + /// ``` + #[inline] + #[allow(clippy::cast_sign_loss)] + pub fn is_i64(&self) -> bool { + match self.n { + N::PosInt(v) => v <= i64::max_value() as u64, + N::NegInt(_) => true, + N::Float(_) => false, + } + } + + /// Returns true if the `Number` is an integer between zero and `u64::MAX`. + /// + /// For any Number on which `is_u64` returns true, `as_u64` is guaranteed to + /// return the integer value. + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let v: serde_yaml::Value = serde_yaml::from_str(r#" + /// a: 64 + /// b: -64 + /// c: 256.0 + /// "#)?; + /// + /// assert!(v["a"].is_u64()); + /// + /// // Negative integer. + /// assert!(!v["b"].is_u64()); + /// + /// // Numbers with a decimal point are not considered integers. + /// assert!(!v["c"].is_u64()); + /// # Ok(()) + /// # } + /// ``` + #[inline] + pub fn is_u64(&self) -> bool { + match self.n { + N::PosInt(_) => true, + N::NegInt(_) | N::Float(_) => false, + } + } + + /// Returns true if the `Number` can be represented by f64. + /// + /// For any Number on which `is_f64` returns true, `as_f64` is guaranteed to + /// return the floating point value. + /// + /// Currently this function returns true if and only if both `is_i64` and + /// `is_u64` return false but this is not a guarantee in the future. + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let v: serde_yaml::Value = serde_yaml::from_str(r#" + /// a: 256.0 + /// b: 64 + /// c: -64 + /// "#)?; + /// + /// assert!(v["a"].is_f64()); + /// + /// // Integers. + /// assert!(!v["b"].is_f64()); + /// assert!(!v["c"].is_f64()); + /// # Ok(()) + /// # } + /// ``` + #[inline] + pub fn is_f64(&self) -> bool { + match self.n { + N::Float(_) => true, + N::PosInt(_) | N::NegInt(_) => false, + } + } + + /// If the `Number` is an integer, represent it as i64 if possible. Returns + /// None otherwise. + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let big = i64::MAX as u64 + 10; + /// let v: serde_yaml::Value = serde_yaml::from_str(r#" + /// a: 64 + /// b: 9223372036854775817 + /// c: 256.0 + /// "#)?; + /// + /// assert_eq!(v["a"].as_i64(), Some(64)); + /// assert_eq!(v["b"].as_i64(), None); + /// assert_eq!(v["c"].as_i64(), None); + /// # Ok(()) + /// # } + /// ``` + #[inline] + pub fn as_i64(&self) -> Option { + match self.n { + N::PosInt(n) => { + if n <= i64::max_value() as u64 { + Some(n as i64) + } else { + None + } + } + N::NegInt(n) => Some(n), + N::Float(_) => None, + } + } + + /// If the `Number` is an integer, represent it as u64 if possible. Returns + /// None otherwise. + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let v: serde_yaml::Value = serde_yaml::from_str(r#" + /// a: 64 + /// b: -64 + /// c: 256.0 + /// "#)?; + /// + /// assert_eq!(v["a"].as_u64(), Some(64)); + /// assert_eq!(v["b"].as_u64(), None); + /// assert_eq!(v["c"].as_u64(), None); + /// # Ok(()) + /// # } + /// ``` + #[inline] + pub fn as_u64(&self) -> Option { + match self.n { + N::PosInt(n) => Some(n), + N::NegInt(_) | N::Float(_) => None, + } + } + + /// Represents the number as f64 if possible. Returns None otherwise. + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let v: serde_yaml::Value = serde_yaml::from_str(r#" + /// a: 256.0 + /// b: 64 + /// c: -64 + /// "#)?; + /// + /// assert_eq!(v["a"].as_f64(), Some(256.0)); + /// assert_eq!(v["b"].as_f64(), Some(64.0)); + /// assert_eq!(v["c"].as_f64(), Some(-64.0)); + /// # Ok(()) + /// # } + /// ``` + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let v: serde_yaml::Value = serde_yaml::from_str(".inf")?; + /// assert_eq!(v.as_f64(), Some(f64::INFINITY)); + /// + /// let v: serde_yaml::Value = serde_yaml::from_str("-.inf")?; + /// assert_eq!(v.as_f64(), Some(f64::NEG_INFINITY)); + /// + /// let v: serde_yaml::Value = serde_yaml::from_str(".nan")?; + /// assert!(v.as_f64().unwrap().is_nan()); + /// # Ok(()) + /// # } + /// ``` + #[inline] + pub fn as_f64(&self) -> Option { + match self.n { + N::PosInt(n) => Some(n as f64), + N::NegInt(n) => Some(n as f64), + N::Float(n) => Some(n), + } + } + + /// Returns true if this value is NaN and false otherwise. + /// + /// ``` + /// # use serde_yaml::Number; + /// # + /// assert!(!Number::from(256.0).is_nan()); + /// + /// assert!(Number::from(f64::NAN).is_nan()); + /// + /// assert!(!Number::from(f64::INFINITY).is_nan()); + /// + /// assert!(!Number::from(f64::NEG_INFINITY).is_nan()); + /// + /// assert!(!Number::from(1).is_nan()); + /// ``` + #[inline] + pub fn is_nan(&self) -> bool { + match self.n { + N::PosInt(_) | N::NegInt(_) => false, + N::Float(f) => f.is_nan(), + } + } + + /// Returns true if this value is positive infinity or negative infinity and + /// false otherwise. + /// + /// ``` + /// # use serde_yaml::Number; + /// # + /// assert!(!Number::from(256.0).is_infinite()); + /// + /// assert!(!Number::from(f64::NAN).is_infinite()); + /// + /// assert!(Number::from(f64::INFINITY).is_infinite()); + /// + /// assert!(Number::from(f64::NEG_INFINITY).is_infinite()); + /// + /// assert!(!Number::from(1).is_infinite()); + /// ``` + #[inline] + pub fn is_infinite(&self) -> bool { + match self.n { + N::PosInt(_) | N::NegInt(_) => false, + N::Float(f) => f.is_infinite(), + } + } + + /// Returns true if this number is neither infinite nor NaN. + /// + /// ``` + /// # use serde_yaml::Number; + /// # + /// assert!(Number::from(256.0).is_finite()); + /// + /// assert!(!Number::from(f64::NAN).is_finite()); + /// + /// assert!(!Number::from(f64::INFINITY).is_finite()); + /// + /// assert!(!Number::from(f64::NEG_INFINITY).is_finite()); + /// + /// assert!(Number::from(1).is_finite()); + /// ``` + #[inline] + pub fn is_finite(&self) -> bool { + match self.n { + N::PosInt(_) | N::NegInt(_) => true, + N::Float(f) => f.is_finite(), + } + } +} + +impl Display for Number { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.n { + N::PosInt(i) => formatter.write_str(itoa::Buffer::new().format(i)), + N::NegInt(i) => formatter.write_str(itoa::Buffer::new().format(i)), + N::Float(f) if f.is_nan() => formatter.write_str(".nan"), + N::Float(f) if f.is_infinite() => { + if f.is_sign_negative() { + formatter.write_str("-.inf") + } else { + formatter.write_str(".inf") + } + } + N::Float(f) => formatter.write_str(ryu::Buffer::new().format_finite(f)), + } + } +} + +impl FromStr for Number { + type Err = Error; + + fn from_str(repr: &str) -> Result { + if let Ok(result) = de::visit_int(NumberVisitor, repr) { + return result; + } + if !de::digits_but_not_number(repr) { + if let Some(float) = de::parse_f64(repr) { + return Ok(float.into()); + } + } + Err(error::new(ErrorImpl::FailedToParseNumber)) + } +} + +impl PartialEq for N { + fn eq(&self, other: &N) -> bool { + match (*self, *other) { + (N::PosInt(a), N::PosInt(b)) => a == b, + (N::NegInt(a), N::NegInt(b)) => a == b, + (N::Float(a), N::Float(b)) => { + if a.is_nan() && b.is_nan() { + // YAML only has one NaN; + // the bit representation isn't preserved + true + } else { + a == b + } + } + _ => false, + } + } +} + +impl PartialOrd for N { + fn partial_cmp(&self, other: &Self) -> Option { + match (*self, *other) { + (N::Float(a), N::Float(b)) => { + if a.is_nan() && b.is_nan() { + // YAML only has one NaN + Some(Ordering::Equal) + } else { + a.partial_cmp(&b) + } + } + _ => Some(self.total_cmp(other)), + } + } +} + +impl N { + fn total_cmp(&self, other: &Self) -> Ordering { + match (*self, *other) { + (N::PosInt(a), N::PosInt(b)) => a.cmp(&b), + (N::NegInt(a), N::NegInt(b)) => a.cmp(&b), + // negint is always less than zero + (N::NegInt(_), N::PosInt(_)) => Ordering::Less, + (N::PosInt(_), N::NegInt(_)) => Ordering::Greater, + (N::Float(a), N::Float(b)) => a.partial_cmp(&b).unwrap_or_else(|| { + // arbitrarily sort the NaN last + if !a.is_nan() { + Ordering::Less + } else if !b.is_nan() { + Ordering::Greater + } else { + Ordering::Equal + } + }), + // arbitrarily sort integers below floats + // FIXME: maybe something more sensible? + (_, N::Float(_)) => Ordering::Less, + (N::Float(_), _) => Ordering::Greater, + } + } +} + +impl Number { + pub(crate) fn total_cmp(&self, other: &Self) -> Ordering { + self.n.total_cmp(&other.n) + } +} + +impl Serialize for Number { + #[inline] + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self.n { + N::PosInt(i) => serializer.serialize_u64(i), + N::NegInt(i) => serializer.serialize_i64(i), + N::Float(f) => serializer.serialize_f64(f), + } + } +} + +struct NumberVisitor; + +impl<'de> Visitor<'de> for NumberVisitor { + type Value = Number; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a number") + } + + #[inline] + fn visit_i64(self, value: i64) -> Result { + Ok(value.into()) + } + + #[inline] + fn visit_u64(self, value: u64) -> Result { + Ok(value.into()) + } + + #[inline] + fn visit_f64(self, value: f64) -> Result { + Ok(value.into()) + } +} + +impl<'de> Deserialize<'de> for Number { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_any(NumberVisitor) + } +} + +impl<'de> Deserializer<'de> for Number { + type Error = Error; + + #[inline] + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.n { + N::PosInt(i) => visitor.visit_u64(i), + N::NegInt(i) => visitor.visit_i64(i), + N::Float(f) => visitor.visit_f64(f), + } + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de, 'a> Deserializer<'de> for &'a Number { + type Error = Error; + + #[inline] + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.n { + N::PosInt(i) => visitor.visit_u64(i), + N::NegInt(i) => visitor.visit_i64(i), + N::Float(f) => visitor.visit_f64(f), + } + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +macro_rules! from_signed { + ($($signed_ty:ident)*) => { + $( + impl From<$signed_ty> for Number { + #[inline] + #[allow(clippy::cast_sign_loss)] + fn from(i: $signed_ty) -> Self { + if i < 0 { + Number { n: N::NegInt(i as i64) } + } else { + Number { n: N::PosInt(i as u64) } + } + } + } + )* + }; +} + +macro_rules! from_unsigned { + ($($unsigned_ty:ident)*) => { + $( + impl From<$unsigned_ty> for Number { + #[inline] + fn from(u: $unsigned_ty) -> Self { + Number { n: N::PosInt(u as u64) } + } + } + )* + }; +} + +from_signed!(i8 i16 i32 i64 isize); +from_unsigned!(u8 u16 u32 u64 usize); + +impl From for Number { + fn from(f: f32) -> Self { + Number::from(f as f64) + } +} + +impl From for Number { + fn from(mut f: f64) -> Self { + if f.is_nan() { + // Destroy NaN sign, signaling, and payload. YAML only has one NaN. + f = f64::NAN.copysign(1.0); + } + Number { n: N::Float(f) } + } +} + +// This is fine, because we don't _really_ implement hash for floats +// all other hash functions should work as expected +#[allow(clippy::derived_hash_with_manual_eq)] +impl Hash for Number { + fn hash(&self, state: &mut H) { + match self.n { + N::Float(_) => { + // you should feel bad for using f64 as a map key + 3.hash(state); + } + N::PosInt(u) => u.hash(state), + N::NegInt(i) => i.hash(state), + } + } +} + +pub(crate) fn unexpected(number: &Number) -> Unexpected { + match number.n { + N::PosInt(u) => Unexpected::Unsigned(u), + N::NegInt(i) => Unexpected::Signed(i), + N::Float(f) => Unexpected::Float(f), + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/path.rs b/bitbox02-bt/vendor/serde_yaml/src/path.rs new file mode 100644 index 0000000..095add0 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/path.rs @@ -0,0 +1,34 @@ +use std::fmt::{self, Display}; + +/// Path to the current value in the input, like `dependencies.serde.typo1`. +#[derive(Copy, Clone)] +pub enum Path<'a> { + Root, + Seq { parent: &'a Path<'a>, index: usize }, + Map { parent: &'a Path<'a>, key: &'a str }, + Alias { parent: &'a Path<'a> }, + Unknown { parent: &'a Path<'a> }, +} + +impl<'a> Display for Path<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + struct Parent<'a>(&'a Path<'a>); + + impl<'a> Display for Parent<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match self.0 { + Path::Root => Ok(()), + path => write!(formatter, "{}.", path), + } + } + } + + match self { + Path::Root => formatter.write_str("."), + Path::Seq { parent, index } => write!(formatter, "{}[{}]", parent, index), + Path::Map { parent, key } => write!(formatter, "{}{}", Parent(parent), key), + Path::Alias { parent } => write!(formatter, "{}", parent), + Path::Unknown { parent } => write!(formatter, "{}?", Parent(parent)), + } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/ser.rs b/bitbox02-bt/vendor/serde_yaml/src/ser.rs new file mode 100644 index 0000000..23c761b --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/ser.rs @@ -0,0 +1,714 @@ +//! YAML Serialization +//! +//! This module provides YAML serialization with the type `Serializer`. + +use crate::error::{self, Error, ErrorImpl}; +use crate::libyaml; +use crate::libyaml::emitter::{Emitter, Event, Mapping, Scalar, ScalarStyle, Sequence}; +use crate::value::tagged::{self, MaybeTag}; +use serde::de::Visitor; +use serde::ser::{self, Serializer as _}; +use std::fmt::{self, Display}; +use std::io; +use std::marker::PhantomData; +use std::mem; +use std::num; +use std::str; + +type Result = std::result::Result; + +/// A structure for serializing Rust values into YAML. +/// +/// # Example +/// +/// ``` +/// use anyhow::Result; +/// use serde::Serialize; +/// use std::collections::BTreeMap; +/// +/// fn main() -> Result<()> { +/// let mut buffer = Vec::new(); +/// let mut ser = serde_yaml::Serializer::new(&mut buffer); +/// +/// let mut object = BTreeMap::new(); +/// object.insert("k", 107); +/// object.serialize(&mut ser)?; +/// +/// object.insert("J", 74); +/// object.serialize(&mut ser)?; +/// +/// assert_eq!(buffer, b"k: 107\n---\nJ: 74\nk: 107\n"); +/// Ok(()) +/// } +/// ``` +pub struct Serializer { + depth: usize, + state: State, + emitter: Emitter<'static>, + writer: PhantomData, +} + +enum State { + NothingInParticular, + CheckForTag, + CheckForDuplicateTag, + FoundTag(String), + AlreadyTagged, +} + +impl Serializer +where + W: io::Write, +{ + /// Creates a new YAML serializer. + pub fn new(writer: W) -> Self { + let mut emitter = Emitter::new({ + let writer = Box::new(writer); + unsafe { mem::transmute::, Box>(writer) } + }); + emitter.emit(Event::StreamStart).unwrap(); + Serializer { + depth: 0, + state: State::NothingInParticular, + emitter, + writer: PhantomData, + } + } + + /// Calls [`.flush()`](io::Write::flush) on the underlying `io::Write` + /// object. + pub fn flush(&mut self) -> Result<()> { + self.emitter.flush()?; + Ok(()) + } + + /// Unwrap the underlying `io::Write` object from the `Serializer`. + pub fn into_inner(mut self) -> Result { + self.emitter.emit(Event::StreamEnd)?; + self.emitter.flush()?; + let writer = self.emitter.into_inner(); + Ok(*unsafe { Box::from_raw(Box::into_raw(writer).cast::()) }) + } + + fn emit_scalar(&mut self, mut scalar: Scalar) -> Result<()> { + self.flush_mapping_start()?; + if let Some(tag) = self.take_tag() { + scalar.tag = Some(tag); + } + self.value_start()?; + self.emitter.emit(Event::Scalar(scalar))?; + self.value_end() + } + + fn emit_sequence_start(&mut self) -> Result<()> { + self.flush_mapping_start()?; + self.value_start()?; + let tag = self.take_tag(); + self.emitter.emit(Event::SequenceStart(Sequence { tag }))?; + Ok(()) + } + + fn emit_sequence_end(&mut self) -> Result<()> { + self.emitter.emit(Event::SequenceEnd)?; + self.value_end() + } + + fn emit_mapping_start(&mut self) -> Result<()> { + self.flush_mapping_start()?; + self.value_start()?; + let tag = self.take_tag(); + self.emitter.emit(Event::MappingStart(Mapping { tag }))?; + Ok(()) + } + + fn emit_mapping_end(&mut self) -> Result<()> { + self.emitter.emit(Event::MappingEnd)?; + self.value_end() + } + + fn value_start(&mut self) -> Result<()> { + if self.depth == 0 { + self.emitter.emit(Event::DocumentStart)?; + } + self.depth += 1; + Ok(()) + } + + fn value_end(&mut self) -> Result<()> { + self.depth -= 1; + if self.depth == 0 { + self.emitter.emit(Event::DocumentEnd)?; + } + Ok(()) + } + + fn take_tag(&mut self) -> Option { + let state = mem::replace(&mut self.state, State::NothingInParticular); + if let State::FoundTag(mut tag) = state { + if !tag.starts_with('!') { + tag.insert(0, '!'); + } + Some(tag) + } else { + self.state = state; + None + } + } + + fn flush_mapping_start(&mut self) -> Result<()> { + if let State::CheckForTag = self.state { + self.state = State::NothingInParticular; + self.emit_mapping_start()?; + } else if let State::CheckForDuplicateTag = self.state { + self.state = State::NothingInParticular; + } + Ok(()) + } +} + +impl<'a, W> ser::Serializer for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + type SerializeSeq = Self; + type SerializeTuple = Self; + type SerializeTupleStruct = Self; + type SerializeTupleVariant = Self; + type SerializeMap = Self; + type SerializeStruct = Self; + type SerializeStructVariant = Self; + + fn serialize_bool(self, v: bool) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: if v { "true" } else { "false" }, + style: ScalarStyle::Plain, + }) + } + + fn serialize_i8(self, v: i8) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_i16(self, v: i16) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_i32(self, v: i32) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_i64(self, v: i64) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_i128(self, v: i128) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_u8(self, v: u8) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_u16(self, v: u16) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_u32(self, v: u32) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_u64(self, v: u64) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_u128(self, v: u128) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: itoa::Buffer::new().format(v), + style: ScalarStyle::Plain, + }) + } + + fn serialize_f32(self, v: f32) -> Result<()> { + let mut buffer = ryu::Buffer::new(); + self.emit_scalar(Scalar { + tag: None, + value: match v.classify() { + num::FpCategory::Infinite if v.is_sign_positive() => ".inf", + num::FpCategory::Infinite => "-.inf", + num::FpCategory::Nan => ".nan", + _ => buffer.format_finite(v), + }, + style: ScalarStyle::Plain, + }) + } + + fn serialize_f64(self, v: f64) -> Result<()> { + let mut buffer = ryu::Buffer::new(); + self.emit_scalar(Scalar { + tag: None, + value: match v.classify() { + num::FpCategory::Infinite if v.is_sign_positive() => ".inf", + num::FpCategory::Infinite => "-.inf", + num::FpCategory::Nan => ".nan", + _ => buffer.format_finite(v), + }, + style: ScalarStyle::Plain, + }) + } + + fn serialize_char(self, value: char) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: value.encode_utf8(&mut [0u8; 4]), + style: ScalarStyle::SingleQuoted, + }) + } + + fn serialize_str(self, value: &str) -> Result<()> { + struct InferScalarStyle; + + impl<'de> Visitor<'de> for InferScalarStyle { + type Value = ScalarStyle; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("I wonder") + } + + fn visit_bool(self, _v: bool) -> Result { + Ok(ScalarStyle::SingleQuoted) + } + + fn visit_i64(self, _v: i64) -> Result { + Ok(ScalarStyle::SingleQuoted) + } + + fn visit_i128(self, _v: i128) -> Result { + Ok(ScalarStyle::SingleQuoted) + } + + fn visit_u64(self, _v: u64) -> Result { + Ok(ScalarStyle::SingleQuoted) + } + + fn visit_u128(self, _v: u128) -> Result { + Ok(ScalarStyle::SingleQuoted) + } + + fn visit_f64(self, _v: f64) -> Result { + Ok(ScalarStyle::SingleQuoted) + } + + fn visit_str(self, v: &str) -> Result { + Ok(if crate::de::digits_but_not_number(v) { + ScalarStyle::SingleQuoted + } else { + ScalarStyle::Any + }) + } + + fn visit_unit(self) -> Result { + Ok(ScalarStyle::SingleQuoted) + } + } + + let style = if value.contains('\n') { + ScalarStyle::Literal + } else { + let result = crate::de::visit_untagged_scalar( + InferScalarStyle, + value, + None, + libyaml::parser::ScalarStyle::Plain, + ); + result.unwrap_or(ScalarStyle::Any) + }; + + self.emit_scalar(Scalar { + tag: None, + value, + style, + }) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<()> { + Err(error::new(ErrorImpl::BytesUnsupported)) + } + + fn serialize_unit(self) -> Result<()> { + self.emit_scalar(Scalar { + tag: None, + value: "null", + style: ScalarStyle::Plain, + }) + } + + fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { + self.serialize_unit() + } + + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> Result<()> { + self.serialize_str(variant) + } + + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + if let State::FoundTag(_) = self.state { + return Err(error::new(ErrorImpl::SerializeNestedEnum)); + } + self.state = State::FoundTag(variant.to_owned()); + value.serialize(&mut *self) + } + + fn serialize_none(self) -> Result<()> { + self.serialize_unit() + } + + fn serialize_some(self, value: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + value.serialize(self) + } + + fn serialize_seq(self, _len: Option) -> Result { + self.emit_sequence_start()?; + Ok(self) + } + + fn serialize_tuple(self, _len: usize) -> Result { + self.emit_sequence_start()?; + Ok(self) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + self.emit_sequence_start()?; + Ok(self) + } + + fn serialize_tuple_variant( + self, + _enm: &'static str, + _idx: u32, + variant: &'static str, + _len: usize, + ) -> Result { + if let State::FoundTag(_) = self.state { + return Err(error::new(ErrorImpl::SerializeNestedEnum)); + } + self.state = State::FoundTag(variant.to_owned()); + self.emit_sequence_start()?; + Ok(self) + } + + fn serialize_map(self, len: Option) -> Result { + if len == Some(1) { + self.state = if let State::FoundTag(_) = self.state { + self.emit_mapping_start()?; + State::CheckForDuplicateTag + } else { + State::CheckForTag + }; + } else { + self.emit_mapping_start()?; + } + Ok(self) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { + self.emit_mapping_start()?; + Ok(self) + } + + fn serialize_struct_variant( + self, + _enm: &'static str, + _idx: u32, + variant: &'static str, + _len: usize, + ) -> Result { + if let State::FoundTag(_) = self.state { + return Err(error::new(ErrorImpl::SerializeNestedEnum)); + } + self.state = State::FoundTag(variant.to_owned()); + self.emit_mapping_start()?; + Ok(self) + } + + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display, + { + let string = if let State::CheckForTag | State::CheckForDuplicateTag = self.state { + match tagged::check_for_tag(value) { + MaybeTag::NotTag(string) => string, + MaybeTag::Tag(string) => { + return if let State::CheckForDuplicateTag = self.state { + Err(error::new(ErrorImpl::SerializeNestedEnum)) + } else { + self.state = State::FoundTag(string); + Ok(()) + }; + } + } + } else { + value.to_string() + }; + + self.serialize_str(&string) + } +} + +impl<'a, W> ser::SerializeSeq for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + fn serialize_element(&mut self, elem: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + elem.serialize(&mut **self) + } + + fn end(self) -> Result<()> { + self.emit_sequence_end() + } +} + +impl<'a, W> ser::SerializeTuple for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + fn serialize_element(&mut self, elem: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + elem.serialize(&mut **self) + } + + fn end(self) -> Result<()> { + self.emit_sequence_end() + } +} + +impl<'a, W> ser::SerializeTupleStruct for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + fn serialize_field(&mut self, value: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + value.serialize(&mut **self) + } + + fn end(self) -> Result<()> { + self.emit_sequence_end() + } +} + +impl<'a, W> ser::SerializeTupleVariant for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + fn serialize_field(&mut self, v: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + v.serialize(&mut **self) + } + + fn end(self) -> Result<()> { + self.emit_sequence_end() + } +} + +impl<'a, W> ser::SerializeMap for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + fn serialize_key(&mut self, key: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + self.flush_mapping_start()?; + key.serialize(&mut **self) + } + + fn serialize_value(&mut self, value: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + value.serialize(&mut **self) + } + + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), Self::Error> + where + K: ?Sized + ser::Serialize, + V: ?Sized + ser::Serialize, + { + key.serialize(&mut **self)?; + let tagged = matches!(self.state, State::FoundTag(_)); + value.serialize(&mut **self)?; + if tagged { + self.state = State::AlreadyTagged; + } + Ok(()) + } + + fn end(self) -> Result<()> { + if let State::CheckForTag = self.state { + self.emit_mapping_start()?; + } + if !matches!(self.state, State::AlreadyTagged) { + self.emit_mapping_end()?; + } + self.state = State::NothingInParticular; + Ok(()) + } +} + +impl<'a, W> ser::SerializeStruct for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + fn serialize_field(&mut self, key: &'static str, value: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.serialize_str(key)?; + value.serialize(&mut **self) + } + + fn end(self) -> Result<()> { + self.emit_mapping_end() + } +} + +impl<'a, W> ser::SerializeStructVariant for &'a mut Serializer +where + W: io::Write, +{ + type Ok = (); + type Error = Error; + + fn serialize_field(&mut self, field: &'static str, v: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.serialize_str(field)?; + v.serialize(&mut **self) + } + + fn end(self) -> Result<()> { + self.emit_mapping_end() + } +} + +/// Serialize the given data structure as YAML into the IO stream. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// return an error. +pub fn to_writer(writer: W, value: &T) -> Result<()> +where + W: io::Write, + T: ?Sized + ser::Serialize, +{ + let mut serializer = Serializer::new(writer); + value.serialize(&mut serializer) +} + +/// Serialize the given data structure as a String of YAML. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// return an error. +pub fn to_string(value: &T) -> Result +where + T: ?Sized + ser::Serialize, +{ + let mut vec = Vec::with_capacity(128); + to_writer(&mut vec, value)?; + String::from_utf8(vec).map_err(|error| error::new(ErrorImpl::FromUtf8(error))) +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/de.rs b/bitbox02-bt/vendor/serde_yaml/src/value/de.rs new file mode 100644 index 0000000..b1ff576 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/de.rs @@ -0,0 +1,1242 @@ +use crate::value::tagged::{self, TagStringVisitor}; +use crate::value::TaggedValue; +use crate::{number, Error, Mapping, Sequence, Value}; +use serde::de::value::{BorrowedStrDeserializer, StrDeserializer}; +use serde::de::{ + self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error as _, Expected, MapAccess, + SeqAccess, Unexpected, VariantAccess, Visitor, +}; +use serde::forward_to_deserialize_any; +use std::fmt; +use std::slice; +use std::vec; + +impl<'de> Deserialize<'de> for Value { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct ValueVisitor; + + impl<'de> Visitor<'de> for ValueVisitor { + type Value = Value; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("any YAML value") + } + + fn visit_bool(self, b: bool) -> Result + where + E: de::Error, + { + Ok(Value::Bool(b)) + } + + fn visit_i64(self, i: i64) -> Result + where + E: de::Error, + { + Ok(Value::Number(i.into())) + } + + fn visit_u64(self, u: u64) -> Result + where + E: de::Error, + { + Ok(Value::Number(u.into())) + } + + fn visit_f64(self, f: f64) -> Result + where + E: de::Error, + { + Ok(Value::Number(f.into())) + } + + fn visit_str(self, s: &str) -> Result + where + E: de::Error, + { + Ok(Value::String(s.to_owned())) + } + + fn visit_string(self, s: String) -> Result + where + E: de::Error, + { + Ok(Value::String(s)) + } + + fn visit_unit(self) -> Result + where + E: de::Error, + { + Ok(Value::Null) + } + + fn visit_none(self) -> Result + where + E: de::Error, + { + Ok(Value::Null) + } + + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer) + } + + fn visit_seq(self, data: A) -> Result + where + A: SeqAccess<'de>, + { + let de = serde::de::value::SeqAccessDeserializer::new(data); + let sequence = Sequence::deserialize(de)?; + Ok(Value::Sequence(sequence)) + } + + fn visit_map(self, data: A) -> Result + where + A: MapAccess<'de>, + { + let de = serde::de::value::MapAccessDeserializer::new(data); + let mapping = Mapping::deserialize(de)?; + Ok(Value::Mapping(mapping)) + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + let (tag, contents) = data.variant_seed(TagStringVisitor)?; + let value = contents.newtype_variant()?; + Ok(Value::Tagged(Box::new(TaggedValue { tag, value }))) + } + } + + deserializer.deserialize_any(ValueVisitor) + } +} + +impl Value { + fn deserialize_number<'de, V>(&self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag_ref() { + Value::Number(n) => n.deserialize_any(visitor), + other => Err(other.invalid_type(&visitor)), + } + } +} + +fn visit_sequence<'de, V>(sequence: Sequence, visitor: V) -> Result +where + V: Visitor<'de>, +{ + let len = sequence.len(); + let mut deserializer = SeqDeserializer::new(sequence); + let seq = visitor.visit_seq(&mut deserializer)?; + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(seq) + } else { + Err(Error::invalid_length(len, &"fewer elements in sequence")) + } +} + +fn visit_sequence_ref<'de, V>(sequence: &'de Sequence, visitor: V) -> Result +where + V: Visitor<'de>, +{ + let len = sequence.len(); + let mut deserializer = SeqRefDeserializer::new(sequence); + let seq = visitor.visit_seq(&mut deserializer)?; + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(seq) + } else { + Err(Error::invalid_length(len, &"fewer elements in sequence")) + } +} + +fn visit_mapping<'de, V>(mapping: Mapping, visitor: V) -> Result +where + V: Visitor<'de>, +{ + let len = mapping.len(); + let mut deserializer = MapDeserializer::new(mapping); + let map = visitor.visit_map(&mut deserializer)?; + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(map) + } else { + Err(Error::invalid_length(len, &"fewer elements in map")) + } +} + +fn visit_mapping_ref<'de, V>(mapping: &'de Mapping, visitor: V) -> Result +where + V: Visitor<'de>, +{ + let len = mapping.len(); + let mut deserializer = MapRefDeserializer::new(mapping); + let map = visitor.visit_map(&mut deserializer)?; + let remaining = deserializer.iter.unwrap().len(); + if remaining == 0 { + Ok(map) + } else { + Err(Error::invalid_length(len, &"fewer elements in map")) + } +} + +impl<'de> Deserializer<'de> for Value { + type Error = Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_unit(), + Value::Bool(v) => visitor.visit_bool(v), + Value::Number(n) => n.deserialize_any(visitor), + Value::String(v) => visitor.visit_string(v), + Value::Sequence(v) => visit_sequence(v, visitor), + Value::Mapping(v) => visit_mapping(v, visitor), + Value::Tagged(tagged) => visitor.visit_enum(*tagged), + } + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag() { + Value::Bool(v) => visitor.visit_bool(v), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(visitor) + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(visitor) + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag() { + Value::String(v) => visitor.visit_string(v), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_byte_buf(visitor) + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag() { + Value::String(v) => visitor.visit_string(v), + Value::Sequence(v) => visit_sequence(v, visitor), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_none(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_unit(), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_unit_struct(self, _name: &'static str, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_unit(visitor) + } + + fn deserialize_newtype_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag() { + Value::Sequence(v) => visit_sequence(v, visitor), + Value::Null => visit_sequence(Sequence::new(), visitor), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_tuple(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag() { + Value::Mapping(v) => visit_mapping(v, visitor), + Value::Null => visit_mapping(Mapping::new(), visitor), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_struct( + self, + _name: &'static str, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_map(visitor) + } + + fn deserialize_enum( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let tag; + visitor.visit_enum(match self { + Value::Tagged(tagged) => EnumDeserializer { + tag: { + tag = tagged.tag.string; + tagged::nobang(&tag) + }, + value: Some(tagged.value), + }, + Value::String(variant) => EnumDeserializer { + tag: { + tag = variant; + &tag + }, + value: None, + }, + other => { + return Err(Error::invalid_type( + other.unexpected(), + &"a Value::Tagged enum", + )); + } + }) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(visitor) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + drop(self); + visitor.visit_unit() + } +} + +struct EnumDeserializer<'a> { + tag: &'a str, + value: Option, +} + +impl<'a, 'de> EnumAccess<'de> for EnumDeserializer<'a> { + type Error = Error; + type Variant = VariantDeserializer; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Error> + where + V: DeserializeSeed<'de>, + { + let str_de = StrDeserializer::::new(self.tag); + let variant = seed.deserialize(str_de)?; + let visitor = VariantDeserializer { value: self.value }; + Ok((variant, visitor)) + } +} + +struct VariantDeserializer { + value: Option, +} + +impl<'de> VariantAccess<'de> for VariantDeserializer { + type Error = Error; + + fn unit_variant(self) -> Result<(), Error> { + match self.value { + Some(value) => value.unit_variant(), + None => Ok(()), + } + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + match self.value { + Some(value) => value.newtype_variant_seed(seed), + None => Err(Error::invalid_type( + Unexpected::UnitVariant, + &"newtype variant", + )), + } + } + + fn tuple_variant(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.value { + Some(value) => value.tuple_variant(len, visitor), + None => Err(Error::invalid_type( + Unexpected::UnitVariant, + &"tuple variant", + )), + } + } + + fn struct_variant( + self, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + match self.value { + Some(value) => value.struct_variant(fields, visitor), + None => Err(Error::invalid_type( + Unexpected::UnitVariant, + &"struct variant", + )), + } + } +} + +pub(crate) struct SeqDeserializer { + iter: vec::IntoIter, +} + +impl SeqDeserializer { + pub(crate) fn new(vec: Vec) -> Self { + SeqDeserializer { + iter: vec.into_iter(), + } + } +} + +impl<'de> Deserializer<'de> for SeqDeserializer { + type Error = Error; + + #[inline] + fn deserialize_any(mut self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = visitor.visit_seq(&mut self)?; + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(Error::invalid_length(len, &"fewer elements in sequence")) + } + } + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + drop(self); + visitor.visit_unit() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier + } +} + +impl<'de> SeqAccess<'de> for SeqDeserializer { + type Error = Error; + + fn next_element_seed(&mut self, seed: T) -> Result, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => seed.deserialize(value).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +pub(crate) struct MapDeserializer { + iter: ::IntoIter, + value: Option, +} + +impl MapDeserializer { + pub(crate) fn new(map: Mapping) -> Self { + MapDeserializer { + iter: map.into_iter(), + value: None, + } + } +} + +impl<'de> MapAccess<'de> for MapDeserializer { + type Error = Error; + + fn next_key_seed(&mut self, seed: T) -> Result, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(key).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + match self.value.take() { + Some(value) => seed.deserialize(value), + None => panic!("visit_value called before visit_key"), + } + } + + fn size_hint(&self) -> Option { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +impl<'de> Deserializer<'de> for MapDeserializer { + type Error = Error; + + #[inline] + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_map(self) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + drop(self); + visitor.visit_unit() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier + } +} + +impl<'de> Deserializer<'de> for &'de Value { + type Error = Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_unit(), + Value::Bool(v) => visitor.visit_bool(*v), + Value::Number(n) => n.deserialize_any(visitor), + Value::String(v) => visitor.visit_borrowed_str(v), + Value::Sequence(v) => visit_sequence_ref(v, visitor), + Value::Mapping(v) => visit_mapping_ref(v, visitor), + Value::Tagged(tagged) => visitor.visit_enum(&**tagged), + } + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag_ref() { + Value::Bool(v) => visitor.visit_bool(*v), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_number(visitor) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(visitor) + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag_ref() { + Value::String(v) => visitor.visit_borrowed_str(v), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_str(visitor) + } + + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag_ref() { + Value::String(v) => visitor.visit_borrowed_str(v), + Value::Sequence(v) => visit_sequence_ref(v, visitor), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_bytes(visitor) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_none(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_unit(), + _ => Err(self.invalid_type(&visitor)), + } + } + + fn deserialize_unit_struct(self, _name: &'static str, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_unit(visitor) + } + + fn deserialize_newtype_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + static EMPTY: Sequence = Sequence::new(); + match self.untag_ref() { + Value::Sequence(v) => visit_sequence_ref(v, visitor), + Value::Null => visit_sequence_ref(&EMPTY, visitor), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_tuple(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.untag_ref() { + Value::Mapping(v) => visit_mapping_ref(v, visitor), + Value::Null => visitor.visit_map(&mut MapRefDeserializer { + iter: None, + value: None, + }), + other => Err(other.invalid_type(&visitor)), + } + } + + fn deserialize_struct( + self, + _name: &'static str, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_map(visitor) + } + + fn deserialize_enum( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_enum(match self { + Value::Tagged(tagged) => EnumRefDeserializer { + tag: tagged::nobang(&tagged.tag.string), + value: Some(&tagged.value), + }, + Value::String(variant) => EnumRefDeserializer { + tag: variant, + value: None, + }, + other => { + return Err(Error::invalid_type( + other.unexpected(), + &"a Value::Tagged enum", + )); + } + }) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(visitor) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } +} + +struct EnumRefDeserializer<'de> { + tag: &'de str, + value: Option<&'de Value>, +} + +impl<'de> EnumAccess<'de> for EnumRefDeserializer<'de> { + type Error = Error; + type Variant = VariantRefDeserializer<'de>; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Error> + where + V: DeserializeSeed<'de>, + { + let str_de = BorrowedStrDeserializer::::new(self.tag); + let variant = seed.deserialize(str_de)?; + let visitor = VariantRefDeserializer { value: self.value }; + Ok((variant, visitor)) + } +} + +struct VariantRefDeserializer<'de> { + value: Option<&'de Value>, +} + +impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> { + type Error = Error; + + fn unit_variant(self) -> Result<(), Error> { + match self.value { + Some(value) => value.unit_variant(), + None => Ok(()), + } + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + match self.value { + Some(value) => value.newtype_variant_seed(seed), + None => Err(Error::invalid_type( + Unexpected::UnitVariant, + &"newtype variant", + )), + } + } + + fn tuple_variant(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.value { + Some(value) => value.tuple_variant(len, visitor), + None => Err(Error::invalid_type( + Unexpected::UnitVariant, + &"tuple variant", + )), + } + } + + fn struct_variant( + self, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + match self.value { + Some(value) => value.struct_variant(fields, visitor), + None => Err(Error::invalid_type( + Unexpected::UnitVariant, + &"struct variant", + )), + } + } +} + +pub(crate) struct SeqRefDeserializer<'de> { + iter: slice::Iter<'de, Value>, +} + +impl<'de> SeqRefDeserializer<'de> { + pub(crate) fn new(slice: &'de [Value]) -> Self { + SeqRefDeserializer { iter: slice.iter() } + } +} + +impl<'de> Deserializer<'de> for SeqRefDeserializer<'de> { + type Error = Error; + + #[inline] + fn deserialize_any(mut self, visitor: V) -> Result + where + V: Visitor<'de>, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = visitor.visit_seq(&mut self)?; + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(Error::invalid_length(len, &"fewer elements in sequence")) + } + } + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier + } +} + +impl<'de> SeqAccess<'de> for SeqRefDeserializer<'de> { + type Error = Error; + + fn next_element_seed(&mut self, seed: T) -> Result, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => seed.deserialize(value).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> Option { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +pub(crate) struct MapRefDeserializer<'de> { + iter: Option<<&'de Mapping as IntoIterator>::IntoIter>, + value: Option<&'de Value>, +} + +impl<'de> MapRefDeserializer<'de> { + pub(crate) fn new(map: &'de Mapping) -> Self { + MapRefDeserializer { + iter: Some(map.iter()), + value: None, + } + } +} + +impl<'de> MapAccess<'de> for MapRefDeserializer<'de> { + type Error = Error; + + fn next_key_seed(&mut self, seed: T) -> Result, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.as_mut().and_then(Iterator::next) { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(key).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed(&mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + match self.value.take() { + Some(value) => seed.deserialize(value), + None => panic!("visit_value called before visit_key"), + } + } + + fn size_hint(&self) -> Option { + match self.iter.as_ref()?.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +impl<'de> Deserializer<'de> for MapRefDeserializer<'de> { + type Error = Error; + + #[inline] + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_map(self) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier + } +} + +impl Value { + #[cold] + fn invalid_type(&self, exp: &dyn Expected) -> E + where + E: de::Error, + { + de::Error::invalid_type(self.unexpected(), exp) + } + + #[cold] + pub(crate) fn unexpected(&self) -> Unexpected { + match self { + Value::Null => Unexpected::Unit, + Value::Bool(b) => Unexpected::Bool(*b), + Value::Number(n) => number::unexpected(n), + Value::String(s) => Unexpected::Str(s), + Value::Sequence(_) => Unexpected::Seq, + Value::Mapping(_) => Unexpected::Map, + Value::Tagged(_) => Unexpected::Enum, + } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/debug.rs b/bitbox02-bt/vendor/serde_yaml/src/value/debug.rs new file mode 100644 index 0000000..060f9ec --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/debug.rs @@ -0,0 +1,57 @@ +use crate::mapping::Mapping; +use crate::value::{Number, Value}; +use std::fmt::{self, Debug, Display}; + +impl Debug for Value { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Value::Null => formatter.write_str("Null"), + Value::Bool(boolean) => write!(formatter, "Bool({})", boolean), + Value::Number(number) => write!(formatter, "Number({})", number), + Value::String(string) => write!(formatter, "String({:?})", string), + Value::Sequence(sequence) => { + formatter.write_str("Sequence ")?; + formatter.debug_list().entries(sequence).finish() + } + Value::Mapping(mapping) => Debug::fmt(mapping, formatter), + Value::Tagged(tagged) => Debug::fmt(tagged, formatter), + } + } +} + +struct DisplayNumber<'a>(&'a Number); + +impl<'a> Debug for DisplayNumber<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(self.0, formatter) + } +} + +impl Debug for Number { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "Number({})", self) + } +} + +impl Debug for Mapping { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Mapping ")?; + let mut debug = formatter.debug_map(); + for (k, v) in self { + let tmp; + debug.entry( + match k { + Value::Bool(boolean) => boolean, + Value::Number(number) => { + tmp = DisplayNumber(number); + &tmp + } + Value::String(string) => string, + _ => k, + }, + v, + ); + } + debug.finish() + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/from.rs b/bitbox02-bt/vendor/serde_yaml/src/value/from.rs new file mode 100644 index 0000000..82412c4 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/from.rs @@ -0,0 +1,178 @@ +use crate::{Mapping, Value}; + +// Implement a bunch of conversion to make it easier to create YAML values +// on the fly. + +macro_rules! from_number { + ($($ty:ident)*) => { + $( + impl From<$ty> for Value { + fn from(n: $ty) -> Self { + Value::Number(n.into()) + } + } + )* + }; +} + +from_number! { + i8 i16 i32 i64 isize + u8 u16 u32 u64 usize + f32 f64 +} + +impl From for Value { + /// Convert boolean to `Value` + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let b = false; + /// let x: Value = b.into(); + /// ``` + fn from(f: bool) -> Self { + Value::Bool(f) + } +} + +impl From for Value { + /// Convert `String` to `Value` + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let s: String = "lorem".to_string(); + /// let x: Value = s.into(); + /// ``` + fn from(f: String) -> Self { + Value::String(f) + } +} + +impl<'a> From<&'a str> for Value { + /// Convert string slice to `Value` + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let s: &str = "lorem"; + /// let x: Value = s.into(); + /// ``` + fn from(f: &str) -> Self { + Value::String(f.to_string()) + } +} + +use std::borrow::Cow; + +impl<'a> From> for Value { + /// Convert copy-on-write string to `Value` + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::Value; + /// use std::borrow::Cow; + /// + /// let s: Cow = Cow::Borrowed("lorem"); + /// let x: Value = s.into(); + /// ``` + /// + /// ``` + /// use serde_yaml::Value; + /// use std::borrow::Cow; + /// + /// let s: Cow = Cow::Owned("lorem".to_string()); + /// let x: Value = s.into(); + /// ``` + fn from(f: Cow<'a, str>) -> Self { + Value::String(f.to_string()) + } +} + +impl From for Value { + /// Convert map (with string keys) to `Value` + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::{Mapping, Value}; + /// + /// let mut m = Mapping::new(); + /// m.insert("Lorem".into(), "ipsum".into()); + /// let x: Value = m.into(); + /// ``` + fn from(f: Mapping) -> Self { + Value::Mapping(f) + } +} + +impl> From> for Value { + /// Convert a `Vec` to `Value` + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let v = vec!["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into(); + /// ``` + fn from(f: Vec) -> Self { + Value::Sequence(f.into_iter().map(Into::into).collect()) + } +} + +impl<'a, T: Clone + Into> From<&'a [T]> for Value { + /// Convert a slice to `Value` + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let v: &[&str] = &["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into(); + /// ``` + fn from(f: &'a [T]) -> Self { + Value::Sequence(f.iter().cloned().map(Into::into).collect()) + } +} + +impl> FromIterator for Value { + /// Convert an iteratable type to a YAML sequence + /// + /// # Examples + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let v = std::iter::repeat(42).take(5); + /// let x: Value = v.collect(); + /// ``` + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into_iter().collect(); + /// ``` + /// + /// ``` + /// use std::iter::FromIterator; + /// use serde_yaml::Value; + /// + /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]); + /// ``` + fn from_iter>(iter: I) -> Self { + let vec = iter.into_iter().map(T::into).collect(); + + Value::Sequence(vec) + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/index.rs b/bitbox02-bt/vendor/serde_yaml/src/value/index.rs new file mode 100644 index 0000000..9a886d5 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/index.rs @@ -0,0 +1,279 @@ +use crate::mapping::Entry; +use crate::{mapping, private, Mapping, Value}; +use std::fmt::{self, Debug}; +use std::ops; + +/// A type that can be used to index into a `serde_yaml::Value`. See the `get` +/// and `get_mut` methods of `Value`. +/// +/// This trait is sealed and cannot be implemented for types outside of +/// `serde_yaml`. +pub trait Index: private::Sealed { + /// Return None if the key is not already in the sequence or object. + #[doc(hidden)] + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>; + + /// Return None if the key is not already in the sequence or object. + #[doc(hidden)] + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value>; + + /// Panic if sequence index out of bounds. If key is not already in the object, + /// insert it with a value of null. Panic if Value is a type that cannot be + /// indexed into, except if Value is null then it can be treated as an empty + /// object. + #[doc(hidden)] + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value; +} + +impl Index for usize { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + match v.untag_ref() { + Value::Sequence(vec) => vec.get(*self), + Value::Mapping(vec) => vec.get(&Value::Number((*self).into())), + _ => None, + } + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + match v.untag_mut() { + Value::Sequence(vec) => vec.get_mut(*self), + Value::Mapping(vec) => vec.get_mut(&Value::Number((*self).into())), + _ => None, + } + } + fn index_or_insert<'v>(&self, mut v: &'v mut Value) -> &'v mut Value { + loop { + match v { + Value::Sequence(vec) => { + let len = vec.len(); + return vec.get_mut(*self).unwrap_or_else(|| { + panic!( + "cannot access index {} of YAML sequence of length {}", + self, len + ) + }); + } + Value::Mapping(map) => { + let n = Value::Number((*self).into()); + return map.entry(n).or_insert(Value::Null); + } + Value::Tagged(tagged) => v = &mut tagged.value, + _ => panic!("cannot access index {} of YAML {}", self, Type(v)), + } + } + } +} + +fn index_into_mapping<'v, I>(index: &I, v: &'v Value) -> Option<&'v Value> +where + I: ?Sized + mapping::Index, +{ + match v.untag_ref() { + Value::Mapping(map) => map.get(index), + _ => None, + } +} + +fn index_into_mut_mapping<'v, I>(index: &I, v: &'v mut Value) -> Option<&'v mut Value> +where + I: ?Sized + mapping::Index, +{ + match v.untag_mut() { + Value::Mapping(map) => map.get_mut(index), + _ => None, + } +} + +fn index_or_insert_mapping<'v, I>(index: &I, mut v: &'v mut Value) -> &'v mut Value +where + I: ?Sized + mapping::Index + ToOwned + Debug, + Value: From, +{ + if let Value::Null = *v { + *v = Value::Mapping(Mapping::new()); + return match v { + Value::Mapping(map) => match map.entry(index.to_owned().into()) { + Entry::Vacant(entry) => entry.insert(Value::Null), + Entry::Occupied(_) => unreachable!(), + }, + _ => unreachable!(), + }; + } + loop { + match v { + Value::Mapping(map) => { + return map.entry(index.to_owned().into()).or_insert(Value::Null); + } + Value::Tagged(tagged) => v = &mut tagged.value, + _ => panic!("cannot access key {:?} in YAML {}", index, Type(v)), + } + } +} + +impl Index for Value { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + index_into_mapping(self, v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + index_into_mut_mapping(self, v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + index_or_insert_mapping(self, v) + } +} + +impl Index for str { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + index_into_mapping(self, v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + index_into_mut_mapping(self, v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + index_or_insert_mapping(self, v) + } +} + +impl Index for String { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + self.as_str().index_into(v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + self.as_str().index_into_mut(v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + self.as_str().index_or_insert(v) + } +} + +impl<'a, T> Index for &'a T +where + T: ?Sized + Index, +{ + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + (**self).index_into(v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + (**self).index_into_mut(v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + (**self).index_or_insert(v) + } +} + +/// Used in panic messages. +struct Type<'a>(&'a Value); + +impl<'a> fmt::Display for Type<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.0 { + Value::Null => formatter.write_str("null"), + Value::Bool(_) => formatter.write_str("boolean"), + Value::Number(_) => formatter.write_str("number"), + Value::String(_) => formatter.write_str("string"), + Value::Sequence(_) => formatter.write_str("sequence"), + Value::Mapping(_) => formatter.write_str("mapping"), + Value::Tagged(_) => unreachable!(), + } + } +} + +// The usual semantics of Index is to panic on invalid indexing. +// +// That said, the usual semantics are for things like `Vec` and `BTreeMap` which +// have different use cases than Value. If you are working with a Vec, you know +// that you are working with a Vec and you can get the len of the Vec and make +// sure your indices are within bounds. The Value use cases are more +// loosey-goosey. You got some YAML from an endpoint and you want to pull values +// out of it. Outside of this Index impl, you already have the option of using +// `value.as_sequence()` and working with the Vec directly, or matching on +// `Value::Sequence` and getting the Vec directly. The Index impl means you can +// skip that and index directly into the thing using a concise syntax. You don't +// have to check the type, you don't have to check the len, it is all about what +// you expect the Value to look like. +// +// Basically the use cases that would be well served by panicking here are +// better served by using one of the other approaches: `get` and `get_mut`, +// `as_sequence`, or match. The value of this impl is that it adds a way of +// working with Value that is not well served by the existing approaches: +// concise and careless and sometimes that is exactly what you want. +impl ops::Index for Value +where + I: Index, +{ + type Output = Value; + + /// Index into a `serde_yaml::Value` using the syntax `value[0]` or + /// `value["k"]`. + /// + /// Returns `Value::Null` if the type of `self` does not match the type of + /// the index, for example if the index is a string and `self` is a sequence + /// or a number. Also returns `Value::Null` if the given key does not exist + /// in the map or the given index is not within the bounds of the sequence. + /// + /// For retrieving deeply nested values, you should have a look at the + /// `Value::pointer` method. + /// + /// # Examples + /// + /// ``` + /// # use serde_yaml::Value; + /// # + /// # fn main() -> serde_yaml::Result<()> { + /// let data: serde_yaml::Value = serde_yaml::from_str(r#"{ x: { y: [z, zz] } }"#)?; + /// + /// assert_eq!(data["x"]["y"], serde_yaml::from_str::(r#"["z", "zz"]"#).unwrap()); + /// assert_eq!(data["x"]["y"][0], serde_yaml::from_str::(r#""z""#).unwrap()); + /// + /// assert_eq!(data["a"], serde_yaml::from_str::(r#"null"#).unwrap()); // returns null for undefined values + /// assert_eq!(data["a"]["b"], serde_yaml::from_str::(r#"null"#).unwrap()); // does not panic + /// # Ok(()) + /// # } + /// ``` + fn index(&self, index: I) -> &Value { + static NULL: Value = Value::Null; + index.index_into(self).unwrap_or(&NULL) + } +} + +impl ops::IndexMut for Value +where + I: Index, +{ + /// Write into a `serde_yaml::Value` using the syntax `value[0] = ...` or + /// `value["k"] = ...`. + /// + /// If the index is a number, the value must be a sequence of length bigger + /// than the index. Indexing into a value that is not a sequence or a + /// sequence that is too small will panic. + /// + /// If the index is a string, the value must be an object or null which is + /// treated like an empty object. If the key is not already present in the + /// object, it will be inserted with a value of null. Indexing into a value + /// that is neither an object nor null will panic. + /// + /// # Examples + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// let mut data: serde_yaml::Value = serde_yaml::from_str(r#"{x: 0}"#)?; + /// + /// // replace an existing key + /// data["x"] = serde_yaml::from_str(r#"1"#)?; + /// + /// // insert a new key + /// data["y"] = serde_yaml::from_str(r#"[false, false, false]"#)?; + /// + /// // replace a value in a sequence + /// data["y"][0] = serde_yaml::from_str(r#"true"#)?; + /// + /// // inserted a deeply nested key + /// data["a"]["b"]["c"]["d"] = serde_yaml::from_str(r#"true"#)?; + /// + /// println!("{:?}", data); + /// # Ok(()) + /// # } + /// ``` + fn index_mut(&mut self, index: I) -> &mut Value { + index.index_or_insert(self) + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/mod.rs b/bitbox02-bt/vendor/serde_yaml/src/value/mod.rs new file mode 100644 index 0000000..27a170b --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/mod.rs @@ -0,0 +1,698 @@ +//! The Value enum, a loosely typed way of representing any valid YAML value. + +mod de; +mod debug; +mod from; +mod index; +mod partial_eq; +mod ser; +pub(crate) mod tagged; + +use crate::error::{self, Error, ErrorImpl}; +use serde::de::{Deserialize, DeserializeOwned, IntoDeserializer}; +use serde::Serialize; +use std::hash::{Hash, Hasher}; +use std::mem; + +pub use self::index::Index; +pub use self::ser::Serializer; +pub use self::tagged::{Tag, TaggedValue}; +#[doc(inline)] +pub use crate::mapping::Mapping; +pub use crate::number::Number; + +/// Represents any valid YAML value. +#[derive(Clone, PartialEq, PartialOrd)] +pub enum Value { + /// Represents a YAML null value. + Null, + /// Represents a YAML boolean. + Bool(bool), + /// Represents a YAML numerical value, whether integer or floating point. + Number(Number), + /// Represents a YAML string. + String(String), + /// Represents a YAML sequence in which the elements are + /// `serde_yaml::Value`. + Sequence(Sequence), + /// Represents a YAML mapping in which the keys and values are both + /// `serde_yaml::Value`. + Mapping(Mapping), + /// A representation of YAML's `!Tag` syntax, used for enums. + Tagged(Box), +} + +/// The default value is `Value::Null`. +/// +/// This is useful for handling omitted `Value` fields when deserializing. +/// +/// # Examples +/// +/// ``` +/// # use serde_derive::Deserialize; +/// use serde::Deserialize; +/// use serde_yaml::Value; +/// +/// #[derive(Deserialize)] +/// struct Settings { +/// level: i32, +/// #[serde(default)] +/// extras: Value, +/// } +/// +/// # fn try_main() -> Result<(), serde_yaml::Error> { +/// let data = r#" { "level": 42 } "#; +/// let s: Settings = serde_yaml::from_str(data)?; +/// +/// assert_eq!(s.level, 42); +/// assert_eq!(s.extras, Value::Null); +/// # +/// # Ok(()) +/// # } +/// # +/// # try_main().unwrap() +/// ``` +impl Default for Value { + fn default() -> Value { + Value::Null + } +} + +/// A YAML sequence in which the elements are `serde_yaml::Value`. +pub type Sequence = Vec; + +/// Convert a `T` into `serde_yaml::Value` which is an enum that can represent +/// any valid YAML data. +/// +/// This conversion can fail if `T`'s implementation of `Serialize` decides to +/// return an error. +/// +/// ``` +/// # use serde_yaml::Value; +/// let val = serde_yaml::to_value("s").unwrap(); +/// assert_eq!(val, Value::String("s".to_owned())); +/// ``` +pub fn to_value(value: T) -> Result +where + T: Serialize, +{ + value.serialize(Serializer) +} + +/// Interpret a `serde_yaml::Value` as an instance of type `T`. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a YAML map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the YAML map or some number is too big to fit in the expected primitive +/// type. +/// +/// ``` +/// # use serde_yaml::Value; +/// let val = Value::String("foo".to_owned()); +/// let s: String = serde_yaml::from_value(val).unwrap(); +/// assert_eq!("foo", s); +/// ``` +pub fn from_value(value: Value) -> Result +where + T: DeserializeOwned, +{ + Deserialize::deserialize(value) +} + +impl Value { + /// Index into a YAML sequence or map. A string index can be used to access + /// a value in a map, and a usize index can be used to access an element of + /// an sequence. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is a sequence or + /// a number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the sequence. + /// + /// ``` + /// # fn main() -> serde_yaml::Result<()> { + /// use serde_yaml::Value; + /// + /// let object: Value = serde_yaml::from_str(r#"{ A: 65, B: 66, C: 67 }"#)?; + /// let x = object.get("A").unwrap(); + /// assert_eq!(x, 65); + /// + /// let sequence: Value = serde_yaml::from_str(r#"[ "A", "B", "C" ]"#)?; + /// let x = sequence.get(2).unwrap(); + /// assert_eq!(x, &Value::String("C".into())); + /// + /// assert_eq!(sequence.get("A"), None); + /// # Ok(()) + /// # } + /// ``` + /// + /// Square brackets can also be used to index into a value in a more concise + /// way. This returns `Value::Null` in cases where `get` would have returned + /// `None`. + /// + /// ``` + /// # use serde_yaml::Value; + /// # + /// # fn main() -> serde_yaml::Result<()> { + /// let object: Value = serde_yaml::from_str(r#" + /// A: [a, á, à] + /// B: [b, b́] + /// C: [c, ć, ć̣, ḉ] + /// 42: true + /// "#)?; + /// assert_eq!(object["B"][0], Value::String("b".into())); + /// + /// assert_eq!(object[Value::String("D".into())], Value::Null); + /// assert_eq!(object["D"], Value::Null); + /// assert_eq!(object[0]["x"]["y"]["z"], Value::Null); + /// + /// assert_eq!(object[42], Value::Bool(true)); + /// # Ok(()) + /// # } + /// ``` + pub fn get(&self, index: I) -> Option<&Value> { + index.index_into(self) + } + + /// Index into a YAML sequence or map. A string index can be used to access + /// a value in a map, and a usize index can be used to access an element of + /// an sequence. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is a sequence or + /// a number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the sequence. + pub fn get_mut(&mut self, index: I) -> Option<&mut Value> { + index.index_into_mut(self) + } + + /// Returns true if the `Value` is a Null. Returns false otherwise. + /// + /// For any Value on which `is_null` returns true, `as_null` is guaranteed + /// to return `Some(())`. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("null").unwrap(); + /// assert!(v.is_null()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert!(!v.is_null()); + /// ``` + pub fn is_null(&self) -> bool { + if let Value::Null = self.untag_ref() { + true + } else { + false + } + } + + /// If the `Value` is a Null, returns (). Returns None otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("null").unwrap(); + /// assert_eq!(v.as_null(), Some(())); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_null(), None); + /// ``` + pub fn as_null(&self) -> Option<()> { + match self.untag_ref() { + Value::Null => Some(()), + _ => None, + } + } + + /// Returns true if the `Value` is a Boolean. Returns false otherwise. + /// + /// For any Value on which `is_boolean` returns true, `as_bool` is + /// guaranteed to return the boolean value. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("true").unwrap(); + /// assert!(v.is_bool()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("42").unwrap(); + /// assert!(!v.is_bool()); + /// ``` + pub fn is_bool(&self) -> bool { + self.as_bool().is_some() + } + + /// If the `Value` is a Boolean, returns the associated bool. Returns None + /// otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("true").unwrap(); + /// assert_eq!(v.as_bool(), Some(true)); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("42").unwrap(); + /// assert_eq!(v.as_bool(), None); + /// ``` + pub fn as_bool(&self) -> Option { + match self.untag_ref() { + Value::Bool(b) => Some(*b), + _ => None, + } + } + + /// Returns true if the `Value` is a Number. Returns false otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("5").unwrap(); + /// assert!(v.is_number()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("true").unwrap(); + /// assert!(!v.is_number()); + /// ``` + pub fn is_number(&self) -> bool { + match self.untag_ref() { + Value::Number(_) => true, + _ => false, + } + } + + /// Returns true if the `Value` is an integer between `i64::MIN` and + /// `i64::MAX`. + /// + /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to + /// return the integer value. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("1337").unwrap(); + /// assert!(v.is_i64()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("null").unwrap(); + /// assert!(!v.is_i64()); + /// ``` + pub fn is_i64(&self) -> bool { + self.as_i64().is_some() + } + + /// If the `Value` is an integer, represent it as i64 if possible. Returns + /// None otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("1337").unwrap(); + /// assert_eq!(v.as_i64(), Some(1337)); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_i64(), None); + /// ``` + pub fn as_i64(&self) -> Option { + match self.untag_ref() { + Value::Number(n) => n.as_i64(), + _ => None, + } + } + + /// Returns true if the `Value` is an integer between `u64::MIN` and + /// `u64::MAX`. + /// + /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to + /// return the integer value. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("1337").unwrap(); + /// assert!(v.is_u64()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("null").unwrap(); + /// assert!(!v.is_u64()); + /// ``` + pub fn is_u64(&self) -> bool { + self.as_u64().is_some() + } + + /// If the `Value` is an integer, represent it as u64 if possible. Returns + /// None otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("1337").unwrap(); + /// assert_eq!(v.as_u64(), Some(1337)); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_u64(), None); + /// ``` + pub fn as_u64(&self) -> Option { + match self.untag_ref() { + Value::Number(n) => n.as_u64(), + _ => None, + } + } + + /// Returns true if the `Value` is a number that can be represented by f64. + /// + /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to + /// return the floating point value. + /// + /// Currently this function returns true if and only if both `is_i64` and + /// `is_u64` return false but this is not a guarantee in the future. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("256.01").unwrap(); + /// assert!(v.is_f64()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("true").unwrap(); + /// assert!(!v.is_f64()); + /// ``` + pub fn is_f64(&self) -> bool { + match self.untag_ref() { + Value::Number(n) => n.is_f64(), + _ => false, + } + } + + /// If the `Value` is a number, represent it as f64 if possible. Returns + /// None otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("13.37").unwrap(); + /// assert_eq!(v.as_f64(), Some(13.37)); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_f64(), None); + /// ``` + pub fn as_f64(&self) -> Option { + match self.untag_ref() { + Value::Number(i) => i.as_f64(), + _ => None, + } + } + + /// Returns true if the `Value` is a String. Returns false otherwise. + /// + /// For any Value on which `is_string` returns true, `as_str` is guaranteed + /// to return the string slice. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("'lorem ipsum'").unwrap(); + /// assert!(v.is_string()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("42").unwrap(); + /// assert!(!v.is_string()); + /// ``` + pub fn is_string(&self) -> bool { + self.as_str().is_some() + } + + /// If the `Value` is a String, returns the associated str. Returns None + /// otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("'lorem ipsum'").unwrap(); + /// assert_eq!(v.as_str(), Some("lorem ipsum")); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_str(), None); + /// ``` + pub fn as_str(&self) -> Option<&str> { + match self.untag_ref() { + Value::String(s) => Some(s), + _ => None, + } + } + + /// Returns true if the `Value` is a sequence. Returns false otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("[1, 2, 3]").unwrap(); + /// assert!(v.is_sequence()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("true").unwrap(); + /// assert!(!v.is_sequence()); + /// ``` + pub fn is_sequence(&self) -> bool { + self.as_sequence().is_some() + } + + /// If the `Value` is a sequence, return a reference to it if possible. + /// Returns None otherwise. + /// + /// ``` + /// # use serde_yaml::{Value, Number}; + /// let v: Value = serde_yaml::from_str("[1, 2]").unwrap(); + /// assert_eq!(v.as_sequence(), Some(&vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))])); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_sequence(), None); + /// ``` + pub fn as_sequence(&self) -> Option<&Sequence> { + match self.untag_ref() { + Value::Sequence(seq) => Some(seq), + _ => None, + } + } + + /// If the `Value` is a sequence, return a mutable reference to it if + /// possible. Returns None otherwise. + /// + /// ``` + /// # use serde_yaml::{Value, Number}; + /// let mut v: Value = serde_yaml::from_str("[1]").unwrap(); + /// let s = v.as_sequence_mut().unwrap(); + /// s.push(Value::Number(Number::from(2))); + /// assert_eq!(s, &vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))]); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let mut v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_sequence_mut(), None); + /// ``` + pub fn as_sequence_mut(&mut self) -> Option<&mut Sequence> { + match self.untag_mut() { + Value::Sequence(seq) => Some(seq), + _ => None, + } + } + + /// Returns true if the `Value` is a mapping. Returns false otherwise. + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("a: 42").unwrap(); + /// assert!(v.is_mapping()); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("true").unwrap(); + /// assert!(!v.is_mapping()); + /// ``` + pub fn is_mapping(&self) -> bool { + self.as_mapping().is_some() + } + + /// If the `Value` is a mapping, return a reference to it if possible. + /// Returns None otherwise. + /// + /// ``` + /// # use serde_yaml::{Value, Mapping, Number}; + /// let v: Value = serde_yaml::from_str("a: 42").unwrap(); + /// + /// let mut expected = Mapping::new(); + /// expected.insert(Value::String("a".into()),Value::Number(Number::from(42))); + /// + /// assert_eq!(v.as_mapping(), Some(&expected)); + /// ``` + /// + /// ``` + /// # use serde_yaml::Value; + /// let v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_mapping(), None); + /// ``` + pub fn as_mapping(&self) -> Option<&Mapping> { + match self.untag_ref() { + Value::Mapping(map) => Some(map), + _ => None, + } + } + + /// If the `Value` is a mapping, return a reference to it if possible. + /// Returns None otherwise. + /// + /// ``` + /// # use serde_yaml::{Value, Mapping, Number}; + /// let mut v: Value = serde_yaml::from_str("a: 42").unwrap(); + /// let m = v.as_mapping_mut().unwrap(); + /// m.insert(Value::String("b".into()), Value::Number(Number::from(21))); + /// + /// let mut expected = Mapping::new(); + /// expected.insert(Value::String("a".into()), Value::Number(Number::from(42))); + /// expected.insert(Value::String("b".into()), Value::Number(Number::from(21))); + /// + /// assert_eq!(m, &expected); + /// ``` + /// + /// ``` + /// # use serde_yaml::{Value, Mapping}; + /// let mut v: Value = serde_yaml::from_str("false").unwrap(); + /// assert_eq!(v.as_mapping_mut(), None); + /// ``` + pub fn as_mapping_mut(&mut self) -> Option<&mut Mapping> { + match self.untag_mut() { + Value::Mapping(map) => Some(map), + _ => None, + } + } + + /// Performs merging of `<<` keys into the surrounding mapping. + /// + /// The intended use of this in YAML is described in + /// . + /// + /// ``` + /// use serde_yaml::Value; + /// + /// let config = "\ + /// tasks: + /// build: &webpack_shared + /// command: webpack + /// args: build + /// inputs: + /// - 'src/**/*' + /// start: + /// <<: *webpack_shared + /// args: start + /// "; + /// + /// let mut value: Value = serde_yaml::from_str(config).unwrap(); + /// value.apply_merge().unwrap(); + /// + /// assert_eq!(value["tasks"]["start"]["command"], "webpack"); + /// assert_eq!(value["tasks"]["start"]["args"], "start"); + /// ``` + pub fn apply_merge(&mut self) -> Result<(), Error> { + let mut stack = Vec::new(); + stack.push(self); + while let Some(node) = stack.pop() { + match node { + Value::Mapping(mapping) => { + match mapping.remove("<<") { + Some(Value::Mapping(merge)) => { + for (k, v) in merge { + mapping.entry(k).or_insert(v); + } + } + Some(Value::Sequence(sequence)) => { + for value in sequence { + match value { + Value::Mapping(merge) => { + for (k, v) in merge { + mapping.entry(k).or_insert(v); + } + } + Value::Sequence(_) => { + return Err(error::new(ErrorImpl::SequenceInMergeElement)); + } + Value::Tagged(_) => { + return Err(error::new(ErrorImpl::TaggedInMerge)); + } + _unexpected => { + return Err(error::new(ErrorImpl::ScalarInMergeElement)); + } + } + } + } + None => {} + Some(Value::Tagged(_)) => return Err(error::new(ErrorImpl::TaggedInMerge)), + Some(_unexpected) => return Err(error::new(ErrorImpl::ScalarInMerge)), + } + stack.extend(mapping.values_mut()); + } + Value::Sequence(sequence) => stack.extend(sequence), + Value::Tagged(tagged) => stack.push(&mut tagged.value), + _ => {} + } + } + Ok(()) + } +} + +impl Eq for Value {} + +// NOTE: This impl must be kept consistent with HashLikeValue's Hash impl in +// mapping.rs in order for value[str] indexing to work. +impl Hash for Value { + fn hash(&self, state: &mut H) { + mem::discriminant(self).hash(state); + match self { + Value::Null => {} + Value::Bool(v) => v.hash(state), + Value::Number(v) => v.hash(state), + Value::String(v) => v.hash(state), + Value::Sequence(v) => v.hash(state), + Value::Mapping(v) => v.hash(state), + Value::Tagged(v) => v.hash(state), + } + } +} + +impl<'de> IntoDeserializer<'de, Error> for Value { + type Deserializer = Self; + + fn into_deserializer(self) -> Self::Deserializer { + self + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/partial_eq.rs b/bitbox02-bt/vendor/serde_yaml/src/value/partial_eq.rs new file mode 100644 index 0000000..023b7dd --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/partial_eq.rs @@ -0,0 +1,87 @@ +use crate::Value; + +impl PartialEq for Value { + /// Compare `str` with YAML value + /// + /// # Examples + /// + /// ``` + /// # use serde_yaml::Value; + /// assert!(Value::String("lorem".into()) == *"lorem"); + /// ``` + fn eq(&self, other: &str) -> bool { + self.as_str().map_or(false, |s| s == other) + } +} + +impl<'a> PartialEq<&'a str> for Value { + /// Compare `&str` with YAML value + /// + /// # Examples + /// + /// ``` + /// # use serde_yaml::Value; + /// assert!(Value::String("lorem".into()) == "lorem"); + /// ``` + fn eq(&self, other: &&str) -> bool { + self.as_str().map_or(false, |s| s == *other) + } +} + +impl PartialEq for Value { + /// Compare YAML value with String + /// + /// # Examples + /// + /// ``` + /// # use serde_yaml::Value; + /// assert!(Value::String("lorem".into()) == "lorem".to_string()); + /// ``` + fn eq(&self, other: &String) -> bool { + self.as_str().map_or(false, |s| s == other) + } +} + +impl PartialEq for Value { + /// Compare YAML value with bool + /// + /// # Examples + /// + /// ``` + /// # use serde_yaml::Value; + /// assert!(Value::Bool(true) == true); + /// ``` + fn eq(&self, other: &bool) -> bool { + self.as_bool().map_or(false, |b| b == *other) + } +} + +macro_rules! partialeq_numeric { + ($([$($ty:ty)*], $conversion:ident, $base:ty)*) => { + $($( + impl PartialEq<$ty> for Value { + fn eq(&self, other: &$ty) -> bool { + self.$conversion().map_or(false, |i| i == (*other as $base)) + } + } + + impl<'a> PartialEq<$ty> for &'a Value { + fn eq(&self, other: &$ty) -> bool { + self.$conversion().map_or(false, |i| i == (*other as $base)) + } + } + + impl<'a> PartialEq<$ty> for &'a mut Value { + fn eq(&self, other: &$ty) -> bool { + self.$conversion().map_or(false, |i| i == (*other as $base)) + } + } + )*)* + } +} + +partialeq_numeric! { + [i8 i16 i32 i64 isize], as_i64, i64 + [u8 u16 u32 u64 usize], as_u64, u64 + [f32 f64], as_f64, f64 +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/ser.rs b/bitbox02-bt/vendor/serde_yaml/src/value/ser.rs new file mode 100644 index 0000000..50b08d6 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/ser.rs @@ -0,0 +1,840 @@ +use crate::error::{self, Error, ErrorImpl}; +use crate::value::tagged::{self, MaybeTag}; +use crate::value::{to_value, Mapping, Number, Sequence, Tag, TaggedValue, Value}; +use serde::ser::{self, Serialize}; +use std::fmt::Display; +use std::mem; + +type Result = std::result::Result; + +impl Serialize for Value { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + Value::Null => serializer.serialize_unit(), + Value::Bool(b) => serializer.serialize_bool(*b), + Value::Number(n) => n.serialize(serializer), + Value::String(s) => serializer.serialize_str(s), + Value::Sequence(seq) => seq.serialize(serializer), + Value::Mapping(mapping) => { + use serde::ser::SerializeMap; + let mut map = serializer.serialize_map(Some(mapping.len()))?; + for (k, v) in mapping { + map.serialize_entry(k, v)?; + } + map.end() + } + Value::Tagged(tagged) => tagged.serialize(serializer), + } + } +} + +/// Serializer whose output is a `Value`. +/// +/// This is the serializer that backs [`serde_yaml::to_value`][crate::to_value]. +/// Unlike the main serde_yaml serializer which goes from some serializable +/// value of type `T` to YAML text, this one goes from `T` to +/// `serde_yaml::Value`. +/// +/// The `to_value` function is implementable as: +/// +/// ``` +/// use serde::Serialize; +/// use serde_yaml::{Error, Value}; +/// +/// pub fn to_value(input: T) -> Result +/// where +/// T: Serialize, +/// { +/// input.serialize(serde_yaml::value::Serializer) +/// } +/// ``` +pub struct Serializer; + +impl ser::Serializer for Serializer { + type Ok = Value; + type Error = Error; + + type SerializeSeq = SerializeArray; + type SerializeTuple = SerializeArray; + type SerializeTupleStruct = SerializeArray; + type SerializeTupleVariant = SerializeTupleVariant; + type SerializeMap = SerializeMap; + type SerializeStruct = SerializeStruct; + type SerializeStructVariant = SerializeStructVariant; + + fn serialize_bool(self, v: bool) -> Result { + Ok(Value::Bool(v)) + } + + fn serialize_i8(self, v: i8) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_i16(self, v: i16) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_i32(self, v: i32) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_i64(self, v: i64) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_i128(self, v: i128) -> Result { + if let Ok(v) = u64::try_from(v) { + self.serialize_u64(v) + } else if let Ok(v) = i64::try_from(v) { + self.serialize_i64(v) + } else { + Ok(Value::String(v.to_string())) + } + } + + fn serialize_u8(self, v: u8) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_u16(self, v: u16) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_u32(self, v: u32) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_u64(self, v: u64) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_u128(self, v: u128) -> Result { + if let Ok(v) = u64::try_from(v) { + self.serialize_u64(v) + } else { + Ok(Value::String(v.to_string())) + } + } + + fn serialize_f32(self, v: f32) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_f64(self, v: f64) -> Result { + Ok(Value::Number(Number::from(v))) + } + + fn serialize_char(self, value: char) -> Result { + Ok(Value::String(value.to_string())) + } + + fn serialize_str(self, value: &str) -> Result { + Ok(Value::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result { + let vec = value + .iter() + .map(|&b| Value::Number(Number::from(b))) + .collect(); + Ok(Value::Sequence(vec)) + } + + fn serialize_unit(self) -> Result { + Ok(Value::Null) + } + + fn serialize_unit_struct(self, _name: &'static str) -> Result { + self.serialize_unit() + } + + fn serialize_unit_variant( + self, + _name: &str, + _variant_index: u32, + variant: &str, + ) -> Result { + Ok(Value::String(variant.to_owned())) + } + + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result + where + T: ?Sized + ser::Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant( + self, + _name: &str, + _variant_index: u32, + variant: &str, + value: &T, + ) -> Result + where + T: ?Sized + ser::Serialize, + { + if variant.is_empty() { + return Err(error::new(ErrorImpl::EmptyTag)); + } + Ok(Value::Tagged(Box::new(TaggedValue { + tag: Tag::new(variant), + value: to_value(value)?, + }))) + } + + fn serialize_none(self) -> Result { + self.serialize_unit() + } + + fn serialize_some(self, value: &V) -> Result + where + V: ?Sized + ser::Serialize, + { + value.serialize(self) + } + + fn serialize_seq(self, len: Option) -> Result { + let sequence = match len { + None => Sequence::new(), + Some(len) => Sequence::with_capacity(len), + }; + Ok(SerializeArray { sequence }) + } + + fn serialize_tuple(self, len: usize) -> Result { + self.serialize_seq(Some(len)) + } + + fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result { + self.serialize_seq(Some(len)) + } + + fn serialize_tuple_variant( + self, + _enum: &'static str, + _idx: u32, + variant: &'static str, + len: usize, + ) -> Result { + if variant.is_empty() { + return Err(error::new(ErrorImpl::EmptyTag)); + } + Ok(SerializeTupleVariant { + tag: variant, + sequence: Sequence::with_capacity(len), + }) + } + + fn serialize_map(self, len: Option) -> Result { + if len == Some(1) { + Ok(SerializeMap::CheckForTag) + } else { + Ok(SerializeMap::Untagged { + mapping: Mapping::new(), + next_key: None, + }) + } + } + + fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { + Ok(SerializeStruct { + mapping: Mapping::new(), + }) + } + + fn serialize_struct_variant( + self, + _enum: &'static str, + _idx: u32, + variant: &'static str, + _len: usize, + ) -> Result { + if variant.is_empty() { + return Err(error::new(ErrorImpl::EmptyTag)); + } + Ok(SerializeStructVariant { + tag: variant, + mapping: Mapping::new(), + }) + } +} + +pub struct SerializeArray { + sequence: Sequence, +} + +impl ser::SerializeSeq for SerializeArray { + type Ok = Value; + type Error = Error; + + fn serialize_element(&mut self, elem: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + self.sequence.push(to_value(elem)?); + Ok(()) + } + + fn end(self) -> Result { + Ok(Value::Sequence(self.sequence)) + } +} + +impl ser::SerializeTuple for SerializeArray { + type Ok = Value; + type Error = Error; + + fn serialize_element(&mut self, elem: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, elem) + } + + fn end(self) -> Result { + ser::SerializeSeq::end(self) + } +} + +impl ser::SerializeTupleStruct for SerializeArray { + type Ok = Value; + type Error = Error; + + fn serialize_field(&mut self, value: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, value) + } + + fn end(self) -> Result { + ser::SerializeSeq::end(self) + } +} + +pub struct SerializeTupleVariant { + tag: &'static str, + sequence: Sequence, +} + +impl ser::SerializeTupleVariant for SerializeTupleVariant { + type Ok = Value; + type Error = Error; + + fn serialize_field(&mut self, v: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.sequence.push(to_value(v)?); + Ok(()) + } + + fn end(self) -> Result { + Ok(Value::Tagged(Box::new(TaggedValue { + tag: Tag::new(self.tag), + value: Value::Sequence(self.sequence), + }))) + } +} + +pub enum SerializeMap { + CheckForTag, + Tagged(TaggedValue), + Untagged { + mapping: Mapping, + next_key: Option, + }, +} + +impl ser::SerializeMap for SerializeMap { + type Ok = Value; + type Error = Error; + + fn serialize_key(&mut self, key: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + let key = Some(to_value(key)?); + match self { + SerializeMap::CheckForTag => { + *self = SerializeMap::Untagged { + mapping: Mapping::new(), + next_key: key, + }; + } + SerializeMap::Tagged(tagged) => { + let mut mapping = Mapping::new(); + mapping.insert( + Value::String(tagged.tag.to_string()), + mem::take(&mut tagged.value), + ); + *self = SerializeMap::Untagged { + mapping, + next_key: key, + }; + } + SerializeMap::Untagged { next_key, .. } => *next_key = key, + } + Ok(()) + } + + fn serialize_value(&mut self, value: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + let (mapping, key) = match self { + SerializeMap::CheckForTag | SerializeMap::Tagged(_) => unreachable!(), + SerializeMap::Untagged { mapping, next_key } => (mapping, next_key), + }; + match key.take() { + Some(key) => mapping.insert(key, to_value(value)?), + None => panic!("serialize_value called before serialize_key"), + }; + Ok(()) + } + + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<()> + where + K: ?Sized + ser::Serialize, + V: ?Sized + ser::Serialize, + { + struct CheckForTag; + struct NotTag { + delegate: T, + } + + impl ser::Serializer for CheckForTag { + type Ok = MaybeTag; + type Error = Error; + + type SerializeSeq = NotTag; + type SerializeTuple = NotTag; + type SerializeTupleStruct = NotTag; + type SerializeTupleVariant = NotTag; + type SerializeMap = NotTag; + type SerializeStruct = NotTag; + type SerializeStructVariant = NotTag; + + fn serialize_bool(self, v: bool) -> Result { + Serializer.serialize_bool(v).map(MaybeTag::NotTag) + } + + fn serialize_i8(self, v: i8) -> Result { + Serializer.serialize_i8(v).map(MaybeTag::NotTag) + } + + fn serialize_i16(self, v: i16) -> Result { + Serializer.serialize_i16(v).map(MaybeTag::NotTag) + } + + fn serialize_i32(self, v: i32) -> Result { + Serializer.serialize_i32(v).map(MaybeTag::NotTag) + } + + fn serialize_i64(self, v: i64) -> Result { + Serializer.serialize_i64(v).map(MaybeTag::NotTag) + } + + fn serialize_i128(self, v: i128) -> Result { + Serializer.serialize_i128(v).map(MaybeTag::NotTag) + } + + fn serialize_u8(self, v: u8) -> Result { + Serializer.serialize_u8(v).map(MaybeTag::NotTag) + } + + fn serialize_u16(self, v: u16) -> Result { + Serializer.serialize_u16(v).map(MaybeTag::NotTag) + } + + fn serialize_u32(self, v: u32) -> Result { + Serializer.serialize_u32(v).map(MaybeTag::NotTag) + } + + fn serialize_u64(self, v: u64) -> Result { + Serializer.serialize_u64(v).map(MaybeTag::NotTag) + } + + fn serialize_u128(self, v: u128) -> Result { + Serializer.serialize_u128(v).map(MaybeTag::NotTag) + } + + fn serialize_f32(self, v: f32) -> Result { + Serializer.serialize_f32(v).map(MaybeTag::NotTag) + } + + fn serialize_f64(self, v: f64) -> Result { + Serializer.serialize_f64(v).map(MaybeTag::NotTag) + } + + fn serialize_char(self, value: char) -> Result { + Serializer.serialize_char(value).map(MaybeTag::NotTag) + } + + fn serialize_str(self, value: &str) -> Result { + Serializer.serialize_str(value).map(MaybeTag::NotTag) + } + + fn serialize_bytes(self, value: &[u8]) -> Result { + Serializer.serialize_bytes(value).map(MaybeTag::NotTag) + } + + fn serialize_unit(self) -> Result { + Serializer.serialize_unit().map(MaybeTag::NotTag) + } + + fn serialize_unit_struct(self, name: &'static str) -> Result { + Serializer.serialize_unit_struct(name).map(MaybeTag::NotTag) + } + + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result { + Serializer + .serialize_unit_variant(name, variant_index, variant) + .map(MaybeTag::NotTag) + } + + fn serialize_newtype_struct(self, name: &'static str, value: &T) -> Result + where + T: ?Sized + ser::Serialize, + { + Serializer + .serialize_newtype_struct(name, value) + .map(MaybeTag::NotTag) + } + + fn serialize_newtype_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + ser::Serialize, + { + Serializer + .serialize_newtype_variant(name, variant_index, variant, value) + .map(MaybeTag::NotTag) + } + + fn serialize_none(self) -> Result { + Serializer.serialize_none().map(MaybeTag::NotTag) + } + + fn serialize_some(self, value: &V) -> Result + where + V: ?Sized + ser::Serialize, + { + Serializer.serialize_some(value).map(MaybeTag::NotTag) + } + + fn serialize_seq(self, len: Option) -> Result { + Ok(NotTag { + delegate: Serializer.serialize_seq(len)?, + }) + } + + fn serialize_tuple(self, len: usize) -> Result { + Ok(NotTag { + delegate: Serializer.serialize_tuple(len)?, + }) + } + + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(NotTag { + delegate: Serializer.serialize_tuple_struct(name, len)?, + }) + } + + fn serialize_tuple_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + Ok(NotTag { + delegate: Serializer.serialize_tuple_variant( + name, + variant_index, + variant, + len, + )?, + }) + } + + fn serialize_map(self, len: Option) -> Result { + Ok(NotTag { + delegate: Serializer.serialize_map(len)?, + }) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(NotTag { + delegate: Serializer.serialize_struct(name, len)?, + }) + } + + fn serialize_struct_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + Ok(NotTag { + delegate: Serializer.serialize_struct_variant( + name, + variant_index, + variant, + len, + )?, + }) + } + + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display, + { + Ok(match tagged::check_for_tag(value) { + MaybeTag::Tag(tag) => MaybeTag::Tag(tag), + MaybeTag::NotTag(string) => MaybeTag::NotTag(Value::String(string)), + }) + } + } + + impl ser::SerializeSeq for NotTag { + type Ok = MaybeTag; + type Error = Error; + + fn serialize_element(&mut self, elem: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + self.delegate.serialize_element(elem) + } + + fn end(self) -> Result { + self.delegate.end().map(MaybeTag::NotTag) + } + } + + impl ser::SerializeTuple for NotTag { + type Ok = MaybeTag; + type Error = Error; + + fn serialize_element(&mut self, elem: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + self.delegate.serialize_element(elem) + } + + fn end(self) -> Result { + self.delegate.end().map(MaybeTag::NotTag) + } + } + + impl ser::SerializeTupleStruct for NotTag { + type Ok = MaybeTag; + type Error = Error; + + fn serialize_field(&mut self, value: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.delegate.serialize_field(value) + } + + fn end(self) -> Result { + self.delegate.end().map(MaybeTag::NotTag) + } + } + + impl ser::SerializeTupleVariant for NotTag { + type Ok = MaybeTag; + type Error = Error; + + fn serialize_field(&mut self, v: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.delegate.serialize_field(v) + } + + fn end(self) -> Result { + self.delegate.end().map(MaybeTag::NotTag) + } + } + + impl ser::SerializeMap for NotTag { + type Ok = MaybeTag; + type Error = Error; + + fn serialize_key(&mut self, key: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + self.delegate.serialize_key(key) + } + + fn serialize_value(&mut self, value: &T) -> Result<()> + where + T: ?Sized + ser::Serialize, + { + self.delegate.serialize_value(value) + } + + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<()> + where + K: ?Sized + ser::Serialize, + V: ?Sized + ser::Serialize, + { + self.delegate.serialize_entry(key, value) + } + + fn end(self) -> Result { + self.delegate.end().map(MaybeTag::NotTag) + } + } + + impl ser::SerializeStruct for NotTag { + type Ok = MaybeTag; + type Error = Error; + + fn serialize_field(&mut self, key: &'static str, value: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.delegate.serialize_field(key, value) + } + + fn end(self) -> Result { + self.delegate.end().map(MaybeTag::NotTag) + } + } + + impl ser::SerializeStructVariant for NotTag { + type Ok = MaybeTag; + type Error = Error; + + fn serialize_field(&mut self, field: &'static str, v: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.delegate.serialize_field(field, v) + } + + fn end(self) -> Result { + self.delegate.end().map(MaybeTag::NotTag) + } + } + + match self { + SerializeMap::CheckForTag => { + let key = key.serialize(CheckForTag)?; + let mut mapping = Mapping::new(); + *self = match key { + MaybeTag::Tag(string) => SerializeMap::Tagged(TaggedValue { + tag: Tag::new(string), + value: to_value(value)?, + }), + MaybeTag::NotTag(key) => { + mapping.insert(key, to_value(value)?); + SerializeMap::Untagged { + mapping, + next_key: None, + } + } + }; + } + SerializeMap::Tagged(tagged) => { + let mut mapping = Mapping::new(); + mapping.insert( + Value::String(tagged.tag.to_string()), + mem::take(&mut tagged.value), + ); + mapping.insert(to_value(key)?, to_value(value)?); + *self = SerializeMap::Untagged { + mapping, + next_key: None, + }; + } + SerializeMap::Untagged { mapping, .. } => { + mapping.insert(to_value(key)?, to_value(value)?); + } + } + Ok(()) + } + + fn end(self) -> Result { + Ok(match self { + SerializeMap::CheckForTag => Value::Mapping(Mapping::new()), + SerializeMap::Tagged(tagged) => Value::Tagged(Box::new(tagged)), + SerializeMap::Untagged { mapping, .. } => Value::Mapping(mapping), + }) + } +} + +pub struct SerializeStruct { + mapping: Mapping, +} + +impl ser::SerializeStruct for SerializeStruct { + type Ok = Value; + type Error = Error; + + fn serialize_field(&mut self, key: &'static str, value: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.mapping.insert(to_value(key)?, to_value(value)?); + Ok(()) + } + + fn end(self) -> Result { + Ok(Value::Mapping(self.mapping)) + } +} + +pub struct SerializeStructVariant { + tag: &'static str, + mapping: Mapping, +} + +impl ser::SerializeStructVariant for SerializeStructVariant { + type Ok = Value; + type Error = Error; + + fn serialize_field(&mut self, field: &'static str, v: &V) -> Result<()> + where + V: ?Sized + ser::Serialize, + { + self.mapping.insert(to_value(field)?, to_value(v)?); + Ok(()) + } + + fn end(self) -> Result { + Ok(Value::Tagged(Box::new(TaggedValue { + tag: Tag::new(self.tag), + value: Value::Mapping(self.mapping), + }))) + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/value/tagged.rs b/bitbox02-bt/vendor/serde_yaml/src/value/tagged.rs new file mode 100644 index 0000000..baf6a0a --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/value/tagged.rs @@ -0,0 +1,474 @@ +use crate::value::de::{MapDeserializer, MapRefDeserializer, SeqDeserializer, SeqRefDeserializer}; +use crate::value::Value; +use crate::Error; +use serde::de::value::{BorrowedStrDeserializer, StrDeserializer}; +use serde::de::{ + Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error as _, VariantAccess, Visitor, +}; +use serde::forward_to_deserialize_any; +use serde::ser::{Serialize, SerializeMap, Serializer}; +use std::cmp::Ordering; +use std::fmt::{self, Debug, Display}; +use std::hash::{Hash, Hasher}; +use std::mem; + +/// A representation of YAML's `!Tag` syntax, used for enums. +/// +/// Refer to the example code on [`TaggedValue`] for an example of deserializing +/// tagged values. +#[derive(Clone)] +pub struct Tag { + pub(crate) string: String, +} + +/// A `Tag` + `Value` representing a tagged YAML scalar, sequence, or mapping. +/// +/// ``` +/// use serde_yaml::value::TaggedValue; +/// use std::collections::BTreeMap; +/// +/// let yaml = " +/// scalar: !Thing x +/// sequence_flow: !Thing [first] +/// sequence_block: !Thing +/// - first +/// mapping_flow: !Thing {k: v} +/// mapping_block: !Thing +/// k: v +/// "; +/// +/// let data: BTreeMap = serde_yaml::from_str(yaml).unwrap(); +/// assert!(data["scalar"].tag == "Thing"); +/// assert!(data["sequence_flow"].tag == "Thing"); +/// assert!(data["sequence_block"].tag == "Thing"); +/// assert!(data["mapping_flow"].tag == "Thing"); +/// assert!(data["mapping_block"].tag == "Thing"); +/// +/// // The leading '!' in tags are not significant. The following is also true. +/// assert!(data["scalar"].tag == "!Thing"); +/// ``` +#[derive(Clone, PartialEq, PartialOrd, Hash, Debug)] +pub struct TaggedValue { + #[allow(missing_docs)] + pub tag: Tag, + #[allow(missing_docs)] + pub value: Value, +} + +impl Tag { + /// Create tag. + /// + /// The leading '!' is not significant. It may be provided, but does not + /// have to be. The following are equivalent: + /// + /// ``` + /// use serde_yaml::value::Tag; + /// + /// assert_eq!(Tag::new("!Thing"), Tag::new("Thing")); + /// + /// let tag = Tag::new("Thing"); + /// assert!(tag == "Thing"); + /// assert!(tag == "!Thing"); + /// assert!(tag.to_string() == "!Thing"); + /// + /// let tag = Tag::new("!Thing"); + /// assert!(tag == "Thing"); + /// assert!(tag == "!Thing"); + /// assert!(tag.to_string() == "!Thing"); + /// ``` + /// + /// Such a tag would serialize to `!Thing` in YAML regardless of whether a + /// '!' was included in the call to `Tag::new`. + /// + /// # Panics + /// + /// Panics if `string.is_empty()`. There is no syntax in YAML for an empty + /// tag. + pub fn new(string: impl Into) -> Self { + let tag: String = string.into(); + assert!(!tag.is_empty(), "empty YAML tag is not allowed"); + Tag { string: tag } + } +} + +impl Value { + pub(crate) fn untag(self) -> Self { + let mut cur = self; + while let Value::Tagged(tagged) = cur { + cur = tagged.value; + } + cur + } + + pub(crate) fn untag_ref(&self) -> &Self { + let mut cur = self; + while let Value::Tagged(tagged) = cur { + cur = &tagged.value; + } + cur + } + + pub(crate) fn untag_mut(&mut self) -> &mut Self { + let mut cur = self; + while let Value::Tagged(tagged) = cur { + cur = &mut tagged.value; + } + cur + } +} + +pub(crate) fn nobang(maybe_banged: &str) -> &str { + match maybe_banged.strip_prefix('!') { + Some("") | None => maybe_banged, + Some(unbanged) => unbanged, + } +} + +impl Eq for Tag {} + +impl PartialEq for Tag { + fn eq(&self, other: &Tag) -> bool { + PartialEq::eq(nobang(&self.string), nobang(&other.string)) + } +} + +impl PartialEq for Tag +where + T: ?Sized + AsRef, +{ + fn eq(&self, other: &T) -> bool { + PartialEq::eq(nobang(&self.string), nobang(other.as_ref())) + } +} + +impl Ord for Tag { + fn cmp(&self, other: &Self) -> Ordering { + Ord::cmp(nobang(&self.string), nobang(&other.string)) + } +} + +impl PartialOrd for Tag { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Hash for Tag { + fn hash(&self, hasher: &mut H) { + nobang(&self.string).hash(hasher); + } +} + +impl Display for Tag { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "!{}", nobang(&self.string)) + } +} + +impl Debug for Tag { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(self, formatter) + } +} + +impl Serialize for TaggedValue { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + struct SerializeTag<'a>(&'a Tag); + + impl<'a> Serialize for SerializeTag<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.collect_str(self.0) + } + } + + let mut map = serializer.serialize_map(Some(1))?; + map.serialize_entry(&SerializeTag(&self.tag), &self.value)?; + map.end() + } +} + +impl<'de> Deserialize<'de> for TaggedValue { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct TaggedValueVisitor; + + impl<'de> Visitor<'de> for TaggedValueVisitor { + type Value = TaggedValue; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a YAML value with a !Tag") + } + + fn visit_enum(self, data: A) -> Result + where + A: EnumAccess<'de>, + { + let (tag, contents) = data.variant_seed(TagStringVisitor)?; + let value = contents.newtype_variant()?; + Ok(TaggedValue { tag, value }) + } + } + + deserializer.deserialize_any(TaggedValueVisitor) + } +} + +impl<'de> Deserializer<'de> for TaggedValue { + type Error = Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_enum(self) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + drop(self); + visitor.visit_unit() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier + } +} + +impl<'de> EnumAccess<'de> for TaggedValue { + type Error = Error; + type Variant = Value; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Error> + where + V: DeserializeSeed<'de>, + { + let tag = StrDeserializer::::new(nobang(&self.tag.string)); + let value = seed.deserialize(tag)?; + Ok((value, self.value)) + } +} + +impl<'de> VariantAccess<'de> for Value { + type Error = Error; + + fn unit_variant(self) -> Result<(), Error> { + Deserialize::deserialize(self) + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + seed.deserialize(self) + } + + fn tuple_variant(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + if let Value::Sequence(v) = self { + Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) + } else { + Err(Error::invalid_type(self.unexpected(), &"tuple variant")) + } + } + + fn struct_variant( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + if let Value::Mapping(v) = self { + Deserializer::deserialize_any(MapDeserializer::new(v), visitor) + } else { + Err(Error::invalid_type(self.unexpected(), &"struct variant")) + } + } +} + +impl<'de> Deserializer<'de> for &'de TaggedValue { + type Error = Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_enum(self) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier + } +} + +impl<'de> EnumAccess<'de> for &'de TaggedValue { + type Error = Error; + type Variant = &'de Value; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Error> + where + V: DeserializeSeed<'de>, + { + let tag = BorrowedStrDeserializer::::new(nobang(&self.tag.string)); + let value = seed.deserialize(tag)?; + Ok((value, &self.value)) + } +} + +impl<'de> VariantAccess<'de> for &'de Value { + type Error = Error; + + fn unit_variant(self) -> Result<(), Error> { + Deserialize::deserialize(self) + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + seed.deserialize(self) + } + + fn tuple_variant(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + if let Value::Sequence(v) = self { + Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) + } else { + Err(Error::invalid_type(self.unexpected(), &"tuple variant")) + } + } + + fn struct_variant( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + if let Value::Mapping(v) = self { + Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor) + } else { + Err(Error::invalid_type(self.unexpected(), &"struct variant")) + } + } +} + +pub(crate) struct TagStringVisitor; + +impl<'de> Visitor<'de> for TagStringVisitor { + type Value = Tag; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a YAML tag string") + } + + fn visit_str(self, string: &str) -> Result + where + E: serde::de::Error, + { + self.visit_string(string.to_owned()) + } + + fn visit_string(self, string: String) -> Result + where + E: serde::de::Error, + { + if string.is_empty() { + return Err(E::custom("empty YAML tag is not allowed")); + } + Ok(Tag::new(string)) + } +} + +impl<'de> DeserializeSeed<'de> for TagStringVisitor { + type Value = Tag; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(self) + } +} + +pub(crate) enum MaybeTag { + Tag(String), + NotTag(T), +} + +pub(crate) fn check_for_tag(value: &T) -> MaybeTag +where + T: ?Sized + Display, +{ + enum CheckForTag { + Empty, + Bang, + Tag(String), + NotTag(String), + } + + impl fmt::Write for CheckForTag { + fn write_str(&mut self, s: &str) -> fmt::Result { + if s.is_empty() { + return Ok(()); + } + match self { + CheckForTag::Empty => { + if s == "!" { + *self = CheckForTag::Bang; + } else { + *self = CheckForTag::NotTag(s.to_owned()); + } + } + CheckForTag::Bang => { + *self = CheckForTag::Tag(s.to_owned()); + } + CheckForTag::Tag(string) => { + let mut string = mem::take(string); + string.push_str(s); + *self = CheckForTag::NotTag(string); + } + CheckForTag::NotTag(string) => { + string.push_str(s); + } + } + Ok(()) + } + } + + let mut check_for_tag = CheckForTag::Empty; + fmt::write(&mut check_for_tag, format_args!("{}", value)).unwrap(); + match check_for_tag { + CheckForTag::Empty => MaybeTag::NotTag(String::new()), + CheckForTag::Bang => MaybeTag::NotTag("!".to_owned()), + CheckForTag::Tag(string) => MaybeTag::Tag(string), + CheckForTag::NotTag(string) => MaybeTag::NotTag(string), + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/src/with.rs b/bitbox02-bt/vendor/serde_yaml/src/with.rs new file mode 100644 index 0000000..d0bdc7c --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/src/with.rs @@ -0,0 +1,2124 @@ +//! Customizations to use with Serde's `#[serde(with = …)]` attribute. + +/// Serialize/deserialize an enum using a YAML map containing one entry in which +/// the key identifies the variant name. +/// +/// # Example +/// +/// ``` +/// # use serde_derive::{Deserialize, Serialize}; +/// use serde::{Deserialize, Serialize}; +/// +/// #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// enum Enum { +/// Unit, +/// Newtype(usize), +/// Tuple(usize, usize), +/// Struct { value: usize }, +/// } +/// +/// #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// struct Struct { +/// #[serde(with = "serde_yaml::with::singleton_map")] +/// w: Enum, +/// #[serde(with = "serde_yaml::with::singleton_map")] +/// x: Enum, +/// #[serde(with = "serde_yaml::with::singleton_map")] +/// y: Enum, +/// #[serde(with = "serde_yaml::with::singleton_map")] +/// z: Enum, +/// } +/// +/// fn main() { +/// let object = Struct { +/// w: Enum::Unit, +/// x: Enum::Newtype(1), +/// y: Enum::Tuple(1, 1), +/// z: Enum::Struct { value: 1 }, +/// }; +/// +/// let yaml = serde_yaml::to_string(&object).unwrap(); +/// print!("{}", yaml); +/// +/// let deserialized: Struct = serde_yaml::from_str(&yaml).unwrap(); +/// assert_eq!(object, deserialized); +/// } +/// ``` +/// +/// The representation using `singleton_map` on all the fields is: +/// +/// ```yaml +/// w: Unit +/// x: +/// Newtype: 1 +/// y: +/// Tuple: +/// - 1 +/// - 1 +/// z: +/// Struct: +/// value: 1 +/// ``` +/// +/// Without `singleton_map`, the default behavior would have been to serialize +/// as: +/// +/// ```yaml +/// w: Unit +/// x: !Newtype 1 +/// y: !Tuple +/// - 1 +/// - 1 +/// z: !Struct +/// value: 1 +/// ``` +pub mod singleton_map { + use crate::value::{Mapping, Sequence, Value}; + use serde::de::{ + self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, IgnoredAny, MapAccess, + Unexpected, VariantAccess, Visitor, + }; + use serde::ser::{ + self, Serialize, SerializeMap, SerializeStructVariant, SerializeTupleVariant, Serializer, + }; + use std::fmt::{self, Display}; + + #[allow(missing_docs)] + pub fn serialize(value: &T, serializer: S) -> Result + where + T: Serialize, + S: Serializer, + { + value.serialize(SingletonMap { + delegate: serializer, + }) + } + + #[allow(missing_docs)] + pub fn deserialize<'de, T, D>(deserializer: D) -> Result + where + T: Deserialize<'de>, + D: Deserializer<'de>, + { + T::deserialize(SingletonMap { + delegate: deserializer, + }) + } + + struct SingletonMap { + delegate: D, + } + + impl Serialize for SingletonMap + where + D: Serialize, + { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.delegate.serialize(SingletonMap { + delegate: serializer, + }) + } + } + + impl Serializer for SingletonMap + where + D: Serializer, + { + type Ok = D::Ok; + type Error = D::Error; + + type SerializeSeq = D::SerializeSeq; + type SerializeTuple = D::SerializeTuple; + type SerializeTupleStruct = D::SerializeTupleStruct; + type SerializeTupleVariant = SerializeTupleVariantAsSingletonMap; + type SerializeMap = D::SerializeMap; + type SerializeStruct = D::SerializeStruct; + type SerializeStructVariant = SerializeStructVariantAsSingletonMap; + + fn serialize_bool(self, v: bool) -> Result { + self.delegate.serialize_bool(v) + } + + fn serialize_i8(self, v: i8) -> Result { + self.delegate.serialize_i8(v) + } + + fn serialize_i16(self, v: i16) -> Result { + self.delegate.serialize_i16(v) + } + + fn serialize_i32(self, v: i32) -> Result { + self.delegate.serialize_i32(v) + } + + fn serialize_i64(self, v: i64) -> Result { + self.delegate.serialize_i64(v) + } + + fn serialize_i128(self, v: i128) -> Result { + self.delegate.serialize_i128(v) + } + + fn serialize_u8(self, v: u8) -> Result { + self.delegate.serialize_u8(v) + } + + fn serialize_u16(self, v: u16) -> Result { + self.delegate.serialize_u16(v) + } + + fn serialize_u32(self, v: u32) -> Result { + self.delegate.serialize_u32(v) + } + + fn serialize_u64(self, v: u64) -> Result { + self.delegate.serialize_u64(v) + } + + fn serialize_u128(self, v: u128) -> Result { + self.delegate.serialize_u128(v) + } + + fn serialize_f32(self, v: f32) -> Result { + self.delegate.serialize_f32(v) + } + + fn serialize_f64(self, v: f64) -> Result { + self.delegate.serialize_f64(v) + } + + fn serialize_char(self, v: char) -> Result { + self.delegate.serialize_char(v) + } + + fn serialize_str(self, v: &str) -> Result { + self.delegate.serialize_str(v) + } + + fn serialize_bytes(self, v: &[u8]) -> Result { + self.delegate.serialize_bytes(v) + } + + fn serialize_unit(self) -> Result { + self.delegate.serialize_unit() + } + + fn serialize_unit_struct(self, name: &'static str) -> Result { + self.delegate.serialize_unit_struct(name) + } + + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result { + self.delegate + .serialize_unit_variant(name, variant_index, variant) + } + + fn serialize_newtype_struct( + self, + name: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + self.delegate.serialize_newtype_struct(name, value) + } + + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + let mut map = self.delegate.serialize_map(Some(1))?; + map.serialize_entry(variant, value)?; + map.end() + } + + fn serialize_none(self) -> Result { + self.delegate.serialize_none() + } + + fn serialize_some(self, value: &V) -> Result + where + V: ?Sized + Serialize, + { + self.delegate + .serialize_some(&SingletonMap { delegate: value }) + } + + fn serialize_seq(self, len: Option) -> Result { + self.delegate.serialize_seq(len) + } + + fn serialize_tuple(self, len: usize) -> Result { + self.delegate.serialize_tuple(len) + } + + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + self.delegate.serialize_tuple_struct(name, len) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + let mut map = self.delegate.serialize_map(Some(1))?; + map.serialize_key(variant)?; + let sequence = Sequence::with_capacity(len); + Ok(SerializeTupleVariantAsSingletonMap { map, sequence }) + } + + fn serialize_map(self, len: Option) -> Result { + self.delegate.serialize_map(len) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + self.delegate.serialize_struct(name, len) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + let mut map = self.delegate.serialize_map(Some(1))?; + map.serialize_key(variant)?; + let mapping = Mapping::with_capacity(len); + Ok(SerializeStructVariantAsSingletonMap { map, mapping }) + } + + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display, + { + self.delegate.collect_str(value) + } + + fn is_human_readable(&self) -> bool { + self.delegate.is_human_readable() + } + } + + struct SerializeTupleVariantAsSingletonMap { + map: M, + sequence: Sequence, + } + + impl SerializeTupleVariant for SerializeTupleVariantAsSingletonMap + where + M: SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, field: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + let value = field + .serialize(crate::value::Serializer) + .map_err(ser::Error::custom)?; + self.sequence.push(value); + Ok(()) + } + + fn end(mut self) -> Result { + self.map.serialize_value(&self.sequence)?; + self.map.end() + } + } + + struct SerializeStructVariantAsSingletonMap { + map: M, + mapping: Mapping, + } + + impl SerializeStructVariant for SerializeStructVariantAsSingletonMap + where + M: SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, name: &'static str, field: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + let value = field + .serialize(crate::value::Serializer) + .map_err(ser::Error::custom)?; + self.mapping.insert(Value::String(name.to_owned()), value); + Ok(()) + } + + fn end(mut self) -> Result { + self.map.serialize_value(&self.mapping)?; + self.map.end() + } + } + + impl<'de, D> Deserializer<'de> for SingletonMap + where + D: Deserializer<'de>, + { + type Error = D::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_any(visitor) + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_bool(visitor) + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_i8(visitor) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_i16(visitor) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_i32(visitor) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_i64(visitor) + } + + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_i128(visitor) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_u8(visitor) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_u16(visitor) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_u32(visitor) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_u64(visitor) + } + + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_u128(visitor) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_f32(visitor) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_f64(visitor) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_char(visitor) + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_str(visitor) + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_string(visitor) + } + + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_bytes(visitor) + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_byte_buf(visitor) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_option(SingletonMapAsEnum { + name: "", + delegate: visitor, + }) + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_unit(visitor) + } + + fn deserialize_unit_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_unit_struct(name, visitor) + } + + fn deserialize_newtype_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_newtype_struct(name, visitor) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_seq(visitor) + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_tuple(len, visitor) + } + + fn deserialize_tuple_struct( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_tuple_struct(name, len, visitor) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_map(visitor) + } + + fn deserialize_struct( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_struct(name, fields, visitor) + } + + fn deserialize_enum( + self, + name: &'static str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_any(SingletonMapAsEnum { + name, + delegate: visitor, + }) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_identifier(visitor) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_ignored_any(visitor) + } + + fn is_human_readable(&self) -> bool { + self.delegate.is_human_readable() + } + } + + struct SingletonMapAsEnum { + name: &'static str, + delegate: D, + } + + impl<'de, V> Visitor<'de> for SingletonMapAsEnum + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.delegate.expecting(formatter) + } + + fn visit_str(self, v: &str) -> Result + where + E: de::Error, + { + self.delegate.visit_enum(de::value::StrDeserializer::new(v)) + } + + fn visit_borrowed_str(self, v: &'de str) -> Result + where + E: de::Error, + { + self.delegate + .visit_enum(de::value::BorrowedStrDeserializer::new(v)) + } + + fn visit_string(self, v: String) -> Result + where + E: de::Error, + { + self.delegate + .visit_enum(de::value::StringDeserializer::new(v)) + } + + fn visit_none(self) -> Result + where + E: de::Error, + { + self.delegate.visit_none() + } + + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + self.delegate.visit_some(SingletonMap { + delegate: deserializer, + }) + } + + fn visit_unit(self) -> Result + where + E: de::Error, + { + self.delegate.visit_unit() + } + + fn visit_map(self, map: A) -> Result + where + A: MapAccess<'de>, + { + self.delegate.visit_enum(SingletonMapAsEnum { + name: self.name, + delegate: map, + }) + } + } + + impl<'de, D> EnumAccess<'de> for SingletonMapAsEnum + where + D: MapAccess<'de>, + { + type Error = D::Error; + type Variant = Self; + + fn variant_seed(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: DeserializeSeed<'de>, + { + match self.delegate.next_key_seed(seed)? { + Some(value) => Ok((value, self)), + None => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + } + + impl<'de, D> VariantAccess<'de> for SingletonMapAsEnum + where + D: MapAccess<'de>, + { + type Error = D::Error; + + fn unit_variant(self) -> Result<(), Self::Error> { + Err(de::Error::invalid_type(Unexpected::Map, &"unit variant")) + } + + fn newtype_variant_seed(mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + let value = self.delegate.next_value_seed(seed)?; + match self.delegate.next_key()? { + None => Ok(value), + Some(IgnoredAny) => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + + fn tuple_variant(mut self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + let value = self + .delegate + .next_value_seed(TupleVariantSeed { len, visitor })?; + match self.delegate.next_key()? { + None => Ok(value), + Some(IgnoredAny) => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + + fn struct_variant( + mut self, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let value = self.delegate.next_value_seed(StructVariantSeed { + name: self.name, + fields, + visitor, + })?; + match self.delegate.next_key()? { + None => Ok(value), + Some(IgnoredAny) => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + } + + struct TupleVariantSeed { + len: usize, + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for TupleVariantSeed + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple(self.len, self.visitor) + } + } + + struct StructVariantSeed { + name: &'static str, + fields: &'static [&'static str], + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for StructVariantSeed + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_struct(self.name, self.fields, self.visitor) + } + } +} + +/// Apply [`singleton_map`] to *all* enums contained within the data structure. +/// +/// # Example +/// +/// ``` +/// # use serde_derive::{Deserialize, Serialize}; +/// use serde::{Deserialize, Serialize}; +/// +/// #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// enum Enum { +/// Int(i32), +/// } +/// +/// #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// struct Inner { +/// a: Enum, +/// bs: Vec, +/// } +/// +/// #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// struct Outer { +/// tagged_style: Inner, +/// +/// #[serde(with = "serde_yaml::with::singleton_map_recursive")] +/// singleton_map_style: Inner, +/// } +/// +/// fn main() { +/// let object = Outer { +/// tagged_style: Inner { +/// a: Enum::Int(0), +/// bs: vec![Enum::Int(1)], +/// }, +/// singleton_map_style: Inner { +/// a: Enum::Int(2), +/// bs: vec![Enum::Int(3)], +/// }, +/// }; +/// +/// let yaml = serde_yaml::to_string(&object).unwrap(); +/// print!("{}", yaml); +/// +/// let deserialized: Outer = serde_yaml::from_str(&yaml).unwrap(); +/// assert_eq!(object, deserialized); +/// } +/// ``` +/// +/// The serialized output is: +/// +/// ```yaml +/// tagged_style: +/// a: !Int 0 +/// bs: +/// - !Int 1 +/// singleton_map_style: +/// a: +/// Int: 2 +/// bs: +/// - Int: 3 +/// ``` +/// +/// This module can also be used for the top-level serializer or deserializer +/// call, without `serde(with = …)`, as follows. +/// +/// ``` +/// # use serde_derive::{Deserialize, Serialize}; +/// # use serde::{Deserialize, Serialize}; +/// # +/// # #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// # enum Enum { +/// # Int(i32), +/// # } +/// # +/// # #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// # struct Inner { +/// # a: Enum, +/// # bs: Vec, +/// # } +/// # +/// use std::io::{self, Write}; +/// +/// fn main() { +/// let object = Inner { +/// a: Enum::Int(0), +/// bs: vec![Enum::Int(1)], +/// }; +/// +/// let mut buf = Vec::new(); +/// let mut serializer = serde_yaml::Serializer::new(&mut buf); +/// serde_yaml::with::singleton_map_recursive::serialize(&object, &mut serializer).unwrap(); +/// io::stdout().write_all(&buf).unwrap(); +/// +/// let deserializer = serde_yaml::Deserializer::from_slice(&buf); +/// let deserialized: Inner = serde_yaml::with::singleton_map_recursive::deserialize(deserializer).unwrap(); +/// assert_eq!(object, deserialized); +/// } +/// ``` +pub mod singleton_map_recursive { + use crate::value::{Mapping, Sequence, Value}; + use serde::de::{ + self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, IgnoredAny, MapAccess, + SeqAccess, Unexpected, VariantAccess, Visitor, + }; + use serde::ser::{ + self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, + SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer, + }; + use std::fmt::{self, Display}; + + #[allow(missing_docs)] + pub fn serialize(value: &T, serializer: S) -> Result + where + T: Serialize, + S: Serializer, + { + value.serialize(SingletonMapRecursive { + delegate: serializer, + }) + } + + #[allow(missing_docs)] + pub fn deserialize<'de, T, D>(deserializer: D) -> Result + where + T: Deserialize<'de>, + D: Deserializer<'de>, + { + T::deserialize(SingletonMapRecursive { + delegate: deserializer, + }) + } + + struct SingletonMapRecursive { + delegate: D, + } + + impl Serialize for SingletonMapRecursive + where + D: Serialize, + { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.delegate.serialize(SingletonMapRecursive { + delegate: serializer, + }) + } + } + + impl Serializer for SingletonMapRecursive + where + D: Serializer, + { + type Ok = D::Ok; + type Error = D::Error; + + type SerializeSeq = SingletonMapRecursive; + type SerializeTuple = SingletonMapRecursive; + type SerializeTupleStruct = SingletonMapRecursive; + type SerializeTupleVariant = SerializeTupleVariantAsSingletonMapRecursive; + type SerializeMap = SingletonMapRecursive; + type SerializeStruct = SingletonMapRecursive; + type SerializeStructVariant = + SerializeStructVariantAsSingletonMapRecursive; + + fn serialize_bool(self, v: bool) -> Result { + self.delegate.serialize_bool(v) + } + + fn serialize_i8(self, v: i8) -> Result { + self.delegate.serialize_i8(v) + } + + fn serialize_i16(self, v: i16) -> Result { + self.delegate.serialize_i16(v) + } + + fn serialize_i32(self, v: i32) -> Result { + self.delegate.serialize_i32(v) + } + + fn serialize_i64(self, v: i64) -> Result { + self.delegate.serialize_i64(v) + } + + fn serialize_i128(self, v: i128) -> Result { + self.delegate.serialize_i128(v) + } + + fn serialize_u8(self, v: u8) -> Result { + self.delegate.serialize_u8(v) + } + + fn serialize_u16(self, v: u16) -> Result { + self.delegate.serialize_u16(v) + } + + fn serialize_u32(self, v: u32) -> Result { + self.delegate.serialize_u32(v) + } + + fn serialize_u64(self, v: u64) -> Result { + self.delegate.serialize_u64(v) + } + + fn serialize_u128(self, v: u128) -> Result { + self.delegate.serialize_u128(v) + } + + fn serialize_f32(self, v: f32) -> Result { + self.delegate.serialize_f32(v) + } + + fn serialize_f64(self, v: f64) -> Result { + self.delegate.serialize_f64(v) + } + + fn serialize_char(self, v: char) -> Result { + self.delegate.serialize_char(v) + } + + fn serialize_str(self, v: &str) -> Result { + self.delegate.serialize_str(v) + } + + fn serialize_bytes(self, v: &[u8]) -> Result { + self.delegate.serialize_bytes(v) + } + + fn serialize_unit(self) -> Result { + self.delegate.serialize_unit() + } + + fn serialize_unit_struct(self, name: &'static str) -> Result { + self.delegate.serialize_unit_struct(name) + } + + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result { + self.delegate + .serialize_unit_variant(name, variant_index, variant) + } + + fn serialize_newtype_struct( + self, + name: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + self.delegate + .serialize_newtype_struct(name, &SingletonMapRecursive { delegate: value }) + } + + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: ?Sized + Serialize, + { + let mut map = self.delegate.serialize_map(Some(1))?; + map.serialize_entry(variant, &SingletonMapRecursive { delegate: value })?; + map.end() + } + + fn serialize_none(self) -> Result { + self.delegate.serialize_none() + } + + fn serialize_some(self, value: &V) -> Result + where + V: ?Sized + Serialize, + { + self.delegate + .serialize_some(&SingletonMapRecursive { delegate: value }) + } + + fn serialize_seq(self, len: Option) -> Result { + Ok(SingletonMapRecursive { + delegate: self.delegate.serialize_seq(len)?, + }) + } + + fn serialize_tuple(self, len: usize) -> Result { + Ok(SingletonMapRecursive { + delegate: self.delegate.serialize_tuple(len)?, + }) + } + + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(SingletonMapRecursive { + delegate: self.delegate.serialize_tuple_struct(name, len)?, + }) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + let mut map = self.delegate.serialize_map(Some(1))?; + map.serialize_key(variant)?; + let sequence = Sequence::with_capacity(len); + Ok(SerializeTupleVariantAsSingletonMapRecursive { map, sequence }) + } + + fn serialize_map(self, len: Option) -> Result { + Ok(SingletonMapRecursive { + delegate: self.delegate.serialize_map(len)?, + }) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result { + Ok(SingletonMapRecursive { + delegate: self.delegate.serialize_struct(name, len)?, + }) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result { + let mut map = self.delegate.serialize_map(Some(1))?; + map.serialize_key(variant)?; + let mapping = Mapping::with_capacity(len); + Ok(SerializeStructVariantAsSingletonMapRecursive { map, mapping }) + } + + fn collect_str(self, value: &T) -> Result + where + T: ?Sized + Display, + { + self.delegate.collect_str(value) + } + + fn is_human_readable(&self) -> bool { + self.delegate.is_human_readable() + } + } + + impl SerializeSeq for SingletonMapRecursive + where + D: SerializeSeq, + { + type Ok = D::Ok; + type Error = D::Error; + + fn serialize_element(&mut self, elem: &T) -> Result<(), Self::Error> + where + T: ?Sized + ser::Serialize, + { + self.delegate + .serialize_element(&SingletonMapRecursive { delegate: elem }) + } + + fn end(self) -> Result { + self.delegate.end() + } + } + + impl SerializeTuple for SingletonMapRecursive + where + D: SerializeTuple, + { + type Ok = D::Ok; + type Error = D::Error; + + fn serialize_element(&mut self, elem: &T) -> Result<(), Self::Error> + where + T: ?Sized + ser::Serialize, + { + self.delegate + .serialize_element(&SingletonMapRecursive { delegate: elem }) + } + + fn end(self) -> Result { + self.delegate.end() + } + } + + impl SerializeTupleStruct for SingletonMapRecursive + where + D: SerializeTupleStruct, + { + type Ok = D::Ok; + type Error = D::Error; + + fn serialize_field(&mut self, value: &V) -> Result<(), Self::Error> + where + V: ?Sized + ser::Serialize, + { + self.delegate + .serialize_field(&SingletonMapRecursive { delegate: value }) + } + + fn end(self) -> Result { + self.delegate.end() + } + } + + struct SerializeTupleVariantAsSingletonMapRecursive { + map: M, + sequence: Sequence, + } + + impl SerializeTupleVariant for SerializeTupleVariantAsSingletonMapRecursive + where + M: SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, field: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + let value = field + .serialize(SingletonMapRecursive { + delegate: crate::value::Serializer, + }) + .map_err(ser::Error::custom)?; + self.sequence.push(value); + Ok(()) + } + + fn end(mut self) -> Result { + self.map.serialize_value(&self.sequence)?; + self.map.end() + } + } + + impl SerializeMap for SingletonMapRecursive + where + D: SerializeMap, + { + type Ok = D::Ok; + type Error = D::Error; + + fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> + where + T: ?Sized + ser::Serialize, + { + self.delegate + .serialize_key(&SingletonMapRecursive { delegate: key }) + } + + fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> + where + T: ?Sized + ser::Serialize, + { + self.delegate + .serialize_value(&SingletonMapRecursive { delegate: value }) + } + + fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), Self::Error> + where + K: ?Sized + ser::Serialize, + V: ?Sized + ser::Serialize, + { + self.delegate.serialize_entry( + &SingletonMapRecursive { delegate: key }, + &SingletonMapRecursive { delegate: value }, + ) + } + + fn end(self) -> Result { + self.delegate.end() + } + } + + impl SerializeStruct for SingletonMapRecursive + where + D: SerializeStruct, + { + type Ok = D::Ok; + type Error = D::Error; + + fn serialize_field(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error> + where + V: ?Sized + ser::Serialize, + { + self.delegate + .serialize_field(key, &SingletonMapRecursive { delegate: value }) + } + + fn end(self) -> Result { + self.delegate.end() + } + } + + struct SerializeStructVariantAsSingletonMapRecursive { + map: M, + mapping: Mapping, + } + + impl SerializeStructVariant for SerializeStructVariantAsSingletonMapRecursive + where + M: SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, name: &'static str, field: &T) -> Result<(), Self::Error> + where + T: ?Sized + Serialize, + { + let value = field + .serialize(SingletonMapRecursive { + delegate: crate::value::Serializer, + }) + .map_err(ser::Error::custom)?; + self.mapping.insert(Value::String(name.to_owned()), value); + Ok(()) + } + + fn end(mut self) -> Result { + self.map.serialize_value(&self.mapping)?; + self.map.end() + } + } + + impl<'de, D> Deserializer<'de> for SingletonMapRecursive + where + D: Deserializer<'de>, + { + type Error = D::Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_any(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_bool(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_bool(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_i8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_i8(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_i16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_i16(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_i32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_i32(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_i64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_i64(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_i128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_i128(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_u8(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_u8(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_u16(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_u16(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_u32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_u32(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_u64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_u64(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_u128(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_u128(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_f32(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_f32(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_f64(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_f64(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_char(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_str(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_str(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_string(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_string(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_bytes(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_bytes(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_byte_buf(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_option(SingletonMapRecursiveAsEnum { + name: "", + delegate: visitor, + }) + } + + fn deserialize_unit(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_unit(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_unit_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_unit_struct(name, SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_newtype_struct( + self, + name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_newtype_struct(name, SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_seq(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_seq(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_tuple(self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_tuple(len, SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_tuple_struct( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_tuple_struct( + name, + len, + SingletonMapRecursive { delegate: visitor }, + ) + } + + fn deserialize_map(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_map(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_struct( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_struct( + name, + fields, + SingletonMapRecursive { delegate: visitor }, + ) + } + + fn deserialize_enum( + self, + name: &'static str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + self.delegate.deserialize_any(SingletonMapRecursiveAsEnum { + name, + delegate: visitor, + }) + } + + fn deserialize_identifier(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_identifier(SingletonMapRecursive { delegate: visitor }) + } + + fn deserialize_ignored_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + self.delegate + .deserialize_ignored_any(SingletonMapRecursive { delegate: visitor }) + } + + fn is_human_readable(&self) -> bool { + self.delegate.is_human_readable() + } + } + + impl<'de, V> Visitor<'de> for SingletonMapRecursive + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.delegate.expecting(formatter) + } + + fn visit_bool(self, v: bool) -> Result + where + E: de::Error, + { + self.delegate.visit_bool(v) + } + + fn visit_i8(self, v: i8) -> Result + where + E: de::Error, + { + self.delegate.visit_i8(v) + } + + fn visit_i16(self, v: i16) -> Result + where + E: de::Error, + { + self.delegate.visit_i16(v) + } + + fn visit_i32(self, v: i32) -> Result + where + E: de::Error, + { + self.delegate.visit_i32(v) + } + + fn visit_i64(self, v: i64) -> Result + where + E: de::Error, + { + self.delegate.visit_i64(v) + } + + fn visit_i128(self, v: i128) -> Result + where + E: de::Error, + { + self.delegate.visit_i128(v) + } + + fn visit_u8(self, v: u8) -> Result + where + E: de::Error, + { + self.delegate.visit_u8(v) + } + + fn visit_u16(self, v: u16) -> Result + where + E: de::Error, + { + self.delegate.visit_u16(v) + } + + fn visit_u32(self, v: u32) -> Result + where + E: de::Error, + { + self.delegate.visit_u32(v) + } + + fn visit_u64(self, v: u64) -> Result + where + E: de::Error, + { + self.delegate.visit_u64(v) + } + + fn visit_u128(self, v: u128) -> Result + where + E: de::Error, + { + self.delegate.visit_u128(v) + } + + fn visit_f32(self, v: f32) -> Result + where + E: de::Error, + { + self.delegate.visit_f32(v) + } + + fn visit_f64(self, v: f64) -> Result + where + E: de::Error, + { + self.delegate.visit_f64(v) + } + + fn visit_char(self, v: char) -> Result + where + E: de::Error, + { + self.delegate.visit_char(v) + } + + fn visit_str(self, v: &str) -> Result + where + E: de::Error, + { + self.delegate.visit_str(v) + } + + fn visit_borrowed_str(self, v: &'de str) -> Result + where + E: de::Error, + { + self.delegate.visit_borrowed_str(v) + } + + fn visit_string(self, v: String) -> Result + where + E: de::Error, + { + self.delegate.visit_string(v) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where + E: de::Error, + { + self.delegate.visit_bytes(v) + } + + fn visit_borrowed_bytes(self, v: &'de [u8]) -> Result + where + E: de::Error, + { + self.delegate.visit_borrowed_bytes(v) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: de::Error, + { + self.delegate.visit_byte_buf(v) + } + + fn visit_none(self) -> Result + where + E: de::Error, + { + self.delegate.visit_none() + } + + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + self.delegate.visit_some(SingletonMapRecursive { + delegate: deserializer, + }) + } + + fn visit_unit(self) -> Result + where + E: de::Error, + { + self.delegate.visit_unit() + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + self.delegate.visit_newtype_struct(SingletonMapRecursive { + delegate: deserializer, + }) + } + + fn visit_seq(self, seq: A) -> Result + where + A: SeqAccess<'de>, + { + self.delegate + .visit_seq(SingletonMapRecursive { delegate: seq }) + } + + fn visit_map(self, map: A) -> Result + where + A: MapAccess<'de>, + { + self.delegate + .visit_map(SingletonMapRecursive { delegate: map }) + } + } + + impl<'de, T> DeserializeSeed<'de> for SingletonMapRecursive + where + T: DeserializeSeed<'de>, + { + type Value = T::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + self.delegate.deserialize(SingletonMapRecursive { + delegate: deserializer, + }) + } + } + + impl<'de, S> SeqAccess<'de> for SingletonMapRecursive + where + S: SeqAccess<'de>, + { + type Error = S::Error; + + fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> + where + T: DeserializeSeed<'de>, + { + self.delegate + .next_element_seed(SingletonMapRecursive { delegate: seed }) + } + } + + impl<'de, M> MapAccess<'de> for SingletonMapRecursive + where + M: MapAccess<'de>, + { + type Error = M::Error; + + fn next_key_seed(&mut self, seed: K) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + { + self.delegate + .next_key_seed(SingletonMapRecursive { delegate: seed }) + } + + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>, + { + self.delegate + .next_value_seed(SingletonMapRecursive { delegate: seed }) + } + } + + struct SingletonMapRecursiveAsEnum { + name: &'static str, + delegate: D, + } + + impl<'de, V> Visitor<'de> for SingletonMapRecursiveAsEnum + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.delegate.expecting(formatter) + } + + fn visit_str(self, v: &str) -> Result + where + E: de::Error, + { + self.delegate.visit_enum(de::value::StrDeserializer::new(v)) + } + + fn visit_borrowed_str(self, v: &'de str) -> Result + where + E: de::Error, + { + self.delegate + .visit_enum(de::value::BorrowedStrDeserializer::new(v)) + } + + fn visit_string(self, v: String) -> Result + where + E: de::Error, + { + self.delegate + .visit_enum(de::value::StringDeserializer::new(v)) + } + + fn visit_none(self) -> Result + where + E: de::Error, + { + self.delegate.visit_none() + } + + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + self.delegate.visit_some(SingletonMapRecursive { + delegate: deserializer, + }) + } + + fn visit_unit(self) -> Result + where + E: de::Error, + { + self.delegate.visit_unit() + } + + fn visit_map(self, map: A) -> Result + where + A: MapAccess<'de>, + { + self.delegate.visit_enum(SingletonMapRecursiveAsEnum { + name: self.name, + delegate: map, + }) + } + } + + impl<'de, D> EnumAccess<'de> for SingletonMapRecursiveAsEnum + where + D: MapAccess<'de>, + { + type Error = D::Error; + type Variant = Self; + + fn variant_seed(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: DeserializeSeed<'de>, + { + match self.delegate.next_key_seed(seed)? { + Some(value) => Ok((value, self)), + None => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + } + + impl<'de, D> VariantAccess<'de> for SingletonMapRecursiveAsEnum + where + D: MapAccess<'de>, + { + type Error = D::Error; + + fn unit_variant(self) -> Result<(), Self::Error> { + Err(de::Error::invalid_type(Unexpected::Map, &"unit variant")) + } + + fn newtype_variant_seed(mut self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + let value = self + .delegate + .next_value_seed(SingletonMapRecursive { delegate: seed })?; + match self.delegate.next_key()? { + None => Ok(value), + Some(IgnoredAny) => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + + fn tuple_variant(mut self, len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + let value = self.delegate.next_value_seed(TupleVariantSeed { + len, + visitor: SingletonMapRecursive { delegate: visitor }, + })?; + match self.delegate.next_key()? { + None => Ok(value), + Some(IgnoredAny) => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + + fn struct_variant( + mut self, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let value = self.delegate.next_value_seed(StructVariantSeed { + name: self.name, + fields, + visitor: SingletonMapRecursive { delegate: visitor }, + })?; + match self.delegate.next_key()? { + None => Ok(value), + Some(IgnoredAny) => Err(de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )), + } + } + } + + struct TupleVariantSeed { + len: usize, + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for TupleVariantSeed + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple(self.len, self.visitor) + } + } + + struct StructVariantSeed { + name: &'static str, + fields: &'static [&'static str], + visitor: V, + } + + impl<'de, V> DeserializeSeed<'de> for StructVariantSeed + where + V: Visitor<'de>, + { + type Value = V::Value; + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_struct(self.name, self.fields, self.visitor) + } + } +} diff --git a/bitbox02-bt/vendor/serde_yaml/tests/test_de.rs b/bitbox02-bt/vendor/serde_yaml/tests/test_de.rs new file mode 100644 index 0000000..b9e948d --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/tests/test_de.rs @@ -0,0 +1,717 @@ +#![allow( + clippy::cast_lossless, + clippy::cast_possible_wrap, + clippy::derive_partial_eq_without_eq, + clippy::similar_names, + clippy::uninlined_format_args +)] + +use indoc::indoc; +use serde_derive::Deserialize; +use serde_yaml::{Deserializer, Number, Value}; +use std::collections::BTreeMap; +use std::fmt::Debug; + +fn test_de(yaml: &str, expected: &T) +where + T: serde::de::DeserializeOwned + PartialEq + Debug, +{ + let deserialized: T = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(*expected, deserialized); + + let value: Value = serde_yaml::from_str(yaml).unwrap(); + let deserialized = T::deserialize(&value).unwrap(); + assert_eq!(*expected, deserialized); + + let deserialized: T = serde_yaml::from_value(value).unwrap(); + assert_eq!(*expected, deserialized); + + serde_yaml::from_str::(yaml).unwrap(); + + let mut deserializer = Deserializer::from_str(yaml); + let document = deserializer.next().unwrap(); + let deserialized = T::deserialize(document).unwrap(); + assert_eq!(*expected, deserialized); + assert!(deserializer.next().is_none()); +} + +fn test_de_no_value<'de, T>(yaml: &'de str, expected: &T) +where + T: serde::de::Deserialize<'de> + PartialEq + Debug, +{ + let deserialized: T = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(*expected, deserialized); + + serde_yaml::from_str::(yaml).unwrap(); + serde_yaml::from_str::(yaml).unwrap(); +} + +fn test_de_seed<'de, T, S>(yaml: &'de str, seed: S, expected: &T) +where + T: PartialEq + Debug, + S: serde::de::DeserializeSeed<'de, Value = T>, +{ + let deserialized: T = seed.deserialize(Deserializer::from_str(yaml)).unwrap(); + assert_eq!(*expected, deserialized); + + serde_yaml::from_str::(yaml).unwrap(); + serde_yaml::from_str::(yaml).unwrap(); +} + +#[test] +fn test_borrowed() { + let yaml = indoc! {" + - plain nonàscii + - 'single quoted' + - \"double quoted\" + "}; + let expected = vec!["plain nonàscii", "single quoted", "double quoted"]; + test_de_no_value(yaml, &expected); +} + +#[test] +fn test_alias() { + let yaml = indoc! {" + first: + &alias + 1 + second: + *alias + third: 3 + "}; + let mut expected = BTreeMap::new(); + expected.insert("first".to_owned(), 1); + expected.insert("second".to_owned(), 1); + expected.insert("third".to_owned(), 3); + test_de(yaml, &expected); +} + +#[test] +fn test_option() { + #[derive(Deserialize, PartialEq, Debug)] + struct Data { + a: Option, + b: Option, + c: Option, + } + let yaml = indoc! {" + b: + c: true + "}; + let expected = Data { + a: None, + b: None, + c: Some(true), + }; + test_de(yaml, &expected); +} + +#[test] +fn test_option_alias() { + #[derive(Deserialize, PartialEq, Debug)] + struct Data { + a: Option, + b: Option, + c: Option, + d: Option, + e: Option, + f: Option, + } + let yaml = indoc! {" + none_f: + &none_f + ~ + none_s: + &none_s + ~ + none_b: + &none_b + ~ + + some_f: + &some_f + 1.0 + some_s: + &some_s + x + some_b: + &some_b + true + + a: *none_f + b: *none_s + c: *none_b + d: *some_f + e: *some_s + f: *some_b + "}; + let expected = Data { + a: None, + b: None, + c: None, + d: Some(1.0), + e: Some("x".to_owned()), + f: Some(true), + }; + test_de(yaml, &expected); +} + +#[test] +fn test_enum_alias() { + #[derive(Deserialize, PartialEq, Debug)] + enum E { + A, + B(u8, u8), + } + #[derive(Deserialize, PartialEq, Debug)] + struct Data { + a: E, + b: E, + } + let yaml = indoc! {" + aref: + &aref + A + bref: + &bref + !B + - 1 + - 2 + + a: *aref + b: *bref + "}; + let expected = Data { + a: E::A, + b: E::B(1, 2), + }; + test_de(yaml, &expected); +} + +#[test] +fn test_enum_representations() { + #[derive(Deserialize, PartialEq, Debug)] + enum Enum { + Unit, + Tuple(i32, i32), + Struct { x: i32, y: i32 }, + String(String), + Number(f64), + } + + let yaml = indoc! {" + - Unit + - 'Unit' + - !Unit + - !Unit ~ + - !Unit null + - !Tuple [0, 0] + - !Tuple + - 0 + - 0 + - !Struct {x: 0, y: 0} + - !Struct + x: 0 + y: 0 + - !String '...' + - !String ... + - !Number 0 + "}; + + let expected = vec![ + Enum::Unit, + Enum::Unit, + Enum::Unit, + Enum::Unit, + Enum::Unit, + Enum::Tuple(0, 0), + Enum::Tuple(0, 0), + Enum::Struct { x: 0, y: 0 }, + Enum::Struct { x: 0, y: 0 }, + Enum::String("...".to_owned()), + Enum::String("...".to_owned()), + Enum::Number(0.0), + ]; + + test_de(yaml, &expected); + + let yaml = indoc! {" + - !String + "}; + let expected = vec![Enum::String(String::new())]; + test_de_no_value(yaml, &expected); +} + +#[test] +fn test_number_as_string() { + #[derive(Deserialize, PartialEq, Debug)] + struct Num { + value: String, + } + let yaml = indoc! {" + # Cannot be represented as u128 + value: 340282366920938463463374607431768211457 + "}; + let expected = Num { + value: "340282366920938463463374607431768211457".to_owned(), + }; + test_de_no_value(yaml, &expected); +} + +#[test] +fn test_empty_string() { + #[derive(Deserialize, PartialEq, Debug)] + struct Struct { + empty: String, + tilde: String, + } + let yaml = indoc! {" + empty: + tilde: ~ + "}; + let expected = Struct { + empty: String::new(), + tilde: "~".to_owned(), + }; + test_de_no_value(yaml, &expected); +} + +#[test] +fn test_i128_big() { + let expected: i128 = i64::MIN as i128 - 1; + let yaml = indoc! {" + -9223372036854775809 + "}; + assert_eq!(expected, serde_yaml::from_str::(yaml).unwrap()); + + let octal = indoc! {" + -0o1000000000000000000001 + "}; + assert_eq!(expected, serde_yaml::from_str::(octal).unwrap()); +} + +#[test] +fn test_u128_big() { + let expected: u128 = u64::MAX as u128 + 1; + let yaml = indoc! {" + 18446744073709551616 + "}; + assert_eq!(expected, serde_yaml::from_str::(yaml).unwrap()); + + let octal = indoc! {" + 0o2000000000000000000000 + "}; + assert_eq!(expected, serde_yaml::from_str::(octal).unwrap()); +} + +#[test] +fn test_number_alias_as_string() { + #[derive(Deserialize, PartialEq, Debug)] + struct Num { + version: String, + value: String, + } + let yaml = indoc! {" + version: &a 1.10 + value: *a + "}; + let expected = Num { + version: "1.10".to_owned(), + value: "1.10".to_owned(), + }; + test_de_no_value(yaml, &expected); +} + +#[test] +fn test_de_mapping() { + #[derive(Debug, Deserialize, PartialEq)] + struct Data { + pub substructure: serde_yaml::Mapping, + } + let yaml = indoc! {" + substructure: + a: 'foo' + b: 'bar' + "}; + + let mut expected = Data { + substructure: serde_yaml::Mapping::new(), + }; + expected.substructure.insert( + serde_yaml::Value::String("a".to_owned()), + serde_yaml::Value::String("foo".to_owned()), + ); + expected.substructure.insert( + serde_yaml::Value::String("b".to_owned()), + serde_yaml::Value::String("bar".to_owned()), + ); + + test_de(yaml, &expected); +} + +#[test] +fn test_byte_order_mark() { + let yaml = "\u{feff}- 0\n"; + let expected = vec![0]; + test_de(yaml, &expected); +} + +#[test] +fn test_bomb() { + #[derive(Debug, Deserialize, PartialEq)] + struct Data { + expected: String, + } + + // This would deserialize an astronomical number of elements if we were + // vulnerable. + let yaml = indoc! {" + a: &a ~ + b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a] + c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b] + d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c] + e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d] + f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e] + g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f] + h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g] + i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h] + j: &j [*i,*i,*i,*i,*i,*i,*i,*i,*i] + k: &k [*j,*j,*j,*j,*j,*j,*j,*j,*j] + l: &l [*k,*k,*k,*k,*k,*k,*k,*k,*k] + m: &m [*l,*l,*l,*l,*l,*l,*l,*l,*l] + n: &n [*m,*m,*m,*m,*m,*m,*m,*m,*m] + o: &o [*n,*n,*n,*n,*n,*n,*n,*n,*n] + p: &p [*o,*o,*o,*o,*o,*o,*o,*o,*o] + q: &q [*p,*p,*p,*p,*p,*p,*p,*p,*p] + r: &r [*q,*q,*q,*q,*q,*q,*q,*q,*q] + s: &s [*r,*r,*r,*r,*r,*r,*r,*r,*r] + t: &t [*s,*s,*s,*s,*s,*s,*s,*s,*s] + u: &u [*t,*t,*t,*t,*t,*t,*t,*t,*t] + v: &v [*u,*u,*u,*u,*u,*u,*u,*u,*u] + w: &w [*v,*v,*v,*v,*v,*v,*v,*v,*v] + x: &x [*w,*w,*w,*w,*w,*w,*w,*w,*w] + y: &y [*x,*x,*x,*x,*x,*x,*x,*x,*x] + z: &z [*y,*y,*y,*y,*y,*y,*y,*y,*y] + expected: string + "}; + + let expected = Data { + expected: "string".to_owned(), + }; + + assert_eq!(expected, serde_yaml::from_str::(yaml).unwrap()); +} + +#[test] +fn test_numbers() { + let cases = [ + ("0xF0", "240"), + ("+0xF0", "240"), + ("-0xF0", "-240"), + ("0o70", "56"), + ("+0o70", "56"), + ("-0o70", "-56"), + ("0b10", "2"), + ("+0b10", "2"), + ("-0b10", "-2"), + ("127", "127"), + ("+127", "127"), + ("-127", "-127"), + (".inf", ".inf"), + (".Inf", ".inf"), + (".INF", ".inf"), + ("-.inf", "-.inf"), + ("-.Inf", "-.inf"), + ("-.INF", "-.inf"), + (".nan", ".nan"), + (".NaN", ".nan"), + (".NAN", ".nan"), + ("0.1", "0.1"), + ]; + for &(yaml, expected) in &cases { + let value = serde_yaml::from_str::(yaml).unwrap(); + match value { + Value::Number(number) => assert_eq!(number.to_string(), expected), + _ => panic!("expected number. input={:?}, result={:?}", yaml, value), + } + } + + // NOT numbers. + let cases = [ + "0127", "+0127", "-0127", "++.inf", "+-.inf", "++1", "+-1", "-+1", "--1", "0x+1", "0x-1", + "-0x+1", "-0x-1", "++0x1", "+-0x1", "-+0x1", "--0x1", + ]; + for yaml in &cases { + let value = serde_yaml::from_str::(yaml).unwrap(); + match value { + Value::String(string) => assert_eq!(string, *yaml), + _ => panic!("expected string. input={:?}, result={:?}", yaml, value), + } + } +} + +#[test] +fn test_nan() { + // There is no negative NaN in YAML. + assert!(serde_yaml::from_str::(".nan") + .unwrap() + .is_sign_positive()); + assert!(serde_yaml::from_str::(".nan") + .unwrap() + .is_sign_positive()); +} + +#[test] +fn test_stateful() { + struct Seed(i64); + + impl<'de> serde::de::DeserializeSeed<'de> for Seed { + type Value = i64; + fn deserialize(self, deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { + struct Visitor(i64); + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = i64; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(formatter, "an integer") + } + + fn visit_i64(self, v: i64) -> Result { + Ok(v * self.0) + } + + fn visit_u64(self, v: u64) -> Result { + Ok(v as i64 * self.0) + } + } + + deserializer.deserialize_any(Visitor(self.0)) + } + } + + let cases = [("3", 5, 15), ("6", 7, 42), ("-5", 9, -45)]; + for &(yaml, seed, expected) in &cases { + test_de_seed(yaml, Seed(seed), &expected); + } +} + +#[test] +fn test_ignore_tag() { + #[derive(Deserialize, Debug, PartialEq)] + struct Data { + struc: Struc, + tuple: Tuple, + newtype: Newtype, + map: BTreeMap, + vec: Vec, + } + + #[derive(Deserialize, Debug, PartialEq)] + struct Struc { + x: usize, + } + + #[derive(Deserialize, Debug, PartialEq)] + struct Tuple(usize, usize); + + #[derive(Deserialize, Debug, PartialEq)] + struct Newtype(usize); + + let yaml = indoc! {" + struc: !wat + x: 0 + tuple: !wat + - 0 + - 0 + newtype: !wat 0 + map: !wat + x: 0 + vec: !wat + - 0 + "}; + + let expected = Data { + struc: Struc { x: 0 }, + tuple: Tuple(0, 0), + newtype: Newtype(0), + map: { + let mut map = BTreeMap::new(); + map.insert('x', 0); + map + }, + vec: vec![0], + }; + + test_de(yaml, &expected); +} + +#[test] +fn test_no_required_fields() { + #[derive(Deserialize, PartialEq, Debug)] + pub struct NoRequiredFields { + optional: Option, + } + + for document in ["", "# comment\n"] { + let expected = NoRequiredFields { optional: None }; + let deserialized: NoRequiredFields = serde_yaml::from_str(document).unwrap(); + assert_eq!(expected, deserialized); + + let expected = Vec::::new(); + let deserialized: Vec = serde_yaml::from_str(document).unwrap(); + assert_eq!(expected, deserialized); + + let expected = BTreeMap::new(); + let deserialized: BTreeMap = serde_yaml::from_str(document).unwrap(); + assert_eq!(expected, deserialized); + + let expected = None; + let deserialized: Option = serde_yaml::from_str(document).unwrap(); + assert_eq!(expected, deserialized); + + let expected = Value::Null; + let deserialized: Value = serde_yaml::from_str(document).unwrap(); + assert_eq!(expected, deserialized); + } +} + +#[test] +fn test_empty_scalar() { + #[derive(Deserialize, PartialEq, Debug)] + struct Struct { + thing: T, + } + + let yaml = "thing:\n"; + let expected = Struct { + thing: serde_yaml::Sequence::new(), + }; + test_de(yaml, &expected); + + let expected = Struct { + thing: serde_yaml::Mapping::new(), + }; + test_de(yaml, &expected); +} + +#[test] +fn test_python_safe_dump() { + #[derive(Deserialize, PartialEq, Debug)] + struct Frob { + foo: u32, + } + + // This matches output produced by PyYAML's `yaml.safe_dump` when using the + // default_style parameter. + // + // >>> import yaml + // >>> d = {"foo": 7200} + // >>> print(yaml.safe_dump(d, default_style="|")) + // "foo": !!int |- + // 7200 + // + let yaml = indoc! {r#" + "foo": !!int |- + 7200 + "#}; + + let expected = Frob { foo: 7200 }; + test_de(yaml, &expected); +} + +#[test] +fn test_tag_resolution() { + // https://yaml.org/spec/1.2.2/#1032-tag-resolution + let yaml = indoc! {" + - null + - Null + - NULL + - ~ + - + - true + - True + - TRUE + - false + - False + - FALSE + - y + - Y + - yes + - Yes + - YES + - n + - N + - no + - No + - NO + - on + - On + - ON + - off + - Off + - OFF + "}; + + let expected = vec![ + Value::Null, + Value::Null, + Value::Null, + Value::Null, + Value::Null, + Value::Bool(true), + Value::Bool(true), + Value::Bool(true), + Value::Bool(false), + Value::Bool(false), + Value::Bool(false), + Value::String("y".to_owned()), + Value::String("Y".to_owned()), + Value::String("yes".to_owned()), + Value::String("Yes".to_owned()), + Value::String("YES".to_owned()), + Value::String("n".to_owned()), + Value::String("N".to_owned()), + Value::String("no".to_owned()), + Value::String("No".to_owned()), + Value::String("NO".to_owned()), + Value::String("on".to_owned()), + Value::String("On".to_owned()), + Value::String("ON".to_owned()), + Value::String("off".to_owned()), + Value::String("Off".to_owned()), + Value::String("OFF".to_owned()), + ]; + + test_de(yaml, &expected); +} + +#[test] +fn test_parse_number() { + let n = "111".parse::().unwrap(); + assert_eq!(n, Number::from(111)); + + let n = "-111".parse::().unwrap(); + assert_eq!(n, Number::from(-111)); + + let n = "-1.1".parse::().unwrap(); + assert_eq!(n, Number::from(-1.1)); + + let n = ".nan".parse::().unwrap(); + assert_eq!(n, Number::from(f64::NAN)); + assert!(n.as_f64().unwrap().is_sign_positive()); + + let n = ".inf".parse::().unwrap(); + assert_eq!(n, Number::from(f64::INFINITY)); + + let n = "-.inf".parse::().unwrap(); + assert_eq!(n, Number::from(f64::NEG_INFINITY)); + + let err = "null".parse::().unwrap_err(); + assert_eq!(err.to_string(), "failed to parse YAML number"); + + let err = " 1 ".parse::().unwrap_err(); + assert_eq!(err.to_string(), "failed to parse YAML number"); +} diff --git a/bitbox02-bt/vendor/serde_yaml/tests/test_error.rs b/bitbox02-bt/vendor/serde_yaml/tests/test_error.rs new file mode 100644 index 0000000..883bb6d --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/tests/test_error.rs @@ -0,0 +1,500 @@ +#![allow(clippy::zero_sized_map_values)] + +use indoc::indoc; +use serde::de::Deserialize; +#[cfg(not(miri))] +use serde::de::{SeqAccess, Visitor}; +use serde_derive::{Deserialize, Serialize}; +use serde_yaml::value::{Tag, TaggedValue}; +use serde_yaml::{Deserializer, Value}; +#[cfg(not(miri))] +use std::collections::BTreeMap; +#[cfg(not(miri))] +use std::fmt; +use std::fmt::Debug; + +fn test_error<'de, T>(yaml: &'de str, expected: &str) +where + T: Deserialize<'de> + Debug, +{ + let result = serde_yaml::from_str::(yaml); + assert_eq!(expected, result.unwrap_err().to_string()); + + let mut deserializer = Deserializer::from_str(yaml); + if let Some(first_document) = deserializer.next() { + if deserializer.next().is_none() { + let result = T::deserialize(first_document); + assert_eq!(expected, result.unwrap_err().to_string()); + } + } +} + +#[test] +fn test_scan_error() { + let yaml = ">\n@"; + let expected = "found character that cannot start any token at line 2 column 1, while scanning for the next token"; + test_error::(yaml, expected); +} + +#[test] +fn test_incorrect_type() { + let yaml = indoc! {" + --- + str + "}; + let expected = "invalid type: string \"str\", expected i16 at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_incorrect_nested_type() { + #[derive(Deserialize, Debug)] + pub struct A { + #[allow(dead_code)] + pub b: Vec, + } + #[derive(Deserialize, Debug)] + pub enum B { + C(#[allow(dead_code)] C), + } + #[derive(Deserialize, Debug)] + pub struct C { + #[allow(dead_code)] + pub d: bool, + } + let yaml = indoc! {" + b: + - !C + d: fase + "}; + let expected = "b[0].d: invalid type: string \"fase\", expected a boolean at line 3 column 8"; + test_error::(yaml, expected); +} + +#[test] +fn test_empty() { + let expected = "EOF while parsing a value"; + test_error::("", expected); +} + +#[test] +fn test_missing_field() { + #[derive(Deserialize, Debug)] + pub struct Basic { + #[allow(dead_code)] + pub v: bool, + #[allow(dead_code)] + pub w: bool, + } + let yaml = indoc! {" + --- + v: true + "}; + let expected = "missing field `w` at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_unknown_anchor() { + let yaml = indoc! {" + --- + *some + "}; + let expected = "unknown anchor at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_ignored_unknown_anchor() { + #[derive(Deserialize, Debug)] + pub struct Wrapper { + #[allow(dead_code)] + pub c: (), + } + let yaml = indoc! {" + b: [*a] + c: ~ + "}; + let expected = "unknown anchor at line 1 column 5"; + test_error::(yaml, expected); +} + +#[test] +fn test_bytes() { + let expected = "serialization and deserialization of bytes in YAML is not implemented"; + test_error::<&[u8]>("...", expected); +} + +#[test] +fn test_two_documents() { + let yaml = indoc! {" + --- + 0 + --- + 1 + "}; + let expected = "deserializing from YAML containing more than one document is not supported"; + test_error::(yaml, expected); +} + +#[test] +fn test_second_document_syntax_error() { + let yaml = indoc! {" + --- + 0 + --- + ] + "}; + + let mut de = Deserializer::from_str(yaml); + let first_doc = de.next().unwrap(); + let result = ::deserialize(first_doc); + assert_eq!(0, result.unwrap()); + + let second_doc = de.next().unwrap(); + let result = ::deserialize(second_doc); + let expected = + "did not find expected node content at line 4 column 1, while parsing a block node"; + assert_eq!(expected, result.unwrap_err().to_string()); +} + +#[test] +fn test_missing_enum_tag() { + #[derive(Deserialize, Debug)] + pub enum E { + V(#[allow(dead_code)] usize), + } + let yaml = indoc! {r#" + "V": 16 + "other": 32 + "#}; + let expected = "invalid type: map, expected a YAML tag starting with '!'"; + test_error::(yaml, expected); +} + +#[test] +fn test_serialize_nested_enum() { + #[derive(Serialize, Debug)] + pub enum Outer { + Inner(Inner), + } + #[derive(Serialize, Debug)] + pub enum Inner { + Newtype(usize), + Tuple(usize, usize), + Struct { x: usize }, + } + + let expected = "serializing nested enums in YAML is not supported yet"; + + let e = Outer::Inner(Inner::Newtype(0)); + let error = serde_yaml::to_string(&e).unwrap_err(); + assert_eq!(error.to_string(), expected); + + let e = Outer::Inner(Inner::Tuple(0, 0)); + let error = serde_yaml::to_string(&e).unwrap_err(); + assert_eq!(error.to_string(), expected); + + let e = Outer::Inner(Inner::Struct { x: 0 }); + let error = serde_yaml::to_string(&e).unwrap_err(); + assert_eq!(error.to_string(), expected); + + let e = Value::Tagged(Box::new(TaggedValue { + tag: Tag::new("Outer"), + value: Value::Tagged(Box::new(TaggedValue { + tag: Tag::new("Inner"), + value: Value::Null, + })), + })); + let error = serde_yaml::to_string(&e).unwrap_err(); + assert_eq!(error.to_string(), expected); +} + +#[test] +fn test_deserialize_nested_enum() { + #[derive(Deserialize, Debug)] + pub enum Outer { + Inner(#[allow(dead_code)] Inner), + } + #[derive(Deserialize, Debug)] + pub enum Inner { + Variant(#[allow(dead_code)] Vec), + } + + let yaml = indoc! {" + --- + !Inner [] + "}; + let expected = "deserializing nested enum in Outer::Inner from YAML is not supported yet at line 2 column 1"; + test_error::(yaml, expected); + + let yaml = indoc! {" + --- + !Variant [] + "}; + let expected = "unknown variant `Variant`, expected `Inner`"; + test_error::(yaml, expected); + + let yaml = indoc! {" + --- + !Inner !Variant [] + "}; + let expected = "deserializing nested enum in Outer::Inner from YAML is not supported yet at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_variant_not_a_seq() { + #[derive(Deserialize, Debug)] + pub enum E { + V(#[allow(dead_code)] usize), + } + let yaml = indoc! {" + --- + !V + value: 0 + "}; + let expected = "invalid type: map, expected usize at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_struct_from_sequence() { + #[derive(Deserialize, Debug)] + pub struct Struct { + #[allow(dead_code)] + pub x: usize, + #[allow(dead_code)] + pub y: usize, + } + let yaml = indoc! {" + [0, 0] + "}; + let expected = "invalid type: sequence, expected struct Struct"; + test_error::(yaml, expected); +} + +#[test] +fn test_bad_bool() { + let yaml = indoc! {" + --- + !!bool str + "}; + let expected = "invalid value: string \"str\", expected a boolean at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_bad_int() { + let yaml = indoc! {" + --- + !!int str + "}; + let expected = "invalid value: string \"str\", expected an integer at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_bad_float() { + let yaml = indoc! {" + --- + !!float str + "}; + let expected = "invalid value: string \"str\", expected a float at line 2 column 1"; + test_error::(yaml, expected); +} + +#[test] +fn test_bad_null() { + let yaml = indoc! {" + --- + !!null str + "}; + let expected = "invalid value: string \"str\", expected null at line 2 column 1"; + test_error::<()>(yaml, expected); +} + +#[test] +fn test_short_tuple() { + let yaml = indoc! {" + --- + [0, 0] + "}; + let expected = "invalid length 2, expected a tuple of size 3 at line 2 column 1"; + test_error::<(u8, u8, u8)>(yaml, expected); +} + +#[test] +fn test_long_tuple() { + let yaml = indoc! {" + --- + [0, 0, 0] + "}; + let expected = "invalid length 3, expected sequence of 2 elements at line 2 column 1"; + test_error::<(u8, u8)>(yaml, expected); +} + +#[test] +fn test_invalid_scalar_type() { + #[derive(Deserialize, Debug)] + pub struct S { + #[allow(dead_code)] + pub x: [i32; 1], + } + + let yaml = "x: ''\n"; + let expected = "x: invalid type: string \"\", expected an array of length 1 at line 1 column 4"; + test_error::(yaml, expected); +} + +#[cfg(not(miri))] +#[test] +fn test_infinite_recursion_objects() { + #[derive(Deserialize, Debug)] + pub struct S { + #[allow(dead_code)] + pub x: Option>, + } + + let yaml = "&a {'x': *a}"; + let expected = "recursion limit exceeded"; + test_error::(yaml, expected); +} + +#[cfg(not(miri))] +#[test] +fn test_infinite_recursion_arrays() { + #[derive(Deserialize, Debug)] + pub struct S( + #[allow(dead_code)] pub usize, + #[allow(dead_code)] pub Option>, + ); + + let yaml = "&a [0, *a]"; + let expected = "recursion limit exceeded"; + test_error::(yaml, expected); +} + +#[cfg(not(miri))] +#[test] +fn test_infinite_recursion_newtype() { + #[derive(Deserialize, Debug)] + pub struct S(#[allow(dead_code)] pub Option>); + + let yaml = "&a [*a]"; + let expected = "recursion limit exceeded"; + test_error::(yaml, expected); +} + +#[cfg(not(miri))] +#[test] +fn test_finite_recursion_objects() { + #[derive(Deserialize, Debug)] + pub struct S { + #[allow(dead_code)] + pub x: Option>, + } + + let yaml = "{'x':".repeat(1_000) + &"}".repeat(1_000); + let expected = "recursion limit exceeded at line 1 column 641"; + test_error::(&yaml, expected); +} + +#[cfg(not(miri))] +#[test] +fn test_finite_recursion_arrays() { + #[derive(Deserialize, Debug)] + pub struct S( + #[allow(dead_code)] pub usize, + #[allow(dead_code)] pub Option>, + ); + + let yaml = "[0, ".repeat(1_000) + &"]".repeat(1_000); + let expected = "recursion limit exceeded at line 1 column 513"; + test_error::(&yaml, expected); +} + +#[cfg(not(miri))] +#[test] +fn test_billion_laughs() { + #[derive(Debug)] + struct X; + + impl<'de> Visitor<'de> for X { + type Value = X; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("exponential blowup") + } + + fn visit_unit(self) -> Result { + Ok(X) + } + + fn visit_seq(self, mut seq: S) -> Result + where + S: SeqAccess<'de>, + { + while let Some(X) = seq.next_element()? {} + Ok(X) + } + } + + impl<'de> Deserialize<'de> for X { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_any(X) + } + } + + let yaml = indoc! {" + a: &a ~ + b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a] + c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b] + d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c] + e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d] + f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e] + g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f] + h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g] + i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h] + "}; + let expected = "repetition limit exceeded"; + test_error::>(yaml, expected); +} + +#[test] +fn test_duplicate_keys() { + let yaml = indoc! {" + --- + thing: true + thing: false + "}; + let expected = "duplicate entry with key \"thing\" at line 2 column 1"; + test_error::(yaml, expected); + + let yaml = indoc! {" + --- + null: true + ~: false + "}; + let expected = "duplicate entry with null key at line 2 column 1"; + test_error::(yaml, expected); + + let yaml = indoc! {" + --- + 99: true + 99: false + "}; + let expected = "duplicate entry with key 99 at line 2 column 1"; + test_error::(yaml, expected); + + let yaml = indoc! {" + --- + {}: true + {}: false + "}; + let expected = "duplicate entry in YAML map at line 2 column 1"; + test_error::(yaml, expected); +} diff --git a/bitbox02-bt/vendor/serde_yaml/tests/test_serde.rs b/bitbox02-bt/vendor/serde_yaml/tests/test_serde.rs new file mode 100644 index 0000000..f16e89c --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/tests/test_serde.rs @@ -0,0 +1,578 @@ +#![allow( + clippy::decimal_literal_representation, + clippy::derive_partial_eq_without_eq, + clippy::unreadable_literal, + clippy::shadow_unrelated +)] + +use indoc::indoc; +use serde::ser::SerializeMap; +use serde_derive::{Deserialize, Serialize}; +use serde_yaml::{Mapping, Number, Value}; +use std::collections::BTreeMap; +use std::fmt::Debug; +use std::iter; + +fn test_serde(thing: &T, yaml: &str) +where + T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug, +{ + let serialized = serde_yaml::to_string(&thing).unwrap(); + assert_eq!(yaml, serialized); + + let value = serde_yaml::to_value(thing).unwrap(); + let serialized = serde_yaml::to_string(&value).unwrap(); + assert_eq!(yaml, serialized); + + let deserialized: T = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(*thing, deserialized); + + let value: Value = serde_yaml::from_str(yaml).unwrap(); + let deserialized = T::deserialize(&value).unwrap(); + assert_eq!(*thing, deserialized); + + let deserialized: T = serde_yaml::from_value(value).unwrap(); + assert_eq!(*thing, deserialized); + + serde_yaml::from_str::(yaml).unwrap(); +} + +#[test] +fn test_default() { + assert_eq!(Value::default(), Value::Null); +} + +#[test] +fn test_int() { + let thing = 256; + let yaml = indoc! {" + 256 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_int_max_u64() { + let thing = u64::MAX; + let yaml = indoc! {" + 18446744073709551615 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_int_min_i64() { + let thing = i64::MIN; + let yaml = indoc! {" + -9223372036854775808 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_int_max_i64() { + let thing = i64::MAX; + let yaml = indoc! {" + 9223372036854775807 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_i128_small() { + let thing: i128 = -256; + let yaml = indoc! {" + -256 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_u128_small() { + let thing: u128 = 256; + let yaml = indoc! {" + 256 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_float() { + let thing = 25.6; + let yaml = indoc! {" + 25.6 + "}; + test_serde(&thing, yaml); + + let thing = 25.; + let yaml = indoc! {" + 25.0 + "}; + test_serde(&thing, yaml); + + let thing = f64::INFINITY; + let yaml = indoc! {" + .inf + "}; + test_serde(&thing, yaml); + + let thing = f64::NEG_INFINITY; + let yaml = indoc! {" + -.inf + "}; + test_serde(&thing, yaml); + + let float: f64 = serde_yaml::from_str(indoc! {" + .nan + "}) + .unwrap(); + assert!(float.is_nan()); +} + +#[test] +fn test_float32() { + let thing: f32 = 25.5; + let yaml = indoc! {" + 25.5 + "}; + test_serde(&thing, yaml); + + let thing = f32::INFINITY; + let yaml = indoc! {" + .inf + "}; + test_serde(&thing, yaml); + + let thing = f32::NEG_INFINITY; + let yaml = indoc! {" + -.inf + "}; + test_serde(&thing, yaml); + + let single_float: f32 = serde_yaml::from_str(indoc! {" + .nan + "}) + .unwrap(); + assert!(single_float.is_nan()); +} + +#[test] +fn test_char() { + let ch = '.'; + let yaml = indoc! {" + '.' + "}; + assert_eq!(yaml, serde_yaml::to_string(&ch).unwrap()); + + let ch = '#'; + let yaml = indoc! {" + '#' + "}; + assert_eq!(yaml, serde_yaml::to_string(&ch).unwrap()); + + let ch = '-'; + let yaml = indoc! {" + '-' + "}; + assert_eq!(yaml, serde_yaml::to_string(&ch).unwrap()); +} + +#[test] +fn test_vec() { + let thing = vec![1, 2, 3]; + let yaml = indoc! {" + - 1 + - 2 + - 3 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_map() { + let mut thing = BTreeMap::new(); + thing.insert("x".to_owned(), 1); + thing.insert("y".to_owned(), 2); + let yaml = indoc! {" + x: 1 + y: 2 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_map_key_value() { + struct Map; + + impl serde::Serialize for Map { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + // Test maps which do not serialize using serialize_entry. + let mut map = serializer.serialize_map(Some(1))?; + map.serialize_key("k")?; + map.serialize_value("v")?; + map.end() + } + } + + let yaml = indoc! {" + k: v + "}; + assert_eq!(yaml, serde_yaml::to_string(&Map).unwrap()); +} + +#[test] +fn test_basic_struct() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Basic { + x: isize, + y: String, + z: bool, + } + let thing = Basic { + x: -4, + y: "hi\tquoted".to_owned(), + z: true, + }; + let yaml = indoc! {r#" + x: -4 + y: "hi\tquoted" + z: true + "#}; + test_serde(&thing, yaml); +} + +#[test] +fn test_string_escapes() { + let yaml = indoc! {" + ascii + "}; + test_serde(&"ascii".to_owned(), yaml); + + let yaml = indoc! {r#" + "\0\a\b\t\n\v\f\r\e\"\\\N\L\P" + "#}; + test_serde( + &"\0\u{7}\u{8}\t\n\u{b}\u{c}\r\u{1b}\"\\\u{85}\u{2028}\u{2029}".to_owned(), + yaml, + ); + + let yaml = indoc! {r#" + "\x1F\uFEFF" + "#}; + test_serde(&"\u{1f}\u{feff}".to_owned(), yaml); + + let yaml = indoc! {" + 🎉 + "}; + test_serde(&"\u{1f389}".to_owned(), yaml); +} + +#[test] +fn test_multiline_string() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Struct { + trailing_newline: String, + no_trailing_newline: String, + } + let thing = Struct { + trailing_newline: "aaa\nbbb\n".to_owned(), + no_trailing_newline: "aaa\nbbb".to_owned(), + }; + let yaml = indoc! {" + trailing_newline: | + aaa + bbb + no_trailing_newline: |- + aaa + bbb + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_strings_needing_quote() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Struct { + boolean: String, + integer: String, + void: String, + leading_zeros: String, + } + let thing = Struct { + boolean: "true".to_owned(), + integer: "1".to_owned(), + void: "null".to_owned(), + leading_zeros: "007".to_owned(), + }; + let yaml = indoc! {" + boolean: 'true' + integer: '1' + void: 'null' + leading_zeros: '007' + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_nested_vec() { + let thing = vec![vec![1, 2, 3], vec![4, 5, 6]]; + let yaml = indoc! {" + - - 1 + - 2 + - 3 + - - 4 + - 5 + - 6 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_nested_struct() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Outer { + inner: Inner, + } + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Inner { + v: u16, + } + let thing = Outer { + inner: Inner { v: 512 }, + }; + let yaml = indoc! {" + inner: + v: 512 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_nested_enum() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + enum Outer { + Inner(Inner), + } + #[derive(Serialize, Deserialize, PartialEq, Debug)] + enum Inner { + Unit, + } + let thing = Outer::Inner(Inner::Unit); + let yaml = indoc! {" + !Inner Unit + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_option() { + let thing = vec![Some(1), None, Some(3)]; + let yaml = indoc! {" + - 1 + - null + - 3 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_unit() { + let thing = vec![(), ()]; + let yaml = indoc! {" + - null + - null + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_unit_struct() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Foo; + let thing = Foo; + let yaml = indoc! {" + null + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_unit_variant() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + enum Variant { + First, + Second, + } + let thing = Variant::First; + let yaml = indoc! {" + First + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_newtype_struct() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct OriginalType { + v: u16, + } + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct NewType(OriginalType); + let thing = NewType(OriginalType { v: 1 }); + let yaml = indoc! {" + v: 1 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_newtype_variant() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + enum Variant { + Size(usize), + } + let thing = Variant::Size(127); + let yaml = indoc! {" + !Size 127 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_tuple_variant() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + enum Variant { + Rgb(u8, u8, u8), + } + let thing = Variant::Rgb(32, 64, 96); + let yaml = indoc! {" + !Rgb + - 32 + - 64 + - 96 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_struct_variant() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + enum Variant { + Color { r: u8, g: u8, b: u8 }, + } + let thing = Variant::Color { + r: 32, + g: 64, + b: 96, + }; + let yaml = indoc! {" + !Color + r: 32 + g: 64 + b: 96 + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_tagged_map_value() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Bindings { + profile: Profile, + } + #[derive(Serialize, Deserialize, PartialEq, Debug)] + enum Profile { + ClassValidator { class_name: String }, + } + let thing = Bindings { + profile: Profile::ClassValidator { + class_name: "ApplicationConfig".to_owned(), + }, + }; + let yaml = indoc! {" + profile: !ClassValidator + class_name: ApplicationConfig + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_value() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + pub struct GenericInstructions { + #[serde(rename = "type")] + pub typ: String, + pub config: Value, + } + let thing = GenericInstructions { + typ: "primary".to_string(), + config: Value::Sequence(vec![ + Value::Null, + Value::Bool(true), + Value::Number(Number::from(65535)), + Value::Number(Number::from(0.54321)), + Value::String("s".into()), + Value::Mapping(Mapping::new()), + ]), + }; + let yaml = indoc! {" + type: primary + config: + - null + - true + - 65535 + - 0.54321 + - s + - {} + "}; + test_serde(&thing, yaml); +} + +#[test] +fn test_mapping() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Data { + pub substructure: Mapping, + } + + let mut thing = Data { + substructure: Mapping::new(), + }; + thing.substructure.insert( + Value::String("a".to_owned()), + Value::String("foo".to_owned()), + ); + thing.substructure.insert( + Value::String("b".to_owned()), + Value::String("bar".to_owned()), + ); + + let yaml = indoc! {" + substructure: + a: foo + b: bar + "}; + + test_serde(&thing, yaml); +} + +#[test] +fn test_long_string() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct Data { + pub string: String, + } + + let thing = Data { + string: iter::repeat(["word", " "]).flatten().take(69).collect(), + }; + + let yaml = indoc! {" + string: word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word + "}; + + test_serde(&thing, yaml); +} diff --git a/bitbox02-bt/vendor/serde_yaml/tests/test_value.rs b/bitbox02-bt/vendor/serde_yaml/tests/test_value.rs new file mode 100644 index 0000000..cce8329 --- /dev/null +++ b/bitbox02-bt/vendor/serde_yaml/tests/test_value.rs @@ -0,0 +1,153 @@ +#![allow( + clippy::derive_partial_eq_without_eq, + clippy::eq_op, + clippy::uninlined_format_args +)] + +use indoc::indoc; +use serde::de::IntoDeserializer; +use serde::Deserialize; +use serde_derive::{Deserialize, Serialize}; +use serde_yaml::{Number, Value}; + +#[test] +fn test_nan() { + let pos_nan = serde_yaml::from_str::(".nan").unwrap(); + assert!(pos_nan.is_f64()); + assert_eq!(pos_nan, pos_nan); + + let neg_fake_nan = serde_yaml::from_str::("-.nan").unwrap(); + assert!(neg_fake_nan.is_string()); + + let significand_mask = 0xF_FFFF_FFFF_FFFF; + let bits = (f64::NAN.copysign(1.0).to_bits() ^ significand_mask) | 1; + let different_pos_nan = Value::Number(Number::from(f64::from_bits(bits))); + assert_eq!(pos_nan, different_pos_nan); +} + +#[test] +fn test_digits() { + let num_string = serde_yaml::from_str::("01").unwrap(); + assert!(num_string.is_string()); +} + +#[test] +fn test_into_deserializer() { + #[derive(Debug, Deserialize, PartialEq)] + struct Test { + first: String, + second: u32, + } + + let value = serde_yaml::from_str::("xyz").unwrap(); + let s = String::deserialize(value.into_deserializer()).unwrap(); + assert_eq!(s, "xyz"); + + let value = serde_yaml::from_str::("- first\n- second\n- third").unwrap(); + let arr = Vec::::deserialize(value.into_deserializer()).unwrap(); + assert_eq!(arr, &["first", "second", "third"]); + + let value = serde_yaml::from_str::("first: abc\nsecond: 99").unwrap(); + let test = Test::deserialize(value.into_deserializer()).unwrap(); + assert_eq!( + test, + Test { + first: "abc".to_string(), + second: 99 + } + ); +} + +#[test] +fn test_merge() { + // From https://yaml.org/type/merge.html. + let yaml = indoc! {" + --- + - &CENTER { x: 1, y: 2 } + - &LEFT { x: 0, y: 2 } + - &BIG { r: 10 } + - &SMALL { r: 1 } + + # All the following maps are equal: + + - # Explicit keys + x: 1 + y: 2 + r: 10 + label: center/big + + - # Merge one map + << : *CENTER + r: 10 + label: center/big + + - # Merge multiple maps + << : [ *CENTER, *BIG ] + label: center/big + + - # Override + << : [ *BIG, *LEFT, *SMALL ] + x: 1 + label: center/big + "}; + + let mut value: Value = serde_yaml::from_str(yaml).unwrap(); + value.apply_merge().unwrap(); + for i in 5..=7 { + assert_eq!(value[4], value[i]); + } +} + +#[test] +fn test_debug() { + let yaml = indoc! {" + 'Null': ~ + Bool: true + Number: 1 + String: ... + Sequence: + - true + EmptySequence: [] + EmptyMapping: {} + Tagged: !tag true + "}; + + let value: Value = serde_yaml::from_str(yaml).unwrap(); + let debug = format!("{:#?}", value); + + let expected = indoc! {r#" + Mapping { + "Null": Null, + "Bool": Bool(true), + "Number": Number(1), + "String": String("..."), + "Sequence": Sequence [ + Bool(true), + ], + "EmptySequence": Sequence [], + "EmptyMapping": Mapping {}, + "Tagged": TaggedValue { + tag: !tag, + value: Bool(true), + }, + }"# + }; + + assert_eq!(debug, expected); +} + +#[test] +fn test_tagged() { + #[derive(Serialize)] + enum Enum { + Variant(usize), + } + + let value = serde_yaml::to_value(&Enum::Variant(0)).unwrap(); + + let deserialized: serde_yaml::Value = serde_yaml::from_value(value.clone()).unwrap(); + assert_eq!(value, deserialized); + + let serialized = serde_yaml::to_value(&value).unwrap(); + assert_eq!(value, serialized); +} diff --git a/bitbox02-bt/vendor/shlex/.cargo-checksum.json b/bitbox02-bt/vendor/shlex/.cargo-checksum.json new file mode 100644 index 0000000..579ecbe --- /dev/null +++ b/bitbox02-bt/vendor/shlex/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"879a16b3fef6fb3251fcac516fe73414109e3b7df5eb2ec4863a7551674038a0","Cargo.toml":"d7eb8c4bce681b4dd1dfc2c98c649754390775f38f4796d491948ddbb53aa2ef","LICENSE-APACHE":"553fffcd9b1cb158bc3e9edc35da85ca5c3b3d7d2e61c883ebcfa8a65814b583","LICENSE-MIT":"4455bf75a91154108304cb283e0fea9948c14f13e20d60887cf2552449dea3b1","README.md":"082e505bba5dffc5904af5602b45d01129173e617db62c81e6c11d71c964ea71","src/bytes.rs":"eadfffcdb7846d341ba451d6118d275b9d0f14a9554984ccfcdbe9a8d77ec5ee","src/lib.rs":"44c8fb929e1443f2446d26025a9bcfca0b329811bbc309b4a6afb8ec17d7de8d","src/quoting_warning.md":"566d6509211ddcd4afbd4f1117c5234567f6b6d01f5da60acfaef011362be045"},"package":"0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/shlex/CHANGELOG.md b/bitbox02-bt/vendor/shlex/CHANGELOG.md new file mode 100644 index 0000000..95552b4 --- /dev/null +++ b/bitbox02-bt/vendor/shlex/CHANGELOG.md @@ -0,0 +1,21 @@ +# 1.2.0 + +* Adds `bytes` module to support operating directly on byte strings. + +# 1.1.0 + +* Adds the `std` feature (enabled by default) +* Disabling the `std` feature makes the crate work in `#![no_std]` mode, assuming presence of the `alloc` crate + +# 1.0.0 + +* Adds the `join` convenience function. +* Fixes parsing of `'\\n'` to match the behavior of bash/Zsh/Python `shlex`. The result was previously `\n`, now it is `\\n`. + +# 0.1.1 + +* Adds handling of `#` comments. + +# 0.1.0 + +This is the initial release. diff --git a/bitbox02-bt/vendor/shlex/Cargo.toml b/bitbox02-bt/vendor/shlex/Cargo.toml new file mode 100644 index 0000000..2b66892 --- /dev/null +++ b/bitbox02-bt/vendor/shlex/Cargo.toml @@ -0,0 +1,35 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +rust-version = "1.46.0" +name = "shlex" +version = "1.3.0" +authors = [ + "comex ", + "Fenhl ", + "Adrian Taylor ", + "Alex Touchet ", + "Daniel Parks ", + "Garrett Berg ", +] +description = "Split a string into shell words, like Python's shlex." +readme = "README.md" +categories = [ + "command-line-interface", + "parser-implementations", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/comex/rust-shlex" + +[features] +default = ["std"] +std = [] diff --git a/bitbox02-bt/vendor/shlex/LICENSE-APACHE b/bitbox02-bt/vendor/shlex/LICENSE-APACHE new file mode 100644 index 0000000..3746504 --- /dev/null +++ b/bitbox02-bt/vendor/shlex/LICENSE-APACHE @@ -0,0 +1,13 @@ +Copyright 2015 Nicholas Allegra (comex). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/shlex/LICENSE-MIT b/bitbox02-bt/vendor/shlex/LICENSE-MIT new file mode 100644 index 0000000..5ec1fe1 --- /dev/null +++ b/bitbox02-bt/vendor/shlex/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Nicholas Allegra (comex). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bitbox02-bt/vendor/shlex/README.md b/bitbox02-bt/vendor/shlex/README.md new file mode 100644 index 0000000..6400a6f --- /dev/null +++ b/bitbox02-bt/vendor/shlex/README.md @@ -0,0 +1,39 @@ +[![ci badge]][ci link] [![crates.io badge]][crates.io link] [![docs.rs badge]][docs.rs link] + +[crates.io badge]: https://img.shields.io/crates/v/shlex.svg?style=flat-square +[crates.io link]: https://crates.io/crates/shlex +[docs.rs badge]: https://img.shields.io/badge/docs-online-dddddd.svg?style=flat-square +[docs.rs link]: https://docs.rs/shlex +[ci badge]: https://img.shields.io/github/actions/workflow/status/comex/rust-shlex/test.yml?branch=master&style=flat-square +[ci link]: https://github.com/comex/rust-shlex/actions + +Same idea as (but implementation not directly based on) the Python shlex +module. However, this implementation does not support any of the Python +module's customization because it makes parsing slower and is fairly useless. +You only get the default settings of shlex.split, which mimic the POSIX shell: + + +This implementation also deviates from the Python version in not treating \r +specially, which I believe is more compliant. + +This crate can be used on either normal Rust strings, or on byte strings with +the `bytes` module. The algorithms used are oblivious to UTF-8 high bytes, so +internally they all work on bytes directly as a micro-optimization. + +Disabling the `std` feature (which is enabled by default) will allow the crate +to work in `no_std` environments, where the `alloc` crate, and a global +allocator, are available. + +# LICENSE + +The source code in this repository is Licensed under either of +- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + https://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or + https://opensource.org/licenses/MIT) + +at your option. + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. diff --git a/bitbox02-bt/vendor/shlex/src/bytes.rs b/bitbox02-bt/vendor/shlex/src/bytes.rs new file mode 100644 index 0000000..af8daad --- /dev/null +++ b/bitbox02-bt/vendor/shlex/src/bytes.rs @@ -0,0 +1,576 @@ +// Copyright 2015 Nicholas Allegra (comex). +// Licensed under the Apache License, Version 2.0 or +// the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +//! [`Shlex`] and friends for byte strings. +//! +//! This is used internally by the [outer module](crate), and may be more +//! convenient if you are working with byte slices (`[u8]`) or types that are +//! wrappers around bytes, such as [`OsStr`](std::ffi::OsStr): +//! +//! ```rust +//! #[cfg(unix)] { +//! use shlex::bytes::quote; +//! use std::ffi::OsStr; +//! use std::os::unix::ffi::OsStrExt; +//! +//! // `\x80` is invalid in UTF-8. +//! let os_str = OsStr::from_bytes(b"a\x80b c"); +//! assert_eq!(quote(os_str.as_bytes()), &b"'a\x80b c'"[..]); +//! } +//! ``` +//! +//! (On Windows, `OsStr` uses 16 bit wide characters so this will not work.) + +extern crate alloc; +use alloc::vec::Vec; +use alloc::borrow::Cow; +#[cfg(test)] +use alloc::vec; +#[cfg(test)] +use alloc::borrow::ToOwned; +#[cfg(all(doc, not(doctest)))] +use crate::{self as shlex, quoting_warning}; + +use super::QuoteError; + +/// An iterator that takes an input byte string and splits it into the words using the same syntax as +/// the POSIX shell. +pub struct Shlex<'a> { + in_iter: core::slice::Iter<'a, u8>, + /// The number of newlines read so far, plus one. + pub line_no: usize, + /// An input string is erroneous if it ends while inside a quotation or right after an + /// unescaped backslash. Since Iterator does not have a mechanism to return an error, if that + /// happens, Shlex just throws out the last token, ends the iteration, and sets 'had_error' to + /// true; best to check it after you're done iterating. + pub had_error: bool, +} + +impl<'a> Shlex<'a> { + pub fn new(in_bytes: &'a [u8]) -> Self { + Shlex { + in_iter: in_bytes.iter(), + line_no: 1, + had_error: false, + } + } + + fn parse_word(&mut self, mut ch: u8) -> Option> { + let mut result: Vec = Vec::new(); + loop { + match ch as char { + '"' => if let Err(()) = self.parse_double(&mut result) { + self.had_error = true; + return None; + }, + '\'' => if let Err(()) = self.parse_single(&mut result) { + self.had_error = true; + return None; + }, + '\\' => if let Some(ch2) = self.next_char() { + if ch2 != '\n' as u8 { result.push(ch2); } + } else { + self.had_error = true; + return None; + }, + ' ' | '\t' | '\n' => { break; }, + _ => { result.push(ch as u8); }, + } + if let Some(ch2) = self.next_char() { ch = ch2; } else { break; } + } + Some(result) + } + + fn parse_double(&mut self, result: &mut Vec) -> Result<(), ()> { + loop { + if let Some(ch2) = self.next_char() { + match ch2 as char { + '\\' => { + if let Some(ch3) = self.next_char() { + match ch3 as char { + // \$ => $ + '$' | '`' | '"' | '\\' => { result.push(ch3); }, + // \ => nothing + '\n' => {}, + // \x => =x + _ => { result.push('\\' as u8); result.push(ch3); } + } + } else { + return Err(()); + } + }, + '"' => { return Ok(()); }, + _ => { result.push(ch2); }, + } + } else { + return Err(()); + } + } + } + + fn parse_single(&mut self, result: &mut Vec) -> Result<(), ()> { + loop { + if let Some(ch2) = self.next_char() { + match ch2 as char { + '\'' => { return Ok(()); }, + _ => { result.push(ch2); }, + } + } else { + return Err(()); + } + } + } + + fn next_char(&mut self) -> Option { + let res = self.in_iter.next().copied(); + if res == Some(b'\n') { self.line_no += 1; } + res + } +} + +impl<'a> Iterator for Shlex<'a> { + type Item = Vec; + fn next(&mut self) -> Option { + if let Some(mut ch) = self.next_char() { + // skip initial whitespace + loop { + match ch as char { + ' ' | '\t' | '\n' => {}, + '#' => { + while let Some(ch2) = self.next_char() { + if ch2 as char == '\n' { break; } + } + }, + _ => { break; } + } + if let Some(ch2) = self.next_char() { ch = ch2; } else { return None; } + } + self.parse_word(ch) + } else { // no initial character + None + } + } + +} + +/// Convenience function that consumes the whole byte string at once. Returns None if the input was +/// erroneous. +pub fn split(in_bytes: &[u8]) -> Option>> { + let mut shl = Shlex::new(in_bytes); + let res = shl.by_ref().collect(); + if shl.had_error { None } else { Some(res) } +} + +/// A more configurable interface to quote strings. If you only want the default settings you can +/// use the convenience functions [`try_quote`] and [`try_join`]. +/// +/// The string equivalent is [`shlex::Quoter`]. +#[derive(Default, Debug, Clone)] +pub struct Quoter { + allow_nul: bool, + // TODO: more options +} + +impl Quoter { + /// Create a new [`Quoter`] with default settings. + #[inline] + pub fn new() -> Self { + Self::default() + } + + /// Set whether to allow [nul bytes](quoting_warning#nul-bytes). By default they are not + /// allowed and will result in an error of [`QuoteError::Nul`]. + #[inline] + pub fn allow_nul(mut self, allow: bool) -> Self { + self.allow_nul = allow; + self + } + + /// Convenience function that consumes an iterable of words and turns it into a single byte string, + /// quoting words when necessary. Consecutive words will be separated by a single space. + pub fn join<'a, I: IntoIterator>(&self, words: I) -> Result, QuoteError> { + Ok(words.into_iter() + .map(|word| self.quote(word)) + .collect::>, QuoteError>>()? + .join(&b' ')) + } + + /// Given a single word, return a byte string suitable to encode it as a shell argument. + /// + /// If given valid UTF-8, this will never produce invalid UTF-8. This is because it only + /// ever inserts valid ASCII characters before or after existing ASCII characters (or + /// returns two single quotes if the input was an empty string). It will never modify a + /// multibyte UTF-8 character. + pub fn quote<'a>(&self, mut in_bytes: &'a [u8]) -> Result, QuoteError> { + if in_bytes.is_empty() { + // Empty string. Special case that isn't meaningful as only part of a word. + return Ok(b"''"[..].into()); + } + if !self.allow_nul && in_bytes.iter().any(|&b| b == b'\0') { + return Err(QuoteError::Nul); + } + let mut out: Vec = Vec::new(); + while !in_bytes.is_empty() { + // Pick a quoting strategy for some prefix of the input. Normally this will cover the + // entire input, but in some case we might need to divide the input into multiple chunks + // that are quoted differently. + let (cur_len, strategy) = quoting_strategy(in_bytes); + if cur_len == in_bytes.len() && strategy == QuotingStrategy::Unquoted && out.is_empty() { + // Entire string can be represented unquoted. Reuse the allocation. + return Ok(in_bytes.into()); + } + let (cur_chunk, rest) = in_bytes.split_at(cur_len); + assert!(rest.len() < in_bytes.len()); // no infinite loop + in_bytes = rest; + append_quoted_chunk(&mut out, cur_chunk, strategy); + } + Ok(out.into()) + } + +} + +#[derive(PartialEq)] +enum QuotingStrategy { + /// No quotes and no backslash escapes. (If backslash escapes would be necessary, we use a + /// different strategy instead.) + Unquoted, + /// Single quoted. + SingleQuoted, + /// Double quotes, potentially with backslash escapes. + DoubleQuoted, + // TODO: add $'xxx' and "$(printf 'xxx')" styles +} + +/// Is this ASCII byte okay to emit unquoted? +const fn unquoted_ok(c: u8) -> bool { + match c as char { + // Allowed characters: + '+' | '-' | '.' | '/' | ':' | '@' | ']' | '_' | + '0'..='9' | 'A'..='Z' | 'a'..='z' + => true, + + // Non-allowed characters: + // From POSIX https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html + // "The application shall quote the following characters if they are to represent themselves:" + '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '\\' | '"' | '\'' | ' ' | '\t' | '\n' | + // "and the following may need to be quoted under certain circumstances[..]:" + '*' | '?' | '[' | '#' | '~' | '=' | '%' | + // Brace expansion. These ought to be in the POSIX list but aren't yet; + // see: https://www.austingroupbugs.net/view.php?id=1193 + '{' | '}' | + // Also quote comma, just to be safe in the extremely odd case that the user of this crate + // is intentionally placing a quoted string inside a brace expansion, e.g.: + // format!("echo foo{{a,b,{}}}" | shlex::quote(some_str)) + ',' | + // '\r' is allowed in a word by all real shells I tested, but is treated as a word + // separator by Python `shlex` | and might be translated to '\n' in interactive mode. + '\r' | + // '!' and '^' are treated specially in interactive mode; see quoting_warning. + '!' | '^' | + // Nul bytes and control characters. + '\x00' ..= '\x1f' | '\x7f' + => false, + '\u{80}' ..= '\u{10ffff}' => { + // This is unreachable since `unquoted_ok` is only called for 0..128. + // Non-ASCII bytes are handled separately in `quoting_strategy`. + // Can't call unreachable!() from `const fn` on old Rust, so... + unquoted_ok(c) + }, + } + // Note: The logic cited above for quoting comma might suggest that `..` should also be quoted, + // it as a special case of brace expansion). But it's not necessary. There are three cases: + // + // 1. The user wants comma-based brace expansion, but the untrusted string being `quote`d + // contains `..`, so they get something like `{foo,bar,3..5}`. + // => That's safe; both Bash and Zsh expand this to `foo bar 3..5` rather than + // `foo bar 3 4 5`. The presence of commas disables sequence expression expansion. + // + // 2. The user wants comma-based brace expansion where the contents of the braces are a + // variable number of `quote`d strings and nothing else. There happens to be exactly + // one string and it contains `..`, so they get something like `{3..5}`. + // => Then this will expand as a sequence expression, which is unintended. But I don't mind, + // because any such code is already buggy. Suppose the untrusted string *didn't* contain + // `,` or `..`, resulting in shell input like `{foo}`. Then the shell would interpret it + // as the literal string `{foo}` rather than brace-expanding it into `foo`. + // + // 3. The user wants a sequence expression and wants to supply an untrusted string as one of + // the endpoints or the increment. + // => Well, that's just silly, since the endpoints can only be numbers or single letters. +} + +/// Optimized version of `unquoted_ok`. +fn unquoted_ok_fast(c: u8) -> bool { + const UNQUOTED_OK_MASK: u128 = { + // Make a mask of all bytes in 0..<0x80 that pass. + let mut c = 0u8; + let mut mask = 0u128; + while c < 0x80 { + if unquoted_ok(c) { + mask |= 1u128 << c; + } + c += 1; + } + mask + }; + ((UNQUOTED_OK_MASK >> c) & 1) != 0 +} + +/// Is this ASCII byte okay to emit in single quotes? +fn single_quoted_ok(c: u8) -> bool { + match c { + // No single quotes in single quotes. + b'\'' => false, + // To work around a Bash bug, ^ is only allowed right after an opening single quote; see + // quoting_warning. + b'^' => false, + // Backslashes in single quotes are literal according to POSIX, but Fish treats them as an + // escape character. Ban them. Fish doesn't aim to be POSIX-compatible, but we *can* + // achieve Fish compatibility using double quotes, so we might as well. + b'\\' => false, + _ => true + } +} + +/// Is this ASCII byte okay to emit in double quotes? +fn double_quoted_ok(c: u8) -> bool { + match c { + // Work around Python `shlex` bug where parsing "\`" and "\$" doesn't strip the + // backslash, even though POSIX requires it. + b'`' | b'$' => false, + // '!' and '^' are treated specially in interactive mode; see quoting_warning. + b'!' | b'^' => false, + _ => true + } +} + +/// Given an input, return a quoting strategy that can cover some prefix of the string, along with +/// the size of that prefix. +/// +/// Precondition: input size is nonzero. (Empty strings are handled by the caller.) +/// Postcondition: returned size is nonzero. +#[cfg_attr(manual_codegen_check, inline(never))] +fn quoting_strategy(in_bytes: &[u8]) -> (usize, QuotingStrategy) { + const UNQUOTED_OK: u8 = 1; + const SINGLE_QUOTED_OK: u8 = 2; + const DOUBLE_QUOTED_OK: u8 = 4; + + let mut prev_ok = SINGLE_QUOTED_OK | DOUBLE_QUOTED_OK | UNQUOTED_OK; + let mut i = 0; + + if in_bytes[0] == b'^' { + // To work around a Bash bug, ^ is only allowed right after an opening single quote; see + // quoting_warning. + prev_ok = SINGLE_QUOTED_OK; + i = 1; + } + + while i < in_bytes.len() { + let c = in_bytes[i]; + let mut cur_ok = prev_ok; + + if c >= 0x80 { + // Normally, non-ASCII characters shouldn't require quoting, but see quoting_warning.md + // about \xa0. For now, just treat all non-ASCII characters as requiring quotes. This + // also ensures things are safe in the off-chance that you're in a legacy 8-bit locale that + // has additional characters satisfying `isblank`. + cur_ok &= !UNQUOTED_OK; + } else { + if !unquoted_ok_fast(c) { + cur_ok &= !UNQUOTED_OK; + } + if !single_quoted_ok(c){ + cur_ok &= !SINGLE_QUOTED_OK; + } + if !double_quoted_ok(c) { + cur_ok &= !DOUBLE_QUOTED_OK; + } + } + + if cur_ok == 0 { + // There are no quoting strategies that would work for both the previous characters and + // this one. So we have to end the chunk before this character. The caller will call + // `quoting_strategy` again to handle the rest of the string. + break; + } + + prev_ok = cur_ok; + i += 1; + } + + // Pick the best allowed strategy. + let strategy = if prev_ok & UNQUOTED_OK != 0 { + QuotingStrategy::Unquoted + } else if prev_ok & SINGLE_QUOTED_OK != 0 { + QuotingStrategy::SingleQuoted + } else if prev_ok & DOUBLE_QUOTED_OK != 0 { + QuotingStrategy::DoubleQuoted + } else { + unreachable!() + }; + debug_assert!(i > 0); + (i, strategy) +} + +fn append_quoted_chunk(out: &mut Vec, cur_chunk: &[u8], strategy: QuotingStrategy) { + match strategy { + QuotingStrategy::Unquoted => { + out.extend_from_slice(cur_chunk); + }, + QuotingStrategy::SingleQuoted => { + out.reserve(cur_chunk.len() + 2); + out.push(b'\''); + out.extend_from_slice(cur_chunk); + out.push(b'\''); + }, + QuotingStrategy::DoubleQuoted => { + out.reserve(cur_chunk.len() + 2); + out.push(b'"'); + for &c in cur_chunk.into_iter() { + if let b'$' | b'`' | b'"' | b'\\' = c { + // Add a preceding backslash. + // Note: We shouldn't actually get here for $ and ` because they don't pass + // `double_quoted_ok`. + out.push(b'\\'); + } + // Add the character itself. + out.push(c); + } + out.push(b'"'); + }, + } +} + +/// Convenience function that consumes an iterable of words and turns it into a single byte string, +/// quoting words when necessary. Consecutive words will be separated by a single space. +/// +/// Uses default settings except that nul bytes are passed through, which [may be +/// dangerous](quoting_warning#nul-bytes), leading to this function being deprecated. +/// +/// Equivalent to [`Quoter::new().allow_nul(true).join(words).unwrap()`](Quoter). +/// +/// (That configuration never returns `Err`, so this function does not panic.) +/// +/// The string equivalent is [shlex::join]. +#[deprecated(since = "1.3.0", note = "replace with `try_join(words)?` to avoid nul byte danger")] +pub fn join<'a, I: IntoIterator>(words: I) -> Vec { + Quoter::new().allow_nul(true).join(words).unwrap() +} + +/// Convenience function that consumes an iterable of words and turns it into a single byte string, +/// quoting words when necessary. Consecutive words will be separated by a single space. +/// +/// Uses default settings. The only error that can be returned is [`QuoteError::Nul`]. +/// +/// Equivalent to [`Quoter::new().join(words)`](Quoter). +/// +/// The string equivalent is [shlex::try_join]. +pub fn try_join<'a, I: IntoIterator>(words: I) -> Result, QuoteError> { + Quoter::new().join(words) +} + +/// Given a single word, return a string suitable to encode it as a shell argument. +/// +/// Uses default settings except that nul bytes are passed through, which [may be +/// dangerous](quoting_warning#nul-bytes), leading to this function being deprecated. +/// +/// Equivalent to [`Quoter::new().allow_nul(true).quote(in_bytes).unwrap()`](Quoter). +/// +/// (That configuration never returns `Err`, so this function does not panic.) +/// +/// The string equivalent is [shlex::quote]. +#[deprecated(since = "1.3.0", note = "replace with `try_quote(str)?` to avoid nul byte danger")] +pub fn quote(in_bytes: &[u8]) -> Cow<[u8]> { + Quoter::new().allow_nul(true).quote(in_bytes).unwrap() +} + +/// Given a single word, return a string suitable to encode it as a shell argument. +/// +/// Uses default settings. The only error that can be returned is [`QuoteError::Nul`]. +/// +/// Equivalent to [`Quoter::new().quote(in_bytes)`](Quoter). +/// +/// (That configuration never returns `Err`, so this function does not panic.) +/// +/// The string equivalent is [shlex::try_quote]. +pub fn try_quote(in_bytes: &[u8]) -> Result, QuoteError> { + Quoter::new().quote(in_bytes) +} + +#[cfg(test)] +const INVALID_UTF8: &[u8] = b"\xa1"; +#[cfg(test)] +const INVALID_UTF8_SINGLEQUOTED: &[u8] = b"'\xa1'"; + +#[test] +#[allow(invalid_from_utf8)] +fn test_invalid_utf8() { + // Check that our test string is actually invalid UTF-8. + assert!(core::str::from_utf8(INVALID_UTF8).is_err()); +} + +#[cfg(test)] +static SPLIT_TEST_ITEMS: &'static [(&'static [u8], Option<&'static [&'static [u8]]>)] = &[ + (b"foo$baz", Some(&[b"foo$baz"])), + (b"foo baz", Some(&[b"foo", b"baz"])), + (b"foo\"bar\"baz", Some(&[b"foobarbaz"])), + (b"foo \"bar\"baz", Some(&[b"foo", b"barbaz"])), + (b" foo \nbar", Some(&[b"foo", b"bar"])), + (b"foo\\\nbar", Some(&[b"foobar"])), + (b"\"foo\\\nbar\"", Some(&[b"foobar"])), + (b"'baz\\$b'", Some(&[b"baz\\$b"])), + (b"'baz\\\''", None), + (b"\\", None), + (b"\"\\", None), + (b"'\\", None), + (b"\"", None), + (b"'", None), + (b"foo #bar\nbaz", Some(&[b"foo", b"baz"])), + (b"foo #bar", Some(&[b"foo"])), + (b"foo#bar", Some(&[b"foo#bar"])), + (b"foo\"#bar", None), + (b"'\\n'", Some(&[b"\\n"])), + (b"'\\\\n'", Some(&[b"\\\\n"])), + (INVALID_UTF8, Some(&[INVALID_UTF8])), +]; + +#[test] +fn test_split() { + for &(input, output) in SPLIT_TEST_ITEMS { + assert_eq!(split(input), output.map(|o| o.iter().map(|&x| x.to_owned()).collect())); + } +} + +#[test] +fn test_lineno() { + let mut sh = Shlex::new(b"\nfoo\nbar"); + while let Some(word) = sh.next() { + if word == b"bar" { + assert_eq!(sh.line_no, 3); + } + } +} + +#[test] +#[allow(deprecated)] +fn test_quote() { + // Validate behavior with invalid UTF-8: + assert_eq!(quote(INVALID_UTF8), INVALID_UTF8_SINGLEQUOTED); + // Replicate a few tests from lib.rs. No need to replicate all of them. + assert_eq!(quote(b""), &b"''"[..]); + assert_eq!(quote(b"foobar"), &b"foobar"[..]); + assert_eq!(quote(b"foo bar"), &b"'foo bar'"[..]); + assert_eq!(quote(b"'\""), &b"\"'\\\"\""[..]); + assert_eq!(quote(b""), &b"''"[..]); +} + +#[test] +#[allow(deprecated)] +fn test_join() { + // Validate behavior with invalid UTF-8: + assert_eq!(join(vec![INVALID_UTF8]), INVALID_UTF8_SINGLEQUOTED); + // Replicate a few tests from lib.rs. No need to replicate all of them. + assert_eq!(join(vec![]), &b""[..]); + assert_eq!(join(vec![&b""[..]]), b"''"); +} diff --git a/bitbox02-bt/vendor/shlex/src/lib.rs b/bitbox02-bt/vendor/shlex/src/lib.rs new file mode 100644 index 0000000..aa5c306 --- /dev/null +++ b/bitbox02-bt/vendor/shlex/src/lib.rs @@ -0,0 +1,358 @@ +// Copyright 2015 Nicholas Allegra (comex). +// Licensed under the Apache License, Version 2.0 or +// the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +//! Parse strings like, and escape strings for, POSIX shells. +//! +//! Same idea as (but implementation not directly based on) the Python shlex module. +//! +//! Disabling the `std` feature (which is enabled by default) will allow the crate to work in +//! `no_std` environments, where the `alloc` crate, and a global allocator, are available. +//! +//! ## Warning +//! +//! The [`try_quote`]/[`try_join`] family of APIs does not quote control characters (because they +//! cannot be quoted portably). +//! +//! This is fully safe in noninteractive contexts, like shell scripts and `sh -c` arguments (or +//! even scripts `source`d from interactive shells). +//! +//! But if you are quoting for human consumption, you should keep in mind that ugly inputs produce +//! ugly outputs (which may not be copy-pastable). +//! +//! And if by chance you are piping the output of [`try_quote`]/[`try_join`] directly to the stdin +//! of an interactive shell, you should stop, because control characters can lead to arbitrary +//! command injection. +//! +//! For more information, and for information about more minor issues, please see [quoting_warning]. +//! +//! ## Compatibility +//! +//! This crate's quoting functionality tries to be compatible with **any POSIX-compatible shell**; +//! it's tested against `bash`, `zsh`, `dash`, Busybox `ash`, and `mksh`, plus `fish` (which is not +//! POSIX-compatible but close enough). +//! +//! It also aims to be compatible with Python `shlex` and C `wordexp`. + +#![cfg_attr(not(feature = "std"), no_std)] + +extern crate alloc; +use alloc::vec::Vec; +use alloc::borrow::Cow; +use alloc::string::String; +#[cfg(test)] +use alloc::vec; +#[cfg(test)] +use alloc::borrow::ToOwned; + +pub mod bytes; +#[cfg(all(doc, not(doctest)))] +#[path = "quoting_warning.md"] +pub mod quoting_warning; + +/// An iterator that takes an input string and splits it into the words using the same syntax as +/// the POSIX shell. +/// +/// See [`bytes::Shlex`]. +pub struct Shlex<'a>(bytes::Shlex<'a>); + +impl<'a> Shlex<'a> { + pub fn new(in_str: &'a str) -> Self { + Self(bytes::Shlex::new(in_str.as_bytes())) + } +} + +impl<'a> Iterator for Shlex<'a> { + type Item = String; + fn next(&mut self) -> Option { + self.0.next().map(|byte_word| { + // Safety: given valid UTF-8, bytes::Shlex will always return valid UTF-8. + unsafe { String::from_utf8_unchecked(byte_word) } + }) + } +} + +impl<'a> core::ops::Deref for Shlex<'a> { + type Target = bytes::Shlex<'a>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a> core::ops::DerefMut for Shlex<'a> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Convenience function that consumes the whole string at once. Returns None if the input was +/// erroneous. +pub fn split(in_str: &str) -> Option> { + let mut shl = Shlex::new(in_str); + let res = shl.by_ref().collect(); + if shl.had_error { None } else { Some(res) } +} + +/// Errors from [`Quoter::quote`], [`Quoter::join`], etc. (and their [`bytes`] counterparts). +/// +/// By default, the only error that can be returned is [`QuoteError::Nul`]. If you call +/// `allow_nul(true)`, then no errors can be returned at all. Any error variants added in the +/// future will not be enabled by default; they will be enabled through corresponding non-default +/// [`Quoter`] options. +/// +/// ...In theory. In the unlikely event that additional classes of inputs are discovered that, +/// like nul bytes, are fundamentally unsafe to quote even for non-interactive shells, the risk +/// will be mitigated by adding corresponding [`QuoteError`] variants that *are* enabled by +/// default. +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum QuoteError { + /// The input contained a nul byte. In most cases, shells fundamentally [cannot handle strings + /// containing nul bytes](quoting_warning#nul-bytes), no matter how they are quoted. But if + /// you're sure you can handle nul bytes, you can call `allow_nul(true)` on the `Quoter` to let + /// them pass through. + Nul, +} + +impl core::fmt::Display for QuoteError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + QuoteError::Nul => f.write_str("cannot shell-quote string containing nul byte"), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for QuoteError {} + +/// A more configurable interface to quote strings. If you only want the default settings you can +/// use the convenience functions [`try_quote`] and [`try_join`]. +/// +/// The bytes equivalent is [`bytes::Quoter`]. +#[derive(Default, Debug, Clone)] +pub struct Quoter { + inner: bytes::Quoter, +} + +impl Quoter { + /// Create a new [`Quoter`] with default settings. + #[inline] + pub fn new() -> Self { + Self::default() + } + + /// Set whether to allow [nul bytes](quoting_warning#nul-bytes). By default they are not + /// allowed and will result in an error of [`QuoteError::Nul`]. + #[inline] + pub fn allow_nul(mut self, allow: bool) -> Self { + self.inner = self.inner.allow_nul(allow); + self + } + + /// Convenience function that consumes an iterable of words and turns it into a single string, + /// quoting words when necessary. Consecutive words will be separated by a single space. + pub fn join<'a, I: IntoIterator>(&self, words: I) -> Result { + // Safety: given valid UTF-8, bytes::join() will always return valid UTF-8. + self.inner.join(words.into_iter().map(|s| s.as_bytes())) + .map(|bytes| unsafe { String::from_utf8_unchecked(bytes) }) + } + + /// Given a single word, return a string suitable to encode it as a shell argument. + pub fn quote<'a>(&self, in_str: &'a str) -> Result, QuoteError> { + Ok(match self.inner.quote(in_str.as_bytes())? { + Cow::Borrowed(out) => { + // Safety: given valid UTF-8, bytes::quote() will always return valid UTF-8. + unsafe { core::str::from_utf8_unchecked(out) }.into() + } + Cow::Owned(out) => { + // Safety: given valid UTF-8, bytes::quote() will always return valid UTF-8. + unsafe { String::from_utf8_unchecked(out) }.into() + } + }) + } +} + +impl From for Quoter { + fn from(inner: bytes::Quoter) -> Quoter { + Quoter { inner } + } +} + +impl From for bytes::Quoter { + fn from(quoter: Quoter) -> bytes::Quoter { + quoter.inner + } +} + +/// Convenience function that consumes an iterable of words and turns it into a single string, +/// quoting words when necessary. Consecutive words will be separated by a single space. +/// +/// Uses default settings except that nul bytes are passed through, which [may be +/// dangerous](quoting_warning#nul-bytes), leading to this function being deprecated. +/// +/// Equivalent to [`Quoter::new().allow_nul(true).join(words).unwrap()`](Quoter). +/// +/// (That configuration never returns `Err`, so this function does not panic.) +/// +/// The bytes equivalent is [bytes::join]. +#[deprecated(since = "1.3.0", note = "replace with `try_join(words)?` to avoid nul byte danger")] +pub fn join<'a, I: IntoIterator>(words: I) -> String { + Quoter::new().allow_nul(true).join(words).unwrap() +} + +/// Convenience function that consumes an iterable of words and turns it into a single string, +/// quoting words when necessary. Consecutive words will be separated by a single space. +/// +/// Uses default settings. The only error that can be returned is [`QuoteError::Nul`]. +/// +/// Equivalent to [`Quoter::new().join(words)`](Quoter). +/// +/// The bytes equivalent is [bytes::try_join]. +pub fn try_join<'a, I: IntoIterator>(words: I) -> Result { + Quoter::new().join(words) +} + +/// Given a single word, return a string suitable to encode it as a shell argument. +/// +/// Uses default settings except that nul bytes are passed through, which [may be +/// dangerous](quoting_warning#nul-bytes), leading to this function being deprecated. +/// +/// Equivalent to [`Quoter::new().allow_nul(true).quote(in_str).unwrap()`](Quoter). +/// +/// (That configuration never returns `Err`, so this function does not panic.) +/// +/// The bytes equivalent is [bytes::quote]. +#[deprecated(since = "1.3.0", note = "replace with `try_quote(str)?` to avoid nul byte danger")] +pub fn quote(in_str: &str) -> Cow { + Quoter::new().allow_nul(true).quote(in_str).unwrap() +} + +/// Given a single word, return a string suitable to encode it as a shell argument. +/// +/// Uses default settings. The only error that can be returned is [`QuoteError::Nul`]. +/// +/// Equivalent to [`Quoter::new().quote(in_str)`](Quoter). +/// +/// (That configuration never returns `Err`, so this function does not panic.) +/// +/// The bytes equivalent is [bytes::try_quote]. +pub fn try_quote(in_str: &str) -> Result, QuoteError> { + Quoter::new().quote(in_str) +} + +#[cfg(test)] +static SPLIT_TEST_ITEMS: &'static [(&'static str, Option<&'static [&'static str]>)] = &[ + ("foo$baz", Some(&["foo$baz"])), + ("foo baz", Some(&["foo", "baz"])), + ("foo\"bar\"baz", Some(&["foobarbaz"])), + ("foo \"bar\"baz", Some(&["foo", "barbaz"])), + (" foo \nbar", Some(&["foo", "bar"])), + ("foo\\\nbar", Some(&["foobar"])), + ("\"foo\\\nbar\"", Some(&["foobar"])), + ("'baz\\$b'", Some(&["baz\\$b"])), + ("'baz\\\''", None), + ("\\", None), + ("\"\\", None), + ("'\\", None), + ("\"", None), + ("'", None), + ("foo #bar\nbaz", Some(&["foo", "baz"])), + ("foo #bar", Some(&["foo"])), + ("foo#bar", Some(&["foo#bar"])), + ("foo\"#bar", None), + ("'\\n'", Some(&["\\n"])), + ("'\\\\n'", Some(&["\\\\n"])), +]; + +#[test] +fn test_split() { + for &(input, output) in SPLIT_TEST_ITEMS { + assert_eq!(split(input), output.map(|o| o.iter().map(|&x| x.to_owned()).collect())); + } +} + +#[test] +fn test_lineno() { + let mut sh = Shlex::new("\nfoo\nbar"); + while let Some(word) = sh.next() { + if word == "bar" { + assert_eq!(sh.line_no, 3); + } + } +} + +#[test] +#[cfg_attr(not(feature = "std"), allow(unreachable_code, unused_mut))] +fn test_quote() { + // This is a list of (unquoted, quoted) pairs. + // But it's using a single long (raw) string literal with an ad-hoc format, just because it's + // hard to read if we have to put the test strings through Rust escaping on top of the escaping + // being tested. (Even raw string literals are noisy for short strings). + // Ad-hoc: "NL" is replaced with a literal newline; no other escape sequences. + let tests = r#" + <> => <''> + => + => <'foo bar'> + <"foo bar'"> => <"\"foo bar'\""> + <'foo bar'> => <"'foo bar'"> + <"> => <'"'> + <"'> => <"\"'"> + => <'hello!world'> + <'hello!world> => <"'hello"'!world'> + <'hello!> => <"'hello"'!'> + => <'hello ''^ world'> + => + => <'!world'"'"> + <{a, b}> => <'{a, b}'> + => <'NL'> + <^> => <'^'> + => + => <'NLx''^'> + => <'NL''^x'> + => <'NL ''^x'> + <{a,b}> => <'{a,b}'> + => <'a,b'> + + <'$> => <"'"'$'> + <"^> => <'"''^'> + "#; + let mut ok = true; + for test in tests.trim().split('\n') { + let parts: Vec = test + .replace("NL", "\n") + .split("=>") + .map(|part| part.trim().trim_start_matches('<').trim_end_matches('>').to_owned()) + .collect(); + assert!(parts.len() == 2); + let unquoted = &*parts[0]; + let quoted_expected = &*parts[1]; + let quoted_actual = try_quote(&parts[0]).unwrap(); + if quoted_expected != quoted_actual { + #[cfg(not(feature = "std"))] + panic!("FAIL: for input <{}>, expected <{}>, got <{}>", + unquoted, quoted_expected, quoted_actual); + #[cfg(feature = "std")] + println!("FAIL: for input <{}>, expected <{}>, got <{}>", + unquoted, quoted_expected, quoted_actual); + ok = false; + } + } + assert!(ok); +} + +#[test] +#[allow(deprecated)] +fn test_join() { + assert_eq!(join(vec![]), ""); + assert_eq!(join(vec![""]), "''"); + assert_eq!(join(vec!["a", "b"]), "a b"); + assert_eq!(join(vec!["foo bar", "baz"]), "'foo bar' baz"); +} + +#[test] +fn test_fallible() { + assert_eq!(try_join(vec!["\0"]), Err(QuoteError::Nul)); + assert_eq!(try_quote("\0"), Err(QuoteError::Nul)); +} diff --git a/bitbox02-bt/vendor/shlex/src/quoting_warning.md b/bitbox02-bt/vendor/shlex/src/quoting_warning.md new file mode 100644 index 0000000..fab9857 --- /dev/null +++ b/bitbox02-bt/vendor/shlex/src/quoting_warning.md @@ -0,0 +1,365 @@ +// vim: textwidth=99 +/* +Meta note: This file is loaded as a .rs file by rustdoc only. +*/ +/*! + +A more detailed version of the [warning at the top level](super#warning) about the `quote`/`join` +family of APIs. + +In general, passing the output of these APIs to a shell should recover the original string(s). +This page lists cases where it fails to do so. + +In noninteractive contexts, there are only minor issues. 'Noninteractive' includes shell scripts +and `sh -c` arguments, or even scripts `source`d from interactive shells. The issues are: + +- [Nul bytes](#nul-bytes) + +- [Overlong commands](#overlong-commands) + +If you are writing directly to the stdin of an interactive (`-i`) shell (i.e., if you are +pretending to be a terminal), or if you are writing to a cooked-mode pty (even if the other end is +noninteractive), then there is a **severe** security issue: + +- [Control characters](#control-characters-interactive-contexts-only) + +Finally, there are some [solved issues](#solved-issues). + +# List of issues + +## Nul bytes + +For non-interactive shells, the most problematic input is nul bytes (bytes with value 0). The +non-deprecated functions all default to returning [`QuoteError::Nul`] when encountering them, but +the deprecated [`quote`] and [`join`] functions leave them as-is. + +In Unix, nul bytes can't appear in command arguments, environment variables, or filenames. It's +not a question of proper quoting; they just can't be used at all. This is a consequence of Unix's +system calls all being designed around nul-terminated C strings. + +Shells inherit that limitation. Most of them do not accept nul bytes in strings even internally. +Even when they do, it's pretty much useless or even dangerous, since you can't pass them to +external commands. + +In some cases, you might fail to pass the nul byte to the shell in the first place. For example, +the following code uses [`join`] to tunnel a command over an SSH connection: + +```rust +std::process::Command::new("ssh") + .arg("myhost") + .arg("--") + .arg(join(my_cmd_args)) +``` + +If any argument in `my_cmd_args` contains a nul byte, then `join(my_cmd_args)` will contain a nul +byte. But `join(my_cmd_args)` is itself being passed as an argument to a command (the ssh +command), and command arguments can't contain nul bytes! So this will simply result in the +`Command` failing to launch. + +Still, there are other ways to smuggle nul bytes into a shell. How the shell reacts depends on the +shell and the method of smuggling. For example, here is Bash 5.2.21 exhibiting three different +behaviors: + +- With ANSI-C quoting, the string is truncated at the first nul byte: + ```bash + $ echo $'foo\0bar' | hexdump -C + 00000000 66 6f 6f 0a |foo.| + ``` + +- With command substitution, nul bytes are removed with a warning: + ```bash + $ echo $(printf 'foo\0bar') | hexdump -C + bash: warning: command substitution: ignored null byte in input + 00000000 66 6f 6f 62 61 72 0a |foobar.| + ``` + +- When a nul byte appears directly in a shell script, it's removed with no warning: + ```bash + $ printf 'echo "foo\0bar"' | bash | hexdump -C + 00000000 66 6f 6f 62 61 72 0a |foobar.| + ``` + +Zsh, in contrast, actually allows nul bytes internally, in shell variables and even arguments to +builtin commands. But if a variable is exported to the environment, or if an argument is used for +an external command, then the child process will see it silently truncated at the first nul. This +might actually be more dangerous, depending on the use case. + +## Overlong commands + +If you pass a long string into a shell, several things might happen: + +- It might succeed, yet the shell might have trouble actually doing anything with it. For example: + + ```bash + x=$(printf '%010000000d' 0); /bin/echo $x + bash: /bin/echo: Argument list too long + ``` + +- If you're using certain shells (e.g. Busybox Ash) *and* using a pty for communication, then the + shell will impose a line length limit, ignoring all input past the limit. + +- If you're using a pty in cooked mode, then by default, if you write so many bytes as input that + it fills the kernel's internal buffer, the kernel will simply drop those bytes, instead of + blocking waiting for the shell to empty out the buffer. In other words, random bits of input can + be lost, which is obviously insecure. + +Future versions of this crate may add an option to [`Quoter`] to check the length for you. + +## Control characters (*interactive contexts only*) + +Control characters are the bytes from `\x00` to `\x1f`, plus `\x7f`. `\x00` (the nul byte) is +discussed [above](#nul-bytes), but what about the rest? Well, many of them correspond to terminal +keyboard shortcuts. For example, when you press Ctrl-A at a shell prompt, your terminal sends the +byte `\x01`. The shell sees that byte and (if not configured differently) takes the standard +action for Ctrl-A, which is to move the cursor to the beginning of the line. + +This means that it's quite dangerous to pipe bytes to an interactive shell. For example, here is a +program that tries to tell Bash to echo an arbitrary string, 'safely': +```rust +use std::process::{Command, Stdio}; +use std::io::Write; + +let evil_string = "\x01do_something_evil; "; +let quoted = shlex::try_quote(evil_string).unwrap(); +println!("quoted string is {:?}", quoted); + +let mut bash = Command::new("bash") + .arg("-i") // force interactive mode + .stdin(Stdio::piped()) + .spawn() + .unwrap(); +let stdin = bash.stdin.as_mut().unwrap(); +write!(stdin, "echo {}\n", quoted).unwrap(); +``` + +Here's the output of the program (with irrelevant bits removed): + +```text +quoted string is "'\u{1}do_something_evil; '" +/tmp comex$ do_something_evil; 'echo ' +bash: do_something_evil: command not found +bash: echo : command not found +``` + +Even though we quoted it, Bash still ran an arbitrary command! + +This is not because the quoting was insufficient, per se. In single quotes, all input is supposed +to be treated as raw data until the closing single quote. And in fact, this would work fine +without the `"-i"` argument. + +But line input is a separate stage from shell syntax parsing. After all, if you type a single +quote on the keyboard, you wouldn't expect it to disable all your keyboard shortcuts. So a control +character always has its designated effect, no matter if it's quoted or backslash-escaped. + +Also, some control characters are interpreted by the kernel tty layer instead, like CTRL-C to send +SIGINT. These can be an issue even with noninteractive shells, but only if using a pty for +communication, as opposed to a pipe. + +To be safe, you just have to avoid sending them. + +### Why not just use hex escapes? + +In any normal programming languages, this would be no big deal. + +Any normal language has a way to escape arbitrary characters in strings by writing out their +numeric values. For example, Rust lets you write them in hexadecimal, like `"\x4f"` (or +`"\u{1d546}"` for Unicode). In this way, arbitrary strings can be represented using only 'nice' +simple characters. Any remotely suspicious character can be replaced with a numeric escape +sequence, where the escape sequence itself consists only of alphanumeric characters and some +punctuation. The result may not be the most readable[^choices], but it's quite safe from being +misinterpreted or corrupted in transit. + +Shell is not normal. It has no numeric escape sequences. + +There are a few different ways to quote characters (unquoted, unquoted-with-backslash, single +quotes, double quotes), but all of them involve writing the character itself. If the input +contains a control character, the output must contain that same character. + +### Mitigation: terminal filters + +In practice, automating interactive shells like in the above example is pretty uncommon these days. +In most cases, the only way for a programmatically generated string to make its way to the input of +an interactive shell is if a human copies and pastes it into their terminal. + +And many terminals detect when you paste a string containing control characters. iTerm2 strips +them out; gnome-terminal replaces them with alternate characters[^gr]; Kitty outright prompts for +confirmation. This mitigates the risk. + +But it's not perfect. Some other terminals don't implement this check or implement it incorrectly. +Also, these checks tend to not filter the tab character, which could trigger tab completion. In +most cases that's a non-issue, because most shells support paste bracketing, which disables tab and +some other control characters[^bracketing] within pasted text. But in some cases paste bracketing +gets disabled. + +### Future possibility: ANSI-C quoting + +I said that shell syntax has no numeric escapes, but that only applies to *portable* shell syntax. +Bash and Zsh support an obscure alternate quoting style with the syntax `$'foo'`. It's called +["ANSI-C quoting"][ansic], and inside it you can use all the escape sequences supported by C, +including hex escapes: + +```bash +$ echo $'\x41\n\x42' +A +B +``` + +But other shells don't support it — including Dash, a popular choice for `/bin/sh`, and Busybox's +Ash, frequently seen on stripped-down embedded systems. This crate's quoting functionality [tries +to be compatible](crate#compatibility) with those shells, plus all other POSIX-compatible shells. +That makes ANSI-C quoting a no-go. + +Still, future versions of this crate may provide an option to enable ANSI-C quoting, at the cost of +reduced portability. + +### Future possibility: printf + +Another option would be to invoke the `printf` command, which is required by POSIX to support octal +escapes. For example, you could 'escape' the Rust string `"\x01"` into the shell syntax `"$(printf +'\001')"`. The shell will execute the command `printf` with the first argument being literally a +backslash followed by three digits; `printf` will output the actual byte with value 1; and the +shell will substitute that back into the original command. + +The problem is that 'escaping' a string into a command substitution just feels too surprising. If +nothing else, it only works with an actual shell; [other languages' shell parsing +routines](crate#compatibility) wouldn't understand it. Neither would this crate's own parser, +though that could be fixed. + +Future versions of this crate may provide an option to use `printf` for quoting. + +### Special note: newlines + +Did you know that `\r` and `\n` are control characters? They aren't as dangerous as other control +characters (if quoted properly). But there's still an issue with them in interactive contexts. + +Namely, in some cases, interactive shells and/or the tty layer will 'helpfully' translate between +different line ending conventions. The possibilities include replacing `\r` with `\n`, replacing +`\n` with `\r\n`, and others. This can't result in command injection, but it's still a lossy +transformation which can result in a failure to round-trip (i.e. the shell sees a different string +from what was originally passed to `quote`). + +Numeric escapes would solve this as well. + +# Solved issues + +## Solved: Past vulnerability (GHSA-r7qv-8r2h-pg27 / RUSTSEC-2024-XXX) + +Versions of this crate before 1.3.0 did not quote `{`, `}`, and `\xa0`. + +See: +- +- (TODO: Add Rustsec link) + +## Solved: `!` and `^` + +There are two non-control characters which have a special meaning in interactive contexts only: `!` and +`^`. Luckily, these can be escaped adequately. + +The `!` character triggers [history expansion][he]; the `^` character can trigger a variant of +history expansion known as [Quick Substitution][qs]. Both of these characters get expanded even +inside of double-quoted strings\! + +If we're in a double-quoted string, then we can't just escape these characters with a backslash. +Only a specific set of characters can be backslash-escaped inside double quotes; the set of +supported characters depends on the shell, but it often doesn't include `!` and `^`.[^escbs] +Trying to backslash-escape an unsupported character produces a literal backslash: +```bash +$ echo "\!" +\! +``` + +However, these characters don't get expanded in single-quoted strings, so this crate just +single-quotes them. + +But there's a Bash bug where `^` actually does get partially expanded in single-quoted strings: +```bash +$ echo ' +> ^a^b +> ' + +!!:s^a^b +``` + +To work around that, this crate forces `^` to appear right after an opening single quote. For +example, the string `"^` is quoted into `'"''^'` instead of `'"^'`. This restriction is overkill, +since `^` is only meaningful right after a newline, but it's a sufficient restriction (after all, a +`^` character can't be preceded by a newline if it's forced to be preceded by a single quote), and +for now it simplifies things. + +## Solved: `\xa0` + +The byte `\xa0` may be treated as a shell word separator, specifically on Bash on macOS when using +the default UTF-8 locale, only when the input is invalid UTF-8. This crate handles the issue by +always using quotes for arguments containing this byte. + +In fact, this crate always uses quotes for arguments containing any non-ASCII bytes. This may be +changed in the future, since it's a bit unfriendly to non-English users. But for now it +minimizes risk, especially considering the large number of different legacy single-byte locales +someone might hypothetically be running their shell in. + +### Demonstration + +```bash +$ echo -e 'ls a\xa0b' | bash +ls: a: No such file or directory +ls: b: No such file or directory +``` +The normal behavior would be to output a single line, e.g.: +```bash +$ echo -e 'ls a\xa0b' | bash +ls: cannot access 'a'$'\240''b': No such file or directory +``` +(The specific quoting in the error doesn't matter.) + +### Cause + +Just for fun, here's why this behavior occurs: + +Bash decides which bytes serve as word separators based on the libc function [`isblank`][isblank]. +On macOS on UTF-8 locales, this passes for `\xa0`, corresponding to U+00A0 NO-BREAK SPACE. + +This is doubly unique compared to the other systems I tested (Linux/glibc, Linux/musl, and +Windows/MSVC). First, the other systems don't allow bytes in the range [0x80, 0xFF] to pass +isfoo functions in UTF-8 locales, even if the corresponding Unicode codepoint +does pass, as determined by the wide-character equivalent function, iswfoo. +Second, the other systems don't treat U+00A0 as blank (even using `iswblank`). + +Meanwhile, Bash checks for multi-byte sequences and forbids them from being treated as special +characters, so the proper UTF-8 encoding of U+00A0, `b"\xc2\xa0"`, is not treated as a word +separator. Treatment as a word separator only happens for `b"\xa0"` alone, which is illegal UTF-8. + +[ansic]: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html +[he]: https://www.gnu.org/software/bash/manual/html_node/History-Interaction.html +[qs]: https://www.gnu.org/software/bash/manual/html_node/Event-Designators.html +[isblank]: https://man7.org/linux/man-pages/man3/isblank.3p.html +[nul]: #nul-bytes + +[^choices]: This can lead to tough choices over which + characters to escape and which to leave as-is, especially when Unicode gets involved and you + have to balance the risk of confusion with the benefit of properly supporting non-English + languages. +
+
+ We don't have the luxury of those choices. + +[^gr]: For example, backspace (in Unicode lingo, U+0008 BACKSPACE) turns into U+2408 SYMBOL FOR BACKSPACE. + +[^bracketing]: It typically disables almost all handling of control characters by the shell proper, + but one necessary exception is the end-of-paste sequence itself (which starts with the control + character `\x1b`). In addition, paste bracketing does not suppress handling of control + characters by the kernel tty layer, such as `\x03` sending SIGINT (which typically clears the + currently typed command, making it dangerous in a similar way to `\x01`). + +[^escbs]: For example, Dash doesn't remove the backslash from `"\!"` because it simply doesn't know + anything about `!` as a special character: it doesn't support history expansion. On the other + end of the spectrum, Zsh supports history expansion and does remove the backslash — though only + in interactive mode. Bash's behavior is weirder. It supports history expansion, and if you + write `"\!"`, the backslash does prevent history expansion from occurring — but it doesn't get + removed! + +*/ + +// `use` declarations to make auto links work: +use ::{quote, join, Shlex, Quoter, QuoteError}; + +// TODO: add more about copy-paste and human readability. diff --git a/bitbox02-bt/vendor/syn-1.0.109/.cargo-checksum.json b/bitbox02-bt/vendor/syn-1.0.109/.cargo-checksum.json new file mode 100644 index 0000000..27e4b5c --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"139a7e42e4c95f9730d4dfe05dd5e09ee59f713eacc310921a61d9fdfc0bdce0","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"ea9f2b6340b302b5608d2bedcda7e2d707f3eaebf4cc983c02d55071ead7096f","benches/file.rs":"3d737ef3878f6e242b003af9bd539e565f98439a12ee44d9548d84e3fdd7af0c","benches/rust.rs":"11ac9fe898a7bf1bd63e8a8cc9c08bd795b01f0248215cff99afaaf28ce87fab","build.rs":"b815649fd2929d3debd93a58f5da2fb8eba506047a6a5ba538347305828a87b0","src/attr.rs":"234d9cebe2c5e92cd0f5e1117bf5755037e2e905788a337000a65d4bd82b63aa","src/await.rs":"8aa22e3c201cb2bdb6b4817fa00901f308ab06817607aa7b884c58c957705969","src/bigint.rs":"efc7f64959980653d73fe4f8bc2a3a2904dc05f45b02c6dc15cd316fa3d7c338","src/buffer.rs":"4d15f35273d485261be4f1a765ae03abc1daee9fc9dac5fb4f9b624d6b22cb58","src/custom_keyword.rs":"5c706fc3611e73d16b8c019d7ecb848a86b1ccfcd9e556f80bb6e6a4abe058a8","src/custom_punctuation.rs":"8a666298e774b0d326642f0f73284f6677d0d0a7c9e4a712c9c98d010b4d8a2c","src/data.rs":"75d2c2b5d6a01bf8a6fa2845e41663d8045a78b4b191f1a1bd7c93619d20017a","src/derive.rs":"ee24a202be2d36ccdff576dd9cd765e94b33ef2286946e6725d75b08e777d462","src/discouraged.rs":"6c6a9298f8d24f578da119557bc588f3bd928f7b79fca27d6bdfe3e786dd005f","src/drops.rs":"013385f1dd95663f1afab41abc1e2eea04181998644828935ca564c74d6462ae","src/error.rs":"b30e738fdab7d10e126350e09f7ad907bf4dc14e684b9ed9eeea001c7ee356e0","src/export.rs":"0cf50d70c32d5fddba8b1193032df62e560237c113df3e86ba26b565cc82838e","src/expr.rs":"5eea3828f3291b0ce5463ed5f0c23fc8a39aeceae68a3247ae02ae467dd35a98","src/ext.rs":"1f648cff1d705a1cea64b32b77482b97a82d2fe0aaf63b40cade91e5c02dc969","src/file.rs":"f86697655222ae294215114f4eae8e6b0b5e2a935d6c479ff8f8f889c4efd2e2","src/gen/clone.rs":"76e89fe155fedf43bc4a252af7e35319b82ce455f584bad8698fdc3f9b7f5d4e","src/gen/debug.rs":"4b05e474e864ce6bf1a5a6ab48ee6c0ecdf41a0d750237990cf2e31963bc1208","src/gen/eq.rs":"79f84836fdcd5cfa352f38055dab7c3246c7757650946c1c701234b11021652a","src/gen/fold.rs":"fcd6a05c8c8e0c36e7ede8593002528b553c8b648fbed452106fd6a8a8c9212a","src/gen/hash.rs":"575e8beae303c1eabda12bf76cbd82672268c502a8ebb8517aab18b40fdbc44e","src/gen/visit.rs":"ced9f6c17d2b3eb3553faab710cb2b3d44d6bca7d1862c8c5da09c3d45debecb","src/gen/visit_mut.rs":"966ea340c53461bf8a1c6bed3c882e4ab8b8907fd18ac35531266f7891ae5f46","src/gen_helper.rs":"ea6c66388365971db6a2fc86cbb208f7eacde77e245bc8623f27a3642a3d7741","src/generics.rs":"b81ce0d3ea0f7accef4590d5181cecc4589395865abaea60b0470da727f17340","src/group.rs":"166f0fbb365471ffa3e4f554b72c2b460cbf7e3a1f9bec6c01ef6bbbcd751041","src/ident.rs":"2443e43561abea7eea577b141422258237a663499c839923d8a5ca6fea2470db","src/item.rs":"419c4d6135a7ca7b8f94b5ba038b6af8fcb3939ae807153a19e3c82e9b01e0b7","src/lib.rs":"de155fed49dffb1756ca8b76d82209fe8bc80c4dda6684f669e98835147869a5","src/lifetime.rs":"b18862ef1e690037a4f308ea897debad7bc5038584e3b26c6d8809752ea0e3c2","src/lit.rs":"667d90787fefac4d25e88509799e8423b9f87125027740c30644dd28adfab95d","src/lookahead.rs":"e2c2b6d55906421e83dab51463b58bc6dcb582f1bff9303c8b62afefb8d71e5f","src/mac.rs":"004cb89f9697564f6c9ee837e08ead68463ef946fb4c13c6c105adf2ba364b2b","src/macros.rs":"936f503c2fcde602f05220954ecaf87625c6138d0af13d33d56c7b6530110084","src/op.rs":"9d499022902743a6a0a19223b356449a979b90e60552d0446497d72750e646a4","src/parse.rs":"7b2f8caddf25a5734cbcdf7cbf043cbf9afbc07b484966cd59ddfcec9f970fb3","src/parse_macro_input.rs":"a5d16859b782bb6a2754c1066468a2f1ea05b57390caa32175bb84064973be7b","src/parse_quote.rs":"d7d996f1382c68b5fbfd4b7327ce1d389cd43c3bb3c4f382a35994d0bb79d8ab","src/pat.rs":"b2de04ae6c01df50eab9d1c3908287aca8424adc2007b926c7bcf74d1f64d40a","src/path.rs":"58a4fb3b1ff76d32cfd84a3914f8cadbf55b363c1929222b362b7465385520ac","src/print.rs":"da6529c1d9d21aaf6c835f66b4e67eacb7cf91a10eb5e9a2143b49bf99b3b5e1","src/punctuated.rs":"44c29523dee76605be2531674fe21ed2f1bbd02559aac8b7a49c70af23129ca1","src/reserved.rs":"e70e028bd55cfa43e23cab4ba29e4dc53a3d91eff685ef2b6e57efc2b87a3428","src/sealed.rs":"896a495a5340eec898527f18bd4ddca408ea03ea0ee3af30074ff48deace778d","src/span.rs":"748c51c6feb223c26d3b1701f5bb98aee823666c775c98106cfa24fe29d8cec1","src/spanned.rs":"3ca016a943637653ab98e373dfb826a120f3c159867346fa38a844439944eb39","src/stmt.rs":"601a6914f1e0bf97ae0d31d474a531d195b8c251a4ded11aa8746ac0018d367b","src/thread.rs":"815eca6bd64f4eef7c447f0809e84108f5428ff50225224b373efd8fbb696874","src/token.rs":"5e423a696f80e281c322f37c87577f9fdc28607e9c007e24896a2b12da62d5ad","src/tt.rs":"32402645b6e82ef1e882945721b59b5fb7b0ee337d1972876362ecacef643d0f","src/ty.rs":"9befd22f8c8ac731b7f68008552a1335797a3ef19184190eec0e103e4ebe18a7","src/verbatim.rs":"96d4280e4556a1841b8dcb306bc35a94d18f71dceb63f3c27a4fe7f776191760","src/whitespace.rs":"e63dd0aa3d34029f17766a8b09c1a6e4479e36c552c8b7023d710a399333aace","tests/common/eq.rs":"e930fb0bdcec3e787986b56785b1db580e5a26a5131df2f2b91a6da37069de15","tests/common/mod.rs":"432ad35577f836a20b517d8c26ed994ac25fe73ef2f461c67688b61b99762015","tests/common/parse.rs":"81580f23583723f7a2a337c4d13ebc021057cd825562fb4e474caa7cc641fed9","tests/debug/gen.rs":"1b7f875344cb04a7dd3df62deac2f410a9d107c097986e68006d87465f5f5306","tests/debug/mod.rs":"3a6bb799f478101f71c84c6f1a854a58afe2f9db43c39017909346ca20262d94","tests/macros/mod.rs":"aff805b35cfd55aef6a1359ff747e4023afcb08d69d86aff4c19465d29dda088","tests/regression.rs":"86731134bfb9bb693d9a4fc62393027de80a8bf031109ea6c7ea475b1ebdde8d","tests/regression/issue1108.rs":"adcc55a42239d344da74216ed85fc14153ddd6ca4dec4872d8339604ba78c185","tests/regression/issue1235.rs":"a2266b10c3f7c7af5734817ab0a3e8b309b51e7d177b63f26e67e6b744d280b0","tests/repo/mod.rs":"159c2c4b6416d26ac42ffc35f6cb587c4c1e2b0f24de9aa42b0337a534d7d86d","tests/repo/progress.rs":"c08d0314a7f3ecf760d471f27da3cd2a500aeb9f1c8331bffb2aa648f9fabf3f","tests/test_asyncness.rs":"cff01db49d28ab23b0b258bc6c0a5cc4071be4fe7248eef344a5d79d2fb649b7","tests/test_attribute.rs":"0ffd99384e1a52ae17d9fed5c4053e411e8f9018decef07ffa621d1faa7329d8","tests/test_derive_input.rs":"62bb86aaaaf730187a46ff700a8e3b2d1a163039b109b6a483aa44ed2b6806fe","tests/test_expr.rs":"41eb343829ad36cdea40cd06d45a90765e7fe6f1e47dd550daf1b6096c3a7b44","tests/test_generics.rs":"54b7d2afc19aa6e9049585f4c8f7d3f0c29ac3bd11a2c769e9df76f18a4f5ecb","tests/test_grouping.rs":"6276c3c73bba649dec5c97904ad2492879f918bc887a2c425d095c654ca0d925","tests/test_ident.rs":"9eb53d1e21edf23e7c9e14dc74dcc2b2538e9221e19dbcc0a44e3acc2e90f3f6","tests/test_item.rs":"a3642c80066f1e7787becfd0278af90a6b7968d6c1249e25e81663aa454cfb2a","tests/test_iterators.rs":"9cf6fde17853ce7d5617e1de9ef901c47ca35c0f1c2dd668c0d0604d7b48598c","tests/test_lit.rs":"137cc9f882cca58f0f2c109535b7ad03c5a35a0aee0cbb9e98ad94710d64e265","tests/test_meta.rs":"65d4586d131f6cac66694ca5e936748ec4e7f7423af6d8da509240e6be14800b","tests/test_parse_buffer.rs":"68d857f776396d064fcc0023c37093c2fbf75ee68e8241d4014d00d1423c18e9","tests/test_parse_stream.rs":"bf1db6fab7ac396fa61012faccbe6ffbc9c3d795ed2900be75e91c5b09b0c62f","tests/test_pat.rs":"d4465f4fc3fd5d6e534ba8efabe1e0ed6da89de4ac7c96effa6bfb880c4287cf","tests/test_path.rs":"71092a5ae2c9143b92a8fe15a92d39958b3c28bd4d4275cfb2d22cbdd53ada07","tests/test_precedence.rs":"736eee861c4c7a3d7d4387d2fb1b5eced1541790d34974f72b0a5532797e73c3","tests/test_receiver.rs":"084eca59984b9a18651da52f2c4407355da3de1335916a12477652999e2d01cc","tests/test_round_trip.rs":"c3c415413d5177a728c7cbbfb7ef44aebbc6a2c821dd56695156e9e33636fd57","tests/test_shebang.rs":"f5772cadad5b56e3112cb16308b779f92bce1c3a48091fc9933deb2276a69331","tests/test_should_parse.rs":"1d3535698a446e2755bfc360676bdb161841a1f454cdef6e7556c6d06a95c89d","tests/test_size.rs":"6720d55569808244ab011364c39931f06aa509cd05f98ab908b0670e8501b3c8","tests/test_stmt.rs":"0601fc32131b5501dfcdc4b4248d46bf21e0a98a49eb19439e1a46869dfb30b7","tests/test_token_trees.rs":"43e56a701817e3c3bfd0cae54a457dd7a38ccb3ca19da41e2b995fdf20e6ed18","tests/test_ty.rs":"f71d7f7f1c038aaabea8dd4c03c0d5752c76d570f8b4885a81659825bbb4d576","tests/test_visibility.rs":"7456fcb3a6634db509748aededff9c2d8b242d511a3e5ee3022e40b232892704","tests/zzz_stable.rs":"2a862e59cb446235ed99aec0e6ada8e16d3ecc30229b29d825b7c0bbc2602989"},"package":"72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"} \ No newline at end of file diff --git a/bitbox02-bt/vendor/syn-1.0.109/Cargo.toml b/bitbox02-bt/vendor/syn-1.0.109/Cargo.toml new file mode 100644 index 0000000..cd26cef --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/Cargo.toml @@ -0,0 +1,147 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.31" +name = "syn" +version = "1.0.109" +authors = ["David Tolnay "] +include = [ + "/benches/**", + "/build.rs", + "/Cargo.toml", + "/LICENSE-APACHE", + "/LICENSE-MIT", + "/README.md", + "/src/**", + "/tests/**", +] +description = "Parser for Rust source code" +documentation = "https://docs.rs/syn" +readme = "README.md" +keywords = [ + "macros", + "syn", +] +categories = [ + "development-tools::procedural-macro-helpers", + "parser-implementations", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/syn" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = [ + "--cfg", + "doc_cfg", +] +targets = ["x86_64-unknown-linux-gnu"] + +[package.metadata.playground] +features = [ + "full", + "visit", + "visit-mut", + "fold", + "extra-traits", +] + +[lib] +doc-scrape-examples = false + +[[bench]] +name = "rust" +harness = false +required-features = [ + "full", + "parsing", +] + +[[bench]] +name = "file" +required-features = [ + "full", + "parsing", +] + +[dependencies.proc-macro2] +version = "1.0.46" +default-features = false + +[dependencies.quote] +version = "1.0" +optional = true +default-features = false + +[dependencies.unicode-ident] +version = "1.0" + +[dev-dependencies.anyhow] +version = "1.0" + +[dev-dependencies.automod] +version = "1.0" + +[dev-dependencies.flate2] +version = "1.0" + +[dev-dependencies.insta] +version = "1.0" + +[dev-dependencies.rayon] +version = "1.0" + +[dev-dependencies.ref-cast] +version = "1.0" + +[dev-dependencies.regex] +version = "1.0" + +[dev-dependencies.reqwest] +version = "0.11" +features = ["blocking"] + +[dev-dependencies.syn-test-suite] +version = "0" + +[dev-dependencies.tar] +version = "0.4.16" + +[dev-dependencies.termcolor] +version = "1.0" + +[dev-dependencies.walkdir] +version = "2.1" + +[features] +clone-impls = [] +default = [ + "derive", + "parsing", + "printing", + "clone-impls", + "proc-macro", +] +derive = [] +extra-traits = [] +fold = [] +full = [] +parsing = [] +printing = ["quote"] +proc-macro = [ + "proc-macro2/proc-macro", + "quote/proc-macro", +] +test = ["syn-test-suite/all-features"] +visit = [] +visit-mut = [] diff --git a/bitbox02-bt/vendor/syn-1.0.109/LICENSE-APACHE b/bitbox02-bt/vendor/syn-1.0.109/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/bitbox02-bt/vendor/syn-1.0.109/LICENSE-MIT b/bitbox02-bt/vendor/syn-1.0.109/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/bitbox02-bt/vendor/syn-1.0.109/README.md b/bitbox02-bt/vendor/syn-1.0.109/README.md new file mode 100644 index 0000000..eeef83d --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/README.md @@ -0,0 +1,285 @@ +Parser for Rust source code +=========================== + +[github](https://github.com/dtolnay/syn) +[crates.io](https://crates.io/crates/syn) +[docs.rs](https://docs.rs/syn) +[build status](https://github.com/dtolnay/syn/actions?query=branch%3Amaster) + +Syn is a parsing library for parsing a stream of Rust tokens into a syntax tree +of Rust source code. + +Currently this library is geared toward use in Rust procedural macros, but +contains some APIs that may be useful more generally. + +- **Data structures** — Syn provides a complete syntax tree that can represent + any valid Rust source code. The syntax tree is rooted at [`syn::File`] which + represents a full source file, but there are other entry points that may be + useful to procedural macros including [`syn::Item`], [`syn::Expr`] and + [`syn::Type`]. + +- **Derives** — Of particular interest to derive macros is [`syn::DeriveInput`] + which is any of the three legal input items to a derive macro. An example + below shows using this type in a library that can derive implementations of a + user-defined trait. + +- **Parsing** — Parsing in Syn is built around [parser functions] with the + signature `fn(ParseStream) -> Result`. Every syntax tree node defined by + Syn is individually parsable and may be used as a building block for custom + syntaxes, or you may dream up your own brand new syntax without involving any + of our syntax tree types. + +- **Location information** — Every token parsed by Syn is associated with a + `Span` that tracks line and column information back to the source of that + token. These spans allow a procedural macro to display detailed error messages + pointing to all the right places in the user's code. There is an example of + this below. + +- **Feature flags** — Functionality is aggressively feature gated so your + procedural macros enable only what they need, and do not pay in compile time + for all the rest. + +[`syn::File`]: https://docs.rs/syn/1.0/syn/struct.File.html +[`syn::Item`]: https://docs.rs/syn/1.0/syn/enum.Item.html +[`syn::Expr`]: https://docs.rs/syn/1.0/syn/enum.Expr.html +[`syn::Type`]: https://docs.rs/syn/1.0/syn/enum.Type.html +[`syn::DeriveInput`]: https://docs.rs/syn/1.0/syn/struct.DeriveInput.html +[parser functions]: https://docs.rs/syn/1.0/syn/parse/index.html + +*Version requirement: Syn supports rustc 1.31 and up.* + +[*Release notes*](https://github.com/dtolnay/syn/releases) + +
+ +## Resources + +The best way to learn about procedural macros is by writing some. Consider +working through [this procedural macro workshop][workshop] to get familiar with +the different types of procedural macros. The workshop contains relevant links +into the Syn documentation as you work through each project. + +[workshop]: https://github.com/dtolnay/proc-macro-workshop + +
+ +## Example of a derive macro + +The canonical derive macro using Syn looks like this. We write an ordinary Rust +function tagged with a `proc_macro_derive` attribute and the name of the trait +we are deriving. Any time that derive appears in the user's code, the Rust +compiler passes their data structure as tokens into our macro. We get to execute +arbitrary Rust code to figure out what to do with those tokens, then hand some +tokens back to the compiler to compile into the user's crate. + +[`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html + +```toml +[dependencies] +syn = "1.0" +quote = "1.0" + +[lib] +proc-macro = true +``` + +```rust +use proc_macro::TokenStream; +use quote::quote; +use syn::{parse_macro_input, DeriveInput}; + +#[proc_macro_derive(MyMacro)] +pub fn my_macro(input: TokenStream) -> TokenStream { + // Parse the input tokens into a syntax tree + let input = parse_macro_input!(input as DeriveInput); + + // Build the output, possibly using quasi-quotation + let expanded = quote! { + // ... + }; + + // Hand the output tokens back to the compiler + TokenStream::from(expanded) +} +``` + +The [`heapsize`] example directory shows a complete working implementation of a +derive macro. It works on any Rust compiler 1.31+. The example derives a +`HeapSize` trait which computes an estimate of the amount of heap memory owned +by a value. + +[`heapsize`]: examples/heapsize + +```rust +pub trait HeapSize { + /// Total number of bytes of heap memory owned by `self`. + fn heap_size_of_children(&self) -> usize; +} +``` + +The derive macro allows users to write `#[derive(HeapSize)]` on data structures +in their program. + +```rust +#[derive(HeapSize)] +struct Demo<'a, T: ?Sized> { + a: Box, + b: u8, + c: &'a str, + d: String, +} +``` + +
+ +## Spans and error reporting + +The token-based procedural macro API provides great control over where the +compiler's error messages are displayed in user code. Consider the error the +user sees if one of their field types does not implement `HeapSize`. + +```rust +#[derive(HeapSize)] +struct Broken { + ok: String, + bad: std::thread::Thread, +} +``` + +By tracking span information all the way through the expansion of a procedural +macro as shown in the `heapsize` example, token-based macros in Syn are able to +trigger errors that directly pinpoint the source of the problem. + +```console +error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied + --> src/main.rs:7:5 + | +7 | bad: std::thread::Thread, + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `std::thread::Thread` +``` + +
+ +## Parsing a custom syntax + +The [`lazy-static`] example directory shows the implementation of a +`functionlike!(...)` procedural macro in which the input tokens are parsed using +Syn's parsing API. + +[`lazy-static`]: examples/lazy-static + +The example reimplements the popular `lazy_static` crate from crates.io as a +procedural macro. + +```rust +lazy_static! { + static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); +} +``` + +The implementation shows how to trigger custom warnings and error messages on +the macro input. + +```console +warning: come on, pick a more creative name + --> src/main.rs:10:16 + | +10 | static ref FOO: String = "lazy_static".to_owned(); + | ^^^ +``` + +
+ +## Testing + +When testing macros, we often care not just that the macro can be used +successfully but also that when the macro is provided with invalid input it +produces maximally helpful error messages. Consider using the [`trybuild`] crate +to write tests for errors that are emitted by your macro or errors detected by +the Rust compiler in the expanded code following misuse of the macro. Such tests +help avoid regressions from later refactors that mistakenly make an error no +longer trigger or be less helpful than it used to be. + +[`trybuild`]: https://github.com/dtolnay/trybuild + +
+ +## Debugging + +When developing a procedural macro it can be helpful to look at what the +generated code looks like. Use `cargo rustc -- -Zunstable-options +--pretty=expanded` or the [`cargo expand`] subcommand. + +[`cargo expand`]: https://github.com/dtolnay/cargo-expand + +To show the expanded code for some crate that uses your procedural macro, run +`cargo expand` from that crate. To show the expanded code for one of your own +test cases, run `cargo expand --test the_test_case` where the last argument is +the name of the test file without the `.rs` extension. + +This write-up by Brandon W Maister discusses debugging in more detail: +[Debugging Rust's new Custom Derive system][debugging]. + +[debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ + +
+ +## Optional features + +Syn puts a lot of functionality behind optional features in order to optimize +compile time for the most common use cases. The following features are +available. + +- **`derive`** *(enabled by default)* — Data structures for representing the + possible input to a derive macro, including structs and enums and types. +- **`full`** — Data structures for representing the syntax tree of all valid + Rust source code, including items and expressions. +- **`parsing`** *(enabled by default)* — Ability to parse input tokens into a + syntax tree node of a chosen type. +- **`printing`** *(enabled by default)* — Ability to print a syntax tree node as + tokens of Rust source code. +- **`visit`** — Trait for traversing a syntax tree. +- **`visit-mut`** — Trait for traversing and mutating in place a syntax tree. +- **`fold`** — Trait for transforming an owned syntax tree. +- **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree + types. +- **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree + types. +- **`proc-macro`** *(enabled by default)* — Runtime dependency on the dynamic + library libproc_macro from rustc toolchain. + +
+ +## Proc macro shim + +Syn operates on the token representation provided by the [proc-macro2] crate +from crates.io rather than using the compiler's built in proc-macro crate +directly. This enables code using Syn to execute outside of the context of a +procedural macro, such as in unit tests or build.rs, and we avoid needing +incompatible ecosystems for proc macros vs non-macro use cases. + +In general all of your code should be written against proc-macro2 rather than +proc-macro. The one exception is in the signatures of procedural macro entry +points, which are required by the language to use `proc_macro::TokenStream`. + +The proc-macro2 crate will automatically detect and use the compiler's data +structures when a procedural macro is active. + +[proc-macro2]: https://docs.rs/proc-macro2/1.0/proc_macro2/ + +
+ +#### License + + +Licensed under either of
Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/bitbox02-bt/vendor/syn-1.0.109/benches/file.rs b/bitbox02-bt/vendor/syn-1.0.109/benches/file.rs new file mode 100644 index 0000000..bd4a247 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/benches/file.rs @@ -0,0 +1,55 @@ +// $ cargo bench --features full,test --bench file + +#![feature(rustc_private, test)] +#![recursion_limit = "1024"] +#![allow( + clippy::items_after_statements, + clippy::missing_panics_doc, + clippy::must_use_candidate +)] + +extern crate test; + +#[macro_use] +#[path = "../tests/macros/mod.rs"] +mod macros; + +#[path = "../tests/common/mod.rs"] +mod common; +#[path = "../tests/repo/mod.rs"] +pub mod repo; + +use proc_macro2::{Span, TokenStream}; +use std::fs; +use std::str::FromStr; +use syn::parse::{ParseStream, Parser}; +use test::Bencher; + +const FILE: &str = "tests/rust/library/core/src/str/mod.rs"; + +fn get_tokens() -> TokenStream { + repo::clone_rust(); + let content = fs::read_to_string(FILE).unwrap(); + TokenStream::from_str(&content).unwrap() +} + +#[bench] +fn baseline(b: &mut Bencher) { + let tokens = get_tokens(); + b.iter(|| drop(tokens.clone())); +} + +#[bench] +fn create_token_buffer(b: &mut Bencher) { + let tokens = get_tokens(); + fn immediate_fail(_input: ParseStream) -> syn::Result<()> { + Err(syn::Error::new(Span::call_site(), "")) + } + b.iter(|| immediate_fail.parse2(tokens.clone())); +} + +#[bench] +fn parse_file(b: &mut Bencher) { + let tokens = get_tokens(); + b.iter(|| syn::parse2::(tokens.clone())); +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/benches/rust.rs b/bitbox02-bt/vendor/syn-1.0.109/benches/rust.rs new file mode 100644 index 0000000..e3f8f55 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/benches/rust.rs @@ -0,0 +1,170 @@ +// $ cargo bench --features full,test --bench rust +// +// Syn only, useful for profiling: +// $ RUSTFLAGS='--cfg syn_only' cargo build --release --features full,test --bench rust + +#![cfg_attr(not(syn_only), feature(rustc_private))] +#![recursion_limit = "1024"] +#![allow(clippy::cast_lossless, clippy::unnecessary_wraps)] + +#[macro_use] +#[path = "../tests/macros/mod.rs"] +mod macros; + +#[path = "../tests/common/mod.rs"] +mod common; +#[path = "../tests/repo/mod.rs"] +mod repo; + +use std::fs; +use std::time::{Duration, Instant}; + +#[cfg(not(syn_only))] +mod tokenstream_parse { + use proc_macro2::TokenStream; + use std::str::FromStr; + + pub fn bench(content: &str) -> Result<(), ()> { + TokenStream::from_str(content).map(drop).map_err(drop) + } +} + +mod syn_parse { + pub fn bench(content: &str) -> Result<(), ()> { + syn::parse_file(content).map(drop).map_err(drop) + } +} + +#[cfg(not(syn_only))] +mod librustc_parse { + extern crate rustc_data_structures; + extern crate rustc_error_messages; + extern crate rustc_errors; + extern crate rustc_parse; + extern crate rustc_session; + extern crate rustc_span; + + use rustc_data_structures::sync::Lrc; + use rustc_error_messages::FluentBundle; + use rustc_errors::{emitter::Emitter, translation::Translate, Diagnostic, Handler}; + use rustc_session::parse::ParseSess; + use rustc_span::source_map::{FilePathMapping, SourceMap}; + use rustc_span::{edition::Edition, FileName}; + + pub fn bench(content: &str) -> Result<(), ()> { + struct SilentEmitter; + + impl Emitter for SilentEmitter { + fn emit_diagnostic(&mut self, _diag: &Diagnostic) {} + fn source_map(&self) -> Option<&Lrc> { + None + } + } + + impl Translate for SilentEmitter { + fn fluent_bundle(&self) -> Option<&Lrc> { + None + } + fn fallback_fluent_bundle(&self) -> &FluentBundle { + panic!("silent emitter attempted to translate a diagnostic"); + } + } + + rustc_span::create_session_if_not_set_then(Edition::Edition2018, |_| { + let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); + let emitter = Box::new(SilentEmitter); + let handler = Handler::with_emitter(false, None, emitter); + let sess = ParseSess::with_span_handler(handler, cm); + if let Err(diagnostic) = rustc_parse::parse_crate_from_source_str( + FileName::Custom("bench".to_owned()), + content.to_owned(), + &sess, + ) { + diagnostic.cancel(); + return Err(()); + }; + Ok(()) + }) + } +} + +#[cfg(not(syn_only))] +mod read_from_disk { + pub fn bench(content: &str) -> Result<(), ()> { + _ = content; + Ok(()) + } +} + +fn exec(mut codepath: impl FnMut(&str) -> Result<(), ()>) -> Duration { + let begin = Instant::now(); + let mut success = 0; + let mut total = 0; + + walkdir::WalkDir::new("tests/rust/src") + .into_iter() + .filter_entry(repo::base_dir_filter) + .for_each(|entry| { + let entry = entry.unwrap(); + let path = entry.path(); + if path.is_dir() { + return; + } + let content = fs::read_to_string(path).unwrap(); + let ok = codepath(&content).is_ok(); + success += ok as usize; + total += 1; + if !ok { + eprintln!("FAIL {}", path.display()); + } + }); + + assert_eq!(success, total); + begin.elapsed() +} + +fn main() { + repo::clone_rust(); + + macro_rules! testcases { + ($($(#[$cfg:meta])* $name:ident,)*) => { + [ + $( + $(#[$cfg])* + (stringify!($name), $name::bench as fn(&str) -> Result<(), ()>), + )* + ] + }; + } + + #[cfg(not(syn_only))] + { + let mut lines = 0; + let mut files = 0; + exec(|content| { + lines += content.lines().count(); + files += 1; + Ok(()) + }); + eprintln!("\n{} lines in {} files", lines, files); + } + + for (name, f) in testcases!( + #[cfg(not(syn_only))] + read_from_disk, + #[cfg(not(syn_only))] + tokenstream_parse, + syn_parse, + #[cfg(not(syn_only))] + librustc_parse, + ) { + eprint!("{:20}", format!("{}:", name)); + let elapsed = exec(f); + eprintln!( + "elapsed={}.{:03}s", + elapsed.as_secs(), + elapsed.subsec_millis(), + ); + } + eprintln!(); +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/build.rs b/bitbox02-bt/vendor/syn-1.0.109/build.rs new file mode 100644 index 0000000..1a2c077 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/build.rs @@ -0,0 +1,51 @@ +use std::env; +use std::process::Command; +use std::str; + +// The rustc-cfg strings below are *not* public API. Please let us know by +// opening a GitHub issue if your build environment requires some way to enable +// these cfgs other than by executing our build script. +fn main() { + let compiler = match rustc_version() { + Some(compiler) => compiler, + None => return, + }; + + if compiler.minor < 36 { + println!("cargo:rustc-cfg=syn_omit_await_from_token_macro"); + } + + if compiler.minor < 39 { + println!("cargo:rustc-cfg=syn_no_const_vec_new"); + } + + if compiler.minor < 40 { + println!("cargo:rustc-cfg=syn_no_non_exhaustive"); + } + + if compiler.minor < 56 { + println!("cargo:rustc-cfg=syn_no_negative_literal_parse"); + } + + if !compiler.nightly { + println!("cargo:rustc-cfg=syn_disable_nightly_tests"); + } +} + +struct Compiler { + minor: u32, + nightly: bool, +} + +fn rustc_version() -> Option { + let rustc = env::var_os("RUSTC")?; + let output = Command::new(rustc).arg("--version").output().ok()?; + let version = str::from_utf8(&output.stdout).ok()?; + let mut pieces = version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + let minor = pieces.next()?.parse().ok()?; + let nightly = version.contains("nightly") || version.ends_with("-dev"); + Some(Compiler { minor, nightly }) +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/attr.rs b/bitbox02-bt/vendor/syn-1.0.109/src/attr.rs new file mode 100644 index 0000000..bace94f --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/attr.rs @@ -0,0 +1,662 @@ +use super::*; +use crate::punctuated::Punctuated; +use proc_macro2::TokenStream; +use std::iter; +use std::slice; + +#[cfg(feature = "parsing")] +use crate::parse::{Parse, ParseBuffer, ParseStream, Parser, Result}; +#[cfg(feature = "parsing")] +use crate::punctuated::Pair; + +ast_struct! { + /// An attribute like `#[repr(transparent)]`. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + ///
+ /// + /// # Syntax + /// + /// Rust has six types of attributes. + /// + /// - Outer attributes like `#[repr(transparent)]`. These appear outside or + /// in front of the item they describe. + /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside + /// of the item they describe, usually a module. + /// - Outer doc comments like `/// # Example`. + /// - Inner doc comments like `//! Please file an issue`. + /// - Outer block comments `/** # Example */`. + /// - Inner block comments `/*! Please file an issue */`. + /// + /// The `style` field of type `AttrStyle` distinguishes whether an attribute + /// is outer or inner. Doc comments and block comments are promoted to + /// attributes, as this is how they are processed by the compiler and by + /// `macro_rules!` macros. + /// + /// The `path` field gives the possibly colon-delimited path against which + /// the attribute is resolved. It is equal to `"doc"` for desugared doc + /// comments. The `tokens` field contains the rest of the attribute body as + /// tokens. + /// + /// ```text + /// #[derive(Copy)] #[crate::precondition x < 5] + /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~ + /// path tokens path tokens + /// ``` + /// + ///
+ /// + /// # Parsing from tokens to Attribute + /// + /// This type does not implement the [`Parse`] trait and thus cannot be + /// parsed directly by [`ParseStream::parse`]. Instead use + /// [`ParseStream::call`] with one of the two parser functions + /// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on + /// which you intend to parse. + /// + /// [`Parse`]: parse::Parse + /// [`ParseStream::parse`]: parse::ParseBuffer::parse + /// [`ParseStream::call`]: parse::ParseBuffer::call + /// + /// ``` + /// use syn::{Attribute, Ident, Result, Token}; + /// use syn::parse::{Parse, ParseStream}; + /// + /// // Parses a unit struct with attributes. + /// // + /// // #[path = "s.tmpl"] + /// // struct S; + /// struct UnitStruct { + /// attrs: Vec, + /// struct_token: Token![struct], + /// name: Ident, + /// semi_token: Token![;], + /// } + /// + /// impl Parse for UnitStruct { + /// fn parse(input: ParseStream) -> Result { + /// Ok(UnitStruct { + /// attrs: input.call(Attribute::parse_outer)?, + /// struct_token: input.parse()?, + /// name: input.parse()?, + /// semi_token: input.parse()?, + /// }) + /// } + /// } + /// ``` + /// + ///


+ /// + /// # Parsing from Attribute to structured arguments + /// + /// The grammar of attributes in Rust is very flexible, which makes the + /// syntax tree not that useful on its own. In particular, arguments of the + /// attribute are held in an arbitrary `tokens: TokenStream`. Macros are + /// expected to check the `path` of the attribute, decide whether they + /// recognize it, and then parse the remaining tokens according to whatever + /// grammar they wish to require for that kind of attribute. + /// + /// If the attribute you are parsing is expected to conform to the + /// conventional structured form of attribute, use [`parse_meta()`] to + /// obtain that structured representation. If the attribute follows some + /// other grammar of its own, use [`parse_args()`] to parse that into the + /// expected data structure. + /// + /// [`parse_meta()`]: Attribute::parse_meta + /// [`parse_args()`]: Attribute::parse_args + /// + ///


+ /// + /// # Doc comments + /// + /// The compiler transforms doc comments, such as `/// comment` and `/*! + /// comment */`, into attributes before macros are expanded. Each comment is + /// expanded into an attribute of the form `#[doc = r"comment"]`. + /// + /// As an example, the following `mod` items are expanded identically: + /// + /// ``` + /// # use syn::{ItemMod, parse_quote}; + /// let doc: ItemMod = parse_quote! { + /// /// Single line doc comments + /// /// We write so many! + /// /** + /// * Multi-line comments... + /// * May span many lines + /// */ + /// mod example { + /// //! Of course, they can be inner too + /// /*! And fit in a single line */ + /// } + /// }; + /// let attr: ItemMod = parse_quote! { + /// #[doc = r" Single line doc comments"] + /// #[doc = r" We write so many!"] + /// #[doc = r" + /// * Multi-line comments... + /// * May span many lines + /// "] + /// mod example { + /// #![doc = r" Of course, they can be inner too"] + /// #![doc = r" And fit in a single line "] + /// } + /// }; + /// assert_eq!(doc, attr); + /// ``` + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct Attribute { + pub pound_token: Token![#], + pub style: AttrStyle, + pub bracket_token: token::Bracket, + pub path: Path, + pub tokens: TokenStream, + } +} + +impl Attribute { + /// Parses the content of the attribute, consisting of the path and tokens, + /// as a [`Meta`] if possible. + /// + /// *This function is available only if Syn is built with the `"parsing"` + /// feature.* + #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + pub fn parse_meta(&self) -> Result { + fn clone_ident_segment(segment: &PathSegment) -> PathSegment { + PathSegment { + ident: segment.ident.clone(), + arguments: PathArguments::None, + } + } + + let path = Path { + leading_colon: self + .path + .leading_colon + .as_ref() + .map(|colon| Token![::](colon.spans)), + segments: self + .path + .segments + .pairs() + .map(|pair| match pair { + Pair::Punctuated(seg, punct) => { + Pair::Punctuated(clone_ident_segment(seg), Token![::](punct.spans)) + } + Pair::End(seg) => Pair::End(clone_ident_segment(seg)), + }) + .collect(), + }; + + let parser = |input: ParseStream| parsing::parse_meta_after_path(path, input); + parse::Parser::parse2(parser, self.tokens.clone()) + } + + /// Parse the arguments to the attribute as a syntax tree. + /// + /// This is similar to `syn::parse2::(attr.tokens)` except that: + /// + /// - the surrounding delimiters are *not* included in the input to the + /// parser; and + /// - the error message has a more useful span when `tokens` is empty. + /// + /// ```text + /// #[my_attr(value < 5)] + /// ^^^^^^^^^ what gets parsed + /// ``` + /// + /// *This function is available only if Syn is built with the `"parsing"` + /// feature.* + #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + pub fn parse_args(&self) -> Result { + self.parse_args_with(T::parse) + } + + /// Parse the arguments to the attribute using the given parser. + /// + /// *This function is available only if Syn is built with the `"parsing"` + /// feature.* + #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + pub fn parse_args_with(&self, parser: F) -> Result { + let parser = |input: ParseStream| { + let args = enter_args(self, input)?; + parse::parse_stream(parser, &args) + }; + parser.parse2(self.tokens.clone()) + } + + /// Parses zero or more outer attributes from the stream. + /// + /// *This function is available only if Syn is built with the `"parsing"` + /// feature.* + #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + pub fn parse_outer(input: ParseStream) -> Result> { + let mut attrs = Vec::new(); + while input.peek(Token![#]) { + attrs.push(input.call(parsing::single_parse_outer)?); + } + Ok(attrs) + } + + /// Parses zero or more inner attributes from the stream. + /// + /// *This function is available only if Syn is built with the `"parsing"` + /// feature.* + #[cfg(feature = "parsing")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + pub fn parse_inner(input: ParseStream) -> Result> { + let mut attrs = Vec::new(); + parsing::parse_inner(input, &mut attrs)?; + Ok(attrs) + } +} + +#[cfg(feature = "parsing")] +fn expected_parentheses(attr: &Attribute) -> String { + let style = match attr.style { + AttrStyle::Outer => "#", + AttrStyle::Inner(_) => "#!", + }; + + let mut path = String::new(); + for segment in &attr.path.segments { + if !path.is_empty() || attr.path.leading_colon.is_some() { + path += "::"; + } + path += &segment.ident.to_string(); + } + + format!("{}[{}(...)]", style, path) +} + +#[cfg(feature = "parsing")] +fn enter_args<'a>(attr: &Attribute, input: ParseStream<'a>) -> Result> { + if input.is_empty() { + let expected = expected_parentheses(attr); + let msg = format!("expected attribute arguments in parentheses: {}", expected); + return Err(crate::error::new2( + attr.pound_token.span, + attr.bracket_token.span, + msg, + )); + } else if input.peek(Token![=]) { + let expected = expected_parentheses(attr); + let msg = format!("expected parentheses: {}", expected); + return Err(input.error(msg)); + }; + + let content; + if input.peek(token::Paren) { + parenthesized!(content in input); + } else if input.peek(token::Bracket) { + bracketed!(content in input); + } else if input.peek(token::Brace) { + braced!(content in input); + } else { + return Err(input.error("unexpected token in attribute arguments")); + } + + if input.is_empty() { + Ok(content) + } else { + Err(input.error("unexpected token in attribute arguments")) + } +} + +ast_enum! { + /// Distinguishes between attributes that decorate an item and attributes + /// that are contained within an item. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Outer attributes + /// + /// - `#[repr(transparent)]` + /// - `/// # Example` + /// - `/** Please file an issue */` + /// + /// # Inner attributes + /// + /// - `#![feature(proc_macro)]` + /// - `//! # Example` + /// - `/*! Please file an issue */` + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub enum AttrStyle { + Outer, + Inner(Token![!]), + } +} + +ast_enum_of_structs! { + /// Content of a compile-time structured attribute. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// ## Path + /// + /// A meta path is like the `test` in `#[test]`. + /// + /// ## List + /// + /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`. + /// + /// ## NameValue + /// + /// A name-value meta is like the `path = "..."` in `#[path = + /// "sys/windows.rs"]`. + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub enum Meta { + Path(Path), + + /// A structured list within an attribute, like `derive(Copy, Clone)`. + List(MetaList), + + /// A name-value pair within an attribute, like `feature = "nightly"`. + NameValue(MetaNameValue), + } +} + +ast_struct! { + /// A structured list within an attribute, like `derive(Copy, Clone)`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct MetaList { + pub path: Path, + pub paren_token: token::Paren, + pub nested: Punctuated, + } +} + +ast_struct! { + /// A name-value pair within an attribute, like `feature = "nightly"`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct MetaNameValue { + pub path: Path, + pub eq_token: Token![=], + pub lit: Lit, + } +} + +impl Meta { + /// Returns the identifier that begins this structured meta item. + /// + /// For example this would return the `test` in `#[test]`, the `derive` in + /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`. + pub fn path(&self) -> &Path { + match self { + Meta::Path(path) => path, + Meta::List(meta) => &meta.path, + Meta::NameValue(meta) => &meta.path, + } + } +} + +ast_enum_of_structs! { + /// Element of a compile-time attribute list. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub enum NestedMeta { + /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which + /// would be a nested `Meta::Path`. + Meta(Meta), + + /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`. + Lit(Lit), + } +} + +/// Conventional argument type associated with an invocation of an attribute +/// macro. +/// +/// For example if we are developing an attribute macro that is intended to be +/// invoked on function items as follows: +/// +/// ``` +/// # const IGNORE: &str = stringify! { +/// #[my_attribute(path = "/v1/refresh")] +/// # }; +/// pub fn refresh() { +/// /* ... */ +/// } +/// ``` +/// +/// The implementation of this macro would want to parse its attribute arguments +/// as type `AttributeArgs`. +/// +/// ``` +/// # extern crate proc_macro; +/// # +/// use proc_macro::TokenStream; +/// use syn::{parse_macro_input, AttributeArgs, ItemFn}; +/// +/// # const IGNORE: &str = stringify! { +/// #[proc_macro_attribute] +/// # }; +/// pub fn my_attribute(args: TokenStream, input: TokenStream) -> TokenStream { +/// let args = parse_macro_input!(args as AttributeArgs); +/// let input = parse_macro_input!(input as ItemFn); +/// +/// /* ... */ +/// # "".parse().unwrap() +/// } +/// ``` +#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] +pub type AttributeArgs = Vec; + +pub trait FilterAttrs<'a> { + type Ret: Iterator; + + fn outer(self) -> Self::Ret; + fn inner(self) -> Self::Ret; +} + +impl<'a> FilterAttrs<'a> for &'a [Attribute] { + type Ret = iter::Filter, fn(&&Attribute) -> bool>; + + fn outer(self) -> Self::Ret { + fn is_outer(attr: &&Attribute) -> bool { + match attr.style { + AttrStyle::Outer => true, + AttrStyle::Inner(_) => false, + } + } + self.iter().filter(is_outer) + } + + fn inner(self) -> Self::Ret { + fn is_inner(attr: &&Attribute) -> bool { + match attr.style { + AttrStyle::Inner(_) => true, + AttrStyle::Outer => false, + } + } + self.iter().filter(is_inner) + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use crate::ext::IdentExt; + use crate::parse::{Parse, ParseStream, Result}; + + pub fn parse_inner(input: ParseStream, attrs: &mut Vec) -> Result<()> { + while input.peek(Token![#]) && input.peek2(Token![!]) { + attrs.push(input.call(parsing::single_parse_inner)?); + } + Ok(()) + } + + pub fn single_parse_inner(input: ParseStream) -> Result { + let content; + Ok(Attribute { + pound_token: input.parse()?, + style: AttrStyle::Inner(input.parse()?), + bracket_token: bracketed!(content in input), + path: content.call(Path::parse_mod_style)?, + tokens: content.parse()?, + }) + } + + pub fn single_parse_outer(input: ParseStream) -> Result { + let content; + Ok(Attribute { + pound_token: input.parse()?, + style: AttrStyle::Outer, + bracket_token: bracketed!(content in input), + path: content.call(Path::parse_mod_style)?, + tokens: content.parse()?, + }) + } + + // Like Path::parse_mod_style but accepts keywords in the path. + fn parse_meta_path(input: ParseStream) -> Result { + Ok(Path { + leading_colon: input.parse()?, + segments: { + let mut segments = Punctuated::new(); + while input.peek(Ident::peek_any) { + let ident = Ident::parse_any(input)?; + segments.push_value(PathSegment::from(ident)); + if !input.peek(Token![::]) { + break; + } + let punct = input.parse()?; + segments.push_punct(punct); + } + if segments.is_empty() { + return Err(input.error("expected path")); + } else if segments.trailing_punct() { + return Err(input.error("expected path segment")); + } + segments + }, + }) + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for Meta { + fn parse(input: ParseStream) -> Result { + let path = input.call(parse_meta_path)?; + parse_meta_after_path(path, input) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for MetaList { + fn parse(input: ParseStream) -> Result { + let path = input.call(parse_meta_path)?; + parse_meta_list_after_path(path, input) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for MetaNameValue { + fn parse(input: ParseStream) -> Result { + let path = input.call(parse_meta_path)?; + parse_meta_name_value_after_path(path, input) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for NestedMeta { + fn parse(input: ParseStream) -> Result { + if input.peek(Lit) && !(input.peek(LitBool) && input.peek2(Token![=])) { + input.parse().map(NestedMeta::Lit) + } else if input.peek(Ident::peek_any) + || input.peek(Token![::]) && input.peek3(Ident::peek_any) + { + input.parse().map(NestedMeta::Meta) + } else { + Err(input.error("expected identifier or literal")) + } + } + } + + pub fn parse_meta_after_path(path: Path, input: ParseStream) -> Result { + if input.peek(token::Paren) { + parse_meta_list_after_path(path, input).map(Meta::List) + } else if input.peek(Token![=]) { + parse_meta_name_value_after_path(path, input).map(Meta::NameValue) + } else { + Ok(Meta::Path(path)) + } + } + + fn parse_meta_list_after_path(path: Path, input: ParseStream) -> Result { + let content; + Ok(MetaList { + path, + paren_token: parenthesized!(content in input), + nested: content.parse_terminated(NestedMeta::parse)?, + }) + } + + fn parse_meta_name_value_after_path(path: Path, input: ParseStream) -> Result { + Ok(MetaNameValue { + path, + eq_token: input.parse()?, + lit: input.parse()?, + }) + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use proc_macro2::TokenStream; + use quote::ToTokens; + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for Attribute { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.pound_token.to_tokens(tokens); + if let AttrStyle::Inner(b) = &self.style { + b.to_tokens(tokens); + } + self.bracket_token.surround(tokens, |tokens| { + self.path.to_tokens(tokens); + self.tokens.to_tokens(tokens); + }); + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for MetaList { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.path.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + self.nested.to_tokens(tokens); + }); + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for MetaNameValue { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.path.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.lit.to_tokens(tokens); + } + } +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/await.rs b/bitbox02-bt/vendor/syn-1.0.109/src/await.rs new file mode 100644 index 0000000..038c6a5 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/await.rs @@ -0,0 +1,2 @@ +// See include!("await.rs") in token.rs. +export_token_macro! {[await]} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/bigint.rs b/bitbox02-bt/vendor/syn-1.0.109/src/bigint.rs new file mode 100644 index 0000000..5397d6b --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/bigint.rs @@ -0,0 +1,66 @@ +use std::ops::{AddAssign, MulAssign}; + +// For implementing base10_digits() accessor on LitInt. +pub struct BigInt { + digits: Vec, +} + +impl BigInt { + pub fn new() -> Self { + BigInt { digits: Vec::new() } + } + + pub fn to_string(&self) -> String { + let mut repr = String::with_capacity(self.digits.len()); + + let mut has_nonzero = false; + for digit in self.digits.iter().rev() { + has_nonzero |= *digit != 0; + if has_nonzero { + repr.push((*digit + b'0') as char); + } + } + + if repr.is_empty() { + repr.push('0'); + } + + repr + } + + fn reserve_two_digits(&mut self) { + let len = self.digits.len(); + let desired = + len + !self.digits.ends_with(&[0, 0]) as usize + !self.digits.ends_with(&[0]) as usize; + self.digits.resize(desired, 0); + } +} + +impl AddAssign for BigInt { + // Assumes increment <16. + fn add_assign(&mut self, mut increment: u8) { + self.reserve_two_digits(); + + let mut i = 0; + while increment > 0 { + let sum = self.digits[i] + increment; + self.digits[i] = sum % 10; + increment = sum / 10; + i += 1; + } + } +} + +impl MulAssign for BigInt { + // Assumes base <=16. + fn mul_assign(&mut self, base: u8) { + self.reserve_two_digits(); + + let mut carry = 0; + for digit in &mut self.digits { + let prod = *digit * base + carry; + *digit = prod % 10; + carry = prod / 10; + } + } +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/buffer.rs b/bitbox02-bt/vendor/syn-1.0.109/src/buffer.rs new file mode 100644 index 0000000..0d5cf30 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/buffer.rs @@ -0,0 +1,398 @@ +//! A stably addressed token buffer supporting efficient traversal based on a +//! cheaply copyable cursor. +//! +//! *This module is available only if Syn is built with the `"parsing"` feature.* + +// This module is heavily commented as it contains most of the unsafe code in +// Syn, and caution should be used when editing it. The public-facing interface +// is 100% safe but the implementation is fragile internally. + +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +use crate::proc_macro as pm; +use crate::Lifetime; +use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::cmp::Ordering; +use std::marker::PhantomData; + +/// Internal type which is used instead of `TokenTree` to represent a token tree +/// within a `TokenBuffer`. +enum Entry { + // Mimicking types from proc-macro. + // Group entries contain the offset to the matching End entry. + Group(Group, usize), + Ident(Ident), + Punct(Punct), + Literal(Literal), + // End entries contain the offset (negative) to the start of the buffer. + End(isize), +} + +/// A buffer that can be efficiently traversed multiple times, unlike +/// `TokenStream` which requires a deep copy in order to traverse more than +/// once. +/// +/// *This type is available only if Syn is built with the `"parsing"` feature.* +pub struct TokenBuffer { + // NOTE: Do not implement clone on this - while the current design could be + // cloned, other designs which could be desirable may not be cloneable. + entries: Box<[Entry]>, +} + +impl TokenBuffer { + fn recursive_new(entries: &mut Vec, stream: TokenStream) { + for tt in stream { + match tt { + TokenTree::Ident(ident) => entries.push(Entry::Ident(ident)), + TokenTree::Punct(punct) => entries.push(Entry::Punct(punct)), + TokenTree::Literal(literal) => entries.push(Entry::Literal(literal)), + TokenTree::Group(group) => { + let group_start_index = entries.len(); + entries.push(Entry::End(0)); // we replace this below + Self::recursive_new(entries, group.stream()); + let group_end_index = entries.len(); + entries.push(Entry::End(-(group_end_index as isize))); + let group_end_offset = group_end_index - group_start_index; + entries[group_start_index] = Entry::Group(group, group_end_offset); + } + } + } + } + + /// Creates a `TokenBuffer` containing all the tokens from the input + /// `proc_macro::TokenStream`. + /// + /// *This method is available only if Syn is built with both the `"parsing"` and + /// `"proc-macro"` features.* + #[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" + ))] + pub fn new(stream: pm::TokenStream) -> Self { + Self::new2(stream.into()) + } + + /// Creates a `TokenBuffer` containing all the tokens from the input + /// `proc_macro2::TokenStream`. + pub fn new2(stream: TokenStream) -> Self { + let mut entries = Vec::new(); + Self::recursive_new(&mut entries, stream); + entries.push(Entry::End(-(entries.len() as isize))); + Self { + entries: entries.into_boxed_slice(), + } + } + + /// Creates a cursor referencing the first token in the buffer and able to + /// traverse until the end of the buffer. + pub fn begin(&self) -> Cursor { + let ptr = self.entries.as_ptr(); + unsafe { Cursor::create(ptr, ptr.add(self.entries.len() - 1)) } + } +} + +/// A cheaply copyable cursor into a `TokenBuffer`. +/// +/// This cursor holds a shared reference into the immutable data which is used +/// internally to represent a `TokenStream`, and can be efficiently manipulated +/// and copied around. +/// +/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer` +/// object and get a cursor to its first token with `begin()`. +/// +/// Two cursors are equal if they have the same location in the same input +/// stream, and have the same scope. +/// +/// *This type is available only if Syn is built with the `"parsing"` feature.* +pub struct Cursor<'a> { + // The current entry which the `Cursor` is pointing at. + ptr: *const Entry, + // This is the only `Entry::End` object which this cursor is allowed to + // point at. All other `End` objects are skipped over in `Cursor::create`. + scope: *const Entry, + // Cursor is covariant in 'a. This field ensures that our pointers are still + // valid. + marker: PhantomData<&'a Entry>, +} + +impl<'a> Cursor<'a> { + /// Creates a cursor referencing a static empty TokenStream. + pub fn empty() -> Self { + // It's safe in this situation for us to put an `Entry` object in global + // storage, despite it not actually being safe to send across threads + // (`Ident` is a reference into a thread-local table). This is because + // this entry never includes a `Ident` object. + // + // This wrapper struct allows us to break the rules and put a `Sync` + // object in global storage. + struct UnsafeSyncEntry(Entry); + unsafe impl Sync for UnsafeSyncEntry {} + static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0)); + + Cursor { + ptr: &EMPTY_ENTRY.0, + scope: &EMPTY_ENTRY.0, + marker: PhantomData, + } + } + + /// This create method intelligently exits non-explicitly-entered + /// `None`-delimited scopes when the cursor reaches the end of them, + /// allowing for them to be treated transparently. + unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self { + // NOTE: If we're looking at a `End`, we want to advance the cursor + // past it, unless `ptr == scope`, which means that we're at the edge of + // our cursor's scope. We should only have `ptr != scope` at the exit + // from None-delimited groups entered with `ignore_none`. + while let Entry::End(_) = *ptr { + if ptr == scope { + break; + } + ptr = ptr.add(1); + } + + Cursor { + ptr, + scope, + marker: PhantomData, + } + } + + /// Get the current entry. + fn entry(self) -> &'a Entry { + unsafe { &*self.ptr } + } + + /// Bump the cursor to point at the next token after the current one. This + /// is undefined behavior if the cursor is currently looking at an + /// `Entry::End`. + /// + /// If the cursor is looking at an `Entry::Group`, the bumped cursor will + /// point at the first token in the group (with the same scope end). + unsafe fn bump_ignore_group(self) -> Cursor<'a> { + Cursor::create(self.ptr.offset(1), self.scope) + } + + /// While the cursor is looking at a `None`-delimited group, move it to look + /// at the first token inside instead. If the group is empty, this will move + /// the cursor past the `None`-delimited group. + /// + /// WARNING: This mutates its argument. + fn ignore_none(&mut self) { + while let Entry::Group(group, _) = self.entry() { + if group.delimiter() == Delimiter::None { + unsafe { *self = self.bump_ignore_group() }; + } else { + break; + } + } + } + + /// Checks whether the cursor is currently pointing at the end of its valid + /// scope. + pub fn eof(self) -> bool { + // We're at eof if we're at the end of our scope. + self.ptr == self.scope + } + + /// If the cursor is pointing at a `Group` with the given delimiter, returns + /// a cursor into that group and one pointing to the next `TokenTree`. + pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> { + // If we're not trying to enter a none-delimited group, we want to + // ignore them. We have to make sure to _not_ ignore them when we want + // to enter them, of course. For obvious reasons. + if delim != Delimiter::None { + self.ignore_none(); + } + + if let Entry::Group(group, end_offset) = self.entry() { + if group.delimiter() == delim { + let end_of_group = unsafe { self.ptr.add(*end_offset) }; + let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; + let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; + return Some((inside_of_group, group.span(), after_group)); + } + } + + None + } + + /// If the cursor is pointing at a `Ident`, returns it along with a cursor + /// pointing at the next `TokenTree`. + pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> { + self.ignore_none(); + match self.entry() { + Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump_ignore_group() })), + _ => None, + } + } + + /// If the cursor is pointing at a `Punct`, returns it along with a cursor + /// pointing at the next `TokenTree`. + pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> { + self.ignore_none(); + match self.entry() { + Entry::Punct(punct) if punct.as_char() != '\'' => { + Some((punct.clone(), unsafe { self.bump_ignore_group() })) + } + _ => None, + } + } + + /// If the cursor is pointing at a `Literal`, return it along with a cursor + /// pointing at the next `TokenTree`. + pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> { + self.ignore_none(); + match self.entry() { + Entry::Literal(literal) => Some((literal.clone(), unsafe { self.bump_ignore_group() })), + _ => None, + } + } + + /// If the cursor is pointing at a `Lifetime`, returns it along with a + /// cursor pointing at the next `TokenTree`. + pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> { + self.ignore_none(); + match self.entry() { + Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => { + let next = unsafe { self.bump_ignore_group() }; + let (ident, rest) = next.ident()?; + let lifetime = Lifetime { + apostrophe: punct.span(), + ident, + }; + Some((lifetime, rest)) + } + _ => None, + } + } + + /// Copies all remaining tokens visible from this cursor into a + /// `TokenStream`. + pub fn token_stream(self) -> TokenStream { + let mut tts = Vec::new(); + let mut cursor = self; + while let Some((tt, rest)) = cursor.token_tree() { + tts.push(tt); + cursor = rest; + } + tts.into_iter().collect() + } + + /// If the cursor is pointing at a `TokenTree`, returns it along with a + /// cursor pointing at the next `TokenTree`. + /// + /// Returns `None` if the cursor has reached the end of its stream. + /// + /// This method does not treat `None`-delimited groups as transparent, and + /// will return a `Group(None, ..)` if the cursor is looking at one. + pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> { + let (tree, len) = match self.entry() { + Entry::Group(group, end_offset) => (group.clone().into(), *end_offset), + Entry::Literal(literal) => (literal.clone().into(), 1), + Entry::Ident(ident) => (ident.clone().into(), 1), + Entry::Punct(punct) => (punct.clone().into(), 1), + Entry::End(_) => return None, + }; + + let rest = unsafe { Cursor::create(self.ptr.add(len), self.scope) }; + Some((tree, rest)) + } + + /// Returns the `Span` of the current token, or `Span::call_site()` if this + /// cursor points to eof. + pub fn span(self) -> Span { + match self.entry() { + Entry::Group(group, _) => group.span(), + Entry::Literal(literal) => literal.span(), + Entry::Ident(ident) => ident.span(), + Entry::Punct(punct) => punct.span(), + Entry::End(_) => Span::call_site(), + } + } + + /// Skip over the next token without cloning it. Returns `None` if this + /// cursor points to eof. + /// + /// This method treats `'lifetimes` as a single token. + pub(crate) fn skip(self) -> Option> { + let len = match self.entry() { + Entry::End(_) => return None, + + // Treat lifetimes as a single tt for the purposes of 'skip'. + Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => { + match unsafe { &*self.ptr.add(1) } { + Entry::Ident(_) => 2, + _ => 1, + } + } + + Entry::Group(_, end_offset) => *end_offset, + _ => 1, + }; + + Some(unsafe { Cursor::create(self.ptr.add(len), self.scope) }) + } +} + +impl<'a> Copy for Cursor<'a> {} + +impl<'a> Clone for Cursor<'a> { + fn clone(&self) -> Self { + *self + } +} + +impl<'a> Eq for Cursor<'a> {} + +impl<'a> PartialEq for Cursor<'a> { + fn eq(&self, other: &Self) -> bool { + self.ptr == other.ptr + } +} + +impl<'a> PartialOrd for Cursor<'a> { + fn partial_cmp(&self, other: &Self) -> Option { + if same_buffer(*self, *other) { + Some(self.ptr.cmp(&other.ptr)) + } else { + None + } + } +} + +pub(crate) fn same_scope(a: Cursor, b: Cursor) -> bool { + a.scope == b.scope +} + +pub(crate) fn same_buffer(a: Cursor, b: Cursor) -> bool { + unsafe { + match (&*a.scope, &*b.scope) { + (Entry::End(a_offset), Entry::End(b_offset)) => { + a.scope.offset(*a_offset) == b.scope.offset(*b_offset) + } + _ => unreachable!(), + } + } +} + +#[cfg(any(feature = "full", feature = "derive"))] +pub(crate) fn cmp_assuming_same_buffer(a: Cursor, b: Cursor) -> Ordering { + a.ptr.cmp(&b.ptr) +} + +pub(crate) fn open_span_of_group(cursor: Cursor) -> Span { + match cursor.entry() { + Entry::Group(group, _) => group.span_open(), + _ => cursor.span(), + } +} + +pub(crate) fn close_span_of_group(cursor: Cursor) -> Span { + match cursor.entry() { + Entry::Group(group, _) => group.span_close(), + _ => cursor.span(), + } +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/custom_keyword.rs b/bitbox02-bt/vendor/syn-1.0.109/src/custom_keyword.rs new file mode 100644 index 0000000..a3ec9d4 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/custom_keyword.rs @@ -0,0 +1,253 @@ +/// Define a type that supports parsing and printing a given identifier as if it +/// were a keyword. +/// +/// # Usage +/// +/// As a convention, it is recommended that this macro be invoked within a +/// module called `kw` or `keyword` and that the resulting parser be invoked +/// with a `kw::` or `keyword::` prefix. +/// +/// ``` +/// mod kw { +/// syn::custom_keyword!(whatever); +/// } +/// ``` +/// +/// The generated syntax tree node supports the following operations just like +/// any built-in keyword token. +/// +/// - [Peeking] — `input.peek(kw::whatever)` +/// +/// - [Parsing] — `input.parse::()?` +/// +/// - [Printing] — `quote!( ... #whatever_token ... )` +/// +/// - Construction from a [`Span`] — `let whatever_token = kw::whatever(sp)` +/// +/// - Field access to its span — `let sp = whatever_token.span` +/// +/// [Peeking]: crate::parse::ParseBuffer::peek +/// [Parsing]: crate::parse::ParseBuffer::parse +/// [Printing]: quote::ToTokens +/// [`Span`]: proc_macro2::Span +/// +/// # Example +/// +/// This example parses input that looks like `bool = true` or `str = "value"`. +/// The key must be either the identifier `bool` or the identifier `str`. If +/// `bool`, the value may be either `true` or `false`. If `str`, the value may +/// be any string literal. +/// +/// The symbols `bool` and `str` are not reserved keywords in Rust so these are +/// not considered keywords in the `syn::token` module. Like any other +/// identifier that is not a keyword, these can be declared as custom keywords +/// by crates that need to use them as such. +/// +/// ``` +/// use syn::{LitBool, LitStr, Result, Token}; +/// use syn::parse::{Parse, ParseStream}; +/// +/// mod kw { +/// syn::custom_keyword!(bool); +/// syn::custom_keyword!(str); +/// } +/// +/// enum Argument { +/// Bool { +/// bool_token: kw::bool, +/// eq_token: Token![=], +/// value: LitBool, +/// }, +/// Str { +/// str_token: kw::str, +/// eq_token: Token![=], +/// value: LitStr, +/// }, +/// } +/// +/// impl Parse for Argument { +/// fn parse(input: ParseStream) -> Result { +/// let lookahead = input.lookahead1(); +/// if lookahead.peek(kw::bool) { +/// Ok(Argument::Bool { +/// bool_token: input.parse::()?, +/// eq_token: input.parse()?, +/// value: input.parse()?, +/// }) +/// } else if lookahead.peek(kw::str) { +/// Ok(Argument::Str { +/// str_token: input.parse::()?, +/// eq_token: input.parse()?, +/// value: input.parse()?, +/// }) +/// } else { +/// Err(lookahead.error()) +/// } +/// } +/// } +/// ``` +#[macro_export] +macro_rules! custom_keyword { + ($ident:ident) => { + #[allow(non_camel_case_types)] + pub struct $ident { + pub span: $crate::__private::Span, + } + + #[doc(hidden)] + #[allow(dead_code, non_snake_case)] + pub fn $ident<__S: $crate::__private::IntoSpans<[$crate::__private::Span; 1]>>( + span: __S, + ) -> $ident { + $ident { + span: $crate::__private::IntoSpans::into_spans(span)[0], + } + } + + impl $crate::__private::Default for $ident { + fn default() -> Self { + $ident { + span: $crate::__private::Span::call_site(), + } + } + } + + $crate::impl_parse_for_custom_keyword!($ident); + $crate::impl_to_tokens_for_custom_keyword!($ident); + $crate::impl_clone_for_custom_keyword!($ident); + $crate::impl_extra_traits_for_custom_keyword!($ident); + }; +} + +// Not public API. +#[cfg(feature = "parsing")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_parse_for_custom_keyword { + ($ident:ident) => { + // For peek. + impl $crate::token::CustomToken for $ident { + fn peek(cursor: $crate::buffer::Cursor) -> $crate::__private::bool { + if let $crate::__private::Some((ident, _rest)) = cursor.ident() { + ident == stringify!($ident) + } else { + false + } + } + + fn display() -> &'static $crate::__private::str { + concat!("`", stringify!($ident), "`") + } + } + + impl $crate::parse::Parse for $ident { + fn parse(input: $crate::parse::ParseStream) -> $crate::parse::Result<$ident> { + input.step(|cursor| { + if let $crate::__private::Some((ident, rest)) = cursor.ident() { + if ident == stringify!($ident) { + return $crate::__private::Ok(($ident { span: ident.span() }, rest)); + } + } + $crate::__private::Err(cursor.error(concat!( + "expected `", + stringify!($ident), + "`" + ))) + }) + } + } + }; +} + +// Not public API. +#[cfg(not(feature = "parsing"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_parse_for_custom_keyword { + ($ident:ident) => {}; +} + +// Not public API. +#[cfg(feature = "printing")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_to_tokens_for_custom_keyword { + ($ident:ident) => { + impl $crate::__private::ToTokens for $ident { + fn to_tokens(&self, tokens: &mut $crate::__private::TokenStream2) { + let ident = $crate::Ident::new(stringify!($ident), self.span); + $crate::__private::TokenStreamExt::append(tokens, ident); + } + } + }; +} + +// Not public API. +#[cfg(not(feature = "printing"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_to_tokens_for_custom_keyword { + ($ident:ident) => {}; +} + +// Not public API. +#[cfg(feature = "clone-impls")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_clone_for_custom_keyword { + ($ident:ident) => { + impl $crate::__private::Copy for $ident {} + + #[allow(clippy::expl_impl_clone_on_copy)] + impl $crate::__private::Clone for $ident { + fn clone(&self) -> Self { + *self + } + } + }; +} + +// Not public API. +#[cfg(not(feature = "clone-impls"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_clone_for_custom_keyword { + ($ident:ident) => {}; +} + +// Not public API. +#[cfg(feature = "extra-traits")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_extra_traits_for_custom_keyword { + ($ident:ident) => { + impl $crate::__private::Debug for $ident { + fn fmt(&self, f: &mut $crate::__private::Formatter) -> $crate::__private::fmt::Result { + $crate::__private::Formatter::write_str( + f, + concat!("Keyword [", stringify!($ident), "]"), + ) + } + } + + impl $crate::__private::Eq for $ident {} + + impl $crate::__private::PartialEq for $ident { + fn eq(&self, _other: &Self) -> $crate::__private::bool { + true + } + } + + impl $crate::__private::Hash for $ident { + fn hash<__H: $crate::__private::Hasher>(&self, _state: &mut __H) {} + } + }; +} + +// Not public API. +#[cfg(not(feature = "extra-traits"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_extra_traits_for_custom_keyword { + ($ident:ident) => {}; +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/custom_punctuation.rs b/bitbox02-bt/vendor/syn-1.0.109/src/custom_punctuation.rs new file mode 100644 index 0000000..118a845 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/custom_punctuation.rs @@ -0,0 +1,300 @@ +/// Define a type that supports parsing and printing a multi-character symbol +/// as if it were a punctuation token. +/// +/// # Usage +/// +/// ``` +/// syn::custom_punctuation!(LeftRightArrow, <=>); +/// ``` +/// +/// The generated syntax tree node supports the following operations just like +/// any built-in punctuation token. +/// +/// - [Peeking] — `input.peek(LeftRightArrow)` +/// +/// - [Parsing] — `input.parse::()?` +/// +/// - [Printing] — `quote!( ... #lrarrow ... )` +/// +/// - Construction from a [`Span`] — `let lrarrow = LeftRightArrow(sp)` +/// +/// - Construction from multiple [`Span`] — `let lrarrow = LeftRightArrow([sp, sp, sp])` +/// +/// - Field access to its spans — `let spans = lrarrow.spans` +/// +/// [Peeking]: crate::parse::ParseBuffer::peek +/// [Parsing]: crate::parse::ParseBuffer::parse +/// [Printing]: quote::ToTokens +/// [`Span`]: proc_macro2::Span +/// +/// # Example +/// +/// ``` +/// use proc_macro2::{TokenStream, TokenTree}; +/// use syn::parse::{Parse, ParseStream, Peek, Result}; +/// use syn::punctuated::Punctuated; +/// use syn::Expr; +/// +/// syn::custom_punctuation!(PathSeparator, ); +/// +/// // expr expr expr ... +/// struct PathSegments { +/// segments: Punctuated, +/// } +/// +/// impl Parse for PathSegments { +/// fn parse(input: ParseStream) -> Result { +/// let mut segments = Punctuated::new(); +/// +/// let first = parse_until(input, PathSeparator)?; +/// segments.push_value(syn::parse2(first)?); +/// +/// while input.peek(PathSeparator) { +/// segments.push_punct(input.parse()?); +/// +/// let next = parse_until(input, PathSeparator)?; +/// segments.push_value(syn::parse2(next)?); +/// } +/// +/// Ok(PathSegments { segments }) +/// } +/// } +/// +/// fn parse_until(input: ParseStream, end: E) -> Result { +/// let mut tokens = TokenStream::new(); +/// while !input.is_empty() && !input.peek(end) { +/// let next: TokenTree = input.parse()?; +/// tokens.extend(Some(next)); +/// } +/// Ok(tokens) +/// } +/// +/// fn main() { +/// let input = r#" a::b c::d::e "#; +/// let _: PathSegments = syn::parse_str(input).unwrap(); +/// } +/// ``` +#[macro_export] +macro_rules! custom_punctuation { + ($ident:ident, $($tt:tt)+) => { + pub struct $ident { + pub spans: $crate::custom_punctuation_repr!($($tt)+), + } + + #[doc(hidden)] + #[allow(dead_code, non_snake_case)] + pub fn $ident<__S: $crate::__private::IntoSpans<$crate::custom_punctuation_repr!($($tt)+)>>( + spans: __S, + ) -> $ident { + let _validate_len = 0 $(+ $crate::custom_punctuation_len!(strict, $tt))*; + $ident { + spans: $crate::__private::IntoSpans::into_spans(spans) + } + } + + impl $crate::__private::Default for $ident { + fn default() -> Self { + $ident($crate::__private::Span::call_site()) + } + } + + $crate::impl_parse_for_custom_punctuation!($ident, $($tt)+); + $crate::impl_to_tokens_for_custom_punctuation!($ident, $($tt)+); + $crate::impl_clone_for_custom_punctuation!($ident, $($tt)+); + $crate::impl_extra_traits_for_custom_punctuation!($ident, $($tt)+); + }; +} + +// Not public API. +#[cfg(feature = "parsing")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_parse_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => { + impl $crate::token::CustomToken for $ident { + fn peek(cursor: $crate::buffer::Cursor) -> bool { + $crate::token::parsing::peek_punct(cursor, $crate::stringify_punct!($($tt)+)) + } + + fn display() -> &'static $crate::__private::str { + concat!("`", $crate::stringify_punct!($($tt)+), "`") + } + } + + impl $crate::parse::Parse for $ident { + fn parse(input: $crate::parse::ParseStream) -> $crate::parse::Result<$ident> { + let spans: $crate::custom_punctuation_repr!($($tt)+) = + $crate::token::parsing::punct(input, $crate::stringify_punct!($($tt)+))?; + Ok($ident(spans)) + } + } + }; +} + +// Not public API. +#[cfg(not(feature = "parsing"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_parse_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => {}; +} + +// Not public API. +#[cfg(feature = "printing")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_to_tokens_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => { + impl $crate::__private::ToTokens for $ident { + fn to_tokens(&self, tokens: &mut $crate::__private::TokenStream2) { + $crate::token::printing::punct($crate::stringify_punct!($($tt)+), &self.spans, tokens) + } + } + }; +} + +// Not public API. +#[cfg(not(feature = "printing"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_to_tokens_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => {}; +} + +// Not public API. +#[cfg(feature = "clone-impls")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_clone_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => { + impl $crate::__private::Copy for $ident {} + + #[allow(clippy::expl_impl_clone_on_copy)] + impl $crate::__private::Clone for $ident { + fn clone(&self) -> Self { + *self + } + } + }; +} + +// Not public API. +#[cfg(not(feature = "clone-impls"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_clone_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => {}; +} + +// Not public API. +#[cfg(feature = "extra-traits")] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_extra_traits_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => { + impl $crate::__private::Debug for $ident { + fn fmt(&self, f: &mut $crate::__private::Formatter) -> $crate::__private::fmt::Result { + $crate::__private::Formatter::write_str(f, stringify!($ident)) + } + } + + impl $crate::__private::Eq for $ident {} + + impl $crate::__private::PartialEq for $ident { + fn eq(&self, _other: &Self) -> $crate::__private::bool { + true + } + } + + impl $crate::__private::Hash for $ident { + fn hash<__H: $crate::__private::Hasher>(&self, _state: &mut __H) {} + } + }; +} + +// Not public API. +#[cfg(not(feature = "extra-traits"))] +#[doc(hidden)] +#[macro_export] +macro_rules! impl_extra_traits_for_custom_punctuation { + ($ident:ident, $($tt:tt)+) => {}; +} + +// Not public API. +#[doc(hidden)] +#[macro_export] +macro_rules! custom_punctuation_repr { + ($($tt:tt)+) => { + [$crate::__private::Span; 0 $(+ $crate::custom_punctuation_len!(lenient, $tt))+] + }; +} + +// Not public API. +#[doc(hidden)] +#[macro_export] +#[rustfmt::skip] +macro_rules! custom_punctuation_len { + ($mode:ident, +) => { 1 }; + ($mode:ident, +=) => { 2 }; + ($mode:ident, &) => { 1 }; + ($mode:ident, &&) => { 2 }; + ($mode:ident, &=) => { 2 }; + ($mode:ident, @) => { 1 }; + ($mode:ident, !) => { 1 }; + ($mode:ident, ^) => { 1 }; + ($mode:ident, ^=) => { 2 }; + ($mode:ident, :) => { 1 }; + ($mode:ident, ::) => { 2 }; + ($mode:ident, ,) => { 1 }; + ($mode:ident, /) => { 1 }; + ($mode:ident, /=) => { 2 }; + ($mode:ident, .) => { 1 }; + ($mode:ident, ..) => { 2 }; + ($mode:ident, ...) => { 3 }; + ($mode:ident, ..=) => { 3 }; + ($mode:ident, =) => { 1 }; + ($mode:ident, ==) => { 2 }; + ($mode:ident, >=) => { 2 }; + ($mode:ident, >) => { 1 }; + ($mode:ident, <=) => { 2 }; + ($mode:ident, <) => { 1 }; + ($mode:ident, *=) => { 2 }; + ($mode:ident, !=) => { 2 }; + ($mode:ident, |) => { 1 }; + ($mode:ident, |=) => { 2 }; + ($mode:ident, ||) => { 2 }; + ($mode:ident, #) => { 1 }; + ($mode:ident, ?) => { 1 }; + ($mode:ident, ->) => { 2 }; + ($mode:ident, <-) => { 2 }; + ($mode:ident, %) => { 1 }; + ($mode:ident, %=) => { 2 }; + ($mode:ident, =>) => { 2 }; + ($mode:ident, ;) => { 1 }; + ($mode:ident, <<) => { 2 }; + ($mode:ident, <<=) => { 3 }; + ($mode:ident, >>) => { 2 }; + ($mode:ident, >>=) => { 3 }; + ($mode:ident, *) => { 1 }; + ($mode:ident, -) => { 1 }; + ($mode:ident, -=) => { 2 }; + ($mode:ident, ~) => { 1 }; + (lenient, $tt:tt) => { 0 }; + (strict, $tt:tt) => {{ $crate::custom_punctuation_unexpected!($tt); 0 }}; +} + +// Not public API. +#[doc(hidden)] +#[macro_export] +macro_rules! custom_punctuation_unexpected { + () => {}; +} + +// Not public API. +#[doc(hidden)] +#[macro_export] +macro_rules! stringify_punct { + ($($tt:tt)+) => { + concat!($(stringify!($tt)),+) + }; +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/data.rs b/bitbox02-bt/vendor/syn-1.0.109/src/data.rs new file mode 100644 index 0000000..3b46661 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/data.rs @@ -0,0 +1,493 @@ +use super::*; +use crate::punctuated::Punctuated; + +ast_struct! { + /// An enum variant. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct Variant { + /// Attributes tagged on the variant. + pub attrs: Vec, + + /// Name of the variant. + pub ident: Ident, + + /// Content stored in the variant. + pub fields: Fields, + + /// Explicit discriminant: `Variant = 1` + pub discriminant: Option<(Token![=], Expr)>, + } +} + +ast_enum_of_structs! { + /// Data stored within an enum variant or struct. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub enum Fields { + /// Named fields of a struct or struct variant such as `Point { x: f64, + /// y: f64 }`. + Named(FieldsNamed), + + /// Unnamed fields of a tuple struct or tuple variant such as `Some(T)`. + Unnamed(FieldsUnnamed), + + /// Unit struct or unit variant such as `None`. + Unit, + } +} + +ast_struct! { + /// Named fields of a struct or struct variant such as `Point { x: f64, + /// y: f64 }`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct FieldsNamed { + pub brace_token: token::Brace, + pub named: Punctuated, + } +} + +ast_struct! { + /// Unnamed fields of a tuple struct or tuple variant such as `Some(T)`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct FieldsUnnamed { + pub paren_token: token::Paren, + pub unnamed: Punctuated, + } +} + +impl Fields { + /// Get an iterator over the borrowed [`Field`] items in this object. This + /// iterator can be used to iterate over a named or unnamed struct or + /// variant's fields uniformly. + pub fn iter(&self) -> punctuated::Iter { + match self { + Fields::Unit => crate::punctuated::empty_punctuated_iter(), + Fields::Named(f) => f.named.iter(), + Fields::Unnamed(f) => f.unnamed.iter(), + } + } + + /// Get an iterator over the mutably borrowed [`Field`] items in this + /// object. This iterator can be used to iterate over a named or unnamed + /// struct or variant's fields uniformly. + pub fn iter_mut(&mut self) -> punctuated::IterMut { + match self { + Fields::Unit => crate::punctuated::empty_punctuated_iter_mut(), + Fields::Named(f) => f.named.iter_mut(), + Fields::Unnamed(f) => f.unnamed.iter_mut(), + } + } + + /// Returns the number of fields. + pub fn len(&self) -> usize { + match self { + Fields::Unit => 0, + Fields::Named(f) => f.named.len(), + Fields::Unnamed(f) => f.unnamed.len(), + } + } + + /// Returns `true` if there are zero fields. + pub fn is_empty(&self) -> bool { + match self { + Fields::Unit => true, + Fields::Named(f) => f.named.is_empty(), + Fields::Unnamed(f) => f.unnamed.is_empty(), + } + } +} + +impl IntoIterator for Fields { + type Item = Field; + type IntoIter = punctuated::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + match self { + Fields::Unit => Punctuated::::new().into_iter(), + Fields::Named(f) => f.named.into_iter(), + Fields::Unnamed(f) => f.unnamed.into_iter(), + } + } +} + +impl<'a> IntoIterator for &'a Fields { + type Item = &'a Field; + type IntoIter = punctuated::Iter<'a, Field>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a> IntoIterator for &'a mut Fields { + type Item = &'a mut Field; + type IntoIter = punctuated::IterMut<'a, Field>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +ast_struct! { + /// A field of a struct or enum variant. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct Field { + /// Attributes tagged on the field. + pub attrs: Vec, + + /// Visibility of the field. + pub vis: Visibility, + + /// Name of the field, if any. + /// + /// Fields of tuple structs have no names. + pub ident: Option, + + pub colon_token: Option, + + /// Type of the field. + pub ty: Type, + } +} + +ast_enum_of_structs! { + /// The visibility level of an item: inherited or `pub` or + /// `pub(restricted)`. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub enum Visibility { + /// A public visibility level: `pub`. + Public(VisPublic), + + /// A crate-level visibility: `crate`. + Crate(VisCrate), + + /// A visibility level restricted to some path: `pub(self)` or + /// `pub(super)` or `pub(crate)` or `pub(in some::module)`. + Restricted(VisRestricted), + + /// An inherited visibility, which usually means private. + Inherited, + } +} + +ast_struct! { + /// A public visibility level: `pub`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct VisPublic { + pub pub_token: Token![pub], + } +} + +ast_struct! { + /// A crate-level visibility: `crate`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct VisCrate { + pub crate_token: Token![crate], + } +} + +ast_struct! { + /// A visibility level restricted to some path: `pub(self)` or + /// `pub(super)` or `pub(crate)` or `pub(in some::module)`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct VisRestricted { + pub pub_token: Token![pub], + pub paren_token: token::Paren, + pub in_token: Option, + pub path: Box, + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use crate::ext::IdentExt; + use crate::parse::discouraged::Speculative; + use crate::parse::{Parse, ParseStream, Result}; + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for Variant { + fn parse(input: ParseStream) -> Result { + let attrs = input.call(Attribute::parse_outer)?; + let _visibility: Visibility = input.parse()?; + let ident: Ident = input.parse()?; + let fields = if input.peek(token::Brace) { + Fields::Named(input.parse()?) + } else if input.peek(token::Paren) { + Fields::Unnamed(input.parse()?) + } else { + Fields::Unit + }; + let discriminant = if input.peek(Token![=]) { + let eq_token: Token![=] = input.parse()?; + let discriminant: Expr = input.parse()?; + Some((eq_token, discriminant)) + } else { + None + }; + Ok(Variant { + attrs, + ident, + fields, + discriminant, + }) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for FieldsNamed { + fn parse(input: ParseStream) -> Result { + let content; + Ok(FieldsNamed { + brace_token: braced!(content in input), + named: content.parse_terminated(Field::parse_named)?, + }) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for FieldsUnnamed { + fn parse(input: ParseStream) -> Result { + let content; + Ok(FieldsUnnamed { + paren_token: parenthesized!(content in input), + unnamed: content.parse_terminated(Field::parse_unnamed)?, + }) + } + } + + impl Field { + /// Parses a named (braced struct) field. + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + pub fn parse_named(input: ParseStream) -> Result { + Ok(Field { + attrs: input.call(Attribute::parse_outer)?, + vis: input.parse()?, + ident: Some(if input.peek(Token![_]) { + input.call(Ident::parse_any) + } else { + input.parse() + }?), + colon_token: Some(input.parse()?), + ty: input.parse()?, + }) + } + + /// Parses an unnamed (tuple struct) field. + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + pub fn parse_unnamed(input: ParseStream) -> Result { + Ok(Field { + attrs: input.call(Attribute::parse_outer)?, + vis: input.parse()?, + ident: None, + colon_token: None, + ty: input.parse()?, + }) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for Visibility { + fn parse(input: ParseStream) -> Result { + // Recognize an empty None-delimited group, as produced by a $:vis + // matcher that matched no tokens. + if input.peek(token::Group) { + let ahead = input.fork(); + let group = crate::group::parse_group(&ahead)?; + if group.content.is_empty() { + input.advance_to(&ahead); + return Ok(Visibility::Inherited); + } + } + + if input.peek(Token![pub]) { + Self::parse_pub(input) + } else if input.peek(Token![crate]) { + Self::parse_crate(input) + } else { + Ok(Visibility::Inherited) + } + } + } + + impl Visibility { + fn parse_pub(input: ParseStream) -> Result { + let pub_token = input.parse::()?; + + if input.peek(token::Paren) { + let ahead = input.fork(); + + let content; + let paren_token = parenthesized!(content in ahead); + if content.peek(Token![crate]) + || content.peek(Token![self]) + || content.peek(Token![super]) + { + let path = content.call(Ident::parse_any)?; + + // Ensure there are no additional tokens within `content`. + // Without explicitly checking, we may misinterpret a tuple + // field as a restricted visibility, causing a parse error. + // e.g. `pub (crate::A, crate::B)` (Issue #720). + if content.is_empty() { + input.advance_to(&ahead); + return Ok(Visibility::Restricted(VisRestricted { + pub_token, + paren_token, + in_token: None, + path: Box::new(Path::from(path)), + })); + } + } else if content.peek(Token![in]) { + let in_token: Token![in] = content.parse()?; + let path = content.call(Path::parse_mod_style)?; + + input.advance_to(&ahead); + return Ok(Visibility::Restricted(VisRestricted { + pub_token, + paren_token, + in_token: Some(in_token), + path: Box::new(path), + })); + } + } + + Ok(Visibility::Public(VisPublic { pub_token })) + } + + fn parse_crate(input: ParseStream) -> Result { + if input.peek2(Token![::]) { + Ok(Visibility::Inherited) + } else { + Ok(Visibility::Crate(VisCrate { + crate_token: input.parse()?, + })) + } + } + + #[cfg(feature = "full")] + pub(crate) fn is_some(&self) -> bool { + match self { + Visibility::Inherited => false, + _ => true, + } + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use crate::print::TokensOrDefault; + use proc_macro2::TokenStream; + use quote::{ToTokens, TokenStreamExt}; + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for Variant { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append_all(&self.attrs); + self.ident.to_tokens(tokens); + self.fields.to_tokens(tokens); + if let Some((eq_token, disc)) = &self.discriminant { + eq_token.to_tokens(tokens); + disc.to_tokens(tokens); + } + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for FieldsNamed { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.brace_token.surround(tokens, |tokens| { + self.named.to_tokens(tokens); + }); + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for FieldsUnnamed { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.paren_token.surround(tokens, |tokens| { + self.unnamed.to_tokens(tokens); + }); + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for Field { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append_all(&self.attrs); + self.vis.to_tokens(tokens); + if let Some(ident) = &self.ident { + ident.to_tokens(tokens); + TokensOrDefault(&self.colon_token).to_tokens(tokens); + } + self.ty.to_tokens(tokens); + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for VisPublic { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.pub_token.to_tokens(tokens); + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for VisCrate { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.crate_token.to_tokens(tokens); + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for VisRestricted { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.pub_token.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + // TODO: If we have a path which is not "self" or "super" or + // "crate", automatically add the "in" token. + self.in_token.to_tokens(tokens); + self.path.to_tokens(tokens); + }); + } + } +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/derive.rs b/bitbox02-bt/vendor/syn-1.0.109/src/derive.rs new file mode 100644 index 0000000..af9bb91 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/derive.rs @@ -0,0 +1,274 @@ +use super::*; +use crate::punctuated::Punctuated; + +ast_struct! { + /// Data structure sent to a `proc_macro_derive` macro. + /// + /// *This type is available only if Syn is built with the `"derive"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] + pub struct DeriveInput { + /// Attributes tagged on the whole struct or enum. + pub attrs: Vec, + + /// Visibility of the struct or enum. + pub vis: Visibility, + + /// Name of the struct or enum. + pub ident: Ident, + + /// Generics required to complete the definition. + pub generics: Generics, + + /// Data within the struct or enum. + pub data: Data, + } +} + +ast_enum_of_structs! { + /// The storage of a struct, enum or union data structure. + /// + /// *This type is available only if Syn is built with the `"derive"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: Expr#syntax-tree-enums + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] + pub enum Data { + /// A struct input to a `proc_macro_derive` macro. + Struct(DataStruct), + + /// An enum input to a `proc_macro_derive` macro. + Enum(DataEnum), + + /// An untagged union input to a `proc_macro_derive` macro. + Union(DataUnion), + } + + do_not_generate_to_tokens +} + +ast_struct! { + /// A struct input to a `proc_macro_derive` macro. + /// + /// *This type is available only if Syn is built with the `"derive"` + /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] + pub struct DataStruct { + pub struct_token: Token![struct], + pub fields: Fields, + pub semi_token: Option, + } +} + +ast_struct! { + /// An enum input to a `proc_macro_derive` macro. + /// + /// *This type is available only if Syn is built with the `"derive"` + /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] + pub struct DataEnum { + pub enum_token: Token![enum], + pub brace_token: token::Brace, + pub variants: Punctuated, + } +} + +ast_struct! { + /// An untagged union input to a `proc_macro_derive` macro. + /// + /// *This type is available only if Syn is built with the `"derive"` + /// feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] + pub struct DataUnion { + pub union_token: Token![union], + pub fields: FieldsNamed, + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use crate::parse::{Parse, ParseStream, Result}; + + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for DeriveInput { + fn parse(input: ParseStream) -> Result { + let attrs = input.call(Attribute::parse_outer)?; + let vis = input.parse::()?; + + let lookahead = input.lookahead1(); + if lookahead.peek(Token![struct]) { + let struct_token = input.parse::()?; + let ident = input.parse::()?; + let generics = input.parse::()?; + let (where_clause, fields, semi) = data_struct(input)?; + Ok(DeriveInput { + attrs, + vis, + ident, + generics: Generics { + where_clause, + ..generics + }, + data: Data::Struct(DataStruct { + struct_token, + fields, + semi_token: semi, + }), + }) + } else if lookahead.peek(Token![enum]) { + let enum_token = input.parse::()?; + let ident = input.parse::()?; + let generics = input.parse::()?; + let (where_clause, brace, variants) = data_enum(input)?; + Ok(DeriveInput { + attrs, + vis, + ident, + generics: Generics { + where_clause, + ..generics + }, + data: Data::Enum(DataEnum { + enum_token, + brace_token: brace, + variants, + }), + }) + } else if lookahead.peek(Token![union]) { + let union_token = input.parse::()?; + let ident = input.parse::()?; + let generics = input.parse::()?; + let (where_clause, fields) = data_union(input)?; + Ok(DeriveInput { + attrs, + vis, + ident, + generics: Generics { + where_clause, + ..generics + }, + data: Data::Union(DataUnion { + union_token, + fields, + }), + }) + } else { + Err(lookahead.error()) + } + } + } + + pub fn data_struct( + input: ParseStream, + ) -> Result<(Option, Fields, Option)> { + let mut lookahead = input.lookahead1(); + let mut where_clause = None; + if lookahead.peek(Token![where]) { + where_clause = Some(input.parse()?); + lookahead = input.lookahead1(); + } + + if where_clause.is_none() && lookahead.peek(token::Paren) { + let fields = input.parse()?; + + lookahead = input.lookahead1(); + if lookahead.peek(Token![where]) { + where_clause = Some(input.parse()?); + lookahead = input.lookahead1(); + } + + if lookahead.peek(Token![;]) { + let semi = input.parse()?; + Ok((where_clause, Fields::Unnamed(fields), Some(semi))) + } else { + Err(lookahead.error()) + } + } else if lookahead.peek(token::Brace) { + let fields = input.parse()?; + Ok((where_clause, Fields::Named(fields), None)) + } else if lookahead.peek(Token![;]) { + let semi = input.parse()?; + Ok((where_clause, Fields::Unit, Some(semi))) + } else { + Err(lookahead.error()) + } + } + + pub fn data_enum( + input: ParseStream, + ) -> Result<( + Option, + token::Brace, + Punctuated, + )> { + let where_clause = input.parse()?; + + let content; + let brace = braced!(content in input); + let variants = content.parse_terminated(Variant::parse)?; + + Ok((where_clause, brace, variants)) + } + + pub fn data_union(input: ParseStream) -> Result<(Option, FieldsNamed)> { + let where_clause = input.parse()?; + let fields = input.parse()?; + Ok((where_clause, fields)) + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use crate::attr::FilterAttrs; + use crate::print::TokensOrDefault; + use proc_macro2::TokenStream; + use quote::ToTokens; + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for DeriveInput { + fn to_tokens(&self, tokens: &mut TokenStream) { + for attr in self.attrs.outer() { + attr.to_tokens(tokens); + } + self.vis.to_tokens(tokens); + match &self.data { + Data::Struct(d) => d.struct_token.to_tokens(tokens), + Data::Enum(d) => d.enum_token.to_tokens(tokens), + Data::Union(d) => d.union_token.to_tokens(tokens), + } + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + match &self.data { + Data::Struct(data) => match &data.fields { + Fields::Named(fields) => { + self.generics.where_clause.to_tokens(tokens); + fields.to_tokens(tokens); + } + Fields::Unnamed(fields) => { + fields.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); + TokensOrDefault(&data.semi_token).to_tokens(tokens); + } + Fields::Unit => { + self.generics.where_clause.to_tokens(tokens); + TokensOrDefault(&data.semi_token).to_tokens(tokens); + } + }, + Data::Enum(data) => { + self.generics.where_clause.to_tokens(tokens); + data.brace_token.surround(tokens, |tokens| { + data.variants.to_tokens(tokens); + }); + } + Data::Union(data) => { + self.generics.where_clause.to_tokens(tokens); + data.fields.to_tokens(tokens); + } + } + } + } +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/discouraged.rs b/bitbox02-bt/vendor/syn-1.0.109/src/discouraged.rs new file mode 100644 index 0000000..a46129b --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/discouraged.rs @@ -0,0 +1,194 @@ +//! Extensions to the parsing API with niche applicability. + +use super::*; + +/// Extensions to the `ParseStream` API to support speculative parsing. +pub trait Speculative { + /// Advance this parse stream to the position of a forked parse stream. + /// + /// This is the opposite operation to [`ParseStream::fork`]. You can fork a + /// parse stream, perform some speculative parsing, then join the original + /// stream to the fork to "commit" the parsing from the fork to the main + /// stream. + /// + /// If you can avoid doing this, you should, as it limits the ability to + /// generate useful errors. That said, it is often the only way to parse + /// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem + /// is that when the fork fails to parse an `A`, it's impossible to tell + /// whether that was because of a syntax error and the user meant to provide + /// an `A`, or that the `A`s are finished and it's time to start parsing + /// `B`s. Use with care. + /// + /// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by + /// parsing `B*` and removing the leading members of `A` from the + /// repetition, bypassing the need to involve the downsides associated with + /// speculative parsing. + /// + /// [`ParseStream::fork`]: ParseBuffer::fork + /// + /// # Example + /// + /// There has been chatter about the possibility of making the colons in the + /// turbofish syntax like `path::to::` no longer required by accepting + /// `path::to` in expression position. Specifically, according to [RFC + /// 2544], [`PathSegment`] parsing should always try to consume a following + /// `<` token as the start of generic arguments, and reset to the `<` if + /// that fails (e.g. the token is acting as a less-than operator). + /// + /// This is the exact kind of parsing behavior which requires the "fork, + /// try, commit" behavior that [`ParseStream::fork`] discourages. With + /// `advance_to`, we can avoid having to parse the speculatively parsed + /// content a second time. + /// + /// This change in behavior can be implemented in syn by replacing just the + /// `Parse` implementation for `PathSegment`: + /// + /// ``` + /// # use syn::ext::IdentExt; + /// use syn::parse::discouraged::Speculative; + /// # use syn::parse::{Parse, ParseStream}; + /// # use syn::{Ident, PathArguments, Result, Token}; + /// + /// pub struct PathSegment { + /// pub ident: Ident, + /// pub arguments: PathArguments, + /// } + /// # + /// # impl From for PathSegment + /// # where + /// # T: Into, + /// # { + /// # fn from(ident: T) -> Self { + /// # PathSegment { + /// # ident: ident.into(), + /// # arguments: PathArguments::None, + /// # } + /// # } + /// # } + /// + /// impl Parse for PathSegment { + /// fn parse(input: ParseStream) -> Result { + /// if input.peek(Token![super]) + /// || input.peek(Token![self]) + /// || input.peek(Token![Self]) + /// || input.peek(Token![crate]) + /// { + /// let ident = input.call(Ident::parse_any)?; + /// return Ok(PathSegment::from(ident)); + /// } + /// + /// let ident = input.parse()?; + /// if input.peek(Token![::]) && input.peek3(Token![<]) { + /// return Ok(PathSegment { + /// ident, + /// arguments: PathArguments::AngleBracketed(input.parse()?), + /// }); + /// } + /// if input.peek(Token![<]) && !input.peek(Token![<=]) { + /// let fork = input.fork(); + /// if let Ok(arguments) = fork.parse() { + /// input.advance_to(&fork); + /// return Ok(PathSegment { + /// ident, + /// arguments: PathArguments::AngleBracketed(arguments), + /// }); + /// } + /// } + /// Ok(PathSegment::from(ident)) + /// } + /// } + /// + /// # syn::parse_str::("a").unwrap(); + /// ``` + /// + /// # Drawbacks + /// + /// The main drawback of this style of speculative parsing is in error + /// presentation. Even if the lookahead is the "correct" parse, the error + /// that is shown is that of the "fallback" parse. To use the same example + /// as the turbofish above, take the following unfinished "turbofish": + /// + /// ```text + /// let _ = f<&'a fn(), for<'a> serde::>(); + /// ``` + /// + /// If this is parsed as generic arguments, we can provide the error message + /// + /// ```text + /// error: expected identifier + /// --> src.rs:L:C + /// | + /// L | let _ = f<&'a fn(), for<'a> serde::>(); + /// | ^ + /// ``` + /// + /// but if parsed using the above speculative parsing, it falls back to + /// assuming that the `<` is a less-than when it fails to parse the generic + /// arguments, and tries to interpret the `&'a` as the start of a labelled + /// loop, resulting in the much less helpful error + /// + /// ```text + /// error: expected `:` + /// --> src.rs:L:C + /// | + /// L | let _ = f<&'a fn(), for<'a> serde::>(); + /// | ^^ + /// ``` + /// + /// This can be mitigated with various heuristics (two examples: show both + /// forks' parse errors, or show the one that consumed more tokens), but + /// when you can control the grammar, sticking to something that can be + /// parsed LL(3) and without the LL(*) speculative parsing this makes + /// possible, displaying reasonable errors becomes much more simple. + /// + /// [RFC 2544]: https://github.com/rust-lang/rfcs/pull/2544 + /// [`PathSegment`]: crate::PathSegment + /// + /// # Performance + /// + /// This method performs a cheap fixed amount of work that does not depend + /// on how far apart the two streams are positioned. + /// + /// # Panics + /// + /// The forked stream in the argument of `advance_to` must have been + /// obtained by forking `self`. Attempting to advance to any other stream + /// will cause a panic. + fn advance_to(&self, fork: &Self); +} + +impl<'a> Speculative for ParseBuffer<'a> { + fn advance_to(&self, fork: &Self) { + if !crate::buffer::same_scope(self.cursor(), fork.cursor()) { + panic!("Fork was not derived from the advancing parse stream"); + } + + let (self_unexp, self_sp) = inner_unexpected(self); + let (fork_unexp, fork_sp) = inner_unexpected(fork); + if !Rc::ptr_eq(&self_unexp, &fork_unexp) { + match (fork_sp, self_sp) { + // Unexpected set on the fork, but not on `self`, copy it over. + (Some(span), None) => { + self_unexp.set(Unexpected::Some(span)); + } + // Unexpected unset. Use chain to propagate errors from fork. + (None, None) => { + fork_unexp.set(Unexpected::Chain(self_unexp)); + + // Ensure toplevel 'unexpected' tokens from the fork don't + // bubble up the chain by replacing the root `unexpected` + // pointer, only 'unexpected' tokens from existing group + // parsers should bubble. + fork.unexpected + .set(Some(Rc::new(Cell::new(Unexpected::None)))); + } + // Unexpected has been set on `self`. No changes needed. + (_, Some(_)) => {} + } + } + + // See comment on `cell` in the struct definition. + self.cell + .set(unsafe { mem::transmute::>(fork.cursor()) }); + } +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/drops.rs b/bitbox02-bt/vendor/syn-1.0.109/src/drops.rs new file mode 100644 index 0000000..89b42d8 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/drops.rs @@ -0,0 +1,58 @@ +use std::iter; +use std::mem::ManuallyDrop; +use std::ops::{Deref, DerefMut}; +use std::option; +use std::slice; + +#[repr(transparent)] +pub(crate) struct NoDrop(ManuallyDrop); + +impl NoDrop { + pub(crate) fn new(value: T) -> Self + where + T: TrivialDrop, + { + NoDrop(ManuallyDrop::new(value)) + } +} + +impl Deref for NoDrop { + type Target = T; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for NoDrop { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +pub(crate) trait TrivialDrop {} + +impl TrivialDrop for iter::Empty {} +impl<'a, T> TrivialDrop for slice::Iter<'a, T> {} +impl<'a, T> TrivialDrop for slice::IterMut<'a, T> {} +impl<'a, T> TrivialDrop for option::IntoIter<&'a T> {} +impl<'a, T> TrivialDrop for option::IntoIter<&'a mut T> {} + +#[test] +fn test_needs_drop() { + use std::mem::needs_drop; + + struct NeedsDrop; + + impl Drop for NeedsDrop { + fn drop(&mut self) {} + } + + assert!(needs_drop::()); + + // Test each of the types with a handwritten TrivialDrop impl above. + assert!(!needs_drop::>()); + assert!(!needs_drop::>()); + assert!(!needs_drop::>()); + assert!(!needs_drop::>()); + assert!(!needs_drop::>()); +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/error.rs b/bitbox02-bt/vendor/syn-1.0.109/src/error.rs new file mode 100644 index 0000000..e301367 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/error.rs @@ -0,0 +1,428 @@ +#[cfg(feature = "parsing")] +use crate::buffer::Cursor; +use crate::thread::ThreadBound; +use proc_macro2::{ + Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree, +}; +#[cfg(feature = "printing")] +use quote::ToTokens; +use std::fmt::{self, Debug, Display}; +use std::iter::FromIterator; +use std::slice; +use std::vec; + +/// The result of a Syn parser. +pub type Result = std::result::Result; + +/// Error returned when a Syn parser cannot parse the input tokens. +/// +/// # Error reporting in proc macros +/// +/// The correct way to report errors back to the compiler from a procedural +/// macro is by emitting an appropriately spanned invocation of +/// [`compile_error!`] in the generated code. This produces a better diagnostic +/// message than simply panicking the macro. +/// +/// [`compile_error!`]: std::compile_error! +/// +/// When parsing macro input, the [`parse_macro_input!`] macro handles the +/// conversion to `compile_error!` automatically. +/// +/// [`parse_macro_input!`]: crate::parse_macro_input! +/// +/// ``` +/// # extern crate proc_macro; +/// # +/// use proc_macro::TokenStream; +/// use syn::{parse_macro_input, AttributeArgs, ItemFn}; +/// +/// # const IGNORE: &str = stringify! { +/// #[proc_macro_attribute] +/// # }; +/// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream { +/// let args = parse_macro_input!(args as AttributeArgs); +/// let input = parse_macro_input!(input as ItemFn); +/// +/// /* ... */ +/// # TokenStream::new() +/// } +/// ``` +/// +/// For errors that arise later than the initial parsing stage, the +/// [`.to_compile_error()`] or [`.into_compile_error()`] methods can be used to +/// perform an explicit conversion to `compile_error!`. +/// +/// [`.to_compile_error()`]: Error::to_compile_error +/// [`.into_compile_error()`]: Error::into_compile_error +/// +/// ``` +/// # extern crate proc_macro; +/// # +/// # use proc_macro::TokenStream; +/// # use syn::{parse_macro_input, DeriveInput}; +/// # +/// # const IGNORE: &str = stringify! { +/// #[proc_macro_derive(MyDerive)] +/// # }; +/// pub fn my_derive(input: TokenStream) -> TokenStream { +/// let input = parse_macro_input!(input as DeriveInput); +/// +/// // fn(DeriveInput) -> syn::Result +/// expand::my_derive(input) +/// .unwrap_or_else(syn::Error::into_compile_error) +/// .into() +/// } +/// # +/// # mod expand { +/// # use proc_macro2::TokenStream; +/// # use syn::{DeriveInput, Result}; +/// # +/// # pub fn my_derive(input: DeriveInput) -> Result { +/// # unimplemented!() +/// # } +/// # } +/// ``` +pub struct Error { + messages: Vec, +} + +struct ErrorMessage { + // Span is implemented as an index into a thread-local interner to keep the + // size small. It is not safe to access from a different thread. We want + // errors to be Send and Sync to play nicely with the Failure crate, so pin + // the span we're given to its original thread and assume it is + // Span::call_site if accessed from any other thread. + start_span: ThreadBound, + end_span: ThreadBound, + message: String, +} + +#[cfg(test)] +struct _Test +where + Error: Send + Sync; + +impl Error { + /// Usually the [`ParseStream::error`] method will be used instead, which + /// automatically uses the correct span from the current position of the + /// parse stream. + /// + /// Use `Error::new` when the error needs to be triggered on some span other + /// than where the parse stream is currently positioned. + /// + /// [`ParseStream::error`]: crate::parse::ParseBuffer::error + /// + /// # Example + /// + /// ``` + /// use syn::{Error, Ident, LitStr, Result, Token}; + /// use syn::parse::ParseStream; + /// + /// // Parses input that looks like `name = "string"` where the key must be + /// // the identifier `name` and the value may be any string literal. + /// // Returns the string literal. + /// fn parse_name(input: ParseStream) -> Result { + /// let name_token: Ident = input.parse()?; + /// if name_token != "name" { + /// // Trigger an error not on the current position of the stream, + /// // but on the position of the unexpected identifier. + /// return Err(Error::new(name_token.span(), "expected `name`")); + /// } + /// input.parse::()?; + /// let s: LitStr = input.parse()?; + /// Ok(s) + /// } + /// ``` + pub fn new(span: Span, message: T) -> Self { + return new(span, message.to_string()); + + fn new(span: Span, message: String) -> Error { + Error { + messages: vec![ErrorMessage { + start_span: ThreadBound::new(span), + end_span: ThreadBound::new(span), + message, + }], + } + } + } + + /// Creates an error with the specified message spanning the given syntax + /// tree node. + /// + /// Unlike the `Error::new` constructor, this constructor takes an argument + /// `tokens` which is a syntax tree node. This allows the resulting `Error` + /// to attempt to span all tokens inside of `tokens`. While you would + /// typically be able to use the `Spanned` trait with the above `Error::new` + /// constructor, implementation limitations today mean that + /// `Error::new_spanned` may provide a higher-quality error message on + /// stable Rust. + /// + /// When in doubt it's recommended to stick to `Error::new` (or + /// `ParseStream::error`)! + #[cfg(feature = "printing")] + pub fn new_spanned(tokens: T, message: U) -> Self { + return new_spanned(tokens.into_token_stream(), message.to_string()); + + fn new_spanned(tokens: TokenStream, message: String) -> Error { + let mut iter = tokens.into_iter(); + let start = iter.next().map_or_else(Span::call_site, |t| t.span()); + let end = iter.last().map_or(start, |t| t.span()); + Error { + messages: vec![ErrorMessage { + start_span: ThreadBound::new(start), + end_span: ThreadBound::new(end), + message, + }], + } + } + } + + /// The source location of the error. + /// + /// Spans are not thread-safe so this function returns `Span::call_site()` + /// if called from a different thread than the one on which the `Error` was + /// originally created. + pub fn span(&self) -> Span { + let start = match self.messages[0].start_span.get() { + Some(span) => *span, + None => return Span::call_site(), + }; + let end = match self.messages[0].end_span.get() { + Some(span) => *span, + None => return Span::call_site(), + }; + start.join(end).unwrap_or(start) + } + + /// Render the error as an invocation of [`compile_error!`]. + /// + /// The [`parse_macro_input!`] macro provides a convenient way to invoke + /// this method correctly in a procedural macro. + /// + /// [`compile_error!`]: std::compile_error! + /// [`parse_macro_input!`]: crate::parse_macro_input! + pub fn to_compile_error(&self) -> TokenStream { + self.messages + .iter() + .map(ErrorMessage::to_compile_error) + .collect() + } + + /// Render the error as an invocation of [`compile_error!`]. + /// + /// [`compile_error!`]: std::compile_error! + /// + /// # Example + /// + /// ``` + /// # extern crate proc_macro; + /// # + /// use proc_macro::TokenStream; + /// use syn::{parse_macro_input, DeriveInput, Error}; + /// + /// # const _: &str = stringify! { + /// #[proc_macro_derive(MyTrait)] + /// # }; + /// pub fn derive_my_trait(input: TokenStream) -> TokenStream { + /// let input = parse_macro_input!(input as DeriveInput); + /// my_trait::expand(input) + /// .unwrap_or_else(Error::into_compile_error) + /// .into() + /// } + /// + /// mod my_trait { + /// use proc_macro2::TokenStream; + /// use syn::{DeriveInput, Result}; + /// + /// pub(crate) fn expand(input: DeriveInput) -> Result { + /// /* ... */ + /// # unimplemented!() + /// } + /// } + /// ``` + pub fn into_compile_error(self) -> TokenStream { + self.to_compile_error() + } + + /// Add another error message to self such that when `to_compile_error()` is + /// called, both errors will be emitted together. + pub fn combine(&mut self, another: Error) { + self.messages.extend(another.messages); + } +} + +impl ErrorMessage { + fn to_compile_error(&self) -> TokenStream { + let start = self + .start_span + .get() + .cloned() + .unwrap_or_else(Span::call_site); + let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site); + + // compile_error!($message) + TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("compile_error", start)), + TokenTree::Punct({ + let mut punct = Punct::new('!', Spacing::Alone); + punct.set_span(start); + punct + }), + TokenTree::Group({ + let mut group = Group::new(Delimiter::Brace, { + TokenStream::from_iter(vec![TokenTree::Literal({ + let mut string = Literal::string(&self.message); + string.set_span(end); + string + })]) + }); + group.set_span(end); + group + }), + ]) + } +} + +#[cfg(feature = "parsing")] +pub fn new_at(scope: Span, cursor: Cursor, message: T) -> Error { + if cursor.eof() { + Error::new(scope, format!("unexpected end of input, {}", message)) + } else { + let span = crate::buffer::open_span_of_group(cursor); + Error::new(span, message) + } +} + +#[cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))] +pub fn new2(start: Span, end: Span, message: T) -> Error { + return new2(start, end, message.to_string()); + + fn new2(start: Span, end: Span, message: String) -> Error { + Error { + messages: vec![ErrorMessage { + start_span: ThreadBound::new(start), + end_span: ThreadBound::new(end), + message, + }], + } + } +} + +impl Debug for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.messages.len() == 1 { + formatter + .debug_tuple("Error") + .field(&self.messages[0]) + .finish() + } else { + formatter + .debug_tuple("Error") + .field(&self.messages) + .finish() + } + } +} + +impl Debug for ErrorMessage { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.message, formatter) + } +} + +impl Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(&self.messages[0].message) + } +} + +impl Clone for Error { + fn clone(&self) -> Self { + Error { + messages: self.messages.clone(), + } + } +} + +impl Clone for ErrorMessage { + fn clone(&self) -> Self { + let start = self + .start_span + .get() + .cloned() + .unwrap_or_else(Span::call_site); + let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site); + ErrorMessage { + start_span: ThreadBound::new(start), + end_span: ThreadBound::new(end), + message: self.message.clone(), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(err: LexError) -> Self { + Error::new(err.span(), "lex error") + } +} + +impl IntoIterator for Error { + type Item = Error; + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + IntoIter { + messages: self.messages.into_iter(), + } + } +} + +pub struct IntoIter { + messages: vec::IntoIter, +} + +impl Iterator for IntoIter { + type Item = Error; + + fn next(&mut self) -> Option { + Some(Error { + messages: vec![self.messages.next()?], + }) + } +} + +impl<'a> IntoIterator for &'a Error { + type Item = Error; + type IntoIter = Iter<'a>; + + fn into_iter(self) -> Self::IntoIter { + Iter { + messages: self.messages.iter(), + } + } +} + +pub struct Iter<'a> { + messages: slice::Iter<'a, ErrorMessage>, +} + +impl<'a> Iterator for Iter<'a> { + type Item = Error; + + fn next(&mut self) -> Option { + Some(Error { + messages: vec![self.messages.next()?.clone()], + }) + } +} + +impl Extend for Error { + fn extend>(&mut self, iter: T) { + for err in iter { + self.combine(err); + } + } +} diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/export.rs b/bitbox02-bt/vendor/syn-1.0.109/src/export.rs new file mode 100644 index 0000000..f478d09 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/export.rs @@ -0,0 +1,39 @@ +pub use std::clone::Clone; +pub use std::cmp::{Eq, PartialEq}; +pub use std::default::Default; +pub use std::fmt::{self, Debug, Formatter}; +pub use std::hash::{Hash, Hasher}; +pub use std::marker::Copy; +pub use std::option::Option::{None, Some}; +pub use std::result::Result::{Err, Ok}; + +#[cfg(feature = "printing")] +pub extern crate quote; + +pub use proc_macro2::{Span, TokenStream as TokenStream2}; + +#[cfg(feature = "parsing")] +pub use crate::group::{parse_braces, parse_brackets, parse_parens}; + +pub use crate::span::IntoSpans; + +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +pub use proc_macro::TokenStream; + +#[cfg(feature = "printing")] +pub use quote::{ToTokens, TokenStreamExt}; + +#[allow(non_camel_case_types)] +pub type bool = help::Bool; +#[allow(non_camel_case_types)] +pub type str = help::Str; + +mod help { + pub type Bool = bool; + pub type Str = str; +} + +pub struct private(pub(crate) ()); diff --git a/bitbox02-bt/vendor/syn-1.0.109/src/expr.rs b/bitbox02-bt/vendor/syn-1.0.109/src/expr.rs new file mode 100644 index 0000000..93a59b0 --- /dev/null +++ b/bitbox02-bt/vendor/syn-1.0.109/src/expr.rs @@ -0,0 +1,3558 @@ +use super::*; +use crate::punctuated::Punctuated; +#[cfg(feature = "full")] +use crate::reserved::Reserved; +use proc_macro2::{Span, TokenStream}; +#[cfg(feature = "printing")] +use quote::IdentFragment; +#[cfg(feature = "printing")] +use std::fmt::{self, Display}; +use std::hash::{Hash, Hasher}; +#[cfg(feature = "parsing")] +use std::mem; + +ast_enum_of_structs! { + /// A Rust expression. + /// + /// *This type is available only if Syn is built with the `"derive"` or `"full"` + /// feature, but most of the variants are not available unless "full" is enabled.* + /// + /// # Syntax tree enums + /// + /// This type is a syntax tree enum. In Syn this and other syntax tree enums + /// are designed to be traversed using the following rebinding idiom. + /// + /// ``` + /// # use syn::Expr; + /// # + /// # fn example(expr: Expr) { + /// # const IGNORE: &str = stringify! { + /// let expr: Expr = /* ... */; + /// # }; + /// match expr { + /// Expr::MethodCall(expr) => { + /// /* ... */ + /// } + /// Expr::Cast(expr) => { + /// /* ... */ + /// } + /// Expr::If(expr) => { + /// /* ... */ + /// } + /// + /// /* ... */ + /// # _ => {} + /// # } + /// # } + /// ``` + /// + /// We begin with a variable `expr` of type `Expr` that has no fields + /// (because it is an enum), and by matching on it and rebinding a variable + /// with the same name `expr` we effectively imbue our variable with all of + /// the data fields provided by the variant that it turned out to be. So for + /// example above if we ended up in the `MethodCall` case then we get to use + /// `expr.receiver`, `expr.args` etc; if we ended up in the `If` case we get + /// to use `expr.cond`, `expr.then_branch`, `expr.else_branch`. + /// + /// This approach avoids repeating the variant names twice on every line. + /// + /// ``` + /// # use syn::{Expr, ExprMethodCall}; + /// # + /// # fn example(expr: Expr) { + /// // Repetitive; recommend not doing this. + /// match expr { + /// Expr::MethodCall(ExprMethodCall { method, args, .. }) => { + /// # } + /// # _ => {} + /// # } + /// # } + /// ``` + /// + /// In general, the name to which a syntax tree enum variant is bound should + /// be a suitable name for the complete syntax tree enum type. + /// + /// ``` + /// # use syn::{Expr, ExprField}; + /// # + /// # fn example(discriminant: ExprField) { + /// // Binding is called `base` which is the name I would use if I were + /// // assigning `*discriminant.base` without an `if let`. + /// if let Expr::Tuple(base) = *discriminant.base { + /// # } + /// # } + /// ``` + /// + /// A sign that you may not be choosing the right variable names is if you + /// see names getting repeated in your code, like accessing + /// `receiver.receiver` or `pat.pat` or `cond.cond`. + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + #[cfg_attr(not(syn_no_non_exhaustive), non_exhaustive)] + pub enum Expr { + /// A slice literal expression: `[a, b, c, d]`. + Array(ExprArray), + + /// An assignment expression: `a = compute()`. + Assign(ExprAssign), + + /// A compound assignment expression: `counter += 1`. + AssignOp(ExprAssignOp), + + /// An async block: `async { ... }`. + Async(ExprAsync), + + /// An await expression: `fut.await`. + Await(ExprAwait), + + /// A binary operation: `a + b`, `a * b`. + Binary(ExprBinary), + + /// A blocked scope: `{ ... }`. + Block(ExprBlock), + + /// A box expression: `box f`. + Box(ExprBox), + + /// A `break`, with an optional label to break and an optional + /// expression. + Break(ExprBreak), + + /// A function call expression: `invoke(a, b)`. + Call(ExprCall), + + /// A cast expression: `foo as f64`. + Cast(ExprCast), + + /// A closure expression: `|a, b| a + b`. + Closure(ExprClosure), + + /// A `continue`, with an optional label. + Continue(ExprContinue), + + /// Access of a named struct field (`obj.k`) or unnamed tuple struct + /// field (`obj.0`). + Field(ExprField), + + /// A for loop: `for pat in expr { ... }`. + ForLoop(ExprForLoop), + + /// An expression contained within invisible delimiters. + /// + /// This variant is important for faithfully representing the precedence + /// of expressions and is related to `None`-delimited spans in a + /// `TokenStream`. + Group(ExprGroup), + + /// An `if` expression with an optional `else` block: `if expr { ... } + /// else { ... }`. + /// + /// The `else` branch expression may only be an `If` or `Block` + /// expression, not any of the other types of expression. + If(ExprIf), + + /// A square bracketed indexing expression: `vector[2]`. + Index(ExprIndex), + + /// A `let` guard: `let Some(x) = opt`. + Let(ExprLet), + + /// A literal in place of an expression: `1`, `"foo"`. + Lit(ExprLit), + + /// Conditionless loop: `loop { ... }`. + Loop(ExprLoop), + + /// A macro invocation expression: `format!("{}", q)`. + Macro(ExprMacro), + + /// A `match` expression: `match n { Some(n) => {}, None => {} }`. + Match(ExprMatch), + + /// A method call expression: `x.foo::(a, b)`. + MethodCall(ExprMethodCall), + + /// A parenthesized expression: `(a + b)`. + Paren(ExprParen), + + /// A path like `std::mem::replace` possibly containing generic + /// parameters and a qualified self-type. + /// + /// A plain identifier like `x` is a path of length 1. + Path(ExprPath), + + /// A range expression: `1..2`, `1..`, `..2`, `1..=2`, `..=2`. + Range(ExprRange), + + /// A referencing operation: `&a` or `&mut a`. + Reference(ExprReference), + + /// An array literal constructed from one repeated element: `[0u8; N]`. + Repeat(ExprRepeat), + + /// A `return`, with an optional value to be returned. + Return(ExprReturn), + + /// A struct literal expression: `Point { x: 1, y: 1 }`. + /// + /// The `rest` provides the value of the remaining fields as in `S { a: + /// 1, b: 1, ..rest }`. + Struct(ExprStruct), + + /// A try-expression: `expr?`. + Try(ExprTry), + + /// A try block: `try { ... }`. + TryBlock(ExprTryBlock), + + /// A tuple expression: `(a, b, c, d)`. + Tuple(ExprTuple), + + /// A type ascription expression: `foo: f64`. + Type(ExprType), + + /// A unary operation: `!x`, `*x`. + Unary(ExprUnary), + + /// An unsafe block: `unsafe { ... }`. + Unsafe(ExprUnsafe), + + /// Tokens in expression position not interpreted by Syn. + Verbatim(TokenStream), + + /// A while loop: `while expr { ... }`. + While(ExprWhile), + + /// A yield expression: `yield expr`. + Yield(ExprYield), + + // Not public API. + // + // For testing exhaustiveness in downstream code, use the following idiom: + // + // match expr { + // Expr::Array(expr) => {...} + // Expr::Assign(expr) => {...} + // ... + // Expr::Yield(expr) => {...} + // + // #[cfg_attr(test, deny(non_exhaustive_omitted_patterns))] + // _ => { /* some sane fallback */ } + // } + // + // This way we fail your tests but don't break your library when adding + // a variant. You will be notified by a test failure when a variant is + // added, so that you can add code to handle it, but your library will + // continue to compile and work for downstream users in the interim. + #[cfg(syn_no_non_exhaustive)] + #[doc(hidden)] + __NonExhaustive, + } +} + +ast_struct! { + /// A slice literal expression: `[a, b, c, d]`. + /// + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct ExprArray #full { + pub attrs: Vec, + pub bracket_token: token::Bracket, + pub elems: Punctuated, + } +} + +ast_struct! { + /// An assignment expression: `a = compute()`. + /// + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct ExprAssign #full { + pub attrs: Vec, + pub left: Box, + pub eq_token: Token![=], + pub right: Box, + } +} + +ast_struct! { + /// A compound assignment expression: `counter += 1`. + /// + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct ExprAssignOp #full { + pub attrs: Vec, + pub left: Box, + pub op: BinOp, + pub right: Box, + } +} + +ast_struct! { + /// An async block: `async { ... }`. + /// + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct ExprAsync #full { + pub attrs: Vec, + pub async_token: Token![async], + pub capture: Option, + pub block: Block, + } +} + +ast_struct! { + /// An await expression: `fut.await`. + /// + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct ExprAwait #full { + pub attrs: Vec, + pub base: Box, + pub dot_token: Token![.], + pub await_token: token::Await, + } +} + +ast_struct! { + /// A binary operation: `a + b`, `a * b`. + /// + /// *This type is available only if Syn is built with the `"derive"` or + /// `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))] + pub struct ExprBinary { + pub attrs: Vec, + pub left: Box, + pub op: BinOp, + pub right: Box, + } +} + +ast_struct! { + /// A blocked scope: `{ ... }`. + /// + /// *This type is available only if Syn is built with the `"full"` feature.* + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct ExprBlock #full { + pub attrs: Vec, + pub label: Option
+ +Click to show Cargo.toml. +Run this code in the playground. + + +```toml +[dependencies] + +# The core APIs, including the Serialize and Deserialize traits. Always +# required when using Serde. The "derive" feature is only required when +# using #[derive(Serialize, Deserialize)] to make Serde work with structs +# and enums defined in your crate. +serde = { version = "1.0", features = ["derive"] } + +# Each data format lives in its own crate; the sample code below uses JSON +# but you may be using a different one. +serde_json = "1.0" +``` + +